Runway 1.0.1
This commit is contained in:
1 parent
dcf819146b
commit
ce217fc952
259 files changed
+22226
-206
No files matched your search
@@ -0,0 +1,110 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code Article} (or {@code BlogPosting} — the subtype the entry declares as its
|
||||
* {@code type}) from a post's {@code content.schema} entry: {@code headline} (falls back to the page title),
|
||||
* description, image, {@code author} (a {@code Person}), {@code datePublished}/{@code dateModified},
|
||||
* {@code publisher}→Organization. The declared type <b>is</b> the page's own type (since 2.2.0): the properties go on
|
||||
* the page's {@code #webpage} node, which takes the declared {@code @type}, instead of a second node beside it.
|
||||
*
|
||||
* <h2>Where author and dates come from, and why the order matters</h2>
|
||||
* Each of {@code author}, {@code datePublished} and {@code dateModified} is taken from <b>the page's own
|
||||
* provenance first</b> ({@link mx.quest.runway.spi.model.PageMeta#provenance()}), and only then from the
|
||||
* hand-written {@code content.schema} block.
|
||||
*
|
||||
* <p>That order is the whole point of the change. {@code content.schema} matches by exact path or {@code *}
|
||||
* prefix, so a blog is typed by a single {@code /blog/*} block shared by <b>every</b> entry. When these fields
|
||||
* could only come from there, a site had exactly two honest options: omit dates and authorship entirely, or
|
||||
* assert <i>one</i> date and <i>one</i> author identically on every post — a statement that is false of nearly
|
||||
* every page it appears on. Asserting content that is not true of the page is precisely what structured-data
|
||||
* policy prohibits, so the configuration-only design pushed a conscientious operator toward a violation.
|
||||
*
|
||||
* <p>Per-item provenance removes the dilemma: a source that knows its own publication date (a blog entry does)
|
||||
* now supplies it, and the shared block is left to cover only what is genuinely shared. The config path is kept
|
||||
* as a fallback so existing sites keep working unchanged, and so a source that has no provenance can still be
|
||||
* annotated by hand.
|
||||
*/
|
||||
final class ArticleSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Article";
|
||||
}
|
||||
|
||||
/** Every token is a page type: an article (or blog post, or news article) is what the page is. */
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Nothing as a separate node: the article is the page itself ({@link #describePage}). */
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the article's properties to the page's own node: {@code headline} in place of {@code name}, and
|
||||
* author, dates and image. Without a headline (no page title and none configured) the page keeps its name.
|
||||
*/
|
||||
@Override
|
||||
public void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
Map<String, Object> fields = fields(ctx, sc);
|
||||
if (fields.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
page.remove("name");
|
||||
page.putAll(fields);
|
||||
}
|
||||
|
||||
/** The article's own properties, or an empty map when it has no headline. */
|
||||
private static Map<String, Object> fields(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String headline = Schemas.str(cfg, "headline", ctx.page().title());
|
||||
if (headline == null || headline.isBlank()) {
|
||||
return Map.of(); // no headline — leave the page node as it is
|
||||
}
|
||||
Map<String, Object> article = new LinkedHashMap<>();
|
||||
Ld.put(article, "headline", headline);
|
||||
Ld.put(article, "description", Schemas.str(cfg, "description", ctx.page().description()));
|
||||
Ld.putList(article, "image", Schemas.absolute(Schemas.strings(cfg, "image"), sc.base()));
|
||||
// Per-item provenance WINS over the shared content.schema block — see the class contract.
|
||||
mx.quest.runway.spi.model.Provenance prov = ctx.page().provenance();
|
||||
Ld.put(article, "datePublished", isoDate(prov.publishedAt(), Schemas.str(cfg, "datePublished")));
|
||||
Ld.put(article, "dateModified", isoDate(prov.updatedAt(), Schemas.str(cfg, "dateModified")));
|
||||
Ld.put(article, "inLanguage", ctx.locale().toLanguageTag());
|
||||
String author = prov.author() != null ? prov.author() : Schemas.str(cfg, "author");
|
||||
if (author != null) {
|
||||
Map<String, Object> person = new LinkedHashMap<>();
|
||||
person.put("@type", "Person");
|
||||
person.put("name", author);
|
||||
article.put("author", person);
|
||||
}
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(article, "publisher", sc.organizationId());
|
||||
}
|
||||
return article;
|
||||
}
|
||||
|
||||
/**
|
||||
* The item's own instant as a schema.org date, else the configured fallback.
|
||||
*
|
||||
* <p>Rendered as {@code yyyy-MM-dd} (UTC) rather than a full timestamp: schema.org accepts either, and a
|
||||
* publication date is an editorial fact at day granularity. Emitting a second-precision instant would imply
|
||||
* a precision the platform does not actually have — {@code dateModified} in particular is derived from a
|
||||
* file mtime, which moves for reasons that are not editorial.
|
||||
*/
|
||||
private static String isoDate(java.time.Instant instant, String fallback) {
|
||||
if (instant == null) {
|
||||
return fallback;
|
||||
}
|
||||
return java.time.format.DateTimeFormatter.ISO_LOCAL_DATE
|
||||
.format(instant.atZone(java.time.ZoneOffset.UTC));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code ItemList} for a collection / index page (a coffee listing, a services or blog index)
|
||||
* from an {@code items:} list of {@code {name, url}}. Without it a listing page is invisible <em>as a list</em> to
|
||||
* crawlers (no carousel eligibility) and answer engines. Registered under both {@code ItemList} and
|
||||
* {@code CollectionPage}; the node is {@code @id}'d and {@code mainEntityOfPage}-linked to the page. Declared as
|
||||
* {@code CollectionPage} it also makes the page itself a {@code CollectionPage} whose {@code mainEntity} is the list
|
||||
* (since 2.2.0; until then the page stayed the site default and only the list was emitted).
|
||||
*/
|
||||
final class CollectionSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "ItemList";
|
||||
}
|
||||
|
||||
/** {@code CollectionPage} names what the page is; {@code ItemList} only adds the list. */
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return "CollectionPage".equals(token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
for (Map<String, Object> list : nodes(ctx, sc)) {
|
||||
graph.add(list);
|
||||
Ld.ref(page, "mainEntity", (String) list.get("@id"));
|
||||
}
|
||||
}
|
||||
|
||||
/** No item with a {@code url}: no list is published (a CollectionPage is still a CollectionPage). */
|
||||
@Override
|
||||
public Gap gap(String token, Map<String, Object> block) {
|
||||
for (Map<String, Object> member : Schemas.maps(block, "items")) {
|
||||
if (Schemas.str(member, "url") != null) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return new Gap("discover.gap.items", "{0} has no item with a url:, so no list is published.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
List<Map<String, Object>> members = Schemas.maps(sc.pageConfig(), "items");
|
||||
List<Map<String, Object>> elements = new ArrayList<>();
|
||||
int position = 1;
|
||||
for (Map<String, Object> member : members) {
|
||||
String url = Schemas.str(member, "url");
|
||||
if (url == null) {
|
||||
continue; // a list item without a target URL is not useful
|
||||
}
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("@type", "ListItem");
|
||||
item.put("position", position++);
|
||||
Ld.put(item, "name", Schemas.str(member, "name"));
|
||||
item.put("url", url.startsWith("/") ? sc.base() + url : url);
|
||||
elements.add(item);
|
||||
}
|
||||
if (elements.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, Object> list = Ld.node("ItemList", sc.canonical() + "#itemlist");
|
||||
Ld.ref(list, "mainEntityOfPage", sc.webpageId());
|
||||
list.put("itemListElement", elements);
|
||||
return List.of(list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
|
||||
/**
|
||||
* Conditional-GET support for the crawl surfaces (sitemap.xml, llms.txt): crawlers hit these often, and the
|
||||
* content only changes when the site's content does — so both endpoints emit {@code Last-Modified} with
|
||||
* {@code Cache-Control: no-cache} (cache it, but REVALIDATE every time), and answer {@code If-Modified-Since}
|
||||
* with an empty {@code 304} instead of re-serializing the whole document.
|
||||
*
|
||||
* <p><b>The validator must reflect MEMBERSHIP, not just member mtimes.</b> These documents are lists: deleting
|
||||
* or unpublishing an item only <em>removes</em> an {@code updatedAt} from the pool, so a naive
|
||||
* {@code max(updatedAt)} stays the same (or moves backward) and a revalidating crawler would keep its cached
|
||||
* copy — still advertising the removed URL — indefinitely. The validator therefore combines a per-site
|
||||
* <b>fingerprint</b> of the document-shaping facts (item identity, paths, {@code updatedAt}, {@code noindex},
|
||||
* and the host-computed URLs: every locale's address and canonical, and the {@code x-default}) — plus, per
|
||||
* document, the <b>document-level facts</b> it prints that no item carries (llms.txt's site name and
|
||||
* {@code geo.summary}) — with a <b>monotonic</b> emitted instant: while the fingerprint is unchanged the emitted value is stable; any
|
||||
* change advances it to {@code max(newest updatedAt, previous)} — or to <em>now</em> when the change carries no
|
||||
* newer mtime (a removal, an addition with a null {@code updatedAt}). A future-dated {@code updatedAt} (clock
|
||||
* skew, a touched file) is clamped to now so it cannot pin the validator and mask later real changes.
|
||||
*
|
||||
* <p>State is in-memory only. On restart the first request per site seeds the emitted instant with <em>now</em>
|
||||
* — deliberately: seeding with the content mtime would resurrect the removal blind spot for any membership
|
||||
* change that happened around the restart. The cost is one full {@code 200} per crawler after a restart; the
|
||||
* value then stabilizes until content actually changes. HTTP dates are second-granular, so instants are
|
||||
* truncated before comparing.
|
||||
*/
|
||||
final class CrawlConditional {
|
||||
|
||||
private static final DateTimeFormatter HTTP_DATE =
|
||||
DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC);
|
||||
|
||||
/** What the site's crawl documents last looked like (fingerprint) and the validator emitted for it. */
|
||||
private record Validator(String fingerprint, Instant emitted) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validator state per site <b>and document</b>. Until 2.1.0 the sitemap and llms.txt shared one record per site
|
||||
* (both derive from the same catalog list); llms.txt now also folds facts the sitemap does not print, and two
|
||||
* documents with different fingerprints sharing one record would advance each other's validator on every
|
||||
* alternate request.
|
||||
*/
|
||||
private static final ConcurrentMap<String, Validator> STATE = new ConcurrentHashMap<>();
|
||||
|
||||
/** The sitemap's document name — its validator folds the catalog only. */
|
||||
static final String SITEMAP = "sitemap.xml";
|
||||
/** The llms.txt document name — its validator also folds the site name and summary it prints. */
|
||||
static final String LLMS = "llms.txt";
|
||||
|
||||
/** The time source — a test hook ({@link #reset} restores it); production always uses the system clock. */
|
||||
static java.util.function.Supplier<Instant> clock = Instant::now;
|
||||
|
||||
private CrawlConditional() {
|
||||
}
|
||||
|
||||
/** Test hook: forget all per-site validator state (simulates a restart) and restore the system clock. */
|
||||
static void reset() {
|
||||
STATE.clear();
|
||||
clock = Instant::now;
|
||||
}
|
||||
|
||||
/** The sitemap's validator: {@link #lastModified(String, String, List, List)} with no document-level facts. */
|
||||
static Instant lastModified(String siteId, List<CatalogEntry> items) {
|
||||
return lastModified(siteId, SITEMAP, items, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code Last-Modified} validator for {@code siteId}'s crawl document {@code document} built from
|
||||
* {@code items} and the document-level {@code facts} it prints besides them (in a fixed order; a {@code null}
|
||||
* fact folds as empty) — membership-aware and monotonic per the class contract (never in the future, never moves
|
||||
* backward). A change to a fact advances the validator to <em>now</em>: it carries no mtime of its own.
|
||||
*/
|
||||
static Instant lastModified(String siteId, String document, List<CatalogEntry> items, List<String> facts) {
|
||||
Instant now = clock.get().truncatedTo(ChronoUnit.SECONDS);
|
||||
Instant newest = newestUpdatedAt(items, now);
|
||||
String fingerprint = fingerprint(items, facts);
|
||||
// A printable separator ('|' is never part of a site id), never a control character.
|
||||
Validator computed = STATE.compute(siteId + '|' + document, (id, prev) -> {
|
||||
if (prev == null) {
|
||||
return new Validator(fingerprint, now); // restart seed: now, per the class contract
|
||||
}
|
||||
if (prev.fingerprint().equals(fingerprint)) {
|
||||
return prev; // unchanged document keeps its validator — this is what makes 304s possible
|
||||
}
|
||||
Instant advanced = (newest != null && newest.isAfter(prev.emitted())) ? newest : now;
|
||||
if (!advanced.isAfter(prev.emitted())) {
|
||||
// Cannot advance within HTTP-date granularity (a change in the same second as the previous
|
||||
// advance, or a backward clock). Keep the OLD state — fingerprint included — so a later
|
||||
// request re-detects the change and advances once the clock has moved; committing the new
|
||||
// fingerprint now would absorb the change at the old validator forever.
|
||||
return prev;
|
||||
}
|
||||
return new Validator(fingerprint, advanced);
|
||||
});
|
||||
return computed.emitted();
|
||||
}
|
||||
|
||||
/** The newest {@code updatedAt} across {@code items} clamped to {@code now}, or null when none carries one. */
|
||||
private static Instant newestUpdatedAt(List<CatalogEntry> items, Instant now) {
|
||||
Instant newest = null;
|
||||
for (CatalogEntry item : items) {
|
||||
Instant updated = item.ref().updatedAt();
|
||||
if (updated != null && (newest == null || updated.isAfter(newest))) {
|
||||
newest = updated;
|
||||
}
|
||||
}
|
||||
if (newest == null) {
|
||||
return null;
|
||||
}
|
||||
newest = newest.truncatedTo(ChronoUnit.SECONDS);
|
||||
return newest.isAfter(now) ? now : newest; // a future mtime must not pin the validator
|
||||
}
|
||||
|
||||
/**
|
||||
* A digest of the document-shaping facts: identity, paths, mtime, indexability, and the URLs the host computed —
|
||||
* order-sensitive. The URLs are folded in because they change without any item changing: a site that starts
|
||||
* serving another locale gains alternates, and a canonical override moves an item in or out of the sitemap.
|
||||
* (Until 2.0.0 they were not, so a crawler revalidating after such a change kept its old copy.) The document-level
|
||||
* facts come first, each length-prefixed so no fact can shift characters into the next (until 2.1.0 there were
|
||||
* none, so editing the site name or {@code geo.summary} changed llms.txt without advancing its validator).
|
||||
*/
|
||||
private static String fingerprint(List<CatalogEntry> items, List<String> facts) {
|
||||
MessageDigest digest;
|
||||
try {
|
||||
digest = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException("SHA-256 unavailable", impossible);
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(128);
|
||||
sb.append("facts#").append(facts.size()).append(';');
|
||||
for (String fact : facts) {
|
||||
String value = fact == null ? "" : fact;
|
||||
sb.append(value.length()).append(':').append(value);
|
||||
}
|
||||
sb.append('\n');
|
||||
digest.update(sb.toString().getBytes(StandardCharsets.UTF_8));
|
||||
for (CatalogEntry item : items) {
|
||||
sb.setLength(0);
|
||||
sb.append(item.compositeId()).append('|').append(item.ref().path()).append('|')
|
||||
.append(item.ref().localizedPaths()).append('|').append(item.ref().updatedAt()).append('|')
|
||||
.append(item.ref().noindex()).append('|').append(item.xDefaultPath());
|
||||
for (LocalizedUrl url : item.urls()) {
|
||||
sb.append('|').append(url.locale().toLanguageTag()).append('=').append(url.path())
|
||||
.append('>').append(url.canonical());
|
||||
}
|
||||
sb.append('\n');
|
||||
digest.update(sb.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return java.util.HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
|
||||
/** Whether the request's {@code If-Modified-Since} already covers {@code lastModified} (null ⇒ no). */
|
||||
static boolean notModified(RouteRequest req, Instant lastModified) {
|
||||
if (lastModified == null) {
|
||||
return false;
|
||||
}
|
||||
String header = header(req, "If-Modified-Since");
|
||||
if (header == null || header.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Instant since = Instant.from(HTTP_DATE.parse(header.trim()));
|
||||
return !lastModified.truncatedTo(ChronoUnit.SECONDS).isAfter(since);
|
||||
} catch (RuntimeException unparseable) {
|
||||
return false; // an invalid date = an unconditional request
|
||||
}
|
||||
}
|
||||
|
||||
/** The empty {@code 304} carrying the same validator/caching headers as the {@code 200} would. */
|
||||
static RouteResponse notModifiedResponse(Instant lastModified) {
|
||||
return new RouteResponse(304, cacheHeaders(lastModified, null), new byte[0]);
|
||||
}
|
||||
|
||||
/** The response headers for a fresh {@code 200}: content type + validator + revalidate-always caching. */
|
||||
static Map<String, String> cacheHeaders(Instant lastModified, String contentType) {
|
||||
Map<String, String> headers = new java.util.LinkedHashMap<>();
|
||||
if (contentType != null) {
|
||||
headers.put("Content-Type", contentType);
|
||||
}
|
||||
if (lastModified != null) {
|
||||
headers.put("Last-Modified", HTTP_DATE.format(lastModified.truncatedTo(ChronoUnit.SECONDS)));
|
||||
}
|
||||
headers.put("Cache-Control", "no-cache");
|
||||
return headers;
|
||||
}
|
||||
|
||||
private static String header(RouteRequest req, String name) {
|
||||
for (var entry : req.headers().entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(name)) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* Backs the tenant <b>dashboard card</b> and the <b>admin fragment</b> rendered below the plugin's per-tenant
|
||||
* settings form. The templates call it as {@code ${@discoverabilityAdminModel.<method>(tenantSiteId)}} (the bean
|
||||
* name carries the plugin id, as every plugin bean must) to show the plugin's live state for the current site
|
||||
* (which surfaces are on, how many items the sitemap draws from).
|
||||
*
|
||||
* <p>Read-only. A missing or malformed site id (the fragments are only rendered for a tenant, so neither happens in
|
||||
* practice) answers the defaults and a count of {@code 0} rather than failing the console page.
|
||||
*/
|
||||
public class DiscoverAdminModel {
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final ContentCatalogView catalog;
|
||||
private final Map<String, SchemaType> types;
|
||||
private final Messages messages;
|
||||
|
||||
public DiscoverAdminModel(PluginSettings settings, ContentCatalogView catalog) {
|
||||
this(settings, catalog, DiscoverabilityConfig.schemaTypes(), null);
|
||||
}
|
||||
|
||||
DiscoverAdminModel(PluginSettings settings, ContentCatalogView catalog, Map<String, SchemaType> types,
|
||||
Messages messages) {
|
||||
this.settings = settings;
|
||||
this.catalog = catalog;
|
||||
this.types = types;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* What is wrong with the site's Per-page types ({@code content.schema}), one line each, in the operator's UI
|
||||
* language; empty when nothing is. Shown below the settings form after every save.
|
||||
*
|
||||
* <h2>Why</h2>
|
||||
* A mistake there never breaks a page: unreadable YAML turns typing off, and an unknown type or a misplaced
|
||||
* {@code *} is skipped. That is the right behaviour for visitors and the wrong one for the person who typed it,
|
||||
* who until 2.2.0 had no way to see it. A block that applies but publishes nothing of its own (an
|
||||
* {@code FAQPage} with no complete question: {@link SchemaType#gap}) is listed too; an ignored second page type
|
||||
* is reported once, not also for its gaps.
|
||||
*/
|
||||
public List<String> schemaProblems(String siteId) {
|
||||
String text = SiteConfig.str(cfg(siteId), "content.schema", "");
|
||||
List<String> out = new ArrayList<>();
|
||||
String syntax = PageSchemaConfig.syntaxProblem(text);
|
||||
if (syntax != null) {
|
||||
out.add(text("discover.schema.syntax",
|
||||
"Per-page types cannot be read, so no page gets a per-page type: {0}", syntax));
|
||||
return out;
|
||||
}
|
||||
for (String pattern : PageSchemaConfig.ignoredPatterns(text)) {
|
||||
out.add(text("discover.schema.notBlock",
|
||||
"{0}: the value must be a type block (type: ...) or a list of them; ignored.", pattern));
|
||||
}
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(text);
|
||||
for (Map.Entry<String, Object> entry : patterns.entrySet()) {
|
||||
String pattern = entry.getKey();
|
||||
if (!pattern.startsWith("/")) {
|
||||
out.add(text("discover.schema.slash", "{0}: a pattern starts with / and matches page paths.",
|
||||
pattern));
|
||||
}
|
||||
int star = pattern.indexOf('*');
|
||||
if (star >= 0 && star < pattern.length() - 1) {
|
||||
out.add(text("discover.schema.star",
|
||||
"{0}: * works only at the end of a pattern; here it is matched as a character.", pattern));
|
||||
}
|
||||
int pageTypes = 0;
|
||||
for (Map<String, Object> block : PageSchemaConfig.blocks(entry.getValue())) {
|
||||
String token = Schemas.str(block, "type", "");
|
||||
if (token.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
SchemaType handler = types.get(token);
|
||||
if (handler == null) {
|
||||
out.add(text("discover.schema.unknown",
|
||||
"{0}: {1} is not a type this plugin knows; ignored.", pattern, token));
|
||||
} else if (handler.describesPage(token) && ++pageTypes > 1) {
|
||||
if (pageTypes == 2) {
|
||||
out.add(text("discover.schema.twoPageTypes",
|
||||
"{0}: more than one page type; only the first applies.", pattern));
|
||||
}
|
||||
} else {
|
||||
SchemaType.Gap gap = handler.gap(token, block);
|
||||
if (gap != null) {
|
||||
out.add(pattern + ": " + text(gap.code(), gap.fallback(), token));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private String text(String code, String fallback, Object... args) {
|
||||
return messages == null ? java.text.MessageFormat.format(fallback, args)
|
||||
: messages.console(code, fallback, args);
|
||||
}
|
||||
|
||||
public boolean jsonldEnabled(String siteId) {
|
||||
return SiteConfig.bool(cfg(siteId), "jsonld.enabled", true);
|
||||
}
|
||||
|
||||
public String jsonldType(String siteId) {
|
||||
return PageTypes.defaultType(cfg(siteId));
|
||||
}
|
||||
|
||||
public boolean sitemapEnabled(String siteId) {
|
||||
return SiteConfig.bool(cfg(siteId), "sitemap.enabled", true);
|
||||
}
|
||||
|
||||
public boolean geoEnabled(String siteId) {
|
||||
return SiteConfig.bool(cfg(siteId), "geo.enabled", false);
|
||||
}
|
||||
|
||||
public boolean orgConfigured(String siteId) {
|
||||
return !SiteConfig.str(cfg(siteId), "org.name", "").isBlank();
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of published content items the sitemap draws from — kernel pages AND plugin content alike, through
|
||||
* the same host listing the sitemap itself serves from (so this count is always truthful). Items marked
|
||||
* {@code noindex} are included, as before: the count is of the published surface.
|
||||
*/
|
||||
public long pageCount(String siteId) {
|
||||
if (siteId == null) {
|
||||
return 0L;
|
||||
}
|
||||
try {
|
||||
return catalog.entries(siteId).size();
|
||||
} catch (IllegalArgumentException malformedId) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> cfg(String siteId) {
|
||||
if (siteId == null) {
|
||||
return Map.of();
|
||||
}
|
||||
try {
|
||||
return settings.site(siteId).values();
|
||||
} catch (IllegalArgumentException malformedId) {
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
|
||||
* refresh. It wires every bean EXPLICITLY (no {@code @ComponentScan}: scanning a plugin's own package across the
|
||||
* shared child classloader is fragile). The plugin package ({@code mx.quest.discover}) is deliberately OUTSIDE
|
||||
* {@code mx.quest.runway} so the host never double-scans it.
|
||||
*
|
||||
* <p>The {@link HeadContributor} and {@link EndpointContributor}s are list-collected SPIs — plain
|
||||
* {@code @Bean}s, NEVER {@code @Primary}. The head contributor is ordered AFTER the kernel's own SEO
|
||||
* ({@code @Order 100}) and icon ({@code @Order 90}) head contributors, so the plugin's structured data is
|
||||
* spliced last.
|
||||
*
|
||||
* <p><b>Links only the Runway SPI</b> (since 2.0.0). Every host service arrives by ordinary injection of an SPI
|
||||
* type: {@link PluginSettings} (this plugin's per-site settings, bound to this plugin by the jar its code was
|
||||
* loaded from), {@link ContentCatalogView} (the site's published content surface with host-computed URLs) and
|
||||
* {@link Sites}. Every bean name starts with the plugin id ({@code discoverability…}): plugins share the host's
|
||||
* bean namespace.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class DiscoverabilityConfig {
|
||||
|
||||
// --- app-level (platform) settings ----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The app-level settings, bound from {@code runway.plugin.discoverability.*}. Declared as a named {@code @Bean}
|
||||
* rather than through {@code @EnableConfigurationProperties}, which would register it under the generated name
|
||||
* {@code runway.plugin.discoverability-mx.quest.discover.DiscoverabilityProperties} — outside the plugin's bean
|
||||
* prefix.
|
||||
*/
|
||||
@Bean
|
||||
@ConfigurationProperties("runway.plugin.discoverability")
|
||||
public DiscoverabilityProperties discoverabilityProperties() {
|
||||
return new DiscoverabilityProperties();
|
||||
}
|
||||
|
||||
// --- head contributor (SEO+ and GEO in one @graph) ------------------------------------------------
|
||||
|
||||
@Bean
|
||||
@Order(150)
|
||||
public HeadContributor discoverabilityStructuredData(PluginSettings settings) {
|
||||
return new StructuredDataHead(settings, schemaTypes());
|
||||
}
|
||||
|
||||
/**
|
||||
* The content-type registry (item 5), indexed by the type token a tenant declares in {@code content.schema}.
|
||||
* Subtypes are registered under aliases that share one implementation (e.g. {@code BlogPosting}→Article).
|
||||
* Fails fast on a duplicate key so a wiring mistake never silently shadows a type.
|
||||
*/
|
||||
static Map<String, SchemaType> schemaTypes() {
|
||||
Map<String, SchemaType> types = new LinkedHashMap<>();
|
||||
register(types, new FaqPageSchema());
|
||||
register(types, new ProductSchema());
|
||||
register(types, new ArticleSchema(), "BlogPosting", "NewsArticle");
|
||||
register(types, new LocalBusinessSchema(), "CafeOrCoffeeShop");
|
||||
register(types, new ServiceSchema(), "ProfessionalService");
|
||||
register(types, new PersonSchema());
|
||||
register(types, new CollectionSchema(), "CollectionPage");
|
||||
for (String key : SimplePageType.KEYS) {
|
||||
register(types, new SimplePageType(key));
|
||||
}
|
||||
return types;
|
||||
}
|
||||
|
||||
private static void register(Map<String, SchemaType> types, SchemaType type, String... aliases) {
|
||||
put(types, type.key(), type);
|
||||
for (String alias : aliases) {
|
||||
put(types, alias, type);
|
||||
}
|
||||
}
|
||||
|
||||
private static void put(Map<String, SchemaType> types, String key, SchemaType type) {
|
||||
if (types.putIfAbsent(key, type) != null) {
|
||||
throw new IllegalStateException("duplicate schema type key: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
// --- crawl-surface endpoints ----------------------------------------------------------------------
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilitySitemap(ContentCatalogView catalog, PluginSettings settings) {
|
||||
return new SitemapEndpoint(catalog, settings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilityLlms(ContentCatalogView catalog, PluginSettings settings) {
|
||||
return new LlmsTxtEndpoint(catalog, settings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilityRobots(PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
return new RobotsTxtEndpoint(settings, properties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilityIndexNowKey(PluginSettings settings,
|
||||
DiscoverabilityProperties properties) {
|
||||
return new IndexNowKeyEndpoint(settings, properties);
|
||||
}
|
||||
|
||||
// --- IndexNow (outbound: OFF unless the platform operator AND the tenant both enable it) -----------
|
||||
|
||||
/** A {@code SiteEventListener} (collected by type by the host) that queues changed URLs, plus the flush. */
|
||||
@Bean
|
||||
public IndexNowSubmitter discoverabilityIndexNow(Sites sites, PluginSettings settings,
|
||||
DiscoverabilityProperties properties) {
|
||||
return new IndexNowSubmitter(sites, settings, properties);
|
||||
}
|
||||
|
||||
// --- advisory quality check (edit-time detect-and-lift for on-page FAQs) --------------------------
|
||||
|
||||
@Bean
|
||||
public PageQualityCheck discoverabilityFaqAdvisory(PluginSettings settings) {
|
||||
return new FaqAdvisoryCheck(settings, schemaTypes());
|
||||
}
|
||||
|
||||
/** The page editor's line saying what each page is described as, and where that comes from. */
|
||||
@Bean
|
||||
public PageQualityCheck discoverabilityPageType(PluginSettings settings, Messages messages) {
|
||||
return new PageTypeCheck(settings, schemaTypes(), messages);
|
||||
}
|
||||
|
||||
// --- console surface (dashboard card + admin fragment) --------------------------------------------
|
||||
|
||||
/** Read by the templates as {@code ${@discoverabilityAdminModel…}} (renamed from {@code discoverAdminModel}). */
|
||||
@Bean
|
||||
public DiscoverAdminModel discoverabilityAdminModel(PluginSettings settings, ContentCatalogView catalog,
|
||||
Messages messages) {
|
||||
return new DiscoverAdminModel(settings, catalog, schemaTypes(), messages);
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* App-level settings for the discoverability plugin, bound from {@code runway.plugin.discoverability.*}
|
||||
* (the host loads {@code external/plugin-settings/discoverability.yml} as a property source). These are
|
||||
* <b>platform</b> concerns — the default AI/LLM-crawler posture a site inherits, the IndexNow egress switch — never
|
||||
* per-tenant behaviour (which lives in the descriptor's {@code siteSettings} and is read live via
|
||||
* {@code PluginSettings}). Bound by {@code @ConfigurationProperties} on its {@code @Bean} method in
|
||||
* {@link DiscoverabilityConfig#discoverabilityProperties()}; applied on restart.
|
||||
*/
|
||||
public class DiscoverabilityProperties {
|
||||
|
||||
private Robots robots = new Robots();
|
||||
private IndexNow indexnow = new IndexNow();
|
||||
|
||||
public Robots getRobots() {
|
||||
return robots;
|
||||
}
|
||||
|
||||
public void setRobots(Robots robots) {
|
||||
this.robots = robots;
|
||||
}
|
||||
|
||||
public IndexNow getIndexnow() {
|
||||
return indexnow;
|
||||
}
|
||||
|
||||
public void setIndexnow(IndexNow indexnow) {
|
||||
this.indexnow = indexnow == null ? new IndexNow() : indexnow;
|
||||
}
|
||||
|
||||
/**
|
||||
* IndexNow platform settings — the operator's control over whether this deployment talks to third parties
|
||||
* at all.
|
||||
*
|
||||
* <h2>Why the platform switch exists and why it is OFF</h2>
|
||||
* IndexNow is the first thing in this plugin that makes an <b>outbound</b> request on a tenant's behalf: a
|
||||
* tenant enabling it causes this server to POST that tenant's URLs to an external service. Who this
|
||||
* deployment is allowed to talk to is the <b>platform operator's</b> decision — they own the network, the
|
||||
* egress firewall and the incident if it misbehaves — so a tenant cannot switch it on unilaterally.
|
||||
*
|
||||
* <p>Off by default because an upgrade must never start making network calls a deployment was not making
|
||||
* before. A tenant who enables it while the platform has not gets a WARN naming the tenant and the setting
|
||||
* to flip, rather than silence.
|
||||
*/
|
||||
public static class IndexNow {
|
||||
|
||||
/** Whether tenants of this deployment may use IndexNow at all. Off until the operator permits it. */
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* The submission endpoint. Configurable so an operator can point at a specific engine's endpoint or an
|
||||
* internal proxy that carries their egress policy; the default is the shared endpoint, which forwards
|
||||
* to every participating engine.
|
||||
*/
|
||||
private String endpoint = "https://api.indexnow.org/indexnow";
|
||||
|
||||
/**
|
||||
* Seconds to gather changes before submitting. Batching is not an optimisation here — a page save
|
||||
* touching five URLs must not become five outbound requests, and an editor working through a section
|
||||
* would otherwise generate one per keystroke-to-save.
|
||||
*/
|
||||
private int batchSeconds = 60;
|
||||
|
||||
/**
|
||||
* Most URLs in one submission. The spec allows 10,000; a lower cap bounds both the request body and how
|
||||
* much a single misbehaving tenant can send. Overflow is dropped with a WARN, never silently.
|
||||
*/
|
||||
private int maxUrlsPerSubmission = 1000;
|
||||
|
||||
/** Most URLs queued per site between submissions. A bound on memory during a bulk edit or a restore. */
|
||||
private int maxQueuedPerSite = 5000;
|
||||
|
||||
/** Connect/read timeout for the submission. Short: nothing waits on it, and a hung call helps nobody. */
|
||||
private int timeoutSeconds = 10;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public void setEndpoint(String endpoint) {
|
||||
this.endpoint = endpoint;
|
||||
}
|
||||
|
||||
public int getBatchSeconds() {
|
||||
return batchSeconds;
|
||||
}
|
||||
|
||||
public void setBatchSeconds(int batchSeconds) {
|
||||
this.batchSeconds = batchSeconds;
|
||||
}
|
||||
|
||||
public int getMaxUrlsPerSubmission() {
|
||||
return maxUrlsPerSubmission;
|
||||
}
|
||||
|
||||
public void setMaxUrlsPerSubmission(int maxUrlsPerSubmission) {
|
||||
this.maxUrlsPerSubmission = maxUrlsPerSubmission;
|
||||
}
|
||||
|
||||
public int getMaxQueuedPerSite() {
|
||||
return maxQueuedPerSite;
|
||||
}
|
||||
|
||||
public void setMaxQueuedPerSite(int maxQueuedPerSite) {
|
||||
this.maxQueuedPerSite = maxQueuedPerSite;
|
||||
}
|
||||
|
||||
public int getTimeoutSeconds() {
|
||||
return timeoutSeconds;
|
||||
}
|
||||
|
||||
public void setTimeoutSeconds(int timeoutSeconds) {
|
||||
this.timeoutSeconds = timeoutSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code /robots.txt} platform defaults. */
|
||||
public static class Robots {
|
||||
|
||||
/**
|
||||
* The default AI/LLM-crawler policy a site inherits when its per-tenant {@code robots.ai-policy} is
|
||||
* {@code inherit} (the default): {@code allow} (GEO-friendly — the platform default) or {@code disallow}
|
||||
* (opt every un-overriding site out of AI crawling). Bound from {@code robots.ai-default}.
|
||||
*/
|
||||
private String aiDefault = "allow";
|
||||
|
||||
public String getAiDefault() {
|
||||
return aiDefault;
|
||||
}
|
||||
|
||||
public void setAiDefault(String aiDefault) {
|
||||
this.aiDefault = aiDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra AI/LLM crawler user-agent names to cover, <b>appended</b> to the plugin's built-in list. Bound
|
||||
* from {@code robots.ai-agents-extra}; empty by default, so the shipped behaviour is unchanged.
|
||||
*
|
||||
* <p>This exists because the built-in list is a compile-time constant that goes stale silently: when an
|
||||
* operator announces a new agent, every site set to {@code disallow} is un-covered for it until a plugin
|
||||
* release ships — and nothing reports the gap. This setting closes it the same day, without a release.
|
||||
*
|
||||
* <p>It is <b>app-level, not per-tenant</b>, deliberately: the set of agents that exist in the world is a
|
||||
* platform fact, not tenant-owned behaviour. What a tenant chooses to <i>do</i> about them stays
|
||||
* per-tenant, in {@code robots.ai-policy}.
|
||||
*
|
||||
* <p>Additive only, by design — there is no removal list. Naming an agent that has been retired costs one
|
||||
* inert {@code User-agent:} line; being unable to add one that exists costs an un-covered opt-out.
|
||||
*/
|
||||
private List<String> aiAgentsExtra = new ArrayList<>();
|
||||
|
||||
public List<String> getAiAgentsExtra() {
|
||||
return aiAgentsExtra;
|
||||
}
|
||||
|
||||
public void setAiAgentsExtra(List<String> aiAgentsExtra) {
|
||||
this.aiAgentsExtra = aiAgentsExtra == null ? new ArrayList<>() : aiAgentsExtra;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* An <b>advisory</b> {@link PageQualityCheck} that closes the loop on the type-aware structured data: the plugin
|
||||
* <em>emits</em> {@code FAQPage} from {@code content.schema}, and this check <em>detects</em> when a page has an
|
||||
* on-page FAQ (a cluster of {@code <details><summary>…</summary>…</details>} disclosures) that <b>isn't</b>
|
||||
* declared in {@code content.schema} yet, and nudges the author to add it — the "detect & lift" the audit
|
||||
* asked for. FAQ is the single highest-leverage GEO win, so surfacing an unmarked one is worth an INFO finding.
|
||||
*
|
||||
* <p>It runs at <b>edit/advisory time</b> (the host passes the freshly-rendered {@link PageView#resolvedHtml()}),
|
||||
* never at render, and it never edits the page — it only reports. It is <b>quiet when there's nothing to say</b>:
|
||||
* it stays silent unless the page has at least two disclosure clusters (a single {@code <details>} is usually a
|
||||
* "read more", not an FAQ), when the page is <b>already typed</b> {@code FAQPage} (the head renders it as one; no
|
||||
* nagging about a FAQ that's already marked up), and on a noindex page, which carries no structured data. The
|
||||
* finding is localized by its {@code code} via the host's message source
|
||||
* ({@code quality.discoverability.faq.unmarked}); the string here is only the English fallback.
|
||||
*/
|
||||
public class FaqAdvisoryCheck implements PageQualityCheck {
|
||||
|
||||
/** A {@code <details>} disclosure carrying a {@code <summary>} — i.e. a question/answer cluster. */
|
||||
private static final Pattern DISCLOSURE = Pattern.compile(
|
||||
"<details\\b[^>]*>.*?<summary\\b[^>]*>.*?</summary>.*?</details>",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||
|
||||
/** Below this many disclosures a page is unlikely to be an FAQ (avoids flagging a lone "read more"). */
|
||||
private static final int MIN_DISCLOSURES = 2;
|
||||
|
||||
private static final String FALLBACK =
|
||||
"This page has an on-page FAQ (a <details>/<summary> block) that isn't emitting FAQPage structured "
|
||||
+ "data. Add it to the discoverability plugin's content.schema for this path (see the plugin help).";
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Map<String, SchemaType> types;
|
||||
|
||||
public FaqAdvisoryCheck(PluginSettings settings) {
|
||||
this(settings, DiscoverabilityConfig.schemaTypes());
|
||||
}
|
||||
|
||||
FaqAdvisoryCheck(PluginSettings settings, Map<String, SchemaType> types) {
|
||||
this.settings = settings;
|
||||
this.types = types;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/faq-advisory";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Finding> inspect(PageView page) {
|
||||
if (page == null || page.resolvedHtml().isBlank() || countDisclosures(page.resolvedHtml()) < MIN_DISCLOSURES) {
|
||||
return List.of();
|
||||
}
|
||||
if (page.page() != null && page.page().noindex()) {
|
||||
return List.of(); // a noindex page carries no structured data, so FAQPage would do nothing there
|
||||
}
|
||||
if (!SiteConfig.bool(settings.site(page.site().id()).values(), "jsonld.enabled", true)) {
|
||||
return List.of(); // structured data is off for the site, so FAQPage markup would never be published
|
||||
}
|
||||
if (alreadyTypedFaq(page)) {
|
||||
return List.of(); // already marked up as FAQPage — nothing to advise
|
||||
}
|
||||
return List.of(Finding.info("discoverability.faq.unmarked", FALLBACK));
|
||||
}
|
||||
|
||||
private static int countDisclosures(String html) {
|
||||
Matcher m = DISCLOSURE.matcher(html);
|
||||
int count = 0;
|
||||
while (m.find()) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the head renders this page as an {@code FAQPage}: the same {@link PageTypes} answer the head and the
|
||||
* editor's line use. So a misspelt {@code faqpage} (an unknown type) or an {@code FAQPage} block after another
|
||||
* page type (ignored) does not count as typed, as the page served does not carry it either.
|
||||
*/
|
||||
private boolean alreadyTypedFaq(PageView page) {
|
||||
String canonical = page.canonical();
|
||||
if (canonical == null || canonical.isBlank()) {
|
||||
return false; // no canonical to derive a path from — advise rather than assume it's typed
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(page.site().id()).values();
|
||||
return "FAQPage".equals(PageTypes.describe(cfg, PageTypes.pathOf(page), types).type());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("quality.advisory", "quality.geo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code FAQPage} from a {@code faq:} list of question/answer pairs in the page's
|
||||
* {@code content.schema} entry. FAQ is the highest-leverage GEO type — answer engines lift Q&A directly —
|
||||
* so it is the first built-in {@link SchemaType}. The node is {@code mainEntityOfPage}-linked to this page's
|
||||
* {@code WebPage} {@code @id}; each entry becomes a {@code Question} with an {@code acceptedAnswer}.
|
||||
*/
|
||||
final class FaqPageSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "FAQPage";
|
||||
}
|
||||
|
||||
/** An FAQ page is what the page is: the questions become its own {@code mainEntity} (since 2.2.0). */
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
return List.of(); // describes the page itself; see describePage
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
List<Map<String, Object>> questions = questions(sc);
|
||||
if (!questions.isEmpty()) {
|
||||
page.put("mainEntity", questions);
|
||||
}
|
||||
}
|
||||
|
||||
/** No pair with both {@code q} and {@code a}: the page is an FAQPage with no questions. */
|
||||
@Override
|
||||
public Gap gap(String token, Map<String, Object> block) {
|
||||
return questions(block).isEmpty() ? new Gap("discover.gap.faq",
|
||||
"{0} has no question with both q: and a:, so the page is an {0} with no questions.") : null;
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> questions(SchemaContext sc) {
|
||||
return questions(sc.pageConfig());
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> questions(Map<String, Object> block) {
|
||||
List<Map<String, Object>> questions = new ArrayList<>();
|
||||
for (Map<String, Object> qa : Schemas.maps(block, "faq")) {
|
||||
String question = Schemas.str(qa, "q");
|
||||
String answer = Schemas.str(qa, "a");
|
||||
if (question == null || answer == null) {
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> node = new LinkedHashMap<>();
|
||||
node.put("@type", "Question");
|
||||
node.put("name", question);
|
||||
Map<String, Object> accepted = new LinkedHashMap<>();
|
||||
accepted.put("@type", "Answer");
|
||||
accepted.put("text", answer);
|
||||
node.put("acceptedAnswer", accepted);
|
||||
questions.add(node);
|
||||
}
|
||||
return questions;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* Serves the site's IndexNow key file — the proof of ownership the protocol requires.
|
||||
*
|
||||
* <h2>Why a fixed path rather than {@code /<key>.txt}</h2>
|
||||
* IndexNow's usual pattern is a file named after the key itself. That cannot work here: the host matches
|
||||
* routes by exact path and builds the table at startup, while the key is per-site configuration that changes
|
||||
* at runtime. The spec's own {@code keyLocation} field exists for exactly this — a submission may name any URL
|
||||
* on the host as the key's location — so the file lives at a stable path and every submission points there.
|
||||
*
|
||||
* <h2>Not indexable, not in the sitemap, not cached</h2>
|
||||
* It is a verification artifact, not content: it should never appear in search results, and a cached copy
|
||||
* would keep answering with an old key after a tenant rotates it — which fails verification for as long as the
|
||||
* cache lives, in a way that looks like the engine's fault.
|
||||
*/
|
||||
public class IndexNowKeyEndpoint implements EndpointContributor {
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final DiscoverabilityProperties properties;
|
||||
|
||||
public IndexNowKeyEndpoint(PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
this.settings = settings;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/indexnow-key";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
return List.of(new Route("GET", IndexNowSubmitter.KEY_PATH, Realm.TENANT,
|
||||
new SurfacePosture(false, false, false)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
String key = SiteConfig.str(cfg, "indexnow.key", "").trim();
|
||||
|
||||
// 404 unless the platform permits IndexNow AND this site turned it on AND a key is set. Serving a key
|
||||
// for a site that is not using the feature would publish a value that only exists to be verified.
|
||||
if (!properties.getIndexnow().isEnabled()
|
||||
|| !SiteConfig.bool(cfg, "indexnow.enabled", false)
|
||||
|| key.isEmpty()) {
|
||||
return new RouteResponse(404, Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
return new RouteResponse(200,
|
||||
Map.of("Content-Type", "text/plain; charset=utf-8", "Cache-Control", "no-store"),
|
||||
key.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.indexnow-key");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
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 org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
/**
|
||||
* Tells the IndexNow-participating search engines that a site's content changed, instead of waiting for them
|
||||
* to come back and find out.
|
||||
*
|
||||
* <h2>What this is, and what it is not</h2>
|
||||
* IndexNow is a published protocol (Bing, Yandex, Seznam, Naver, Yep). It is a <b>freshness</b> signal, not a
|
||||
* ranking one: it shortens the gap between publishing and being re-crawled by those engines. <b>Google does
|
||||
* not participate</b>, so this changes nothing about Google's view of a site — worth saying plainly, because
|
||||
* the opposite is widely implied and a tenant who turns this on should know what they are buying.
|
||||
*
|
||||
* <h2>Two switches, both off by default, and why</h2>
|
||||
* This is the first thing in the product that makes an <b>outbound</b> request on a tenant's behalf. So it
|
||||
* needs the <b>platform operator's</b> permission (they own the network and the egress policy) <i>and</i> the
|
||||
* tenant's (they own the URLs being disclosed). An upgrade must never start making network calls a deployment
|
||||
* was not making before, so neither switch defaults on. A tenant who enables it while the platform has not
|
||||
* gets a WARN naming both the tenant and the setting to flip — a feature that is silently inert is worse than
|
||||
* one that is off, because nobody can tell the difference from inside.
|
||||
*
|
||||
* <h2>What a change submits: where the item was, and where it is now</h2>
|
||||
* The submitter is a {@link SiteEventListener} in the {@code CONSUMER} phase. Each page write or content change
|
||||
* arrives as a {@link CatalogChange} carrying the item's URLs <b>before</b> the change (as the host last listed
|
||||
* them) and <b>after</b> it; the submitter queues the union. So a <b>deleted</b>, unpublished or moved item reports
|
||||
* its old address — the change most worth telling an engine about, and the one 1.x could not report, because it
|
||||
* resolved the URLs after the host had already dropped the item from its listing. Only the node where the change
|
||||
* happened submits ({@link CatalogChange#local()}): a cluster replays every change on its other nodes, and N nodes
|
||||
* must not send N submissions.
|
||||
*
|
||||
* <h2>Batched, bounded, and off every request thread</h2>
|
||||
* Changes accumulate per site and are submitted by a scheduled flush ({@link #flush()}, a Spring
|
||||
* {@code @Scheduled} method — it runs only while the host has scheduling enabled; see the method). A page save touching five localized URLs
|
||||
* must not become five outbound requests, and a bulk edit or a site restore must not become thousands.
|
||||
* Everything is bounded — queued URLs per site, URLs per submission — and overflow is dropped with a WARN
|
||||
* naming the tenant, never silently. No save ever waits on the network, and a failed submission is logged and
|
||||
* dropped rather than retried indefinitely: a stale IndexNow ping is worthless, and an unbounded retry queue
|
||||
* during an outage is a liability.
|
||||
*
|
||||
* <p>The HTTP call is injected as an {@link Exchange} seam (the same pattern the protection plugin's captcha
|
||||
* verifier uses), so the payload building, the gating and the bounds are unit-testable with no network at all.
|
||||
*/
|
||||
public class IndexNowSubmitter implements SiteEventListener {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(IndexNowSubmitter.class);
|
||||
|
||||
/** The fixed path the site's key file is served at — see {@link IndexNowKeyEndpoint}. */
|
||||
static final String KEY_PATH = "/indexnow-key.txt";
|
||||
|
||||
private final Sites sites;
|
||||
private final PluginSettings settings;
|
||||
private final DiscoverabilityProperties properties;
|
||||
private final Exchange exchange;
|
||||
|
||||
/** siteId → the URLs changed since the last flush. Bounded per site; insertion-ordered for stable batches. */
|
||||
private final Map<String, Set<String>> pending = new ConcurrentHashMap<>();
|
||||
|
||||
/** Sites already warned that they turned IndexNow on while the platform has it off — once per site per run. */
|
||||
private final Set<String> warnedInert = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public IndexNowSubmitter(Sites sites, PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
this(sites, settings, properties, defaultExchange(properties));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param exchange the HTTP seam that performs the submission POST — injectable so the payload, the gating
|
||||
* and the bounds are exercised without a real network call
|
||||
*/
|
||||
IndexNowSubmitter(Sites sites, PluginSettings settings, DiscoverabilityProperties properties, Exchange exchange) {
|
||||
this.sites = sites;
|
||||
this.settings = settings;
|
||||
this.properties = properties;
|
||||
this.exchange = exchange;
|
||||
}
|
||||
|
||||
// --- collecting -----------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A page was created, saved, renamed, deleted, published or unpublished, or a content source announced a change:
|
||||
* every URL the item answered on before the change and every URL it answers on now is stale upstream.
|
||||
*
|
||||
* <p>Acts only on {@link CatalogChange#local() local} changes — the node where the change happened submits; a
|
||||
* peer's replay is ignored. A change that names no item (a site lifecycle event, a settings save, a whole-site
|
||||
* page reload) carries no URLs and is ignored, as 1.x ignored the events without an id. Runs on the writer's
|
||||
* thread, so it only enqueues: the network call happens in {@link #flush()}.
|
||||
*/
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
if (!change.local() || change.id() == null) {
|
||||
return;
|
||||
}
|
||||
enqueue(change.siteId(), change.previousUrls(), change.currentUrls());
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues the item's URLs from before and after the change — {@code previous ∪ current}, in that order,
|
||||
* duplicates dropped — if the site has IndexNow on.
|
||||
*
|
||||
* <p>Gated before doing any work, so a deployment with the feature off pays nothing per save.
|
||||
*/
|
||||
void enqueue(String siteId, List<LocalizedUrl> previous, List<LocalizedUrl> current) {
|
||||
if (siteId == null) {
|
||||
return;
|
||||
}
|
||||
if (!properties.getIndexnow().isEnabled()) {
|
||||
warnIfInert(siteId);
|
||||
return;
|
||||
}
|
||||
SiteView site = siteView(siteId);
|
||||
if (site == null || key(siteId).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<String> urls = urlsOf(site, previous, current);
|
||||
if (urls.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int cap = Math.max(1, properties.getIndexnow().getMaxQueuedPerSite());
|
||||
Set<String> queue = pending.computeIfAbsent(siteId, k -> java.util.Collections.synchronizedSet(
|
||||
new LinkedHashSet<>()));
|
||||
synchronized (queue) {
|
||||
for (String url : urls) {
|
||||
if (queue.size() >= cap) {
|
||||
log.warn("IndexNow queue for site '{}' is full ({} URLs) — dropping further changes until "
|
||||
+ "the next submission. Raise indexnow.max-queued-per-site if this is routine.",
|
||||
siteId, cap);
|
||||
return;
|
||||
}
|
||||
queue.add(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- submitting -----------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Submits each site's accumulated URLs.
|
||||
*
|
||||
* <p>The fixed rate is the platform's {@code indexnow.batch-seconds}; Spring cannot read a bean field for
|
||||
* {@code @Scheduled}, so the annotation names the property and the default matches
|
||||
* {@link DiscoverabilityProperties.IndexNow#getBatchSeconds()}. The value is kept inside the settings form's
|
||||
* range, 5 to 3600 seconds, because a value set by hand (in the host's configuration or the settings file)
|
||||
* never passes the form: 0 or a negative value made the start fail (the scheduler refuses a delay of 0 or less).
|
||||
* A site with nothing queued costs one map lookup.
|
||||
*
|
||||
* <p><b>Scheduling is the host's.</b> The method runs only while the host application has Spring scheduling
|
||||
* enabled, which the kernel does unconditionally. This plugin deliberately does not start a scheduler of its own
|
||||
* (a plugin thread the host neither knows about nor stops).
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "#{T(java.lang.Math).max(5, T(java.lang.Math).min(3600, "
|
||||
+ "${runway.plugin.discoverability.indexnow.batch-seconds:60})) * 1000}")
|
||||
public void flush() {
|
||||
if (!properties.getIndexnow().isEnabled() || pending.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (String siteId : List.copyOf(pending.keySet())) {
|
||||
Set<String> queue = pending.remove(siteId);
|
||||
if (queue == null || queue.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
List<String> urls;
|
||||
synchronized (queue) {
|
||||
urls = List.copyOf(queue);
|
||||
}
|
||||
submit(siteId, urls);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits {@code urls} for one site, trimming to the per-submission cap and logging what was dropped.
|
||||
*
|
||||
* <p>Re-checks the platform switch even though every caller already has. A gate on outbound traffic is not
|
||||
* a place to rely on "no caller can reach here without checking" — the check costs a field read, and the
|
||||
* failure mode of getting it wrong is a deployment making network calls its operator refused.
|
||||
*/
|
||||
void submit(String siteId, List<String> urls) {
|
||||
if (!properties.getIndexnow().isEnabled()) {
|
||||
return;
|
||||
}
|
||||
SiteView site = siteView(siteId);
|
||||
String key = key(siteId);
|
||||
if (site == null || key.isEmpty() || site.baseUrl() == null || site.baseUrl().isBlank()) {
|
||||
return;
|
||||
}
|
||||
int cap = Math.max(1, properties.getIndexnow().getMaxUrlsPerSubmission());
|
||||
List<String> batch = urls;
|
||||
if (urls.size() > cap) {
|
||||
// Named, counted, and attributed to the tenant: a silent trim is indistinguishable from a site
|
||||
// that simply changed less than it did.
|
||||
log.warn("IndexNow submission for site '{}' has {} URLs, over the {} cap — submitting the first {} "
|
||||
+ "and DROPPING {}. The dropped pages are still crawled normally.",
|
||||
siteId, urls.size(), cap, cap, urls.size() - cap);
|
||||
batch = urls.subList(0, cap);
|
||||
}
|
||||
String host = hostOf(site.baseUrl());
|
||||
String payload = payload(host, key, site.baseUrl() + KEY_PATH, batch);
|
||||
try {
|
||||
Exchange.Response response = exchange.post(properties.getIndexnow().getEndpoint(), payload);
|
||||
if (response.status() >= 200 && response.status() < 300) {
|
||||
log.debug("IndexNow: submitted {} URL(s) for site '{}' ({})", batch.size(), siteId,
|
||||
response.status());
|
||||
} else {
|
||||
// 403 means the key file did not verify — the single most likely misconfiguration, and one the
|
||||
// tenant can fix, so say what it means rather than only what happened.
|
||||
log.warn("IndexNow submission for site '{}' was refused ({}): {}{}", siteId, response.status(),
|
||||
abbreviate(response.body()),
|
||||
response.status() == 403
|
||||
? " — the engine could not verify " + site.baseUrl() + KEY_PATH
|
||||
+ "; check the key matches and the path is publicly reachable." : "");
|
||||
}
|
||||
} catch (IOException | RuntimeException failed) {
|
||||
// Dropped, not retried: a stale freshness ping is worthless, and an unbounded retry queue during an
|
||||
// outage is a liability. The pages are still crawled the ordinary way.
|
||||
log.warn("IndexNow submission for site '{}' failed ({} URL(s) not submitted): {}",
|
||||
siteId, batch.size(), failed.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The IndexNow JSON body.
|
||||
*
|
||||
* <p>Hand-built rather than through a mapper because it is four fields and a string list, and the plugin
|
||||
* has no JSON dependency of its own. Every value is escaped — {@code host} and {@code keyLocation} derive
|
||||
* from tenant-controlled configuration, so an unescaped quote would be a payload-injection hole, not a
|
||||
* formatting bug.
|
||||
*/
|
||||
static String payload(String host, String key, String keyLocation, List<String> urls) {
|
||||
StringBuilder json = new StringBuilder(128 + urls.size() * 64);
|
||||
json.append("{\"host\":\"").append(escape(host))
|
||||
.append("\",\"key\":\"").append(escape(key))
|
||||
.append("\",\"keyLocation\":\"").append(escape(keyLocation))
|
||||
.append("\",\"urlList\":[");
|
||||
for (int i = 0; i < urls.size(); i++) {
|
||||
if (i > 0) {
|
||||
json.append(',');
|
||||
}
|
||||
json.append('"').append(escape(urls.get(i))).append('"');
|
||||
}
|
||||
return json.append("]}").toString();
|
||||
}
|
||||
|
||||
private static String escape(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder out = new StringBuilder(value.length());
|
||||
for (char c : value.toCharArray()) {
|
||||
switch (c) {
|
||||
case '"' -> out.append("\\\"");
|
||||
case '\\' -> out.append("\\\\");
|
||||
case '\n' -> out.append("\\n");
|
||||
case '\r' -> out.append("\\r");
|
||||
case '\t' -> out.append("\\t");
|
||||
default -> {
|
||||
if (c < 0x20) {
|
||||
out.append(String.format("\\u%04x", (int) c));
|
||||
} else {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
// --- helpers --------------------------------------------------------------------------------------
|
||||
|
||||
/** The absolute form of every URL in {@code previous} then {@code current}, without duplicates. */
|
||||
private static Set<String> urlsOf(SiteView site, List<LocalizedUrl> previous, List<LocalizedUrl> current) {
|
||||
String base = site.baseUrl();
|
||||
Set<String> urls = new LinkedHashSet<>();
|
||||
if (base == null || base.isBlank()) {
|
||||
return urls;
|
||||
}
|
||||
for (List<LocalizedUrl> list : List.of(previous, current)) {
|
||||
for (LocalizedUrl url : list) {
|
||||
urls.add(url.absolute(base.trim()));
|
||||
}
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
/** The site's IndexNow key, or empty when unset — which is how a tenant leaves the feature off. */
|
||||
/**
|
||||
* The promise in the class Javadoc: a site that turned IndexNow on while the platform has it off is told, in
|
||||
* the log, which setting to flip — once per site per run (the platform switch only changes on restart), and
|
||||
* after that at no cost per save. The site's settings form says the same thing to the tenant.
|
||||
*/
|
||||
private void warnIfInert(String siteId) {
|
||||
if (warnedInert.contains(siteId)) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(siteId).values();
|
||||
if (SiteConfig.bool(cfg, "indexnow.enabled", false) && warnedInert.add(siteId)) {
|
||||
log.warn("site '{}' has IndexNow enabled, but the platform has not permitted it — nothing is submitted. "
|
||||
+ "The platform operator turns it on with discoverability's app-level indexnow.enabled.", siteId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the inert-site warning has been logged for this site (tests). */
|
||||
boolean warnedInert(String siteId) {
|
||||
return warnedInert.contains(siteId);
|
||||
}
|
||||
|
||||
private String key(String siteId) {
|
||||
Map<String, Object> cfg = settings.site(siteId).values();
|
||||
if (!SiteConfig.bool(cfg, "indexnow.enabled", false)) {
|
||||
return "";
|
||||
}
|
||||
String key = SiteConfig.str(cfg, "indexnow.key", "").trim();
|
||||
if (key.isEmpty()) {
|
||||
log.warn("site '{}' has IndexNow enabled but no indexnow.key — nothing is submitted. Generate a "
|
||||
+ "random key and set it, then confirm {} serves it.", siteId, KEY_PATH);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
private SiteView siteView(String siteId) {
|
||||
return sites.find(siteId).orElse(null);
|
||||
}
|
||||
|
||||
/** The bare host of a base URL — what IndexNow's {@code host} field expects (no scheme, no path). */
|
||||
static String hostOf(String baseUrl) {
|
||||
try {
|
||||
String host = URI.create(baseUrl).getHost();
|
||||
return host == null ? "" : host;
|
||||
} catch (IllegalArgumentException notAUrl) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String abbreviate(String body) {
|
||||
if (body == null) {
|
||||
return "";
|
||||
}
|
||||
String flat = body.replaceAll("[\\r\\n]+", " ").trim();
|
||||
return flat.length() <= 200 ? flat : flat.substring(0, 200) + "…";
|
||||
}
|
||||
|
||||
// --- the HTTP seam --------------------------------------------------------------------------------
|
||||
|
||||
/** The outbound call, isolated so everything around it is testable without a network. */
|
||||
public interface Exchange {
|
||||
|
||||
/**
|
||||
* POSTs {@code json} ({@code application/json}) to {@code url}.
|
||||
*
|
||||
* @return the endpoint's response (status + body)
|
||||
* @throws IOException if the request cannot be completed
|
||||
*/
|
||||
Response post(String url, String json) throws IOException;
|
||||
|
||||
/** A minimal HTTP response view — the status and body this submitter needs to log an outcome. */
|
||||
record Response(int status, String body) {
|
||||
}
|
||||
}
|
||||
|
||||
private static Exchange defaultExchange(DiscoverabilityProperties properties) {
|
||||
Duration timeout = Duration.ofSeconds(Math.max(1, properties.getIndexnow().getTimeoutSeconds()));
|
||||
HttpClient client = HttpClient.newBuilder().connectTimeout(timeout).build();
|
||||
return (url, json) -> {
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(timeout)
|
||||
.header("Content-Type", "application/json; charset=utf-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return new Exchange.Response(response.statusCode(), response.body());
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("IndexNow submission interrupted", interrupted);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* The schema.org <b>JSON-LD builder</b> — the shared spine of both SEO+ and GEO. It builds ordered node maps,
|
||||
* serializes them into a single {@code @graph}, and wraps that in a {@code <script type="application/ld+json">}
|
||||
* block escaped so it can never break out of the {@code <head>}. Pure and stateless.
|
||||
*
|
||||
* <p>The {@code @id} conventions are the seam between the two capability areas: the SEO contributor defines the
|
||||
* {@code WebSite}/{@code WebPage}/{@code Organization} nodes, and the GEO contributor <b>enriches those same
|
||||
* nodes by @id reference</b> (adding {@code potentialAction}/{@code speakable}) rather than redefining them —
|
||||
* so a crawler merges them into one entity graph with no duplication.
|
||||
*/
|
||||
final class Ld {
|
||||
|
||||
static final String CONTEXT = "https://schema.org";
|
||||
private static final JsonMapper JSON = JsonMapper.builder().build();
|
||||
|
||||
private Ld() {
|
||||
}
|
||||
|
||||
// --- stable @id conventions (shared by SEO + GEO) ----------------------
|
||||
|
||||
static String websiteId(String base) {
|
||||
return base + "/#website";
|
||||
}
|
||||
|
||||
static String organizationId(String base) {
|
||||
return base + "/#organization";
|
||||
}
|
||||
|
||||
static String webpageId(String canonical) {
|
||||
return canonical + "#webpage";
|
||||
}
|
||||
|
||||
static String softwareId(String base) {
|
||||
return base + "/#software";
|
||||
}
|
||||
|
||||
/** The {@code scheme://host} origin of an absolute URL, or {@code ""} if it is not absolute. */
|
||||
static String origin(String url) {
|
||||
if (url == null) {
|
||||
return "";
|
||||
}
|
||||
int scheme = url.indexOf("://");
|
||||
if (scheme < 0) {
|
||||
return "";
|
||||
}
|
||||
int slash = url.indexOf('/', scheme + 3);
|
||||
return slash < 0 ? url : url.substring(0, slash);
|
||||
}
|
||||
|
||||
// --- node building -----------------------------------------------------
|
||||
|
||||
/** A new node with its {@code @type} (and {@code @id} when non-null). */
|
||||
static Map<String, Object> node(String type, String id) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("@type", type);
|
||||
if (id != null && !id.isBlank()) {
|
||||
m.put("@id", id);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/** Sets {@code key} to {@code value} only when the value is non-blank (empty properties are never emitted). */
|
||||
static void put(Map<String, Object> node, String key, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
node.put(key, value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets {@code key} to a single value or an array (schema.org accepts either), omitting an empty list. */
|
||||
static void putList(Map<String, Object> node, String key, List<String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
node.put(key, values.size() == 1 ? values.get(0) : values);
|
||||
}
|
||||
|
||||
/** Sets {@code key} to an {@code @id} reference to another node. */
|
||||
static void ref(Map<String, Object> node, String key, String id) {
|
||||
if (id != null && !id.isBlank()) {
|
||||
node.put(key, Map.of("@id", id));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes a {@code @graph} of nodes into an escaped {@code <script type="application/ld+json">} block,
|
||||
* or {@code ""} when the graph is empty. {@code <}, {@code >} and {@code &} are unicode-escaped so the JSON
|
||||
* can never terminate the surrounding {@code <script>} element.
|
||||
*/
|
||||
static String script(List<Map<String, Object>> nodes) {
|
||||
List<Map<String, Object>> present = nodes.stream().filter(n -> n != null && !n.isEmpty()).toList();
|
||||
if (present.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
Map<String, Object> graph = new LinkedHashMap<>();
|
||||
graph.put("@context", CONTEXT);
|
||||
graph.put("@graph", present);
|
||||
String json = JSON.writeValueAsString(graph)
|
||||
.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026");
|
||||
return "\n<script type=\"application/ld+json\">" + json + "</script>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* GEO — serves a per-site <b>{@code /llms.txt}</b>, the emerging convention for exposing a site's content to
|
||||
* large-language-model / answer engines in a compact, machine-friendly form: an {@code H1} of the site name, a
|
||||
* one-line summary (the tenant's {@code geo.summary}), then the site's whole published content surface —
|
||||
* kernel pages AND every content source's items (blog entries, any plugin content) — as Markdown links with
|
||||
* their descriptions, in the site's default locale. Built from the host's {@link ContentCatalogView}
|
||||
* (kernel-re-filtered, metadata-only: no item's body is ever read serving this route).
|
||||
*
|
||||
* <p>Each item is linked at {@link CatalogEntry#pathFor(Locale) its address in the default locale}, or — for an
|
||||
* item that does not exist in the default locale — at its primary locale's real address. (Until 2.0.0 such an item
|
||||
* was linked at its unprefixed default path, which the site answers with a 404.)
|
||||
*
|
||||
* <p>Part of the opt-in GEO area: gated by the per-tenant {@code geo.enabled} flag — disabled ⇒ {@code 404}.
|
||||
*/
|
||||
public class LlmsTxtEndpoint implements EndpointContributor {
|
||||
|
||||
private final ContentCatalogView catalog;
|
||||
private final PluginSettings settings;
|
||||
|
||||
public LlmsTxtEndpoint(ContentCatalogView catalog, PluginSettings settings) {
|
||||
this.catalog = catalog;
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/llms";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// Cacheable: this endpoint manages its own caching (Last-Modified + no-cache revalidation).
|
||||
return List.of(new Route("GET", "/llms.txt", Realm.TENANT, new SurfacePosture(true, true, true)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "geo.enabled", false)) {
|
||||
// The route posture is cacheable (so the 200/304 carry their own validators), which means the
|
||||
// dispatcher no longer stamps a fail-safe no-store — so this disabled-path 404 must forbid caching
|
||||
// itself, or a heuristically-cacheable 404 could outlive the tenant re-enabling the surface.
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
String base = PageUrls.base(req.site(), req);
|
||||
Locale def = req.site().defaultLocale();
|
||||
|
||||
List<CatalogEntry> items = catalog.entries(req.site().id());
|
||||
String summary = SiteConfig.str(cfg, "geo.summary", "");
|
||||
// The validator folds what this document prints besides the items: the H1 (the site name), the summary,
|
||||
// the locale every title and link is chosen in, and the site's base URL every link starts with — so editing
|
||||
// any of them advances Last-Modified and a revalidating crawler refetches (until 2.1.0 it kept the old copy).
|
||||
// The base URL, not the request origin: a host-less site reached under two names serves each its own links,
|
||||
// and each crawler's copy stays right for the address it fetched — folding the origin would only make the
|
||||
// validator advance on every alternate request.
|
||||
java.time.Instant newest = CrawlConditional.lastModified(req.site().id(), CrawlConditional.LLMS, items,
|
||||
java.util.Arrays.asList(req.site().displayName(), summary, def.toLanguageTag(),
|
||||
req.site().baseUrl()));
|
||||
if (CrawlConditional.notModified(req, newest)) {
|
||||
return CrawlConditional.notModifiedResponse(newest);
|
||||
}
|
||||
|
||||
StringBuilder out = new StringBuilder(512);
|
||||
out.append("# ").append(req.site().displayName()).append("\n\n");
|
||||
if (!summary.isBlank()) {
|
||||
out.append("> ").append(oneLine(summary)).append("\n\n");
|
||||
}
|
||||
out.append("## Pages\n\n");
|
||||
for (CatalogEntry item : items) {
|
||||
// Same rule as the sitemap: content the site tells robots not to index has no business being
|
||||
// advertised to answer engines either. llms.txt is a recommendation list, not a site dump.
|
||||
if (item.ref().noindex()) {
|
||||
continue;
|
||||
}
|
||||
String title = item.ref().titleFor(def);
|
||||
String label = mdLabel((title == null || title.isBlank()) ? item.ref().id() : title);
|
||||
String url = base + item.pathFor(def);
|
||||
out.append("- [").append(label).append("](").append(url).append(")");
|
||||
String desc = item.ref().descriptionFor(def);
|
||||
if (desc != null && !desc.isBlank()) {
|
||||
out.append(": ").append(oneLine(desc));
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
return new RouteResponse(200,
|
||||
CrawlConditional.cacheHeaders(newest, "text/plain; charset=utf-8"),
|
||||
out.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String oneLine(String text) {
|
||||
return text.replace('\n', ' ').replace('\r', ' ').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* A markdown-safe link label: one line, with the link metacharacters mapped to parentheses-free forms so a
|
||||
* legitimate title like {@code FAQ [updated]} cannot terminate the {@code [label](url)} early and corrupt
|
||||
* the machine-parsed index.
|
||||
*/
|
||||
private static String mdLabel(String text) {
|
||||
return oneLine(text).replace('[', '(').replace(']', ')');
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.geo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits one or more schema.org {@code LocalBusiness} nodes (or the entry's declared subtype, e.g.
|
||||
* {@code CafeOrCoffeeShop}) from a {@code content.schema} entry. A {@code locations:} list yields one node per
|
||||
* location (name/address/geo/telephone/openingHours/priceRange); with no list, a single node is built from the
|
||||
* entry's own fields. {@code geo} is emitted only when both latitude and longitude are provided.
|
||||
*/
|
||||
final class LocalBusinessSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "LocalBusiness";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String type = Schemas.str(cfg, "type", "LocalBusiness"); // LocalBusiness | CafeOrCoffeeShop | …
|
||||
List<Map<String, Object>> locations = Schemas.maps(cfg, "locations");
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
if (locations.isEmpty()) {
|
||||
out.add(business(type, cfg, ctx, sc, 1));
|
||||
} else {
|
||||
int index = 1;
|
||||
for (Map<String, Object> location : locations) {
|
||||
out.add(business(type, location, ctx, sc, index++));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> business(String type, Map<String, Object> b, HeadContext ctx,
|
||||
SchemaContext sc, int index) {
|
||||
// A stable @id per location (canonical#business-N) + a link back to the page, so each node is part of the
|
||||
// graph rather than a bare, unlinked node. geo is emitted below when the tenant supplies coordinates.
|
||||
Map<String, Object> node = Ld.node(type, sc.canonical() + "#business-" + index);
|
||||
Ld.ref(node, "mainEntityOfPage", sc.webpageId());
|
||||
Ld.put(node, "url", Schemas.absolute(Schemas.str(b, "url", sc.canonical()), sc.base()));
|
||||
Ld.put(node, "name", Schemas.str(b, "name", ctx.site().displayName()));
|
||||
Ld.put(node, "telephone", Schemas.str(b, "telephone"));
|
||||
Ld.putList(node, "image", Schemas.absolute(Schemas.strings(b, "image"), sc.base()));
|
||||
Ld.put(node, "priceRange", Schemas.str(b, "priceRange"));
|
||||
Ld.putList(node, "openingHours", Schemas.strings(b, "hours"));
|
||||
|
||||
String street = Schemas.str(b, "street");
|
||||
String locality = Schemas.str(b, "locality");
|
||||
if (street != null || locality != null) {
|
||||
Map<String, Object> address = Ld.node("PostalAddress", null);
|
||||
Ld.put(address, "streetAddress", street);
|
||||
Ld.put(address, "addressLocality", locality);
|
||||
Ld.put(address, "addressRegion", Schemas.str(b, "region"));
|
||||
Ld.put(address, "postalCode", Schemas.str(b, "postalCode"));
|
||||
Ld.put(address, "addressCountry", Schemas.str(b, "country"));
|
||||
node.put("address", address);
|
||||
}
|
||||
|
||||
String latitude = Schemas.str(b, "latitude");
|
||||
String longitude = Schemas.str(b, "longitude");
|
||||
if (latitude != null && longitude != null) {
|
||||
Map<String, Object> geo = new LinkedHashMap<>();
|
||||
geo.put("@type", "GeoCoordinates");
|
||||
geo.put("latitude", latitude);
|
||||
geo.put("longitude", longitude);
|
||||
node.put("geo", geo);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
|
||||
/**
|
||||
* Parses the per-tenant {@code content.schema} text (a small YAML document keyed by URL-path pattern) and
|
||||
* resolves the entry for a given page path. Parsing is memoized by the raw text, so it happens once per distinct
|
||||
* config value (which changes only when the tenant edits it) rather than per request.
|
||||
*
|
||||
* <p>Format — a map of path pattern → entry. An entry is either <b>one type-block</b> (a map with a {@code type}
|
||||
* plus type-specific fields) or a <b>list of type-blocks</b> when a single page carries several types (e.g. a
|
||||
* pricing page that is both an {@code FAQPage} and a set of {@code Offer}s):
|
||||
* <pre>
|
||||
* /coffee-*:
|
||||
* type: Product
|
||||
* currency: USD
|
||||
* /pricing:
|
||||
* - type: FAQPage
|
||||
* faq: [ { q: "Why ranges?", a: "Scope drives cost…" } ]
|
||||
* - type: Service
|
||||
* offers: [ { name: "Advisory Sprint", price: "18000", currency: USD } ]
|
||||
* </pre>
|
||||
* A pattern ending in {@code *} is a prefix match; an <b>exact</b> path always wins, and among prefix patterns
|
||||
* the <b>longest</b> wins. A malformed document disables typing (returns no entries) rather than breaking the page.
|
||||
*/
|
||||
final class PageSchemaConfig {
|
||||
|
||||
private static final YAMLMapper YAML = YAMLMapper.builder().build();
|
||||
private static final int MAX_CACHE = 128;
|
||||
// Memo keyed by the raw config text — self-evicting (a changed value is a new key); bounded as a backstop.
|
||||
// Value: pattern → entry, where an entry is a Map (one type-block) or a List of Maps (several).
|
||||
private static final Map<String, Map<String, Object>> CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
private PageSchemaConfig() {
|
||||
}
|
||||
|
||||
/** Parses {@code content.schema} into {@code pattern → entry}; empty for blank/malformed input. */
|
||||
static Map<String, Object> parse(String text) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Object> cached = CACHE.get(text);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Map<String, Object> parsed = doParse(text);
|
||||
if (CACHE.size() > MAX_CACHE) {
|
||||
CACHE.clear();
|
||||
}
|
||||
CACHE.put(text, parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why {@code text} cannot be used at all, or {@code null} when it parses (blank included): the YAML error, or a
|
||||
* root that is not a map of patterns. {@link #parse} turns either into "no types" so a page never breaks; this
|
||||
* tells the site manager instead.
|
||||
*/
|
||||
static String syntaxProblem(String text) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Object root = YAML.readValue(text, Object.class);
|
||||
return root instanceof Map<?, ?> ? null : "the text is not a list of 'pattern: type' entries";
|
||||
} catch (Exception e) {
|
||||
String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
|
||||
int newline = message.indexOf('\n');
|
||||
return newline > 0 ? message.substring(0, newline) : message;
|
||||
}
|
||||
}
|
||||
|
||||
/** The raw entries whose value is neither one block nor a list of blocks: they are ignored. */
|
||||
static List<String> ignoredPatterns(String text) {
|
||||
List<String> out = new ArrayList<>();
|
||||
try {
|
||||
Object root = YAML.readValue(text, Object.class);
|
||||
if (root instanceof Map<?, ?> map) {
|
||||
for (var entry : map.entrySet()) {
|
||||
if (!(entry.getValue() instanceof Map || entry.getValue() instanceof List)) {
|
||||
out.add(String.valueOf(entry.getKey()));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// syntaxProblem reports it
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> doParse(String text) {
|
||||
try {
|
||||
Object root = YAML.readValue(text, Object.class);
|
||||
if (!(root instanceof Map<?, ?> map)) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (var entry : map.entrySet()) {
|
||||
// An entry is one type-block (Map) or several (List); anything else is ignored.
|
||||
if (entry.getKey() != null && (entry.getValue() instanceof Map || entry.getValue() instanceof List)) {
|
||||
out.put(entry.getKey().toString(), entry.getValue());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} catch (Exception ex) {
|
||||
return Map.of(); // a malformed content.schema disables typing rather than breaking the page
|
||||
}
|
||||
}
|
||||
|
||||
/** The entry (a Map or a List) whose pattern matches {@code path}: exact wins, else the longest {@code *}-prefix. */
|
||||
static Object resolve(Map<String, Object> patterns, String path) {
|
||||
String pattern = matchingPattern(patterns, path);
|
||||
return pattern == null ? null : patterns.get(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* The pattern that matches {@code path}: the path itself when listed, else the longest {@code *}-prefix whose
|
||||
* prefix starts the path; {@code null} when none does. A {@code *} anywhere but at the end is a literal
|
||||
* character.
|
||||
*/
|
||||
static String matchingPattern(Map<String, Object> patterns, String path) {
|
||||
if (patterns.isEmpty() || path == null) {
|
||||
return null;
|
||||
}
|
||||
if (patterns.containsKey(path)) {
|
||||
return path;
|
||||
}
|
||||
String best = null;
|
||||
int bestLen = -1;
|
||||
for (String pattern : patterns.keySet()) {
|
||||
if (pattern.endsWith("*")) {
|
||||
String prefix = pattern.substring(0, pattern.length() - 1);
|
||||
if (path.startsWith(prefix) && prefix.length() > bestLen) {
|
||||
best = pattern;
|
||||
bestLen = prefix.length();
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Normalizes a resolved entry to its list of type-blocks: a single Map → one block; a List → its Map items. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<Map<String, Object>> blocks(Object entry) {
|
||||
if (entry instanceof Map<?, ?> map) {
|
||||
return List.of((Map<String, Object>) map);
|
||||
}
|
||||
if (entry instanceof List<?> list) {
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Object item : list) {
|
||||
if (item instanceof Map<?, ?> map) {
|
||||
out.add((Map<String, Object>) map);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* The page editor's line about structured data: what this page is described as, and where that comes from — the
|
||||
* site's Default page type, or a Per-page types ({@code content.schema}) pattern — plus what the entry adds, and a
|
||||
* warning for a type the plugin does not know, a second page type it ignores, or a block that publishes nothing of
|
||||
* its own (an {@code FAQPage} with no complete question). A noindex page carries no structured data, and the line
|
||||
* says so first, as the head checks it first. A translated page that the default language's entry does not reach
|
||||
* gets a note naming the key that would.
|
||||
*
|
||||
* <h2>Why</h2>
|
||||
* The site form says "Default page type", and nothing showed whether a
|
||||
* given page took it or something else. The answer is computed by {@link PageTypes}, the same code the public page's
|
||||
* {@code <head>} uses, so the editor cannot describe a page differently from how it is served.
|
||||
*
|
||||
* <p>Reported through the existing quality-check seam as {@code INFO} (a neutral observation, never a gate) and
|
||||
* {@code WARNING} findings; their text is resolved here in the operator's UI language, since a finding carries no
|
||||
* message arguments.
|
||||
*/
|
||||
public class PageTypeCheck implements PageQualityCheck {
|
||||
|
||||
static final String CODE = "discoverability.page-type";
|
||||
static final String CODE_UNKNOWN = "discoverability.page-type.unknown";
|
||||
static final String CODE_EXTRA = "discoverability.page-type.extra";
|
||||
static final String CODE_GAP = "discoverability.page-type.gap";
|
||||
static final String CODE_OTHER_LANGUAGE = "discoverability.page-type.other-language";
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Map<String, SchemaType> types;
|
||||
private final Messages messages;
|
||||
|
||||
PageTypeCheck(PluginSettings settings, Map<String, SchemaType> types, Messages messages) {
|
||||
this.settings = settings;
|
||||
this.types = types;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/page-type";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Finding> inspect(PageView page) {
|
||||
if (page == null || page.canonical() == null || page.canonical().isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
if (page.page() != null && page.page().noindex()) {
|
||||
// The head emits no JSON-LD on a noindex page, before it looks at anything else; so does this line.
|
||||
return List.of(Finding.info(CODE, text("discover.pagetype.noindex",
|
||||
"Structured data: this page is excluded from search engines (noindex), so it carries no "
|
||||
+ "structured data.")));
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(page.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "jsonld.enabled", true)) {
|
||||
return List.of(Finding.info(CODE, text("discover.pagetype.off",
|
||||
"Structured data is switched off for this site, so this page is not described to search "
|
||||
+ "engines.")));
|
||||
}
|
||||
String path = PageTypes.pathOf(page);
|
||||
PageTypes.Description d = PageTypes.describe(cfg, path, types);
|
||||
List<Finding> findings = new ArrayList<>();
|
||||
String main = d.source() == PageTypes.Source.SCHEMA
|
||||
? text("discover.pagetype.schema", "Structured data: this page is a {0}, set by Per-page types "
|
||||
+ "(pattern {1}).", d.type(), d.pattern())
|
||||
: text("discover.pagetype.default", "Structured data: this page is a {0}, the site''s Default "
|
||||
+ "page type.", d.type());
|
||||
if (!d.added().isEmpty()) {
|
||||
main = main + " " + text("discover.pagetype.added", "Per-page types also add: {0}.",
|
||||
String.join(", ", d.addedTypes()));
|
||||
}
|
||||
findings.add(Finding.info(CODE, main));
|
||||
PageTypes.OtherLanguageEntry other = PageTypes.otherLanguageEntry(cfg, path, page.site());
|
||||
if (other != null) {
|
||||
findings.add(Finding.info(CODE_OTHER_LANGUAGE, text("discover.pagetype.otherLanguage",
|
||||
"Per-page types: {0} describes the default language''s page, not this one; a page in another "
|
||||
+ "language is matched only by its own path. To describe this page, add {1}.",
|
||||
other.pattern(), other.suggestion())));
|
||||
}
|
||||
if (d.pageBlock() != null) {
|
||||
gap(findings, d.type(), d.pageBlock());
|
||||
}
|
||||
for (Map<String, Object> block : d.added()) {
|
||||
gap(findings, Schemas.str(block, "type", ""), block);
|
||||
}
|
||||
if (!d.unknown().isEmpty()) {
|
||||
findings.add(Finding.warning(CODE_UNKNOWN, text("discover.pagetype.unknown",
|
||||
"Per-page types name {0} for this page, which this plugin does not know; it is ignored.",
|
||||
String.join(", ", d.unknown()))));
|
||||
}
|
||||
if (!d.extraPageTypes().isEmpty()) {
|
||||
findings.add(Finding.warning(CODE_EXTRA, text("discover.pagetype.extra",
|
||||
"Per-page types give this page more than one page type; only the first ({0}) applies, "
|
||||
+ "{1} is ignored.", d.type(), String.join(", ", d.extraPageTypes()))));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
/** A warning for a block that applies but publishes nothing of its own ({@link SchemaType#gap}). */
|
||||
private void gap(List<Finding> findings, String token, Map<String, Object> block) {
|
||||
SchemaType handler = types.get(token);
|
||||
SchemaType.Gap gap = handler == null ? null : handler.gap(token, block);
|
||||
if (gap != null) {
|
||||
findings.add(Finding.warning(CODE_GAP, text(gap.code(), gap.fallback(), token)));
|
||||
}
|
||||
}
|
||||
|
||||
private String text(String code, String fallback, Object... args) {
|
||||
return messages == null ? java.text.MessageFormat.format(fallback, args)
|
||||
: messages.console(code, fallback, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("quality.advisory", "quality.structured-data");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* How one page is described in structured data: its own type, where that type comes from, and what else its
|
||||
* {@code content.schema} entry adds. The one answer both the public page ({@link StructuredDataHead}) and the page
|
||||
* editor's line ({@link PageTypeCheck}) use, so the two can never disagree.
|
||||
*
|
||||
* <h2>The rule</h2>
|
||||
* <ul>
|
||||
* <li>The page's {@code content.schema} entry is found by its own path: the exact path, else the longest
|
||||
* {@code *}-prefix. A page behind a language prefix ({@code /es/faq}) is matched only by a key written for that
|
||||
* path ({@code /es/faq}, {@code /es/*}, {@code /*}); {@code /faq} does not reach it, because an entry's text
|
||||
* (questions, names, a breadcrumb parent) is written in one language and would be published on the other
|
||||
* language's page.</li>
|
||||
* <li>The first block whose type describes the page itself ({@link SchemaType#describesPage}) sets the page's
|
||||
* type; otherwise the page has the site's Default page type ({@code jsonld.type}).</li>
|
||||
* <li>Every other recognized block adds an entity (a product, a service, a business, a person, a list).</li>
|
||||
* <li>A block naming an unknown type is ignored, and so is a second block that describes the page (a page has one
|
||||
* type); both are reported in the editor so neither goes unnoticed.</li>
|
||||
* </ul>
|
||||
*/
|
||||
final class PageTypes {
|
||||
|
||||
/** Where the page's own type came from. */
|
||||
enum Source {
|
||||
/** The site's Default page type ({@code jsonld.type}). */
|
||||
DEFAULT,
|
||||
/** A {@code content.schema} block for this page. */
|
||||
SCHEMA
|
||||
}
|
||||
|
||||
/**
|
||||
* One page's description.
|
||||
*
|
||||
* @param type the page's own {@code @type}
|
||||
* @param source where {@code type} came from
|
||||
* @param pattern the matching {@code content.schema} pattern, or {@code null} when none matches
|
||||
* @param pageBlock the block that set the type ({@code null} when it is the default)
|
||||
* @param added the blocks that add an entity, in declared order
|
||||
* @param unknown type tokens in the entry that no handler knows (a block with no {@code type} is not listed)
|
||||
* @param extraPageTypes page-describing tokens after the first, which are ignored
|
||||
*/
|
||||
record Description(String type, Source source, String pattern, Map<String, Object> pageBlock,
|
||||
List<Map<String, Object>> added, List<String> unknown, List<String> extraPageTypes) {
|
||||
|
||||
/** The type tokens of the added blocks, in order. */
|
||||
List<String> addedTypes() {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (Map<String, Object> block : added) {
|
||||
out.add(Schemas.str(block, "type", ""));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
private PageTypes() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The path of the page a {@link mx.quest.runway.spi.model.PageView} shows, relative to the site base, the way the
|
||||
* head derives it from the canonical URL.
|
||||
*/
|
||||
static String pathOf(mx.quest.runway.spi.model.PageView page) {
|
||||
String base = page.site().baseUrl();
|
||||
base = (base != null && !base.isBlank()) ? base.trim() : "";
|
||||
if (base.endsWith("/")) {
|
||||
base = base.substring(0, base.length() - 1);
|
||||
}
|
||||
return StructuredDataHead.pathOf(base, page.canonical());
|
||||
}
|
||||
|
||||
/** The site's Default page type as the head uses it: {@code Article} when so configured, else {@code WebPage}. */
|
||||
static String defaultType(Map<String, Object> cfg) {
|
||||
return "Article".equals(SiteConfig.str(cfg, "jsonld.type", "WebPage")) ? "Article" : "WebPage";
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes the page at {@code path}.
|
||||
*
|
||||
* @param cfg the site's discoverability settings
|
||||
* @param path the page's path relative to the site base, starting with {@code /}
|
||||
* @param types the type registry, by token
|
||||
*/
|
||||
static Description describe(Map<String, Object> cfg, String path, Map<String, SchemaType> types) {
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", ""));
|
||||
String pattern = PageSchemaConfig.matchingPattern(patterns, path);
|
||||
Map<String, Object> pageBlock = null;
|
||||
String pageType = null;
|
||||
List<Map<String, Object>> added = new ArrayList<>();
|
||||
List<String> unknown = new ArrayList<>();
|
||||
List<String> extraPageTypes = new ArrayList<>();
|
||||
if (pattern != null) {
|
||||
for (Map<String, Object> block : PageSchemaConfig.blocks(patterns.get(pattern))) {
|
||||
String token = Schemas.str(block, "type", "");
|
||||
if (token.isBlank()) {
|
||||
continue; // a block with no type only carries shared fields (a breadcrumb parent)
|
||||
}
|
||||
SchemaType handler = types.get(token);
|
||||
if (handler == null) {
|
||||
unknown.add(token);
|
||||
} else if (handler.describesPage(token)) {
|
||||
if (pageBlock == null) {
|
||||
pageBlock = block;
|
||||
pageType = token;
|
||||
} else {
|
||||
extraPageTypes.add(token);
|
||||
}
|
||||
} else {
|
||||
added.add(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
return pageBlock != null
|
||||
? new Description(pageType, Source.SCHEMA, pattern, pageBlock, added, unknown, extraPageTypes)
|
||||
: new Description(defaultType(cfg), Source.DEFAULT, pattern, null, added, unknown, extraPageTypes);
|
||||
}
|
||||
|
||||
/** The matching {@code content.schema} entry for {@code path}, or {@code null}. */
|
||||
static Object entry(Map<String, Object> cfg, String path) {
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", ""));
|
||||
String pattern = PageSchemaConfig.matchingPattern(patterns, path);
|
||||
return pattern == null ? null : patterns.get(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* The default language's entry that does not reach a translated page.
|
||||
*
|
||||
* @param pattern the pattern matching the same path in the default language ({@code /faq})
|
||||
* @param suggestion the key that would describe this page ({@code /es/faq}; {@code /es/blog/*} for {@code /blog/*})
|
||||
*/
|
||||
record OtherLanguageEntry(String pattern, String suggestion) {
|
||||
}
|
||||
|
||||
/**
|
||||
* For a page behind a non-default language prefix ({@code /es/faq}): the pattern that matches the same path in
|
||||
* the default language ({@code /faq}) but not this page; {@code null} when there is none, or when this page's own
|
||||
* match is at least as specific (the same {@code /*}, or {@code /es/*} beside {@code /*}). Only the page editor
|
||||
* uses it, to say that the other language's entry does not reach this page and which key would.
|
||||
*/
|
||||
static OtherLanguageEntry otherLanguageEntry(Map<String, Object> cfg, String path, SiteView site) {
|
||||
String prefix = path == null || site == null ? null : languagePrefix(path, site);
|
||||
if (prefix == null) {
|
||||
return null;
|
||||
}
|
||||
String stripped = path.length() <= prefix.length() + 1 ? "/" : path.substring(prefix.length());
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", ""));
|
||||
String base = PageSchemaConfig.matchingPattern(patterns, stripped);
|
||||
String own = PageSchemaConfig.matchingPattern(patterns, path);
|
||||
if (base == null || (own != null && specificity(own, path) >= specificity(base, stripped))) {
|
||||
return null; // nothing to say, or this page's own match is at least as specific (/es/*, /*)
|
||||
}
|
||||
return new OtherLanguageEntry(base, base.equals(stripped) ? path : prefix + base);
|
||||
}
|
||||
|
||||
/** How specific a matching pattern is: an exact key above any prefix, a longer prefix above a shorter one. */
|
||||
private static int specificity(String pattern, String path) {
|
||||
return pattern.equals(path) ? Integer.MAX_VALUE : pattern.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* The leading {@code /<language>} of {@code path} when that language is one of the site's languages other than
|
||||
* the default ({@code /es} for {@code /es/faq} and for {@code /es}); {@code null} otherwise.
|
||||
*/
|
||||
static String languagePrefix(String path, SiteView site) {
|
||||
for (Locale locale : site.locales()) {
|
||||
if (locale.equals(site.defaultLocale())) {
|
||||
continue; // the default language's pages are unprefixed
|
||||
}
|
||||
String prefix = "/" + locale.getLanguage();
|
||||
if (path.equals(prefix) || path.startsWith(prefix + "/")) {
|
||||
return prefix;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* The absolute base of the crawl-surface endpoints (sitemap, robots.txt, llms.txt). The URLs themselves come from
|
||||
* the host's content listing ({@code CatalogEntry} / {@code LocalizedUrl}, root-relative) — this plugin never
|
||||
* applies the URL scheme itself; it only prefixes the origin.
|
||||
*/
|
||||
final class PageUrls {
|
||||
|
||||
private PageUrls() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The site's absolute base ({@code scheme://host[:port]}, no trailing slash): the site view's base URL — which
|
||||
* the host fills with the configured base URL, else {@code https://<the site's first host name>} — and, for a
|
||||
* site with neither (a host-less catch-all site), the request's <b>trusted origin</b>
|
||||
* ({@link RouteRequest#origin()}: the scheme and host as the host's trusted-proxy gate leaves them — a configured
|
||||
* proxy's forwarded values applied, raw values otherwise). Empty only when none is known.
|
||||
*
|
||||
* <p>Until 2.0.0 that last fallback was built from the raw {@code Host} header with the scheme read from
|
||||
* {@code X-Forwarded-Proto} — which the kernel does not pass to plugins — or else <i>guessed</i> as
|
||||
* {@code https}. The origin replaces both: no header is trusted unless the operator trusted the proxy that set
|
||||
* it, and the scheme is the one the request actually arrived on.
|
||||
*/
|
||||
static String base(SiteView site, RouteRequest req) {
|
||||
String configured = site.baseUrl();
|
||||
String base = (configured != null && !configured.isBlank()) ? configured.trim() : req.origin().trim();
|
||||
return base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits schema.org {@code Person} node(s) from a {@code content.schema} entry — a {@code people:} list yields
|
||||
* one {@code Person} per member (name/jobTitle/image/sameAs, {@code worksFor}→Organization); with no list, a
|
||||
* single {@code Person} is built from the entry's own fields. A person with no name is skipped.
|
||||
*/
|
||||
final class PersonSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Person";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
List<Map<String, Object>> people = Schemas.maps(cfg, "people");
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
if (people.isEmpty()) {
|
||||
Map<String, Object> single = person(cfg, sc);
|
||||
if (single != null) {
|
||||
out.add(single);
|
||||
}
|
||||
} else {
|
||||
for (Map<String, Object> member : people) {
|
||||
Map<String, Object> node = person(member, sc);
|
||||
if (node != null) {
|
||||
out.add(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> person(Map<String, Object> p, SchemaContext sc) {
|
||||
String name = Schemas.str(p, "name");
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> node = Ld.node("Person", null);
|
||||
Ld.put(node, "name", name);
|
||||
Ld.put(node, "jobTitle", Schemas.str(p, "jobTitle"));
|
||||
Ld.putList(node, "image", Schemas.absolute(Schemas.strings(p, "image"), sc.base()));
|
||||
Ld.putList(node, "sameAs", Schemas.strings(p, "sameAs"));
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(node, "worksFor", sc.organizationId());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code Product} (with a nested {@code Offer}) from a product page's {@code content.schema}
|
||||
* entry — name/description/image/sku, {@code brand}→Organization, and {@code offers}(price/currency/availability/
|
||||
* url). Name and description fall back to the page's title/description. The node is {@code mainEntityOfPage}-linked
|
||||
* to this page's {@code WebPage}.
|
||||
*/
|
||||
final class ProductSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Product";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String name = Schemas.str(cfg, "name", ctx.page().title());
|
||||
if (name == null || name.isBlank()) {
|
||||
return List.of(); // nothing substantive to say — don't emit a bare {@type: Product} node
|
||||
}
|
||||
Map<String, Object> product = Ld.node("Product", null);
|
||||
Ld.put(product, "name", name);
|
||||
Ld.put(product, "description", Schemas.str(cfg, "description", ctx.page().description()));
|
||||
Ld.putList(product, "image", Schemas.absolute(Schemas.strings(cfg, "image"), sc.base()));
|
||||
Ld.put(product, "sku", Schemas.str(cfg, "sku"));
|
||||
Ld.ref(product, "mainEntityOfPage", sc.webpageId());
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(product, "brand", sc.organizationId());
|
||||
}
|
||||
String price = Schemas.str(cfg, "price");
|
||||
if (price != null) {
|
||||
Map<String, Object> offer = new LinkedHashMap<>();
|
||||
offer.put("@type", "Offer");
|
||||
offer.put("price", price);
|
||||
offer.put("priceCurrency", Schemas.str(cfg, "currency", "USD"));
|
||||
String availability = Schemas.str(cfg, "availability");
|
||||
if (availability != null) {
|
||||
offer.put("availability",
|
||||
availability.startsWith("http") ? availability : "https://schema.org/" + availability);
|
||||
}
|
||||
offer.put("url", sc.canonical());
|
||||
product.put("offers", offer);
|
||||
}
|
||||
return List.of(product);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* SEO+/GEO — serves a per-site <b>{@code /robots.txt}</b>. The kernel deliberately does <b>not</b> own this
|
||||
* route (an {@code EndpointContributor} route has exactly one owner, and a kernel handler reading a plugin's
|
||||
* config would hard-code a plugin id into the core); the discoverability plugin owns it because the two things
|
||||
* a rich {@code robots.txt} needs are already the plugin's: the {@code Sitemap:} line points at the plugin's own
|
||||
* {@code /sitemap.xml} (and is emitted only when that surface is enabled, so it never points at a {@code 404}),
|
||||
* and the AI/LLM-crawler policy is a GEO concern that sits beside {@code llms.txt}.
|
||||
*
|
||||
* <p>The body is an <b>explicit</b> named AI/LLM-crawler group (always emitted, so the AI posture is stated
|
||||
* rather than merely implied by the wildcard), then a general {@code User-agent: *} group (allow-all, plus any
|
||||
* tenant {@code robots.extra-disallow} paths), followed by the {@code Sitemap:} line. On the allow posture the
|
||||
* AI group mirrors the general group's exclusions (a most-specific match wins in robots.txt, so a bare
|
||||
* {@code Allow: /} would let those agents bypass the tenant's own Disallow paths); on opt-out it is a clean
|
||||
* {@code Disallow: /}. The AI posture is per-tenant ({@code robots.ai-policy}: {@code allow}/{@code disallow}/
|
||||
* {@code inherit}) falling back to the app-level default ({@code robots.ai-default}, GEO-friendly {@code allow}).
|
||||
* {@code robots.custom} is a full-body escape hatch that replaces the generated output verbatim.
|
||||
*
|
||||
* <p>An install <b>without</b> this plugin serves no {@code /robots.txt} at all, which crawlers treat as
|
||||
* allow-all — functionally identical to the old permissive kernel default.
|
||||
*/
|
||||
public class RobotsTxtEndpoint implements EndpointContributor {
|
||||
|
||||
/**
|
||||
* AI/LLM crawler user-agents grouped under one {@code Disallow: /} when a site opts out of AI crawling.
|
||||
* These are training/answer-engine agents kept distinct from the classic search crawlers (e.g.
|
||||
* {@code Google-Extended} ≠ {@code Googlebot}, {@code Applebot-Extended} ≠ {@code Applebot}), so opting out
|
||||
* of AI never deindexes the site from web search.
|
||||
*
|
||||
* <p><b>This list goes stale, and it fails silently when it does.</b> Operators publish, rename and retire
|
||||
* agent names on their own schedule; an agent missing from this list is simply <i>not covered</i> by an
|
||||
* opt-out, and nothing anywhere reports that — the site owner believes they opted out and did not. That is
|
||||
* not hypothetical: {@code Claude-User} and {@code Claude-SearchBot} were absent from the shipped 1.3.0 list
|
||||
* while {@code ClaudeBot} was present, so a site set to {@code disallow} was still reachable by two of the
|
||||
* three Anthropic agents.
|
||||
*
|
||||
* <p>Because a compile-time constant cannot be corrected without a plugin release, the effective list is
|
||||
* this constant <b>plus</b> the app-level {@code robots.ai-agents-extra} setting
|
||||
* ({@link DiscoverabilityProperties.Robots#getAiAgentsExtra()}) — so an operator can cover a newly announced
|
||||
* agent the same day it is announced. See {@link #aiAgents()}.
|
||||
*
|
||||
* <p>Each agent is also assigned an {@link AiClass}, so a site can decline <b>training</b> while staying
|
||||
* citable by answer engines — see {@link #AI_CLASSES}.
|
||||
*/
|
||||
static final List<String> AI_CRAWLERS = List.of(
|
||||
"GPTBot", "OAI-SearchBot", "ChatGPT-User", // OpenAI: training / retrieval / user-triggered
|
||||
"ClaudeBot", "Claude-SearchBot", "Claude-User", // Anthropic: training / retrieval / user-triggered
|
||||
"anthropic-ai", "Claude-Web", // Anthropic legacy names, kept: harmless if retired
|
||||
"Google-Extended", // Google (Gemini training; NOT Googlebot)
|
||||
"PerplexityBot", "Perplexity-User", // Perplexity: retrieval / user-triggered
|
||||
"CCBot", // Common Crawl (feeds many LLMs)
|
||||
"Bytespider", // ByteDance
|
||||
"Amazonbot", // Amazon
|
||||
"Applebot-Extended", // Apple (AI training opt-out; NOT Applebot)
|
||||
"Meta-ExternalAgent", "FacebookBot", // Meta
|
||||
"cohere-ai", "Diffbot", "Omgilibot", "Timpibot", "YouBot");
|
||||
|
||||
/**
|
||||
* What an AI agent is <i>for</i>. The three roles the operators themselves distinguish, and the reason a
|
||||
* single AI switch was not enough: they carry opposite consequences for a site.
|
||||
*/
|
||||
enum AiClass {
|
||||
|
||||
/** Collecting text to train a model. Declining costs the site nothing it can see. */
|
||||
TRAINING("training"),
|
||||
|
||||
/** Building an index an answer engine cites from. Declining removes the site from those answers. */
|
||||
RETRIEVAL("retrieval"),
|
||||
|
||||
/** Fetching one page because a person asked about it. Declining breaks a visit somebody initiated. */
|
||||
USER("user");
|
||||
|
||||
private final String key;
|
||||
|
||||
AiClass(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
/** The token used in setting keys and in operator-supplied {@code class=Agent} entries. */
|
||||
String key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
static AiClass of(String token) {
|
||||
for (AiClass value : values()) {
|
||||
if (value.key.equalsIgnoreCase(token)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Which class each built-in agent belongs to.
|
||||
*
|
||||
* <h2>How these were assigned, and where the uncertainty is</h2>
|
||||
* The triads are the operators' own published distinction and are not in doubt: OpenAI's
|
||||
* {@code GPTBot}/{@code OAI-SearchBot}/{@code ChatGPT-User}, Anthropic's
|
||||
* {@code ClaudeBot}/{@code Claude-SearchBot}/{@code Claude-User}, Perplexity's
|
||||
* {@code PerplexityBot}/{@code Perplexity-User}. So are the training-only opt-out agents that exist
|
||||
* precisely to be separable from their search siblings — {@code Google-Extended} (not {@code Googlebot}),
|
||||
* {@code Applebot-Extended} (not {@code Applebot}).
|
||||
*
|
||||
* <p>The rest are a best-effort reading of each operator's own description, and some genuinely serve more
|
||||
* than one purpose. <b>An agent whose role is ambiguous is placed in {@link AiClass#TRAINING}</b>, because
|
||||
* that is the class a site opting out is most likely to mean, and a misplaced agent should fail toward
|
||||
* honouring the site's stated intent rather than around it.
|
||||
*
|
||||
* <p>An agent absent from this map is governed by the site's overall {@code robots.ai-policy} — the
|
||||
* behaviour every site had before classes existed, so an operator-added name keeps working unchanged.
|
||||
*/
|
||||
static final Map<String, AiClass> AI_CLASSES = Map.ofEntries(
|
||||
Map.entry("GPTBot", AiClass.TRAINING),
|
||||
Map.entry("OAI-SearchBot", AiClass.RETRIEVAL),
|
||||
Map.entry("ChatGPT-User", AiClass.USER),
|
||||
Map.entry("ClaudeBot", AiClass.TRAINING),
|
||||
Map.entry("Claude-SearchBot", AiClass.RETRIEVAL),
|
||||
Map.entry("Claude-User", AiClass.USER),
|
||||
Map.entry("anthropic-ai", AiClass.TRAINING),
|
||||
Map.entry("Claude-Web", AiClass.TRAINING),
|
||||
Map.entry("Google-Extended", AiClass.TRAINING),
|
||||
Map.entry("PerplexityBot", AiClass.RETRIEVAL),
|
||||
Map.entry("Perplexity-User", AiClass.USER),
|
||||
Map.entry("CCBot", AiClass.TRAINING),
|
||||
Map.entry("Bytespider", AiClass.TRAINING),
|
||||
Map.entry("Amazonbot", AiClass.TRAINING),
|
||||
Map.entry("Applebot-Extended", AiClass.TRAINING),
|
||||
Map.entry("Meta-ExternalAgent", AiClass.TRAINING),
|
||||
Map.entry("FacebookBot", AiClass.TRAINING),
|
||||
Map.entry("cohere-ai", AiClass.TRAINING),
|
||||
Map.entry("Diffbot", AiClass.TRAINING),
|
||||
Map.entry("Omgilibot", AiClass.TRAINING),
|
||||
Map.entry("Timpibot", AiClass.TRAINING),
|
||||
Map.entry("YouBot", AiClass.RETRIEVAL));
|
||||
|
||||
/**
|
||||
* One AI agent as it will be emitted: its name, and the class governing it ({@code null} = the site's
|
||||
* overall policy).
|
||||
*
|
||||
* <p>Name <b>and</b> class together, rather than a name list beside a shared lookup map, because
|
||||
* {@code /robots.txt} is a public route served on many threads at once: a map rebuilt per request would
|
||||
* let one thread read it mid-rebuild and emit an agent under a policy the operator never chose. There is
|
||||
* no shared mutable state here at all — the classification is derived per call and thrown away.
|
||||
*/
|
||||
record Agent(String name, AiClass declaredClass) {
|
||||
}
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RobotsTxtEndpoint.class);
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final DiscoverabilityProperties properties;
|
||||
|
||||
public RobotsTxtEndpoint(PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
this.settings = settings;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/robots";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// Not indexable, not in sitemap, cacheable (content is per-host stable).
|
||||
return List.of(new Route("GET", "/robots.txt", Realm.TENANT, new SurfacePosture(false, false, true)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
|
||||
// Full-body override — replaces the generated output entirely.
|
||||
String custom = SiteConfig.str(cfg, "robots.custom", "");
|
||||
if (!custom.isBlank()) {
|
||||
return RouteResponse.text(200, ensureTrailingNewline(custom));
|
||||
}
|
||||
|
||||
String base = PageUrls.base(req.site(), req);
|
||||
StringBuilder body = new StringBuilder(256);
|
||||
List<String> extra = extraDisallow(cfg);
|
||||
|
||||
// Named AI/LLM-crawler group(s), ALWAYS emitted so the crawl posture is EXPLICIT rather than implied by
|
||||
// the wildcard (a GEO signal). On opt-out a group is a clean Disallow: /. On allow it MIRRORS the
|
||||
// general group (Allow: / + the same tenant Disallow paths) — a most-specific match wins in robots.txt,
|
||||
// so an explicit Allow: / with no exclusions would otherwise let these agents ignore the site's own
|
||||
// extra Disallows.
|
||||
//
|
||||
// ONE group when every class resolves the same way — which is every site that has not set a per-class
|
||||
// override, so their robots.txt is byte-identical to before classes existed. Splitting a site that made
|
||||
// no such choice into three identical groups would churn every crawler's copy to say the same thing.
|
||||
appendAiGroups(body, cfg, extra);
|
||||
|
||||
// The general group: allow-all, plus any tenant-declared extra Disallow paths.
|
||||
body.append("User-agent: *\n");
|
||||
appendAllowWithExclusions(body, extra);
|
||||
|
||||
// Sitemap reference — only when the sitemap surface is actually served (matches SitemapEndpoint's gate).
|
||||
if (!base.isBlank() && SiteConfig.bool(cfg, "sitemap.enabled", true)) {
|
||||
body.append("\nSitemap: ").append(base).append("/sitemap.xml\n");
|
||||
}
|
||||
|
||||
return RouteResponse.text(200, body.toString());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Writes the AI-crawler group(s): one per distinct policy across the three classes.
|
||||
*
|
||||
* <p>A site that has expressed no per-class preference gets exactly the single group it always got —
|
||||
* identical bytes, identical agent order. Only a site that actually distinguishes the classes pays the
|
||||
* extra groups.
|
||||
*/
|
||||
private void appendAiGroups(StringBuilder body, Map<String, Object> cfg, List<String> extra) {
|
||||
boolean training = aiDisallowed(cfg, AiClass.TRAINING);
|
||||
boolean retrieval = aiDisallowed(cfg, AiClass.RETRIEVAL);
|
||||
boolean user = aiDisallowed(cfg, AiClass.USER);
|
||||
List<Agent> agents = aiAgentsClassified();
|
||||
|
||||
if (training == retrieval && retrieval == user) {
|
||||
appendAiGroup(body, agents.stream().map(Agent::name).toList(), training, extra);
|
||||
return;
|
||||
}
|
||||
// Split. Unclassified agents (operator additions with no class= prefix) follow the site's overall
|
||||
// policy, exactly as they did before classes existed — inventing a class for a name we do not
|
||||
// recognise would silently apply a policy the operator never chose.
|
||||
for (AiClass aiClass : AiClass.values()) {
|
||||
List<String> ofClass = agents.stream()
|
||||
.filter(a -> classOf(a) == aiClass).map(Agent::name).toList();
|
||||
if (!ofClass.isEmpty()) {
|
||||
appendAiGroup(body, ofClass, aiDisallowed(cfg, aiClass), extra);
|
||||
}
|
||||
}
|
||||
List<String> unclassified = agents.stream()
|
||||
.filter(a -> classOf(a) == null).map(Agent::name).toList();
|
||||
if (!unclassified.isEmpty()) {
|
||||
appendAiGroup(body, unclassified, aiDisallowed(cfg), extra);
|
||||
}
|
||||
}
|
||||
|
||||
/** One {@code User-agent:} block: the names, then either {@code Disallow: /} or the mirrored allow. */
|
||||
private static void appendAiGroup(StringBuilder body, List<String> agents, boolean disallowed,
|
||||
List<String> extra) {
|
||||
for (String agent : agents) {
|
||||
body.append("User-agent: ").append(agent).append('\n');
|
||||
}
|
||||
if (disallowed) {
|
||||
body.append("Disallow: /\n\n");
|
||||
} else {
|
||||
appendAllowWithExclusions(body, extra);
|
||||
body.append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/** The class of {@code agent} — its declared {@code class=} prefix if any, else the built-in map. */
|
||||
private static AiClass classOf(Agent agent) {
|
||||
return agent.declaredClass() != null ? agent.declaredClass() : AI_CLASSES.get(agent.name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code aiClass} is disallowed for this site: its own override if set, else the site's overall
|
||||
* {@code robots.ai-policy}, else the app-level default.
|
||||
*
|
||||
* <p>The per-class key is {@code robots.ai-training} / {@code -retrieval} / {@code -user} — deliberately
|
||||
* NOT {@code robots.ai-policy.training}, which would make one key both a scalar and a map prefix and is
|
||||
* the kind of shape that parses today and breaks the first time the config is read as a tree.
|
||||
*/
|
||||
private boolean aiDisallowed(Map<String, Object> cfg, AiClass aiClass) {
|
||||
String policy = SiteConfig.str(cfg, "robots.ai-" + aiClass.key(), "inherit").trim();
|
||||
if (policy.equalsIgnoreCase("allow")) {
|
||||
return false;
|
||||
}
|
||||
if (policy.equalsIgnoreCase("disallow")) {
|
||||
return true;
|
||||
}
|
||||
return aiDisallowed(cfg); // inherit → the site's overall AI policy
|
||||
}
|
||||
|
||||
/**
|
||||
* The built-in {@link #AI_CRAWLERS} plus any operator-added names from {@code robots.ai-agents-extra},
|
||||
* de-duplicated case-insensitively and sanitised.
|
||||
*
|
||||
* <p>Sanitisation is not cosmetic: an operator-supplied value lands in a {@code User-agent:} line, so a name
|
||||
* containing CR/LF would let one setting inject arbitrary robots directives into every tenant's file — the
|
||||
* same injection this class already closes for tenant {@code extra-disallow} paths. Whitespace and colons are
|
||||
* stripped for the same reason (a colon would forge a second directive on one line).
|
||||
*
|
||||
* <p>Order is stable: built-ins first in declaration order, then operator additions in the order given, so
|
||||
* the emitted file diffs cleanly between restarts.
|
||||
*/
|
||||
List<String> aiAgents() {
|
||||
return aiAgentsClassified().stream().map(Agent::name).toList();
|
||||
}
|
||||
|
||||
/** As {@link #aiAgents()}, but each name paired with the class its entry declared (if any). */
|
||||
List<Agent> aiAgentsClassified() {
|
||||
List<Agent> agents = new ArrayList<>();
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (String a : AI_CRAWLERS) {
|
||||
agents.add(new Agent(a, null));
|
||||
seen.add(a.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
for (String raw : properties.getRobots().getAiAgentsExtra()) {
|
||||
if (raw == null) {
|
||||
continue;
|
||||
}
|
||||
// An entry may declare which class the agent belongs to: `training=SomeNewBot`. Without it the
|
||||
// agent follows the site's overall AI policy, which is what every operator addition did before
|
||||
// classes existed — so nothing already configured changes meaning.
|
||||
String value = raw;
|
||||
AiClass declared = null;
|
||||
int eq = value.indexOf('=');
|
||||
if (eq > 0) {
|
||||
String token = value.substring(0, eq).trim();
|
||||
declared = AiClass.of(token);
|
||||
// A misspelt class is reported and the AGENT is still honoured, unclassified. Folding the bad
|
||||
// prefix into the name instead would produce a user-agent token that matches nothing, and the
|
||||
// operator would believe they had covered an agent they had not — the exact silent failure
|
||||
// this whole list exists to warn about.
|
||||
if (declared == null) {
|
||||
log.warn("robots.ai-agents-extra entry '{}' names an unknown AI class '{}' — the agent is "
|
||||
+ "still listed, but it follows the site's overall AI policy. Valid classes: {}.",
|
||||
raw, token, java.util.Arrays.stream(AiClass.values()).map(AiClass::key).toList());
|
||||
}
|
||||
value = value.substring(eq + 1);
|
||||
}
|
||||
String clean = value.replaceAll("[\\r\\n:=\\s]", "").trim();
|
||||
if (!clean.isEmpty() && seen.add(clean.toLowerCase(Locale.ROOT))) {
|
||||
agents.add(new Agent(clean, declared));
|
||||
}
|
||||
}
|
||||
return List.copyOf(agents);
|
||||
}
|
||||
|
||||
/** True when this site opts out of AI/LLM crawlers: per-tenant {@code robots.ai-policy}, else the app default. */
|
||||
private boolean aiDisallowed(Map<String, Object> cfg) {
|
||||
String policy = SiteConfig.str(cfg, "robots.ai-policy", "inherit").trim();
|
||||
if (policy.equalsIgnoreCase("allow")) {
|
||||
return false;
|
||||
}
|
||||
if (policy.equalsIgnoreCase("disallow")) {
|
||||
return true;
|
||||
}
|
||||
return "disallow".equalsIgnoreCase(properties.getRobots().getAiDefault()); // inherit → app-level default
|
||||
}
|
||||
|
||||
/** Writes {@code Allow: /} followed by one {@code Disallow:} line per tenant exclusion path. */
|
||||
private static void appendAllowWithExclusions(StringBuilder body, List<String> extra) {
|
||||
body.append("Allow: /\n");
|
||||
for (String path : extra) {
|
||||
body.append("Disallow: ").append(path).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/** Tenant extra Disallow paths, each normalized to start with {@code /} and stripped of CR/LF. */
|
||||
private static List<String> extraDisallow(Map<String, Object> cfg) {
|
||||
List<String> paths = new ArrayList<>();
|
||||
for (String p : SiteConfig.list(cfg, "robots.extra-disallow")) {
|
||||
// Strip CR/LF so one list entry can never inject extra robots lines/directives.
|
||||
String clean = p.replaceAll("[\\r\\n]", "").trim();
|
||||
if (!clean.isEmpty()) {
|
||||
paths.add(clean.startsWith("/") ? clean : "/" + clean);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
private static String ensureTrailingNewline(String s) {
|
||||
return s.endsWith("\n") ? s : s + "\n";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.robots");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The immutable inputs a {@link SchemaType} needs beyond the {@link mx.quest.runway.spi.model.HeadContext}: the
|
||||
* resolved site {@code base} and this page's {@code path}/{@code canonical}, whether it is a homepage, whether
|
||||
* the site declares an Organization, the shared {@code @id}s (so a typed node cross-references the
|
||||
* {@code WebPage}/{@code Organization} by reference rather than redefining them), the current {@code locale},
|
||||
* and the matched per-page config subtree parsed from {@code content.schema}.
|
||||
*
|
||||
* @param base the site base URL (no trailing slash)
|
||||
* @param canonical this page's absolute canonical URL
|
||||
* @param path this page's path relative to base (starts with {@code /})
|
||||
* @param home whether this page is a homepage
|
||||
* @param hasOrg whether the site has a configured Organization (so {@code publisher}/{@code brand} refs apply)
|
||||
* @param websiteId the {@code @id} of the graph's {@code WebSite} node
|
||||
* @param webpageId the {@code @id} of the graph's {@code WebPage} node (for {@code mainEntityOfPage}/{@code isPartOf})
|
||||
* @param organizationId the {@code @id} of the graph's {@code Organization} node ({@code null}/unused when absent)
|
||||
* @param pageConfig the matched {@code content.schema} entry (its {@code type} + type-specific fields)
|
||||
* @param locale the resolved request locale
|
||||
*/
|
||||
record SchemaContext(String base, String canonical, String path, boolean home, boolean hasOrg,
|
||||
String websiteId, String webpageId, String organizationId,
|
||||
Map<String, Object> pageConfig, Locale locale) {
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* A plugin-internal content type that maps a tenant-declared page/section type (e.g. {@code FAQPage},
|
||||
* {@code Product}) to schema.org JSON-LD {@code @graph} node(s). This is the extension seam behind item 5's
|
||||
* type-aware structured data: {@link StructuredDataHead} holds a registry of these keyed by {@link #key()} and,
|
||||
* for a page whose path matches a {@code content.schema} entry, appends {@link #nodes(HeadContext, SchemaContext)}
|
||||
* to the graph — with zero type-aware branching in the contributor itself (capability/registry dispatch, per the
|
||||
* host's capability-driven-SPI principle).
|
||||
*
|
||||
* <p>Implementations are pure and stateless: they read the immutable {@link HeadContext} and the matched
|
||||
* per-page config carried by {@link SchemaContext}, and return plain node maps that reference the shared
|
||||
* {@code #webpage}/{@code #organization} entities by {@code @id}. Content <em>values</em> are tenant-owned (they
|
||||
* come from the config); the plugin owns only the typing mechanism.
|
||||
*/
|
||||
interface SchemaType {
|
||||
|
||||
/** The type token a tenant declares in {@code content.schema} (e.g. {@code "FAQPage"}); the registry key. */
|
||||
String key();
|
||||
|
||||
/**
|
||||
* The schema.org node(s) for this typed page, or an empty list when the config has nothing to emit.
|
||||
*
|
||||
* @param ctx the immutable head context (site, page, locale, canonical)
|
||||
* @param sc the resolved schema context (base, path, shared {@code @id}s, the matched per-page config)
|
||||
*/
|
||||
List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc);
|
||||
|
||||
/**
|
||||
* Whether a block declaring {@code token} (one of the tokens this type is registered under) describes the page
|
||||
* itself — its own {@code #webpage} node's {@code @type} — rather than adding a separate entity. Such a block
|
||||
* replaces the site's Default page type for the pages it matches, and the head then calls
|
||||
* {@link #describePage} instead of {@link #nodes}. Until 2.2.0 every block added a node, so a page declared
|
||||
* {@code Article} carried two Article nodes when the site default was Article as well.
|
||||
*/
|
||||
default boolean describesPage(String token) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a block that {@linkplain #describesPage describes the page}: adds this type's properties to the page's own
|
||||
* node (whose {@code @type} the caller has already set to the declared token) and appends any separate nodes the
|
||||
* type needs to {@code graph}.
|
||||
*
|
||||
* @param page the page's own node, mutable
|
||||
* @param graph the graph being built, for nodes the page refers to by {@code @id}
|
||||
*/
|
||||
default void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
}
|
||||
|
||||
/**
|
||||
* What a block declaring {@code token} lacks to publish what it is for, or {@code null} when it lacks nothing:
|
||||
* an {@code FAQPage} with no complete question, a list with no item that has a {@code url}. Such a block breaks
|
||||
* nothing, so the page is still served; the settings form's Per-page types check and the page editor report it,
|
||||
* since until 2.2.0 nobody saw it. A key that has a default (a product's name falls back to the page title) is
|
||||
* not a gap.
|
||||
*/
|
||||
default Gap gap(String token, Map<String, Object> block) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A gap: the message code and its English text, whose {@code {0}} is the type token.
|
||||
*
|
||||
* @param code the message key, resolved in the operator's UI language
|
||||
* @param fallback the English text
|
||||
*/
|
||||
record Gap(String code, String fallback) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Null-safe readers over the parsed {@code content.schema} entry maps (nested {@code Map}/{@code List} produced
|
||||
* by the YAML parser). Shared by the {@link SchemaType} implementations so each stays a small pure mapper.
|
||||
*/
|
||||
final class Schemas {
|
||||
|
||||
private Schemas() {
|
||||
}
|
||||
|
||||
/** The string value of {@code key}, or {@code null} when absent/blank. */
|
||||
static String str(Map<String, Object> map, String key) {
|
||||
Object v = map == null ? null : map.get(key);
|
||||
if (v == null) {
|
||||
return null;
|
||||
}
|
||||
String s = v.toString();
|
||||
return s.isBlank() ? null : s;
|
||||
}
|
||||
|
||||
/** The string value of {@code key}, or {@code def} when absent/blank. */
|
||||
static String str(Map<String, Object> map, String key, String def) {
|
||||
String v = str(map, key);
|
||||
return v == null ? def : v;
|
||||
}
|
||||
|
||||
/** The list-of-maps value of {@code key} (e.g. {@code faq}, {@code locations}, {@code people}); never null. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<Map<String, Object>> maps(Map<String, Object> map, String key) {
|
||||
Object v = map == null ? null : map.get(key);
|
||||
if (!(v instanceof List<?> list)) {
|
||||
return List.of();
|
||||
}
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Object o : list) {
|
||||
if (o instanceof Map<?, ?> m) {
|
||||
out.add((Map<String, Object>) m);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The list-of-strings value of {@code key} (a scalar is treated as a one-element list); never null. */
|
||||
static List<String> strings(Map<String, Object> map, String key) {
|
||||
Object v = map == null ? null : map.get(key);
|
||||
if (v instanceof List<?> list) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (Object o : list) {
|
||||
if (o != null && !o.toString().isBlank()) {
|
||||
out.add(o.toString());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (v instanceof String s && !s.isBlank()) {
|
||||
return List.of(s);
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code url} made absolute against the site {@code base} when it is root-relative ({@code /img/a.png}); any
|
||||
* other value as given. JSON-LD URLs must be absolute; until 2.2.0 a root-relative image was emitted as written,
|
||||
* which search engines reject.
|
||||
*/
|
||||
static String absolute(String url, String base) {
|
||||
return url != null && url.startsWith("/") && !url.startsWith("//") && base != null && !base.isBlank()
|
||||
? base + url : url;
|
||||
}
|
||||
|
||||
/** {@link #absolute} applied to each URL of a list. */
|
||||
static List<String> absolute(List<String> urls, String base) {
|
||||
List<String> out = new ArrayList<>(urls.size());
|
||||
for (String url : urls) {
|
||||
out.add(absolute(url, base));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code Service} (or the entry's declared subtype, e.g. {@code ProfessionalService}) from a
|
||||
* service page's {@code content.schema} entry: name/description/{@code serviceType}/{@code areaServed}/{@code offers},
|
||||
* with {@code provider}→Organization and {@code mainEntityOfPage}→WebPage. Name and description fall back to the
|
||||
* page's title/description. An {@code offers:} list turns a pricing page's tiers into machine-readable
|
||||
* {@code Offer}s (a recurring tier declares {@code unit:} → a {@code UnitPriceSpecification}, e.g. per month).
|
||||
*/
|
||||
final class ServiceSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Service";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String name = Schemas.str(cfg, "name", ctx.page().title());
|
||||
if (name == null || name.isBlank()) {
|
||||
return List.of(); // nothing substantive to say — don't emit a bare {@type: Service} node
|
||||
}
|
||||
String type = Schemas.str(cfg, "type", "Service"); // Service | ProfessionalService
|
||||
Map<String, Object> service = Ld.node(type, null);
|
||||
Ld.put(service, "name", name);
|
||||
Ld.put(service, "description", Schemas.str(cfg, "description", ctx.page().description()));
|
||||
Ld.put(service, "serviceType", Schemas.str(cfg, "serviceType"));
|
||||
Ld.putList(service, "areaServed", Schemas.strings(cfg, "areaServed"));
|
||||
List<Map<String, Object>> offers = offers(cfg);
|
||||
if (!offers.isEmpty()) {
|
||||
service.put("offers", offers);
|
||||
}
|
||||
Ld.ref(service, "mainEntityOfPage", sc.webpageId());
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(service, "provider", sc.organizationId());
|
||||
}
|
||||
return List.of(service);
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code offers:} list mapped to schema.org {@code Offer} nodes. An offer needs a {@code price}; a
|
||||
* {@code unit:} (e.g. {@code month}) makes it a recurring {@code UnitPriceSpecification}, else a flat
|
||||
* {@code price}/{@code priceCurrency}. Currency defaults to USD. Offers without a price are skipped.
|
||||
*/
|
||||
private static List<Map<String, Object>> offers(Map<String, Object> cfg) {
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Map<String, Object> o : Schemas.maps(cfg, "offers")) {
|
||||
String price = Schemas.str(o, "price");
|
||||
if (price == null) {
|
||||
continue;
|
||||
}
|
||||
String currency = Schemas.str(o, "currency", "USD");
|
||||
String unit = Schemas.str(o, "unit");
|
||||
Map<String, Object> offer = new LinkedHashMap<>();
|
||||
offer.put("@type", "Offer");
|
||||
Ld.put(offer, "name", Schemas.str(o, "name"));
|
||||
if (unit != null) {
|
||||
Map<String, Object> spec = new LinkedHashMap<>();
|
||||
spec.put("@type", "UnitPriceSpecification");
|
||||
spec.put("price", price);
|
||||
spec.put("priceCurrency", currency);
|
||||
spec.put("unitText", unit);
|
||||
offer.put("priceSpecification", spec);
|
||||
} else {
|
||||
offer.put("price", price);
|
||||
offer.put("priceCurrency", currency);
|
||||
}
|
||||
out.add(offer);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* A schema.org page type that only names what the page is — {@code AboutPage}, {@code ContactPage},
|
||||
* {@code WebPage} and the like — with no properties of its own. Declared in {@code content.schema}, it becomes the
|
||||
* page's own {@code @type}, replacing the site's Default page type; so a site whose default is {@code Article} can
|
||||
* say its contact page is a {@code ContactPage}, and a single page can go back to a plain {@code WebPage}.
|
||||
*/
|
||||
final class SimplePageType implements SchemaType {
|
||||
|
||||
/**
|
||||
* The page types this class serves, each registered as its own key. Not {@code ProfilePage} or {@code QAPage}:
|
||||
* Google requires a {@code mainEntity} on both (the person; the one user-submitted question with its answers),
|
||||
* which a type with no keys cannot give, so declaring them would only earn a Search Console error. Site-authored
|
||||
* questions are an {@code FAQPage}.
|
||||
*/
|
||||
static final List<String> KEYS = List.of("WebPage", "AboutPage", "ContactPage", "ItemPage", "SearchResultsPage");
|
||||
|
||||
private final String key;
|
||||
|
||||
SimplePageType(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
return List.of(); // describes the page itself; see describesPage
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Null/absent-safe typed readers over this plugin's effective per-site settings map — the
|
||||
* {@code SettingsView.values()} that {@code PluginSettings.site(siteId)} returns: the descriptor's
|
||||
* {@code siteSettings} defaults overlaid by the values stored for the site, each already coerced by the host to
|
||||
* its declared type (boolean→Boolean, int→Long, list→List<String>, enum/string/text→String).
|
||||
*
|
||||
* <p>Kept instead of the {@code SettingsView} accessors on purpose: these are the readers 1.x used, and their
|
||||
* lenient rules for a hand-edited value (any string other than true/on/yes/1 reads as {@code false}; a blank value
|
||||
* falls back) are part of what an unchanged site renders. The code fallbacks passed in equal the descriptor's
|
||||
* declared defaults ({@code DescriptorDefaultsTest} proves the rendered surfaces do not change when the defaults
|
||||
* are applied), so they matter only for a key the descriptor declares without a default.
|
||||
*/
|
||||
final class SiteConfig {
|
||||
|
||||
private SiteConfig() {
|
||||
}
|
||||
|
||||
static boolean bool(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()) {
|
||||
return s.equalsIgnoreCase("true") || s.equalsIgnoreCase("on") || s.equalsIgnoreCase("yes") || s.equals("1");
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
static String str(Map<String, Object> cfg, String key, String def) {
|
||||
Object v = cfg.get(key);
|
||||
return (v == null || v.toString().isBlank()) ? def : v.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<String> list(Map<String, Object> cfg, String key) {
|
||||
Object v = cfg.get(key);
|
||||
if (v instanceof List<?> l) {
|
||||
return l.stream().map(String::valueOf).map(String::trim).filter(s -> !s.isBlank()).toList();
|
||||
}
|
||||
if (v instanceof String s && !s.isBlank()) {
|
||||
return List.of(s.split("[,\\n]")).stream().map(String::trim).filter(x -> !x.isBlank()).toList();
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Alternate;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* SEO+ — serves a per-site <b>{@code /sitemap.xml}</b> enumerating the site's whole published content surface —
|
||||
* kernel pages AND every content source's items (blog entries, any plugin content) through the host's
|
||||
* {@link ContentCatalogView} — each {@code <url>} carrying its {@code hreflang} alternates, {@code x-default}, and
|
||||
* (when the item knows it) a {@code <lastmod>}. Every URL is one the host computed ({@link CatalogEntry#urls()},
|
||||
* {@link CatalogEntry#xDefaultPath()}) with the SAME code the head-injection alternates use, so the
|
||||
* {@code <head>} and the sitemap provably agree about every item's URLs; this class only prefixes the origin.
|
||||
*
|
||||
* <p>The catalog is already kernel-re-filtered (published-only, path-safe, reserved paths dropped) and
|
||||
* metadata-only (no item's body is ever read serving this route — a sitemap request stays cheap no matter how
|
||||
* many sources are installed).
|
||||
*
|
||||
* <p>The route is tenant-scoped and {@link SurfacePosture#discoverable()}. It honors the per-tenant
|
||||
* {@code sitemap.enabled} flag — disabled ⇒ {@code 404}, so a tenant can opt out without uninstalling the
|
||||
* plugin.
|
||||
*/
|
||||
public class SitemapEndpoint implements EndpointContributor {
|
||||
|
||||
private final ContentCatalogView catalog;
|
||||
private final PluginSettings settings;
|
||||
|
||||
public SitemapEndpoint(ContentCatalogView catalog, PluginSettings settings) {
|
||||
this.catalog = catalog;
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/sitemap";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// Indexable + in-sitemap + CACHEABLE: this endpoint manages its own caching (Last-Modified +
|
||||
// no-cache revalidation below) — the dispatcher must not stamp no-store over it.
|
||||
SurfacePosture posture = new SurfacePosture(true, true, true);
|
||||
List<Route> routes = new java.util.ArrayList<>(MAX_SHARDS + 1);
|
||||
routes.add(new Route("GET", SITEMAP_PATH, Realm.TENANT, posture));
|
||||
// Shard routes are declared STATICALLY, one per possible shard, because the host matches routes by
|
||||
// exact path — there is no pattern form, deliberately (a pattern on a public tenant route is a
|
||||
// path-safety surface nobody needs). A shard beyond what a site actually has answers 404; nothing
|
||||
// links to it, so the only way to reach one is to type it.
|
||||
for (int shard = 1; shard <= MAX_SHARDS; shard++) {
|
||||
routes.add(new Route("GET", shardPath(shard), Realm.TENANT, posture));
|
||||
}
|
||||
return List.copyOf(routes);
|
||||
}
|
||||
|
||||
/** The path of shard {@code n} (1-based), e.g. {@code /sitemap-3.xml}. */
|
||||
private static String shardPath(int n) {
|
||||
return "/sitemap-" + n + ".xml";
|
||||
}
|
||||
|
||||
/** The shard number a path names, or {@code 0} when it is the index itself / not a shard path. */
|
||||
private static int shardNumber(String path) {
|
||||
if (path == null || !path.startsWith("/sitemap-") || !path.endsWith(".xml")) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(path.substring("/sitemap-".length(), path.length() - ".xml".length()));
|
||||
} catch (NumberFormatException notAShard) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "sitemap.enabled", true)) {
|
||||
// The route posture is cacheable (so the 200/304 carry their own validators), which means the
|
||||
// dispatcher no longer stamps a fail-safe no-store — so this disabled-path 404 must forbid caching
|
||||
// itself, or a heuristically-cacheable 404 could outlive the tenant re-enabling the surface.
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
String base = PageUrls.base(req.site(), req);
|
||||
List<CatalogEntry> items = catalog.entries(req.site().id());
|
||||
|
||||
// Conditional GET: crawlers revalidate constantly; when nothing changed since their copy, answer 304
|
||||
// without re-serializing the document. The index and every shard share the site's newest instant —
|
||||
// coarse (any edit revalidates all of them) but honest: a per-shard instant would claim a shard is
|
||||
// unchanged while an item moved into or out of it.
|
||||
java.time.Instant newest = CrawlConditional.lastModified(req.site().id(), items);
|
||||
if (CrawlConditional.notModified(req, newest)) {
|
||||
return CrawlConditional.notModifiedResponse(newest);
|
||||
}
|
||||
|
||||
Listing listing = listing(items, base);
|
||||
int shard = shardNumber(req.path());
|
||||
if (shard > 0) {
|
||||
return shardResponse(listing, shard, newest, req.site().id());
|
||||
}
|
||||
if (listing.urls().size() <= SHARD_URLS) {
|
||||
// The ordinary case, and the shape every small site keeps: one plain <urlset>, no index, no extra
|
||||
// round trip. Splitting a 40-URL site across an index would cost a crawler two fetches to learn
|
||||
// nothing.
|
||||
return ok(urlsetDocument(listing.urls(), 0, listing.urls().size()), newest);
|
||||
}
|
||||
return ok(indexDocument(listing, base, newest), newest);
|
||||
}
|
||||
|
||||
/** One sitemap entry: the URL to list, its alternates block (pre-rendered), and its {@code <lastmod>}. */
|
||||
private record Entry(String url, String alternates, String lastmod) {
|
||||
}
|
||||
|
||||
/** The site's whole sitemap surface, and what was left out of it. */
|
||||
private record Listing(List<Entry> urls, int skippedNoindex, int skippedCanonical) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every URL this site advertises, in a <b>stable, content-derived order</b>.
|
||||
*
|
||||
* <h2>Why it is sorted</h2>
|
||||
* {@link ContentCatalogView#entries} returns items grouped by source in an order it does not promise, which is stable
|
||||
* within a boot and says nothing across boots or across the nodes of a cluster. Shard membership is
|
||||
* derived from position in this list, so an unsorted list would let two nodes behind the same load
|
||||
* balancer serve <b>different content for the same shard number</b> — a crawler alternating between them
|
||||
* would see URLs appear and vanish with nothing in the response to explain it. Sorting by URL makes the
|
||||
* boundaries a function of the content alone.
|
||||
*
|
||||
* <p>Metadata only: no item's body is read here, so this stays cheap however many sources are installed.
|
||||
*/
|
||||
private static Listing listing(List<CatalogEntry> items, String base) {
|
||||
List<Entry> entries = new java.util.ArrayList<>();
|
||||
int skippedNoindex = 0;
|
||||
int skippedCanonical = 0;
|
||||
|
||||
for (CatalogEntry item : items) {
|
||||
// A sitemap is a set of RECOMMENDATIONS to index. Listing a URL the same site tells robots not to
|
||||
// index contradicts itself, so drop those here rather than in the host listing — the router, the search
|
||||
// indexer and llms.txt all legitimately need the full published set.
|
||||
if (item.ref().noindex()) {
|
||||
skippedNoindex++;
|
||||
continue;
|
||||
}
|
||||
// Likewise a page whose canonical points somewhere ELSE is, by its own declaration, not the
|
||||
// authoritative URL. Emitting it would advertise a self-declared non-canonical address. (A canonical
|
||||
// equal to the item's own URL is the normal self-referential case and stays.)
|
||||
if (pointsElsewhere(item, base)) {
|
||||
skippedCanonical++;
|
||||
continue;
|
||||
}
|
||||
// The host's URLs — the same computation the head-injection alternates use (provable agreement): one
|
||||
// per available locale, each a REAL routing address (never the canonical override).
|
||||
List<Alternate> alternates = item.urls().stream().map(url -> url.alternate(base)).toList();
|
||||
String xDefault = base + item.xDefaultPath();
|
||||
String lastmod = item.ref().updatedAt() == null ? null : item.ref().updatedAt().toString();
|
||||
|
||||
StringBuilder links = new StringBuilder(128);
|
||||
for (Alternate alt : alternates) {
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"").append(alt.hreflang())
|
||||
.append("\" href=\"").append(xml(alt.url())).append("\"/>\n");
|
||||
}
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"")
|
||||
.append(xml(xDefault)).append("\"/>\n");
|
||||
String block = links.toString();
|
||||
|
||||
for (Alternate self : alternates) {
|
||||
entries.add(new Entry(self.url(), block, lastmod));
|
||||
}
|
||||
}
|
||||
entries.sort(java.util.Comparator.comparing(Entry::url));
|
||||
return new Listing(List.copyOf(entries), skippedNoindex, skippedCanonical);
|
||||
}
|
||||
|
||||
/** One shard's {@code <urlset>}, or {@code 404} for a shard this site does not have. */
|
||||
private RouteResponse shardResponse(Listing listing, int shard, java.time.Instant newest, String siteId) {
|
||||
int total = listing.urls().size();
|
||||
if (total <= SHARD_URLS) {
|
||||
// Not sharded at all: the shard paths exist as routes on every site, so they must say "no" rather
|
||||
// than duplicate /sitemap.xml at a second address — two URLs serving one document is exactly the
|
||||
// duplicate-content shape the rest of this plugin works to avoid.
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
int from = (shard - 1) * SHARD_URLS;
|
||||
if (from >= total) {
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
int to = Math.min(from + SHARD_URLS, total);
|
||||
warnIfTruncated(listing, siteId);
|
||||
return ok(urlsetDocument(listing.urls(), from, to), newest);
|
||||
}
|
||||
|
||||
/** The {@code <sitemapindex>} naming each shard this site actually has. */
|
||||
private byte[] indexDocument(Listing listing, String base, java.time.Instant newest) {
|
||||
int shards = Math.min(shardCount(listing.urls().size()), MAX_SHARDS);
|
||||
StringBuilder xml = new StringBuilder(256 + shards * 128);
|
||||
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
.append("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
|
||||
for (int shard = 1; shard <= shards; shard++) {
|
||||
xml.append(" <sitemap>\n")
|
||||
.append(" <loc>").append(xml(base + shardPath(shard))).append("</loc>\n");
|
||||
if (newest != null) {
|
||||
xml.append(" <lastmod>").append(newest).append("</lastmod>\n");
|
||||
}
|
||||
xml.append(" </sitemap>\n");
|
||||
}
|
||||
xml.append("</sitemapindex>\n");
|
||||
return xml.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** A {@code <urlset>} over {@code urls[from, to)}. */
|
||||
private static byte[] urlsetDocument(List<Entry> urls, int from, int to) {
|
||||
StringBuilder xml = new StringBuilder(512 + (to - from) * 256);
|
||||
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"")
|
||||
.append(" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n");
|
||||
for (int i = from; i < to; i++) {
|
||||
Entry entry = urls.get(i);
|
||||
xml.append(" <url>\n")
|
||||
.append(" <loc>").append(xml(entry.url())).append("</loc>\n");
|
||||
if (entry.lastmod() != null) {
|
||||
xml.append(" <lastmod>").append(entry.lastmod()).append("</lastmod>\n");
|
||||
}
|
||||
xml.append(entry.alternates()).append(" </url>\n");
|
||||
}
|
||||
xml.append("</urlset>\n");
|
||||
return xml.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** How many shards {@code total} URLs need. */
|
||||
private static int shardCount(int total) {
|
||||
return (total + SHARD_URLS - 1) / SHARD_URLS;
|
||||
}
|
||||
|
||||
private static void warnIfTruncated(Listing listing, String siteId) {
|
||||
int needed = shardCount(listing.urls().size());
|
||||
if (needed > MAX_SHARDS) {
|
||||
// LOUD, and naming the tenant: a silently truncated sitemap is indistinguishable from a small site,
|
||||
// so an operator would have no way to learn that content stopped being advertised.
|
||||
log.warn("sitemap for site '{}' needs {} shards but only {} are served ({} URLs per shard) — "
|
||||
+ "{} URL(s) beyond {} are NOT advertised.", siteId, needed, MAX_SHARDS, SHARD_URLS,
|
||||
listing.urls().size() - (long) MAX_SHARDS * SHARD_URLS, (long) MAX_SHARDS * SHARD_URLS);
|
||||
}
|
||||
}
|
||||
|
||||
private static RouteResponse ok(byte[] body, java.time.Instant newest) {
|
||||
return new RouteResponse(200,
|
||||
CrawlConditional.cacheHeaders(newest, "application/xml; charset=utf-8"), body);
|
||||
}
|
||||
|
||||
/** The route the index (or, for a small site, the single {@code <urlset>}) is served at. */
|
||||
private static final String SITEMAP_PATH = "/sitemap.xml";
|
||||
|
||||
/**
|
||||
* URLs per shard, and how many shards are served — together the ceiling on what a site can advertise
|
||||
* ({@value #SHARD_URLS} × {@value #MAX_SHARDS}).
|
||||
*
|
||||
* <h2>Why 10,000 and not the spec's 50,000</h2>
|
||||
* sitemaps.org allows <b>50,000 URLs and 50 MB</b> per file, and a conformant consumer may reject a
|
||||
* document that exceeds either — so an unbounded generator does not degrade gracefully on a large tenant,
|
||||
* it loses the whole sitemap at once. But the spec cap is not the binding constraint here: this is a
|
||||
* <b>public, anonymous</b> route, and a 50,000-URL document with {@code hreflang} alternates is tens of
|
||||
* megabytes assembled in the heap, per concurrent request. A smaller shard keeps each response comfortably
|
||||
* inside both the spec and a sane memory envelope, and costs a crawler only extra round trips it makes
|
||||
* anyway.
|
||||
*
|
||||
* <p>{@value #MAX_SHARDS} shards is a real ceiling — {@value #SHARD_URLS} × {@value #MAX_SHARDS}
|
||||
* URLs — because the host matches routes by exact path, so each shard is a declared route rather than a
|
||||
* pattern. Well past any filesystem-backed tenant, four times the single-file limit it replaces, and it
|
||||
* still WARNs loudly rather than truncating in silence.
|
||||
*/
|
||||
private static final int SHARD_URLS = 10_000;
|
||||
private static final int MAX_SHARDS = 20;
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SitemapEndpoint.class);
|
||||
|
||||
/**
|
||||
* Whether {@code item} declares a canonical URL pointing somewhere other than its own address — in which case
|
||||
* the item asks not to be treated as the authoritative URL and has no business in the sitemap.
|
||||
*
|
||||
* <p>The override is read from {@link LocalizedUrl#canonical()} (the host hands it over as given; equal to the
|
||||
* URL's own path when there is none). A root-relative override ({@code /about}) is resolved against
|
||||
* {@code base} before comparing, as the kernel does for the {@code <head>} canonical: it names an address on
|
||||
* this site, so {@code /about} on the {@code /about} page is the self-referential case. (Until 2.0.0 the raw
|
||||
* value was compared with the absolute URLs, so such a page was dropped from the sitemap.)
|
||||
*
|
||||
* <p>Compared against every locale's address and the {@code x-default}, because a localized variant is its own
|
||||
* address: a canonical matching any of the item's own URLs is the ordinary self-referential case.
|
||||
*/
|
||||
private static boolean pointsElsewhere(CatalogEntry item, String base) {
|
||||
String override = null;
|
||||
for (LocalizedUrl url : item.urls()) {
|
||||
if (!url.canonical().equals(url.path())) {
|
||||
override = url.canonical();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (override == null || override.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String want = override.trim();
|
||||
if (want.startsWith("/")) {
|
||||
want = base + want;
|
||||
}
|
||||
for (LocalizedUrl url : item.urls()) {
|
||||
if (url.absolute(base).equals(want)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return !want.equals(base + item.xDefaultPath());
|
||||
}
|
||||
|
||||
/** XML text/attribute escaping for URLs (chiefly {@code &} in query strings). */
|
||||
private static String xml(String value) {
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.sitemap");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* SEO+ and GEO — the single {@code HeadContributor} that injects one schema.org {@code @graph} of JSON-LD into
|
||||
* every indexable page's {@code <head>}. This is the layer the lean kernel deliberately leaves out: the kernel
|
||||
* already emits canonical, hreflang, robots, Open Graph and Twitter cards, so this contributor adds only the
|
||||
* structured-data {@code @graph} — never a tag the kernel already produces.
|
||||
*
|
||||
* <p>It emits <b>one</b> {@code <script type="application/ld+json">} block whose {@code @graph} carries each
|
||||
* entity <b>exactly once</b>: {@code WebSite} (with the GEO {@code SearchAction} folded in as its
|
||||
* {@code potentialAction}), {@code Organization}, {@code WebPage}/{@code Article} (with the GEO
|
||||
* {@code speakable} folded in), and {@code BreadcrumbList} on deep pages. Folding GEO into the same nodes — rather
|
||||
* than re-declaring {@code #website}/{@code #webpage} in a second block — means a JSON-LD consumer that parses
|
||||
* each {@code <script>} independently still sees complete entities.
|
||||
*
|
||||
* <p>Pure and stateless. Emits nothing for a preview or {@code noindex} render (structured data belongs only on
|
||||
* indexable pages), or when the tenant turns {@code jsonld.enabled} off (which also suppresses the GEO signals,
|
||||
* since a {@code SearchAction}/{@code speakable} that references an undefined {@code #website}/{@code #webpage}
|
||||
* would be an orphan). GEO signals are additionally gated by the opt-in {@code geo.enabled} flag. All URLs are
|
||||
* anchored on the host-resolved {@link HeadContext#canonical()} so the graph is internally consistent — made
|
||||
* absolute against {@link HeadContext#origin()} on a host-less site, whose canonical is root-relative (since 2.1.0;
|
||||
* it is why the plugin needs SPI 1.0.0).
|
||||
*/
|
||||
public class StructuredDataHead implements HeadContributor {
|
||||
|
||||
static final String PLUGIN_ID = "discoverability";
|
||||
|
||||
/**
|
||||
* Default {@code speakable} selectors when the tenant has not customized {@code geo.speakable}. Only elements
|
||||
* the shipped seed master (and a typical custom master) actually render — {@code <article>} is intentionally
|
||||
* NOT a default, since the seed masters have none and a phantom selector helps no assistant. A tenant whose
|
||||
* master really has {@code <article>} adds it back in the per-site GEO settings.
|
||||
*/
|
||||
private static final List<String> DEFAULT_SPEAKABLE = List.of("h1", "main");
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Map<String, SchemaType> types;
|
||||
|
||||
public StructuredDataHead(PluginSettings settings, Map<String, SchemaType> types) {
|
||||
this.settings = settings;
|
||||
this.types = types == null ? Map.of() : types;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/structured-data";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String render(HeadContext ctx) {
|
||||
if (ctx.preview() || ctx.noindex()) {
|
||||
return "";
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(ctx.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "jsonld.enabled", true)) {
|
||||
return "";
|
||||
}
|
||||
if (ctx.canonical() == null || ctx.canonical().isBlank()) {
|
||||
return ""; // no URL to anchor the graph — emit nothing rather than a broken graph
|
||||
}
|
||||
String base = baseFor(ctx, ctx.canonical());
|
||||
// A host-less site's canonical is root-relative (the kernel prefixes only a base URL it knows); JSON-LD
|
||||
// URLs and @ids must be absolute, so it is anchored on the trusted origin the page is served under.
|
||||
String canonical = absolute(ctx.canonical(), base);
|
||||
String siteUrl = base.isBlank() ? null : base + "/";
|
||||
String path = pathOf(base, canonical);
|
||||
boolean geo = SiteConfig.bool(cfg, "geo.enabled", false);
|
||||
List<Map<String, Object>> graph = new ArrayList<>();
|
||||
|
||||
// WebSite — the GEO SearchAction is folded in as potentialAction so #website is defined exactly once.
|
||||
Map<String, Object> website = Ld.node("WebSite", Ld.websiteId(base));
|
||||
Ld.put(website, "url", siteUrl);
|
||||
Ld.put(website, "name", ctx.site().displayName());
|
||||
Ld.put(website, "inLanguage", ctx.locale().toLanguageTag());
|
||||
if (geo && !base.isBlank()) {
|
||||
String searchUrl = SiteConfig.str(cfg, "search.url", "");
|
||||
if (!searchUrl.isBlank()) {
|
||||
website.put("potentialAction", searchAction(base, searchUrl));
|
||||
}
|
||||
}
|
||||
graph.add(website);
|
||||
|
||||
// Organization (only when the tenant has named one)
|
||||
String orgName = SiteConfig.str(cfg, "org.name", "");
|
||||
boolean hasOrg = !orgName.isBlank();
|
||||
if (hasOrg) {
|
||||
Map<String, Object> org = Ld.node("Organization", Ld.organizationId(base));
|
||||
Ld.put(org, "name", orgName);
|
||||
Ld.put(org, "url", siteUrl);
|
||||
Ld.put(org, "logo", absolutize(SiteConfig.str(cfg, "org.logo", ""), base));
|
||||
Ld.putList(org, "sameAs", SiteConfig.list(cfg, "org.sameas"));
|
||||
graph.add(org);
|
||||
}
|
||||
|
||||
// The page's own node — its type is the site's Default page type, or the page type its content.schema entry
|
||||
// declares (PageTypes: the same answer the page editor shows). The GEO speakable is folded in so #webpage is
|
||||
// defined exactly once.
|
||||
PageTypes.Description described = PageTypes.describe(cfg, path, types);
|
||||
String type = described.type();
|
||||
Map<String, Object> page = Ld.node(type, Ld.webpageId(canonical));
|
||||
Ld.put(page, "url", canonical);
|
||||
Ld.put(page, "Article".equals(type) ? "headline" : "name", ctx.page().title());
|
||||
Ld.put(page, "description", ctx.page().description());
|
||||
Ld.put(page, "inLanguage", ctx.locale().toLanguageTag());
|
||||
Ld.ref(page, "isPartOf", Ld.websiteId(base));
|
||||
if (hasOrg) {
|
||||
Ld.ref(page, "publisher", Ld.organizationId(base));
|
||||
}
|
||||
if (geo) {
|
||||
List<String> selectors = SiteConfig.list(cfg, "geo.speakable");
|
||||
if (selectors.isEmpty()) {
|
||||
selectors = DEFAULT_SPEAKABLE;
|
||||
}
|
||||
Map<String, Object> speakable = new LinkedHashMap<>();
|
||||
speakable.put("@type", "SpeakableSpecification");
|
||||
speakable.put("cssSelector", selectors);
|
||||
page.put("speakable", speakable);
|
||||
}
|
||||
graph.add(page);
|
||||
if (described.pageBlock() != null) {
|
||||
types.get(type).describePage(page, ctx,
|
||||
schemaContext(ctx, base, canonical, path, hasOrg, described.pageBlock()), graph);
|
||||
}
|
||||
|
||||
// SoftwareApplication — a product/app entity emitted on the HOMEPAGE ONLY (so it never leaks onto
|
||||
// interior pages the way a hand-authored extra-head block did), @id-linked into this same graph. The
|
||||
// tenant configures it via software.* instead of hand-authoring raw JSON-LD in seo.yml's extraHead.
|
||||
if (SiteConfig.bool(cfg, "software.enabled", false) && isHome(path, ctx)) {
|
||||
graph.add(softwareApplication(cfg, base, siteUrl, canonical, orgName, hasOrg, ctx));
|
||||
}
|
||||
|
||||
// Type-aware structured data — a tenant declares a page/section type in content.schema; the matching
|
||||
// SchemaType maps it to schema.org nodes that reference this WebPage / Organization by @id. The head
|
||||
// contributor stays type-blind: it dispatches through the registry, never branches on a concrete type.
|
||||
appendTypedNodes(ctx, described.added(), base, canonical, path, hasOrg, graph);
|
||||
|
||||
// BreadcrumbList (home → [collection] → this page), @id'd and linked from WebPage.breadcrumb.
|
||||
if (SiteConfig.bool(cfg, "jsonld.breadcrumbs", true) && siteUrl != null) {
|
||||
Map<String, Object> crumbs =
|
||||
breadcrumbs(base, canonical, path, ctx.page().title(), collectionParent(cfg, path, ctx));
|
||||
if (crumbs != null) {
|
||||
graph.add(crumbs);
|
||||
Ld.ref(page, "breadcrumb", (String) crumbs.get("@id"));
|
||||
}
|
||||
}
|
||||
|
||||
return Ld.script(graph);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the site's {@code SoftwareApplication} node from the {@code software.*} config. {@code name}
|
||||
* falls back to the organization name / site display name; {@code url} to the homepage; {@code offers} is
|
||||
* emitted only when a price is set (price {@code 0} = free); {@code publisher} references the Organization.
|
||||
*/
|
||||
private static Map<String, Object> softwareApplication(Map<String, Object> cfg, String base, String siteUrl,
|
||||
String canonical, String orgName, boolean hasOrg, HeadContext ctx) {
|
||||
Map<String, Object> app = Ld.node("SoftwareApplication", Ld.softwareId(base));
|
||||
String name = SiteConfig.str(cfg, "software.name", "");
|
||||
if (name.isBlank()) {
|
||||
name = orgName.isBlank() ? ctx.site().displayName() : orgName;
|
||||
}
|
||||
Ld.put(app, "name", name);
|
||||
String url = SiteConfig.str(cfg, "software.url", "");
|
||||
Ld.put(app, "url", !url.isBlank() ? url : (siteUrl != null ? siteUrl : canonical));
|
||||
Ld.put(app, "applicationCategory", SiteConfig.str(cfg, "software.category", ""));
|
||||
Ld.put(app, "operatingSystem", SiteConfig.str(cfg, "software.os", "Web"));
|
||||
String description = SiteConfig.str(cfg, "software.description", "");
|
||||
Ld.put(app, "description", description.isBlank() ? ctx.page().description() : description);
|
||||
Ld.put(app, "inLanguage", ctx.locale().toLanguageTag());
|
||||
Ld.put(app, "license", SiteConfig.str(cfg, "software.license", ""));
|
||||
Ld.put(app, "screenshot", SiteConfig.str(cfg, "software.screenshot", ""));
|
||||
String price = SiteConfig.str(cfg, "software.price", "");
|
||||
if (!price.isBlank()) {
|
||||
Map<String, Object> offer = new LinkedHashMap<>();
|
||||
offer.put("@type", "Offer");
|
||||
offer.put("price", price);
|
||||
offer.put("priceCurrency", SiteConfig.str(cfg, "software.currency", "USD"));
|
||||
app.put("offers", offer);
|
||||
}
|
||||
if (hasOrg) {
|
||||
Ld.ref(app, "publisher", Ld.organizationId(base));
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the nodes of the blocks that add an entity to the page (a product, a service, a business, a person, a
|
||||
* list), each through its registered {@link SchemaType}. The block that describes the page itself has already
|
||||
* shaped the page's own node; {@link PageTypes} decided which is which.
|
||||
*/
|
||||
private void appendTypedNodes(HeadContext ctx, List<Map<String, Object>> blocks, String base, String canonical,
|
||||
String path, boolean hasOrg, List<Map<String, Object>> graph) {
|
||||
// A path may declare SEVERAL type-blocks (e.g. an FAQPage AND a set of Offers on a pricing page);
|
||||
// dispatch each through the registry. The contributor stays type-blind — no instanceof/switch.
|
||||
for (Map<String, Object> block : blocks) {
|
||||
SchemaType type = types.get(Schemas.str(block, "type", ""));
|
||||
List<Map<String, Object>> nodes =
|
||||
type.nodes(ctx, schemaContext(ctx, base, canonical, path, hasOrg, block));
|
||||
if (nodes != null) {
|
||||
for (Map<String, Object> node : nodes) {
|
||||
if (node != null && !node.isEmpty()) {
|
||||
graph.add(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static SchemaContext schemaContext(HeadContext ctx, String base, String canonical, String path,
|
||||
boolean hasOrg, Map<String, Object> block) {
|
||||
return new SchemaContext(base, canonical, path, isHome(path, ctx), hasOrg,
|
||||
Ld.websiteId(base), Ld.webpageId(canonical), hasOrg ? Ld.organizationId(base) : null,
|
||||
block, ctx.locale());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a root-relative URL (one that starts with {@code /}) to absolute against the site base, so a
|
||||
* portable seed can ship {@code org.logo: /static/img/logo.svg} without hard-coding a host; an
|
||||
* already-absolute or blank value passes through unchanged.
|
||||
*/
|
||||
private static String absolutize(String url, String base) {
|
||||
return (url != null && url.startsWith("/") && !base.isBlank()) ? base + url : url;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path portion of the (absolute) canonical relative to the site base ({@code "/"} for the home). Guards
|
||||
* against a per-page <b>canonical override to a different host</b>: when the canonical does not start with
|
||||
* the site base (or its own origin), the raw canonical is returned — which is neither {@code "/"} nor a
|
||||
* {@code /}-rooted path, so {@code isHome()}, {@code content.schema} matching and breadcrumbs all correctly
|
||||
* treat it as "not this site's home / no path match" rather than slicing a garbage substring. Package-private
|
||||
* so the FAQ advisory can resolve a page's path the same way the render-time typing does.
|
||||
*/
|
||||
static String pathOf(String base, String canonical) {
|
||||
String origin = (base == null || base.isBlank()) ? Ld.origin(canonical) : base;
|
||||
if (!origin.isBlank() && canonical.startsWith(origin)) {
|
||||
String path = canonical.substring(origin.length());
|
||||
return path.isEmpty() ? "/" : path;
|
||||
}
|
||||
return canonical; // canonical diverges from the site base (a cross-domain per-page canonical override)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code path} addresses a homepage — the default-locale home ({@code "/"}) or a localized home
|
||||
* ({@code /<locale>}), matched against the site's actual locale set so a real 2-letter slug is not mistaken
|
||||
* for a locale prefix.
|
||||
*/
|
||||
private static boolean isHome(String path, HeadContext ctx) {
|
||||
String p = (path.length() > 1 && path.endsWith("/")) ? path.substring(0, path.length() - 1) : path;
|
||||
if (p.isEmpty() || p.equals("/")) {
|
||||
return true;
|
||||
}
|
||||
String seg = p.startsWith("/") ? p.substring(1) : p;
|
||||
Locale def = ctx.site().defaultLocale();
|
||||
for (Locale locale : ctx.site().locales()) {
|
||||
// The DEFAULT locale's home is "/" (unprefixed), never "/<code>", so a "/<default-code>" path is a
|
||||
// real page, not a home — skipping it removes the most likely code-vs-slug collision (e.g. "/en").
|
||||
if (locale.equals(def)) {
|
||||
continue;
|
||||
}
|
||||
if (seg.equalsIgnoreCase(locale.getLanguage()) || seg.equalsIgnoreCase(locale.toLanguageTag())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The site base: the site's base URL (configured, or derived from its host name), else — a host-less site,
|
||||
* such as the platform's catch-all default — the trusted origin the page is served under
|
||||
* ({@link HeadContext#origin()}, SPI 1.0.0: the request's scheme and host as the kernel's trusted-proxy gate left
|
||||
* them, never a raw {@code X-Forwarded-*} header), else the origin of an absolute canonical. {@code ""} only
|
||||
* when none is known. Until 2.1.0 a host-less site had no base here, so its graph was root-relative and carried
|
||||
* no {@code SearchAction} and no breadcrumb trail.
|
||||
*/
|
||||
static String baseFor(HeadContext ctx, String canonical) {
|
||||
String configured = ctx.site().baseUrl();
|
||||
String base;
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
base = configured.trim();
|
||||
} else if (!ctx.origin().isBlank()) {
|
||||
base = ctx.origin().trim();
|
||||
} else {
|
||||
base = Ld.origin(canonical);
|
||||
}
|
||||
return base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code canonical} made absolute against {@code base} when it is root-relative ({@code /about}); an absolute
|
||||
* canonical (the usual case, and every cross-domain override) passes through unchanged, and with no base known
|
||||
* ({@code ""}) a root-relative one stays as it is. A protocol-relative {@code //host/x} is left alone — it already
|
||||
* names a host.
|
||||
*/
|
||||
static String absolute(String canonical, String base) {
|
||||
return canonical.startsWith("/") && !canonical.startsWith("//") ? base + canonical : canonical;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a schema.org {@code SearchAction} for the site's search URL. A {@code {query}} or
|
||||
* {@code {search_term_string}} placeholder is honored; otherwise a {@code q=} parameter is appended.
|
||||
*/
|
||||
private static Map<String, Object> searchAction(String base, String searchUrl) {
|
||||
String template = searchUrl.startsWith("http")
|
||||
? searchUrl
|
||||
: base + (searchUrl.startsWith("/") ? "" : "/") + searchUrl;
|
||||
if (template.contains("{query}")) {
|
||||
template = template.replace("{query}", "{search_term_string}");
|
||||
} else if (!template.contains("{search_term_string}")) {
|
||||
template = template + (template.contains("?") ? "&" : "?") + "q={search_term_string}";
|
||||
}
|
||||
Map<String, Object> action = new LinkedHashMap<>();
|
||||
action.put("@type", "SearchAction");
|
||||
// NEVER Map.of() for a node that is serialized: java.util.Map.of randomizes iteration order PER JVM
|
||||
// INSTANCE (ImmutableCollections.SALT), so the emitted JSON-LD key order flipped on roughly every
|
||||
// other restart — stable within one run, different after the next. Found in a live deployment by an operator
|
||||
// byte-diffing homepages across an upgrade, who reasonably read it as a one-off change between builds;
|
||||
// it was not, it was every restart, forever. Harmless semantically (the graphs are equal), but it made
|
||||
// rendered output non-reproducible and quietly broke the promise of the page's strong ETag, which
|
||||
// folds metadata and templates and therefore did NOT change when the body did.
|
||||
Map<String, Object> target = new LinkedHashMap<>();
|
||||
target.put("@type", "EntryPoint");
|
||||
target.put("urlTemplate", template);
|
||||
action.put("target", target);
|
||||
action.put("query-input", "required name=search_term_string");
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code Home → [collection] → page} breadcrumb with a stable {@code @id} (so the {@code WebPage} can point
|
||||
* at it); {@code null} for the home page (or a cross-domain canonical). When {@code parent} is non-null (a
|
||||
* content.schema {@code breadcrumb: {name, url}} on a detail page under a collection) it becomes the middle
|
||||
* level, so a product's trail reads {@code Home → Coffees → Ethiopia Guji} rather than {@code Home → Guji}.
|
||||
*/
|
||||
private static Map<String, Object> breadcrumbs(String base, String canonical, String path, String pageTitle,
|
||||
Map<String, Object> parent) {
|
||||
if (path.isBlank() || path.equals("/") || !path.startsWith("/")) {
|
||||
return null; // home, or a canonical that isn't a path under this site — no breadcrumb trail
|
||||
}
|
||||
List<Map<String, Object>> items = new ArrayList<>();
|
||||
int position = 1;
|
||||
items.add(listItem(position++, "Home", base + "/"));
|
||||
if (parent != null) {
|
||||
String parentUrl = Schemas.str(parent, "url");
|
||||
items.add(listItem(position++, Schemas.str(parent, "name"),
|
||||
parentUrl != null && parentUrl.startsWith("/") ? base + parentUrl : parentUrl));
|
||||
}
|
||||
items.add(listItem(position, (pageTitle == null || pageTitle.isBlank()) ? path : pageTitle, canonical));
|
||||
Map<String, Object> list = Ld.node("BreadcrumbList", canonical + "#breadcrumb");
|
||||
list.put("itemListElement", items);
|
||||
return list;
|
||||
}
|
||||
|
||||
private static Map<String, Object> listItem(int position, String name, String item) {
|
||||
Map<String, Object> node = new LinkedHashMap<>();
|
||||
node.put("@type", "ListItem");
|
||||
node.put("position", position);
|
||||
Ld.put(node, "name", name);
|
||||
Ld.put(node, "item", item);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** The optional parent-collection level a page declares in content.schema ({@code breadcrumb: {name, url}}). */
|
||||
private static Map<String, Object> collectionParent(Map<String, Object> cfg, String path, HeadContext ctx) {
|
||||
Object entry = PageTypes.entry(cfg, path);
|
||||
for (Map<String, Object> block : PageSchemaConfig.blocks(entry)) {
|
||||
if (block.get("breadcrumb") instanceof Map<?, ?> map) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> parent = (Map<String, Object>) map;
|
||||
if (Schemas.str(parent, "name") != null && Schemas.str(parent, "url") != null) {
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("head.structured-data", "head.per-locale", "head.geo");
|
||||
}
|
||||
|
||||
/**
|
||||
* This contributor's whole per-site input: its own settings file.
|
||||
*
|
||||
* <p>Declared so the kernel can fold it into each page's {@code ETag}. Head markup is spliced in at the
|
||||
* response edge, <b>after</b> the page validator has been computed and may already have answered
|
||||
* {@code 304} — so without this, changing a per-site setting here (organisation name, GEO, the search URL)
|
||||
* changed the delivered page and not its validator, and every client and CDN holding the old one kept the
|
||||
* previous markup indefinitely.
|
||||
*/
|
||||
@Override
|
||||
public java.util.List<String> headInputs(String siteId) {
|
||||
return java.util.List.of("plugins/discoverability.yml");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.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.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The membership-aware crawl validator: {@code Last-Modified} must advance on ANY document change — including
|
||||
* removals, which a naive {@code max(updatedAt)} can never see (deleting an item only removes an mtime from
|
||||
* the pool) — while staying stable for unchanged documents so revalidating crawlers actually get their 304s.
|
||||
* Time is injected via the class's clock hook; {@code reset()} simulates a restart.
|
||||
*/
|
||||
class CrawlConditionalTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN), null);
|
||||
private static final Instant T0 = Instant.parse("2026-07-17T10:00:00Z");
|
||||
|
||||
private Instant now;
|
||||
|
||||
@BeforeEach
|
||||
void freezeClock() {
|
||||
CrawlConditional.reset();
|
||||
now = T0;
|
||||
CrawlConditional.clock = () -> now;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreClock() {
|
||||
CrawlConditional.reset();
|
||||
}
|
||||
|
||||
private static CatalogEntry item(String id, Instant updatedAt) {
|
||||
return Entries.of("blog", new ContentRef(id, "/blog/" + id, Map.of(), List.of(EN),
|
||||
Map.of("en", id), Map.of(), "", "__site__/acme/e", true, updatedAt, false, null, null, Map.of()), SITE);
|
||||
}
|
||||
|
||||
private static RouteRequest revalidating(Instant lastModified) {
|
||||
Map<String, String> headers = Map.of("If-Modified-Since",
|
||||
CrawlConditional.cacheHeaders(lastModified, null).get("Last-Modified"));
|
||||
return new RouteRequest(SITE, EN, "GET", "/sitemap.xml", Map.of(), headers, new byte[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedDocumentKeepsItsValidatorSoRevalidationYields304() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant first = CrawlConditional.lastModified("acme", items);
|
||||
now = T0.plusSeconds(300);
|
||||
Instant later = CrawlConditional.lastModified("acme", items);
|
||||
assertEquals(first, later, "an unchanged document keeps a stable validator");
|
||||
assertTrue(CrawlConditional.notModified(revalidating(first), later), "a revalidating crawler gets 304");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRemovalAdvancesTheValidatorSoStaleCopiesAreRefetched() {
|
||||
// The naive max(updatedAt) blind spot: deleting an item only REMOVES an mtime — the max never moves.
|
||||
CatalogEntry a = item("a", T0.minusSeconds(7200));
|
||||
CatalogEntry b = item("b", T0.minusSeconds(3600));
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(a, b));
|
||||
|
||||
now = T0.plusSeconds(600); // the entry is deleted ten minutes later
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(a));
|
||||
assertTrue(after.isAfter(before), "a removal must advance the validator");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after),
|
||||
"a crawler holding the pre-removal copy gets a fresh 200, never a stale 304");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAdditionWithoutUpdatedAtStillAdvances() {
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(item("a", T0.minusSeconds(3600))));
|
||||
now = T0.plusSeconds(60);
|
||||
Instant after = CrawlConditional.lastModified("acme",
|
||||
List.of(item("a", T0.minusSeconds(3600)), item("new", null)));
|
||||
assertTrue(after.isAfter(before), "a new null-updatedAt item is still a document change");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFutureMtimeCannotPinTheValidator() {
|
||||
// Clock skew / a touched file: a future updatedAt would otherwise mask every later real change.
|
||||
Instant seeded = CrawlConditional.lastModified("acme", List.of(item("a", T0.plusSeconds(86400))));
|
||||
assertFalse(seeded.isAfter(now), "the validator is clamped to now, never in the future");
|
||||
now = T0.plusSeconds(120);
|
||||
Instant advanced = CrawlConditional.lastModified("acme",
|
||||
List.of(item("a", T0.plusSeconds(86400)), item("b", null)));
|
||||
assertTrue(advanced.isAfter(seeded), "later changes still advance past the clamped value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSameSecondChangeIsReDetectedOnceTheClockMoves() {
|
||||
// A change landing in the same second as the previous advance cannot advance a second-granular
|
||||
// validator — the state must NOT absorb it (or it would 304 forever); the next request re-detects it.
|
||||
Instant seeded = CrawlConditional.lastModified("acme", List.of(item("a", null), item("b", null)));
|
||||
Instant sameSecond = CrawlConditional.lastModified("acme", List.of(item("a", null)));
|
||||
assertEquals(seeded, sameSecond, "within the same second the validator cannot advance yet");
|
||||
now = T0.plusSeconds(1);
|
||||
Instant next = CrawlConditional.lastModified("acme", List.of(item("a", null)));
|
||||
assertTrue(next.isAfter(seeded), "the held change advances as soon as the clock moves");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restartSeedsWithNowSoAcrossRestartRemovalsAreNeverMasked() {
|
||||
Instant before = CrawlConditional.lastModified("acme",
|
||||
List.of(item("a", T0.minusSeconds(7200)), item("b", T0.minusSeconds(3600))));
|
||||
CrawlConditional.reset(); // the app restarts; the entry was deleted while it was down
|
||||
CrawlConditional.clock = () -> now;
|
||||
now = T0.plusSeconds(900);
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(item("a", T0.minusSeconds(7200))));
|
||||
assertTrue(after.isAfter(before), "seeding with now (not the content mtime) covers the restart gap");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after),
|
||||
"a crawler from before the restart re-fetches and drops the removed URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* A change of the host-computed URLs alone — the site starts serving a second locale, so every item gains an
|
||||
* alternate — reshapes the sitemap while no item's id, path, mtime or indexability moves. 1.x left it out of the
|
||||
* fingerprint, so a revalidating crawler kept the old document; since 2.0.0 the URLs are part of it.
|
||||
*/
|
||||
@Test
|
||||
void aChangeOfTheComputedUrlsAloneAdvancesTheValidator() {
|
||||
ContentRef ref = new ContentRef("a", "/a", Map.of(), List.of(EN, ES), Map.of("en", "a"), Map.of(), "",
|
||||
"__site__/acme/a", true, T0.minusSeconds(3600), false, null, null, Map.of());
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", ref, SITE)));
|
||||
now = T0.plusSeconds(60);
|
||||
SiteView bilingual = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", ref, bilingual)));
|
||||
assertTrue(after.isAfter(before), "a new alternate is a document change");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after));
|
||||
}
|
||||
|
||||
/** …and so does a canonical override appearing (it moves the item out of the sitemap). */
|
||||
@Test
|
||||
void aNewCanonicalOverrideAdvancesTheValidator() {
|
||||
ContentRef plain = new ContentRef("a", "/a", Map.of(), List.of(EN), Map.of("en", "a"), Map.of(), "",
|
||||
"__site__/acme/a", true, null, false, null, null, Map.of());
|
||||
ContentRef elsewhere = new ContentRef("a", "/a", Map.of(), List.of(EN), Map.of("en", "a"), Map.of(), "",
|
||||
"__site__/acme/a", true, null, false, "https://other.test/a", null, Map.of());
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", plain, SITE)));
|
||||
now = T0.plusSeconds(60);
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", elsewhere, SITE)));
|
||||
assertTrue(after.isAfter(before));
|
||||
}
|
||||
|
||||
// --- document-level facts (2.1.0) -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* llms.txt prints the site name and {@code geo.summary}, which no catalog item carries; until 2.1.0 the validator
|
||||
* folded the items only, so editing either changed the document while a revalidating crawler kept its copy.
|
||||
*/
|
||||
@Test
|
||||
void aChangedDocumentFactAdvancesTheValidator() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant before = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
List.of("Acme", "We build things."));
|
||||
now = T0.plusSeconds(60);
|
||||
assertEquals(before, CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
List.of("Acme", "We build things.")), "unchanged facts keep the validator");
|
||||
Instant after = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
List.of("Acme", "We build better things."));
|
||||
assertEquals(now, after, "a fact carries no mtime of its own, so the change advances to now");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after));
|
||||
}
|
||||
|
||||
/** Facts are length-prefixed: moving characters from one fact to the next is a different document. */
|
||||
@Test
|
||||
void factsCannotAliasByShiftingCharactersAcrossTheBoundary() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant before = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("Acme", "Co"));
|
||||
now = T0.plusSeconds(60);
|
||||
Instant after = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("AcmeC", "o"));
|
||||
assertTrue(after.isAfter(before), "['Acme','Co'] and ['AcmeC','o'] are different documents");
|
||||
now = T0.plusSeconds(120);
|
||||
Instant nulled = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
java.util.Arrays.asList("AcmeC", null));
|
||||
assertTrue(nulled.isAfter(after), "a fact that disappears is a change too (null folds as empty)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Each document keeps its own validator: llms.txt folds facts the sitemap does not, and one shared record per
|
||||
* site would let the two documents advance each other's validator on every alternate request.
|
||||
*/
|
||||
@Test
|
||||
void theSitemapAndLlmsTxtKeepSeparateValidators() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant sitemap = CrawlConditional.lastModified("acme", items);
|
||||
now = T0.plusSeconds(60);
|
||||
CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("Acme", "One"));
|
||||
now = T0.plusSeconds(120);
|
||||
CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("Acme", "Two"));
|
||||
now = T0.plusSeconds(180);
|
||||
assertEquals(sitemap, CrawlConditional.lastModified("acme", items),
|
||||
"llms.txt's changes do not move the sitemap's validator");
|
||||
assertEquals(sitemap, CrawlConditional.lastModified("acme", CrawlConditional.SITEMAP, items, List.of()),
|
||||
"the two-argument form is the sitemap's");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The settings change that came with the SPI: 1.x read only the values a site had STORED and applied its own code
|
||||
* fallbacks; since 2.0.0 the host's {@code PluginSettings} applies the descriptor's declared {@code default:}s first.
|
||||
* If a code fallback and its declared default ever disagreed, an unchanged site would render differently after the
|
||||
* upgrade. This renders every surface twice — with the declared defaults applied and with none — for a site that
|
||||
* stored nothing, and for one that stored blank values the form may write, and requires identical bytes.
|
||||
*/
|
||||
class DescriptorDefaultsTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
|
||||
/** Stored values a site may hold without meaning anything: blank fields the settings form saved. */
|
||||
private static final Map<String, Object> BLANKS = Map.ofEntries(
|
||||
Map.entry("jsonld.type", ""), Map.entry("robots.ai-policy", ""), Map.entry("robots.ai-training", ""),
|
||||
Map.entry("robots.ai-retrieval", ""), Map.entry("robots.ai-user", ""), Map.entry("geo.speakable", ""),
|
||||
Map.entry("software.os", ""), Map.entry("software.currency", ""), Map.entry("org.sameas", ""),
|
||||
Map.entry("geo.enabled", true), Map.entry("software.enabled", true), Map.entry("software.name", "App"),
|
||||
Map.entry("software.price", "0"));
|
||||
|
||||
@BeforeEach
|
||||
void freshValidators() {
|
||||
CrawlConditional.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDeclaredDefaultsAreTheCodeFallbacks() {
|
||||
// Every key with a declared default — so a key added later without its twin in code fails here.
|
||||
assertEquals(java.util.Set.of("jsonld.enabled", "jsonld.type", "jsonld.breadcrumbs", "org.sameas",
|
||||
"sitemap.enabled", "robots.ai-policy", "robots.ai-training", "robots.ai-retrieval",
|
||||
"robots.ai-user", "geo.enabled", "geo.speakable", "software.enabled", "software.os",
|
||||
"software.currency", "indexnow.enabled"),
|
||||
TestSettings.declaredDefaults().keySet(), "the set of declared per-site defaults this test covers");
|
||||
for (Map<String, Object> stored : List.of(Map.<String, Object>of(), BLANKS,
|
||||
Map.<String, Object>of("geo.enabled", true, "software.enabled", true, "software.name", "App",
|
||||
"software.price", "0", "org.name", "Acme Corp"))) {
|
||||
assertEquals(render(TestSettings.bare().site("acme", stored)),
|
||||
render(TestSettings.declared().site("acme", stored)), "stored: " + stored);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRenderingIsNotTriviallyEmpty() {
|
||||
String all = render(TestSettings.declared().site("acme", Map.of("geo.enabled", true)));
|
||||
assertFalse(all.isBlank());
|
||||
for (String part : List.of("\"@type\":\"WebSite\"", "SpeakableSpecification", "<urlset", "## Pages",
|
||||
"User-agent: *", "Sitemap: https://acme.test/sitemap.xml")) {
|
||||
assertTrue(all.contains(part), "the comparison covers " + part);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every settings-driven surface, concatenated: head JSON-LD, robots.txt, sitemap, llms.txt, card values. */
|
||||
private static String render(PluginSettings settings) {
|
||||
CrawlConditional.reset();
|
||||
ContentRef about = ContentRef.of("about", "/about", Map.of(), List.of(EN), Map.of("en", "About"),
|
||||
Map.of("en", "Who"), "__site__/acme/about", Instant.parse("2026-07-17T10:00:00Z"));
|
||||
ContentRef home = ContentRef.of("index", "/", Map.of(), List.of(EN), Map.of("en", "Home"), Map.of(),
|
||||
"__site__/acme/index", Instant.parse("2026-07-17T10:00:00Z"));
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", Entries.page(home, SITE)).entry("acme", Entries.page(about, SITE));
|
||||
StringBuilder out = new StringBuilder();
|
||||
StructuredDataHead head = new StructuredDataHead(settings, Map.of());
|
||||
for (String path : List.of("/", "/about")) {
|
||||
PageMeta meta = new PageMeta(path.equals("/") ? "index" : "about", "T", "D", List.of(EN), EN, true, false);
|
||||
out.append(head.render(new HeadContext(SITE, meta, EN, "https://acme.test" + path,
|
||||
"https://acme.test" + path, List.of(), false, false))).append('\n');
|
||||
}
|
||||
DiscoverabilityProperties props = new DiscoverabilityProperties();
|
||||
out.append(text(new RobotsTxtEndpoint(settings, props).handle(req("/robots.txt"))));
|
||||
out.append(text(new SitemapEndpoint(catalog, settings).handle(req("/sitemap.xml"))));
|
||||
out.append(text(new LlmsTxtEndpoint(catalog, settings).handle(req("/llms.txt"))));
|
||||
out.append(new IndexNowKeyEndpoint(settings, props).handle(req("/indexnow-key.txt")).status()).append('\n');
|
||||
DiscoverAdminModel model = new DiscoverAdminModel(settings, catalog);
|
||||
out.append(model.jsonldEnabled("acme")).append(model.jsonldType("acme")).append(model.sitemapEnabled("acme"))
|
||||
.append(model.geoEnabled("acme")).append(model.orgConfigured("acme")).append('\n');
|
||||
out.append(new FaqAdvisoryCheck(settings).inspect(new PageView(SITE,
|
||||
new PageMeta("faq", "F", "", List.of(EN), EN, true, false), EN, "https://acme.test/faq",
|
||||
"<details><summary>a</summary>b</details><details><summary>c</summary>d</details>")));
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static RouteRequest req(String path) {
|
||||
return new RouteRequest(SITE, EN, "GET", path, Map.of(), Map.of(), new byte[0], Map.of(), null, "");
|
||||
}
|
||||
|
||||
private static String text(mx.quest.runway.spi.model.RouteResponse response) {
|
||||
return response.status() + "\n" + new String(response.body(), StandardCharsets.UTF_8) + "\n";
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
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.EndpointContributor;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
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.FakeSiteServices;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host, checked at build time: the wiring over SPI services only, the bean-name rule,
|
||||
* the bean names the templates reference, the app-level settings binding, the descriptor (SPI floor, release
|
||||
* version) and that the compiled classes link nothing of the host but the SPI — the same things the kernel's
|
||||
* load-time checks warn about (and refuse from Runway 1.0).
|
||||
*/
|
||||
class DiscoverabilityConfigTest {
|
||||
|
||||
private static final String PREFIX = "discoverability";
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(DiscoverabilityConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromSpiServicesUnderPrefixedNamesAndBindsTheAppSettings() {
|
||||
SiteView acme = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().entry("acme", Entries.page(
|
||||
ContentRef.of("about", "/about", Map.of(), List.of(EN), Map.of("en", "About"), Map.of(),
|
||||
"__site__/acme/about", null), acme));
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
// What the host provides: the SPI services, and Spring Boot's @ConfigurationProperties binding.
|
||||
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("app-level", Map.of(
|
||||
"runway.plugin.discoverability.indexnow.enabled", "true",
|
||||
"runway.plugin.discoverability.indexnow.max-urls-per-submission", "7",
|
||||
"runway.plugin.discoverability.robots.ai-default", "disallow")));
|
||||
ConfigurationPropertiesBindingPostProcessor.register(ctx);
|
||||
ctx.registerBean(PluginSettings.class, () -> TestSettings.declared().site("acme", Map.of("org.name", "Acme")));
|
||||
ctx.registerBean(ContentCatalogView.class, () -> catalog);
|
||||
ctx.registerBean(Sites.class, () -> new FakeSiteServices().site(acme));
|
||||
ctx.register(DiscoverabilityConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
for (String name : ctx.getBeanDefinitionNames()) {
|
||||
if (ctx.getBeanFactory().getBeanDefinition(name).getFactoryBeanName() != null) {
|
||||
assertTrue(name.startsWith(PREFIX), "every plugin bean carries the plugin id: " + name);
|
||||
}
|
||||
}
|
||||
assertInstanceOf(StructuredDataHead.class, ctx.getBean("discoverabilityStructuredData", HeadContributor.class));
|
||||
assertInstanceOf(SitemapEndpoint.class, ctx.getBean("discoverabilitySitemap", EndpointContributor.class));
|
||||
assertInstanceOf(LlmsTxtEndpoint.class, ctx.getBean("discoverabilityLlms", EndpointContributor.class));
|
||||
assertInstanceOf(RobotsTxtEndpoint.class, ctx.getBean("discoverabilityRobots", EndpointContributor.class));
|
||||
assertInstanceOf(IndexNowKeyEndpoint.class,
|
||||
ctx.getBean("discoverabilityIndexNowKey", EndpointContributor.class));
|
||||
assertInstanceOf(FaqAdvisoryCheck.class, ctx.getBean("discoverabilityFaqAdvisory", PageQualityCheck.class));
|
||||
assertEquals(List.of("discoverabilityIndexNow"), List.of(ctx.getBeanNamesForType(SiteEventListener.class)),
|
||||
"IndexNow is collected by the host as a SiteEventListener");
|
||||
|
||||
DiscoverabilityProperties props = ctx.getBean("discoverabilityProperties", DiscoverabilityProperties.class);
|
||||
assertTrue(props.getIndexnow().isEnabled(), "app-level settings bind through the named @Bean");
|
||||
assertEquals(7, props.getIndexnow().getMaxUrlsPerSubmission());
|
||||
assertEquals("disallow", props.getRobots().getAiDefault());
|
||||
assertEquals(1, ctx.getBeanNamesForType(DiscoverabilityProperties.class).length,
|
||||
"one properties bean — no second one under @EnableConfigurationProperties' generated name");
|
||||
|
||||
DiscoverAdminModel model = ctx.getBean("discoverabilityAdminModel", DiscoverAdminModel.class);
|
||||
assertEquals(1, model.pageCount("acme"), "the admin model counts the injected listing");
|
||||
assertTrue(model.orgConfigured("acme"), "…and reads the injected settings");
|
||||
assertEquals(0, model.pageCount("other"));
|
||||
assertEquals(0, model.pageCount(null), "no tenant bound → 0, not an error page");
|
||||
assertEquals(0, model.pageCount("../x"), "a malformed id → 0, not an error page");
|
||||
assertTrue(model.jsonldEnabled(null), "no tenant → the defaults");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
|
||||
assertEquals(Set.of("discoverabilityProperties", "discoverabilityStructuredData", "discoverabilitySitemap",
|
||||
"discoverabilityLlms", "discoverabilityRobots", "discoverabilityIndexNowKey", "discoverabilityIndexNow",
|
||||
"discoverabilityFaqAdvisory", "discoverabilityPageType", "discoverabilityAdminModel"),
|
||||
beanMethodNames());
|
||||
for (Method m : DiscoverabilityConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
assertEquals(0, bean.name().length + bean.value().length,
|
||||
"the bean name is the method name (" + m.getName() + "), never an alias to keep in sync");
|
||||
}
|
||||
}
|
||||
assertFalse(DiscoverabilityConfig.class.isAnnotationPresent(
|
||||
org.springframework.boot.context.properties.EnableConfigurationProperties.class),
|
||||
"@EnableConfigurationProperties would register an unprefixed bean name");
|
||||
}
|
||||
|
||||
@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("\\$\\{\\s*!?\\s*@(\\w+)").matcher(live);
|
||||
while (m.find()) {
|
||||
referenced.add(m.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of("discoverabilityAdminModel"), referenced, "the console templates read the admin model only");
|
||||
assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException {
|
||||
Map<String, Object> yml = TestSettings.descriptor();
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"),
|
||||
"HeadContext.origin() (a host-less site's absolute JSON-LD) arrived in SPI 1.0.0");
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-discoverability</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals("2.3.0", version.group(1));
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree");
|
||||
String defaultBuild = pom.substring(0, pom.indexOf("<profiles>"));
|
||||
assertFalse(defaultBuild.contains("<artifactId>runway-app</artifactId>"),
|
||||
"no runway-app dependency outside the host-it profile");
|
||||
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T18:56:00Z</project.build.outputTimestamp>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePluginStoresNoPerSiteFilesSoItDeclaresNoPersonalData() {
|
||||
assertFalse(TestSettings.descriptor().containsKey("siteData"),
|
||||
"nothing under sites/<id>/plugins/discoverability/ — its settings file is not personal data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternals() throws IOException {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
int scanned = 0;
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
|
||||
scanned++;
|
||||
String rel = classes.relativize(file).toString().replace('\\', '/');
|
||||
if (rel.startsWith("mx/quest/runway/")) {
|
||||
problems.add(rel + " lives under mx.quest.runway");
|
||||
}
|
||||
// The constant pool holds class names and descriptors as (modified) UTF-8; Latin-1 keeps every
|
||||
// byte as one char, so an ASCII pattern finds them without parsing the class file.
|
||||
Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
|
||||
while (m.find()) {
|
||||
problems.add(rel + " → " + m.group());
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(scanned >= 25, "the compiled classes were found (" + scanned + ")");
|
||||
assertTrue(problems.isEmpty(), "host linkage: " + problems);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Builds the {@link CatalogEntry} the host would list for a {@link ContentRef}, applying the kernel's documented URL
|
||||
* rule (its single URL authority, mirrored here so unit tests need no kernel): one URL per <b>available</b> locale —
|
||||
* the item's declared locales the site serves, else the site default — each the locale's localized path under
|
||||
* {@code /<lang>} (no prefix for the site default); the canonical of each URL is the item's override as given; the
|
||||
* {@code x-default} is the primary locale's URL, or — when the site does not serve the primary — the first available
|
||||
* locale's (SPI 1.0.0; until then it was clamped to the site default, an address the item may not exist at).
|
||||
* The host-it profile checks this mirror against the real kernel ({@code HostCatalogParityTest}).
|
||||
*/
|
||||
final class Entries {
|
||||
|
||||
private Entries() {
|
||||
}
|
||||
|
||||
static CatalogEntry of(String sourceKey, ContentRef ref, SiteView site) {
|
||||
Locale def = site.defaultLocale();
|
||||
List<Locale> available = new ArrayList<>();
|
||||
for (Locale locale : ref.locales()) {
|
||||
if (site.locales().contains(locale)) {
|
||||
available.add(locale);
|
||||
}
|
||||
}
|
||||
if (available.isEmpty()) {
|
||||
available.add(def);
|
||||
}
|
||||
List<LocalizedUrl> urls = new ArrayList<>();
|
||||
for (Locale locale : available) {
|
||||
urls.add(new LocalizedUrl(locale, url(ref, locale, def), ref.canonical()));
|
||||
}
|
||||
Locale primary = ref.primaryLocale(def);
|
||||
if (!site.locales().contains(primary)) {
|
||||
primary = available.get(0);
|
||||
}
|
||||
return new CatalogEntry(sourceKey, ref, urls, url(ref, primary, def));
|
||||
}
|
||||
|
||||
static CatalogEntry page(ContentRef ref, SiteView site) {
|
||||
return of("pages", ref, site);
|
||||
}
|
||||
|
||||
private static String url(ContentRef ref, Locale locale, Locale def) {
|
||||
String path = ref.pathFor(locale);
|
||||
return locale.equals(def) ? path : "/" + locale.getLanguage() + path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* FaqAdvisoryCheck: flags an unmarked on-page FAQ ({@code <details>/<summary>} clusters), stays silent below the
|
||||
* threshold, when there's no FAQ, on a noindex page, and when the head renders the page as an {@code FAQPage}.
|
||||
*/
|
||||
class FaqAdvisoryCheckTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final FaqAdvisoryCheck check = new FaqAdvisoryCheck(config);
|
||||
|
||||
private void cfg(Map<String, Object> map) {
|
||||
config.site("acme", map);
|
||||
}
|
||||
|
||||
private static final String TWO_FAQ =
|
||||
"<main><details><summary>Why ranges?</summary>Scope drives cost.</details>"
|
||||
+ "<details><summary>Fixed fee?</summary>Yes, usually.</details></main>";
|
||||
|
||||
private static PageView page(String path, String html) {
|
||||
return page(path, html, false);
|
||||
}
|
||||
|
||||
private static PageView page(String path, String html, boolean noindex) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta meta = new PageMeta(path.substring(1), "T", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
noindex);
|
||||
return new PageView(site, meta, Locale.ENGLISH, "https://acme.test" + path, html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void flagsAnUnmarkedOnPageFaq() {
|
||||
cfg(Map.of()); // no content.schema → the FAQ is not typed
|
||||
List<Finding> found = check.inspect(page("/pricing", TWO_FAQ));
|
||||
assertEquals(1, found.size(), found.toString());
|
||||
assertEquals("discoverability.faq.unmarked", found.get(0).code());
|
||||
assertEquals("INFO", found.get(0).severity().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentWhenTheFaqIsAlreadyTyped() {
|
||||
cfg(Map.of("content.schema", "/pricing:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n"));
|
||||
assertTrue(check.inspect(page("/pricing", TWO_FAQ)).isEmpty(), "already FAQPage-typed → no nag");
|
||||
}
|
||||
|
||||
/** "Already typed" means the head renders the page as an FAQPage, the same answer PageTypes gives it. */
|
||||
@Test
|
||||
void aTypeTheHeadDoesNotApplyDoesNotCountAsTyped() {
|
||||
cfg(Map.of("content.schema", "/pricing:\n type: faqpage\n faq:\n - { q: Q, a: A }\n"));
|
||||
List<Finding> misspelt = check.inspect(page("/pricing", TWO_FAQ));
|
||||
assertEquals(1, misspelt.size(), "faqpage is an unknown type, the page is a WebPage: " + misspelt);
|
||||
assertEquals("discoverability.faq.unmarked", misspelt.get(0).code());
|
||||
cfg(Map.of("content.schema",
|
||||
"/pricing:\n - type: AboutPage\n - type: FAQPage\n faq:\n - { q: Q, a: A }\n"));
|
||||
assertEquals(1, check.inspect(page("/pricing", TWO_FAQ)).size(),
|
||||
"a second page type is ignored, so the page is an AboutPage");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentWhenStructuredDataIsOff() {
|
||||
cfg(Map.of("jsonld.enabled", false));
|
||||
assertTrue(check.inspect(page("/pricing", TWO_FAQ)).isEmpty(), "the head publishes no JSON-LD at all");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentOnANoindexPage() {
|
||||
cfg(Map.of());
|
||||
assertTrue(check.inspect(page("/pricing", TWO_FAQ, true)).isEmpty(), "noindex pages carry no structured data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentBelowTheDisclosureThreshold() {
|
||||
cfg(Map.of());
|
||||
assertTrue(check.inspect(page("/x", "<details><summary>Q</summary>A</details>")).isEmpty(),
|
||||
"a lone <details> is a 'read more', not an FAQ");
|
||||
assertTrue(check.inspect(page("/y", "<p>no faq here</p>")).isEmpty(), "no disclosures at all");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentOnEmptyHtml() {
|
||||
cfg(Map.of());
|
||||
assertTrue(check.inspect(page("/z", "")).isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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 static org.mockito.Mockito.mock;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.content.ContentCatalog;
|
||||
import mx.quest.runway.content.ContentCatalogViewImpl;
|
||||
import mx.quest.runway.content.ContentSourceRegistry;
|
||||
import mx.quest.runway.content.RoutableContent;
|
||||
import mx.quest.runway.page.ContentUrls;
|
||||
import mx.quest.runway.page.LocaleUrls;
|
||||
import mx.quest.runway.page.PageStore;
|
||||
import mx.quest.runway.page.RenderModelBuilder;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.model.Alternate;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* host-it: the sitemap and llms.txt over the REAL kernel catalog ({@code ContentCatalog} behind the kernel's
|
||||
* {@code ContentCatalogViewImpl}), compared with what 1.6.0 computed from the same catalog through the kernel's URL
|
||||
* builders ({@code ContentUrls}, {@code LocaleUrls}) — the before/after proof at unit level, plus the head-vs-sitemap
|
||||
* agreement and the test fixture mirror ({@code Entries}) checked against the kernel.
|
||||
*/
|
||||
class HostCatalogParityTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final Locale FR = Locale.FRENCH;
|
||||
private static final Instant T = Instant.parse("2026-07-17T10:00:00Z");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
|
||||
private static ContentRef ref(String id, String path, Map<String, String> localized, List<Locale> locales,
|
||||
boolean published, boolean noindex, String canonical) {
|
||||
return new ContentRef(id, path, localized, locales, Map.of("en", "T " + id, "es", "T-es " + id),
|
||||
Map.of("en", "D " + id), null, "__site__/acme/" + id, published, T, noindex, canonical, null, Map.of());
|
||||
}
|
||||
|
||||
/** Everything the URL rule distinguishes: locales, localized slugs, an unserved locale, canonicals, noindex. */
|
||||
private static final List<ContentRef> PAGES = List.of(
|
||||
ref("index", "/", Map.of(), List.of(EN, ES), true, false, null),
|
||||
ref("about", "/about", Map.of("es", "/acerca"), List.of(EN, ES), true, false, null),
|
||||
ref("en-only", "/en-only", Map.of(), List.of(), true, false, null),
|
||||
ref("fr-and-es", "/fr-es", Map.of(), List.of(FR, ES), true, false, null),
|
||||
ref("french", "/french", Map.of(), List.of(FR), true, false, null),
|
||||
ref("es-only", "/solo", Map.of("es", "/solo-es"), List.of(ES), true, false, null),
|
||||
ref("draft", "/draft", Map.of(), List.of(EN), false, false, null),
|
||||
ref("hidden", "/hidden", Map.of(), List.of(EN), true, true, null),
|
||||
ref("dupe", "/dupe", Map.of(), List.of(EN), true, false, "https://acme.test/about"),
|
||||
ref("self", "/self", Map.of(), List.of(EN), true, false, "https://acme.test/self"),
|
||||
ref("reserved", "/login", Map.of(), List.of(EN), true, false, null));
|
||||
private static final List<ContentRef> POSTS = List.of(
|
||||
ref("hello", "/blog/hello", Map.of("es", "/blog/hola"), List.of(EN, ES), true, false, null));
|
||||
|
||||
private static ContentSource source(String key, List<ContentRef> refs) {
|
||||
return new ContentSource() {
|
||||
@Override public String key() { return key; }
|
||||
@Override public List<ContentRef> enumerate(SiteView site) { return refs; }
|
||||
@Override public ContentBody body(SiteView site, String id, Locale locale) {
|
||||
throw new IllegalStateException("the crawl surfaces never read a body");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private ContentCatalog catalog;
|
||||
private ContentCatalogViewImpl view;
|
||||
|
||||
@BeforeEach
|
||||
void kernel() {
|
||||
CrawlConditional.reset();
|
||||
ContentSource broken = new ContentSource() {
|
||||
@Override public String key() { return "broken"; }
|
||||
@Override public List<ContentRef> enumerate(SiteView site) { throw new IllegalStateException("boom"); }
|
||||
@Override public ContentBody body(SiteView site, String id, Locale locale) { return ContentBody.empty(); }
|
||||
};
|
||||
catalog = new ContentCatalog(new ContentSourceRegistry(
|
||||
List.of(source("pages", PAGES), broken, source("blog", POSTS))));
|
||||
view = new ContentCatalogViewImpl(catalog, new FakeSiteServices().site(SITE), mock(PageStore.class));
|
||||
}
|
||||
|
||||
private static RouteRequest req(String path) {
|
||||
return new RouteRequest(SITE, EN, "GET", path, Map.of(), Map.of(), new byte[0], Map.of(), null, "");
|
||||
}
|
||||
|
||||
private static String body(mx.quest.runway.spi.model.RouteResponse r) {
|
||||
assertEquals(200, r.status());
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTestFixtureMirrorBuildsExactlyTheKernelsEntries() {
|
||||
for (CatalogEntry kernelEntry : view.entries("acme")) {
|
||||
assertEquals(kernelEntry, Entries.of(kernelEntry.sourceKey(), kernelEntry.ref(), SITE),
|
||||
kernelEntry.compositeId());
|
||||
}
|
||||
assertEquals(10, view.entries("acme").size(),
|
||||
"the published, unreserved items of the healthy sources (noindex is listed; the sitemap drops it)");
|
||||
}
|
||||
|
||||
/**
|
||||
* The 2.0.0 sitemap over the kernel's listing equals the document 1.6.0 built from the same catalog with the
|
||||
* kernel's builders — except the one documented fix in this fixture: none (the fixture's canonicals are absolute).
|
||||
*/
|
||||
@Test
|
||||
void theSitemapIsTheOneOnePointSixBuiltFromTheSameCatalog() {
|
||||
String now = body(new SitemapEndpoint(view, TestSettings.declared()).handle(req("/sitemap.xml")));
|
||||
assertEquals(sitemapAsOnePointSixBuiltIt(), now);
|
||||
assertFalse(now.contains("/draft") || now.contains("/login") || now.contains("/hidden")
|
||||
|| now.contains("/dupe"), now);
|
||||
assertTrue(now.contains("<loc>https://acme.test/blog/hola</loc>") == false
|
||||
&& now.contains("<loc>https://acme.test/es/blog/hola</loc>"), "a healthy source survives a broken one");
|
||||
}
|
||||
|
||||
/**
|
||||
* llms.txt equals 1.6.0's except where an item does not exist at the address 1.6.0 linked (an item missing from
|
||||
* the default locale, fixed in 2.0.0) and — from the SPI 1.0.0 kernel — an item whose primary locale the site does
|
||||
* not serve, whose x-default is now its first available locale's real address.
|
||||
*/
|
||||
@Test
|
||||
void llmsTxtIsTheOneOnePointSixBuiltExceptTheN6Fix() {
|
||||
String now = body(new LlmsTxtEndpoint(view, TestSettings.declared().site("acme", Map.of("geo.enabled", true)))
|
||||
.handle(req("/llms.txt")));
|
||||
String before = llmsAsOnePointSixBuiltIt();
|
||||
assertEquals(before.replace("(https://acme.test/solo)", "(https://acme.test/es/solo-es)")
|
||||
.replace("(https://acme.test/fr-es)", "(https://acme.test/es/fr-es)"), now,
|
||||
"only the two items that do not exist at the unprefixed path moved — to their real Spanish URLs");
|
||||
assertTrue(before.contains("(https://acme.test/solo)"), "1.6.0 linked the unprefixed path, which 404s");
|
||||
// fr-and-es: French first, Spanish served. Before SPI 1.0.0 the kernel clamped its x-default to the site
|
||||
// default, so CatalogEntry.pathFor fell back to the unprefixed /fr-es (a 404), as 1.6.0 did.
|
||||
assertTrue(before.contains("(https://acme.test/fr-es)"), before);
|
||||
assertTrue(now.contains("(https://acme.test/es/fr-es)"), now);
|
||||
}
|
||||
|
||||
@Test
|
||||
void headAlternatesAndSitemapAlternatesProvablyAgree() {
|
||||
String xml = body(new SitemapEndpoint(view, TestSettings.declared()).handle(req("/sitemap.xml")));
|
||||
for (RoutableContent item : catalog.enumerate(SITE)) {
|
||||
if (item.ref().noindex() || item.ref().canonical() != null) {
|
||||
continue;
|
||||
}
|
||||
List<Alternate> head = new RenderModelBuilder()
|
||||
.headContext(SITE, item, EN, "https://acme.test", false).alternates();
|
||||
for (Alternate alternate : head) {
|
||||
String link = "hreflang=\"" + alternate.hreflang() + "\" href=\"" + alternate.url() + "\"";
|
||||
assertTrue(xml.contains(link), "the sitemap carries the head's exact alternate: " + link);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 1.6.0's algorithms, verbatim in substance, over the kernel's builders --------------------------------
|
||||
|
||||
private String sitemapAsOnePointSixBuiltIt() {
|
||||
String base = "https://acme.test";
|
||||
record Entry(String url, String block, String lastmod) { }
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
for (RoutableContent item : catalog.enumerate(SITE)) {
|
||||
if (item.ref().noindex()) {
|
||||
continue;
|
||||
}
|
||||
List<Alternate> alternates = ContentUrls.alternates(item, SITE, base);
|
||||
String xDefault = ContentUrls.xDefault(item, SITE, base);
|
||||
String canonical = item.ref().canonical();
|
||||
if (canonical != null && !canonical.isBlank()) {
|
||||
String want = canonical.trim();
|
||||
if (alternates.stream().noneMatch(a -> a.url().equals(want)) && !want.equals(xDefault)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
StringBuilder links = new StringBuilder();
|
||||
for (Alternate alt : alternates) {
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"").append(alt.hreflang())
|
||||
.append("\" href=\"").append(alt.url()).append("\"/>\n");
|
||||
}
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"").append(xDefault)
|
||||
.append("\"/>\n");
|
||||
for (Alternate self : alternates) {
|
||||
entries.add(new Entry(self.url(), links.toString(), item.ref().updatedAt().toString()));
|
||||
}
|
||||
}
|
||||
entries.sort(Comparator.comparing(Entry::url));
|
||||
StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
||||
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\""
|
||||
+ " xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n");
|
||||
for (Entry e : entries) {
|
||||
xml.append(" <url>\n <loc>").append(e.url()).append("</loc>\n <lastmod>").append(e.lastmod())
|
||||
.append("</lastmod>\n").append(e.block()).append(" </url>\n");
|
||||
}
|
||||
return xml.append("</urlset>\n").toString();
|
||||
}
|
||||
|
||||
private String llmsAsOnePointSixBuiltIt() {
|
||||
StringBuilder out = new StringBuilder("# Acme\n\n## Pages\n\n");
|
||||
for (RoutableContent item : catalog.enumerate(SITE)) {
|
||||
if (item.ref().noindex()) {
|
||||
continue;
|
||||
}
|
||||
out.append("- [").append(item.titleFor(EN)).append("](https://acme.test")
|
||||
.append(LocaleUrls.urlFor(item, EN, EN)).append("): ").append(item.descriptionFor(EN))
|
||||
.append('\n');
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.plugin.PluginSettingDef;
|
||||
import mx.quest.runway.plugin.SitePluginConfigService;
|
||||
import mx.quest.runway.plugin.spi.PluginSettingsImpl;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* host-it: the descriptor through the KERNEL's own parser, and the settings the kernel's {@code PluginSettingsImpl}
|
||||
* hands this plugin compared with the fake every unit test uses ({@code TestSettings}) — so the unit tests' premise
|
||||
* (declared defaults overlaid by stored values) is the kernel's behaviour, not an assumption.
|
||||
*/
|
||||
class HostDescriptorTest {
|
||||
|
||||
private static PluginDescriptor descriptor() throws IOException {
|
||||
try (InputStream in = Files.newInputStream(Path.of("plugin.yml"))) {
|
||||
return PluginDescriptor.read(in);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKernelParsesTheDescriptorWithEveryLayoutKey() throws IOException {
|
||||
PluginDescriptor d = descriptor();
|
||||
assertEquals("discoverability", d.id());
|
||||
// The release number is asserted once, in DiscoverabilityConfigTest (the default build); here the kernel's
|
||||
// parse is compared with the descriptor, so a version bump does not have to remember this profile's test.
|
||||
assertEquals(String.valueOf(TestSettings.descriptor().get("version")), d.version());
|
||||
assertEquals(6, d.settingGroups().size());
|
||||
Map<String, PluginSettingDef> site = new LinkedHashMap<>();
|
||||
d.siteSettings().forEach(def -> site.put(def.key(), def));
|
||||
assertEquals("app:robots.ai-default", site.get("robots.ai-policy").inheritsFrom());
|
||||
assertEquals("indexnow.enabled", site.get("indexnow.enabled").requiresPlatform());
|
||||
assertEquals("jsonld.enabled", site.get("jsonld.type").showWhen());
|
||||
assertTrue(site.get("content.schema").advanced());
|
||||
for (PluginSettingDef def : d.siteSettings()) {
|
||||
assertNotNull(def.group(), def.key());
|
||||
assertNotNull(def.help(), def.key());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKernelsSettingsMergeIsTheOneTheUnitTestsAssume() throws IOException {
|
||||
List<PluginSettingDef> schema = descriptor().siteSettings();
|
||||
for (Map<String, Object> stored : List.<Map<String, Object>>of(Map.of(),
|
||||
Map.of("jsonld.type", "", "geo.enabled", true, "geo.speakable", List.of("h1"), "org.name", "Acme",
|
||||
"unknown.key", "kept"))) {
|
||||
SitePluginConfigService config = mock(SitePluginConfigService.class);
|
||||
when(config.config(anyString(), eq("discoverability"))).thenReturn(stored);
|
||||
PluginSettingsImpl kernel = new PluginSettingsImpl("discoverability", schema, config, null);
|
||||
assertEquals(TestSettings.declared().site("acme", stored).site("acme").values(),
|
||||
kernel.site("acme").values(), "stored: " + stored);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
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.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.config.EmbeddedValueResolver;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.context.expression.StandardBeanExpressionResolver;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
/**
|
||||
* IndexNow: the payload, the two switches, and the bounds.
|
||||
*
|
||||
* <h2>What is worth testing here</h2>
|
||||
* The protocol itself is four JSON fields — there is nothing clever to get right. What can go wrong is
|
||||
* everything <b>around</b> it, and all of it fails quietly:
|
||||
*
|
||||
* <ul>
|
||||
* <li>a switch that does not actually gate, so a deployment starts making outbound calls it never agreed to;</li>
|
||||
* <li>a bound that does not bound, so one tenant's bulk edit becomes an unbounded request;</li>
|
||||
* <li>an unescaped tenant-controlled value in a hand-built JSON body.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>The HTTP call is the injected {@link IndexNowSubmitter.Exchange} seam, so every one of those is exercised
|
||||
* with no network at all — and the recording exchange makes "did anything go out?" an assertion rather than an
|
||||
* assumption.
|
||||
*/
|
||||
class IndexNowSubmitterTest {
|
||||
|
||||
/** An exchange that answers 200 and remembers every call — so "nothing went out" is provable. */
|
||||
private static final class Recorder implements IndexNowSubmitter.Exchange {
|
||||
|
||||
private final List<String> payloads = new ArrayList<>();
|
||||
private int status = 200;
|
||||
|
||||
@Override
|
||||
public Response post(String url, String json) {
|
||||
payloads.add(json);
|
||||
return new Response(status, "ok");
|
||||
}
|
||||
}
|
||||
|
||||
private static DiscoverabilityProperties props(boolean platformEnabled) {
|
||||
DiscoverabilityProperties p = new DiscoverabilityProperties();
|
||||
p.getIndexnow().setEnabled(platformEnabled);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static PluginSettings config(Map<String, Object> cfg) {
|
||||
return TestSettings.declared().site("acme", cfg);
|
||||
}
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
|
||||
private static LocalizedUrl url(Locale locale, String path) {
|
||||
return new LocalizedUrl(locale, path, null);
|
||||
}
|
||||
|
||||
/** A local page change, as the host delivers it: the item's URLs before and after. */
|
||||
private static CatalogChange page(String slug, List<LocalizedUrl> before, List<LocalizedUrl> after) {
|
||||
return new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", slug, null, before, after, true);
|
||||
}
|
||||
|
||||
/** A submitter with both switches on, a key, and a site at https://acme.test. */
|
||||
private static IndexNowSubmitter enabled(IndexNowSubmitter.Exchange exchange) {
|
||||
return new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange);
|
||||
}
|
||||
|
||||
// --- the payload ---------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void thePayloadCarriesTheFourFieldsTheProtocolNeeds() {
|
||||
String json = IndexNowSubmitter.payload("acme.test", "abc123",
|
||||
"https://acme.test/indexnow-key.txt", List.of("https://acme.test/a", "https://acme.test/b"));
|
||||
|
||||
assertEquals("{\"host\":\"acme.test\",\"key\":\"abc123\","
|
||||
+ "\"keyLocation\":\"https://acme.test/indexnow-key.txt\","
|
||||
+ "\"urlList\":[\"https://acme.test/a\",\"https://acme.test/b\"]}", json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tenant-controlled values are escaped.
|
||||
*
|
||||
* <p>{@code host}, {@code key} and {@code keyLocation} all come from per-site configuration, and this body
|
||||
* is assembled by hand. An unescaped quote there is a payload-injection hole, not a formatting bug — and
|
||||
* one that only shows up when somebody puts a quote in a setting.
|
||||
*/
|
||||
@Test
|
||||
void tenantControlledValuesCannotBreakOutOfTheJson() {
|
||||
String json = IndexNowSubmitter.payload("acme.test", "ab\"c\\d\ne", "https://acme.test/k.txt",
|
||||
List.of("https://acme.test/a\"b"));
|
||||
|
||||
assertFalse(json.contains("ab\"c"), json);
|
||||
assertTrue(json.contains("ab\\\"c\\\\d\\ne"), json);
|
||||
assertTrue(json.contains("https://acme.test/a\\\"b"), json);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHostFieldIsTheBareHostname() {
|
||||
assertEquals("acme.test", IndexNowSubmitter.hostOf("https://acme.test"));
|
||||
assertEquals("acme.test", IndexNowSubmitter.hostOf("https://acme.test/some/path"));
|
||||
assertEquals("", IndexNowSubmitter.hostOf("not a url"));
|
||||
}
|
||||
|
||||
// --- the two switches ----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A tenant cannot switch on outbound traffic by itself.
|
||||
*
|
||||
* <p>The platform operator owns the network, the egress firewall and the incident. This is the assertion
|
||||
* that the operator's switch is a real gate rather than a label — and it is made against whether anything
|
||||
* left the process, because that is what "off" has to mean.
|
||||
*/
|
||||
@Test
|
||||
void nothingIsSubmittedWhenThePlatformHasNotPermittedIt() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc")), props(false), exchange);
|
||||
|
||||
// Through submit(), NOT flush(): flush() returns early on an empty queue, so a flush-based version of
|
||||
// this test passes whether or not the gate exists. A test of a switch has to be able to fail when the
|
||||
// switch is removed, and this one does — it is the same "asserting nothing" shape as scanning a
|
||||
// compressed archive for a plaintext secret.
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty(), "the platform switch must gate the network, not just the UI");
|
||||
}
|
||||
|
||||
/** The documented WARN for a site that wants IndexNow while the platform says no — and only for such a site. */
|
||||
@Test
|
||||
void aSiteThatEnabledItWhileThePlatformHasNotIsWarnedOnce() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter wants = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc")), props(false), exchange);
|
||||
wants.onCatalogChanged(page("home", List.of(), List.of(url(EN, "/"))));
|
||||
wants.onCatalogChanged(page("about", List.of(url(EN, "/about")), List.of(url(EN, "/about"))));
|
||||
assertTrue(wants.warnedInert("acme"), "the operator is told which setting to flip");
|
||||
assertTrue(exchange.payloads.isEmpty(), "and still nothing leaves the process");
|
||||
|
||||
IndexNowSubmitter doesNot = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of()), props(false), new Recorder());
|
||||
doesNot.onCatalogChanged(page("home", List.of(), List.of(url(EN, "/"))));
|
||||
assertFalse(doesNot.warnedInert("acme"), "a site that never asked for it is not warned about it");
|
||||
}
|
||||
|
||||
/** …and the positive control: the identical call DOES submit once the platform permits it. */
|
||||
@Test
|
||||
void theSameCallSubmitsOnceThePlatformPermitsIt() {
|
||||
Recorder exchange = new Recorder();
|
||||
new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc")), props(true), exchange)
|
||||
.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertEquals(1, exchange.payloads.size(), "otherwise the test above proves only that nothing works");
|
||||
}
|
||||
|
||||
/** …and a site that has not enabled it is not submitted for either. */
|
||||
@Test
|
||||
void nothingIsSubmittedForASiteThatHasNotEnabledIt() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.key", "abc")), props(true), exchange);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty(), "indexnow.enabled defaults false — silence is the default");
|
||||
}
|
||||
|
||||
/** A site with the switch on but no key submits nothing: there would be nothing for the engine to verify. */
|
||||
@Test
|
||||
void nothingIsSubmittedWithoutAKey() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true)), props(true), exchange);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
/** With both switches on and a key set, the submission goes out and names the key file's fixed location. */
|
||||
@Test
|
||||
void bothSwitchesOnSubmitsAndPointsAtTheKeyFile() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc123")), props(true), exchange);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertTrue(exchange.payloads.get(0).contains("\"keyLocation\":\"https://acme.test/indexnow-key.txt\""),
|
||||
exchange.payloads.get(0));
|
||||
assertTrue(exchange.payloads.get(0).contains("\"host\":\"acme.test\""), exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
// --- the bounds ----------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A submission larger than the cap is trimmed, not sent whole.
|
||||
*
|
||||
* <p>A bulk edit or a restore can change every URL a site has. Without this the body is unbounded, which is
|
||||
* a problem for the endpoint, for the tenant's egress and for anyone reading the log.
|
||||
*/
|
||||
@Test
|
||||
void aSubmissionOverTheCapIsTrimmedRatherThanSentWhole() {
|
||||
Recorder exchange = new Recorder();
|
||||
DiscoverabilityProperties p = props(true);
|
||||
p.getIndexnow().setMaxUrlsPerSubmission(3);
|
||||
List<String> many = new ArrayList<>();
|
||||
for (int i = 0; i < 50; i++) {
|
||||
many.add("https://acme.test/p" + i);
|
||||
}
|
||||
|
||||
new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), p, exchange)
|
||||
.submit("acme", many);
|
||||
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertEquals(3, exchange.payloads.get(0).split("https://acme.test/p", -1).length - 1,
|
||||
exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* A failing endpoint does not throw into the caller, and does not retry.
|
||||
*
|
||||
* <p>A freshness ping that arrives late is worthless, and an unbounded retry queue during an outage is a
|
||||
* liability. The pages are still crawled the ordinary way, so the honest behaviour is to log and drop.
|
||||
*/
|
||||
@Test
|
||||
void aFailingEndpointIsLoggedAndDroppedRatherThanRetried() {
|
||||
IndexNowSubmitter.Exchange failing = (url, json) -> {
|
||||
throw new IOException("connection refused");
|
||||
};
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), failing);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a")); // must not throw
|
||||
}
|
||||
|
||||
/** A refusal (403 = key file did not verify) is likewise survivable. */
|
||||
@Test
|
||||
void aRefusalIsSurvivable() {
|
||||
Recorder exchange = new Recorder();
|
||||
exchange.status = 403;
|
||||
new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange)
|
||||
.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertEquals(1, exchange.payloads.size(), "it was attempted");
|
||||
}
|
||||
|
||||
/** A site with no base URL cannot be submitted for — there is no host to name. */
|
||||
@Test
|
||||
void aSiteWithNoBaseUrlIsSkipped() {
|
||||
Recorder exchange = new Recorder();
|
||||
new IndexNowSubmitter(sites("acme", ""),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange)
|
||||
.submit("acme", List.of("/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
// --- what a change queues (the SPI change events) ------------------------------------------------
|
||||
|
||||
/**
|
||||
* A DELETED page reports where it was, and that address is submitted. 1.x resolved the URLs after
|
||||
* the host had dropped the page from its listing, so a deletion — the change most worth telling an engine
|
||||
* about — submitted nothing.
|
||||
*/
|
||||
@Test
|
||||
void aDeletedPagesOldUrlsAreSubmitted() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
|
||||
submitter.onCatalogChanged(page("about", List.of(url(EN, "/about"), url(ES, "/es/acerca")), List.of()));
|
||||
submitter.flush();
|
||||
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertTrue(exchange.payloads.get(0).endsWith(
|
||||
"\"urlList\":[\"https://acme.test/about\",\"https://acme.test/es/acerca\"]}"), exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** A moved item submits the old address AND the new one, each once, previous first. */
|
||||
@Test
|
||||
void aRenameSubmitsTheUnionOfBeforeAndAfterWithoutDuplicates() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
|
||||
submitter.onCatalogChanged(page("about", List.of(url(EN, "/about"), url(ES, "/es/acerca")),
|
||||
List.of(url(EN, "/about-us"), url(ES, "/es/acerca"))));
|
||||
submitter.flush();
|
||||
|
||||
assertTrue(exchange.payloads.get(0).endsWith("\"urlList\":[\"https://acme.test/about\","
|
||||
+ "\"https://acme.test/es/acerca\",\"https://acme.test/about-us\"]}"), exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** A new page has no previous URLs: its current ones are submitted. */
|
||||
@Test
|
||||
void aNewPageSubmitsItsCurrentUrls() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(page("news", List.of(), List.of(url(EN, "/news"))));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.get(0).contains("\"urlList\":[\"https://acme.test/news\"]"));
|
||||
}
|
||||
|
||||
/** A content source's item (a blog entry) is handled exactly like a page. */
|
||||
@Test
|
||||
void aContentSourceChangeIsSubmittedLikeAPage() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "blog", "hello", "blog",
|
||||
List.of(url(EN, "/blog/hello")), List.of(), true));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.get(0).contains("https://acme.test/blog/hello"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A cluster replays every change on its other nodes ({@code local == false}). Only the node where
|
||||
* the change happened submits — otherwise N nodes send N identical submissions.
|
||||
*/
|
||||
@Test
|
||||
void aPeersReplayedChangeIsIgnored() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", "about", null,
|
||||
List.of(url(EN, "/about")), List.of(), false));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty(), "the originating node submits; a replay never does");
|
||||
}
|
||||
|
||||
/** Changes that name no item carry no URLs: a lifecycle event, a settings save, a whole-site reload. */
|
||||
@Test
|
||||
void changesThatNameNoItemQueueNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
EventDispatch events = new EventDispatch("discoverability", Set.of()).listener(submitter);
|
||||
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, true);
|
||||
events.settings("acme", "discoverability");
|
||||
events.page("acme", null, List.of(url(EN, "/x")), List.of());
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
assertTrue(events.failures().isEmpty(), events.failures().toString());
|
||||
}
|
||||
|
||||
/** Delivered the kernel's way (phases, order), a page deletion reaches the queue. */
|
||||
@Test
|
||||
void itIsAConsumerListenerAndADispatchedDeletionReachesTheQueue() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
assertEquals(SiteEventListener.Phase.CONSUMER, submitter.phase(), "it reads URLs after the sources dropped "
|
||||
+ "their state — the phase whose currentUrls the host fills");
|
||||
new EventDispatch("discoverability", Set.of()).listener(submitter)
|
||||
.page("acme", "about", List.of(url(EN, "/about")), List.of());
|
||||
submitter.flush();
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertTrue(exchange.payloads.get(0).contains("https://acme.test/about"));
|
||||
}
|
||||
|
||||
/** One flush per batch: queued URLs are submitted once and the queue is emptied. */
|
||||
@Test
|
||||
void aFlushSubmitsOnceAndEmptiesTheQueue() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(page("a", List.of(), List.of(url(EN, "/a"))));
|
||||
submitter.onCatalogChanged(page("b", List.of(), List.of(url(EN, "/b"))));
|
||||
submitter.onCatalogChanged(page("a", List.of(url(EN, "/a")), List.of(url(EN, "/a"))));
|
||||
submitter.flush();
|
||||
submitter.flush();
|
||||
assertEquals(1, exchange.payloads.size(), "a second flush has nothing to send");
|
||||
assertTrue(exchange.payloads.get(0).endsWith("[\"https://acme.test/a\",\"https://acme.test/b\"]}"),
|
||||
exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** The per-site queue is bounded: overflow is dropped (with a WARN), not grown. */
|
||||
@Test
|
||||
void theQueueIsBoundedPerSite() {
|
||||
Recorder exchange = new Recorder();
|
||||
DiscoverabilityProperties p = props(true);
|
||||
p.getIndexnow().setMaxQueuedPerSite(2);
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), p, exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(), List.of(url(EN, "/1"), url(ES, "/es/1"))));
|
||||
submitter.onCatalogChanged(page("y", List.of(), List.of(url(EN, "/2"))));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.get(0).endsWith("[\"https://acme.test/1\",\"https://acme.test/es/1\"]}"),
|
||||
"the overflow was dropped: " + exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** With the platform switch off, a change queues nothing — the flush has nothing even if the switch flips. */
|
||||
@Test
|
||||
void withThePlatformOffAChangeQueuesNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
DiscoverabilityProperties p = props(false);
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), p, exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(url(EN, "/x")), List.of()));
|
||||
p.getIndexnow().setEnabled(true);
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
/** A site with no configured base URL cannot be submitted for, so nothing is even queued. */
|
||||
@Test
|
||||
void aChangeOnASiteWithNoBaseUrlQueuesNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", null),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(url(EN, "/x")), List.of()));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
/** An unknown site (deleted between the change and now) queues nothing and does not fail the dispatch. */
|
||||
@Test
|
||||
void anUnknownSiteQueuesNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(new FakeSiteServices(),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(url(EN, "/x")), List.of()));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
private static FakeSiteServices sites(String id, String baseUrl) {
|
||||
return new FakeSiteServices().site(new SiteView(id, "Acme", EN, List.of(EN, ES), baseUrl));
|
||||
}
|
||||
|
||||
/** A hand-set batch interval outside the form's 5..3600 seconds is clamped, never handed to the scheduler as is. */
|
||||
@Test
|
||||
void aHandSetBatchIntervalIsKeptInsideTheFormsRange() throws Exception {
|
||||
String expression =
|
||||
IndexNowSubmitter.class.getMethod("flush").getAnnotation(Scheduled.class).fixedDelayString();
|
||||
assertEquals("60000", delayFor(expression, null), "unset: the 60-second default");
|
||||
assertEquals("60000", delayFor(expression, "60"));
|
||||
assertEquals("5000", delayFor(expression, "0"));
|
||||
assertEquals("5000", delayFor(expression, "-30"));
|
||||
assertEquals("3600000", delayFor(expression, "99999"));
|
||||
}
|
||||
|
||||
private static String delayFor(String expression, String value) {
|
||||
MockEnvironment env = new MockEnvironment();
|
||||
if (value != null) {
|
||||
env.setProperty("runway.plugin.discoverability.indexnow.batch-seconds", value);
|
||||
}
|
||||
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
|
||||
factory.addEmbeddedValueResolver(env::resolveRequiredPlaceholders);
|
||||
factory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
|
||||
return new EmbeddedValueResolver(factory).resolveStringValue(expression);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The JSON-LD core: @id conventions, origin extraction, node building, and safe <script> serialization. */
|
||||
class LdTest {
|
||||
|
||||
@Test
|
||||
void idConventionsAreStableAndAnchored() {
|
||||
assertEquals("https://x.test/#website", Ld.websiteId("https://x.test"));
|
||||
assertEquals("https://x.test/#organization", Ld.organizationId("https://x.test"));
|
||||
assertEquals("https://x.test/about#webpage", Ld.webpageId("https://x.test/about"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void originExtractsSchemeAndHost() {
|
||||
assertEquals("https://x.test", Ld.origin("https://x.test/about?q=1"));
|
||||
assertEquals("http://x.test:8080", Ld.origin("http://x.test:8080/"));
|
||||
assertEquals("", Ld.origin("/relative/path"));
|
||||
assertEquals("", Ld.origin(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scriptWrapsAGraphAndOmitsEmpty() {
|
||||
assertEquals("", Ld.script(List.of()), "an empty graph contributes nothing");
|
||||
Map<String, Object> node = Ld.node("WebPage", "https://x.test/#p");
|
||||
Ld.put(node, "name", "Hello");
|
||||
String out = Ld.script(List.of(node));
|
||||
assertTrue(out.contains("<script type=\"application/ld+json\">"));
|
||||
assertTrue(out.contains("\"@context\":\"https://schema.org\""));
|
||||
assertTrue(out.contains("\"@graph\""));
|
||||
assertTrue(out.contains("\"@type\":\"WebPage\""));
|
||||
assertTrue(out.contains("\"name\":\"Hello\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scriptNeutralizesHtmlBreakoutInsideTheScriptElement() {
|
||||
Map<String, Object> node = Ld.node("WebPage", null);
|
||||
Ld.put(node, "name", "a </script><b> & c");
|
||||
String out = Ld.script(List.of(node));
|
||||
assertFalse(out.contains("</script><b>"), "raw < / > / & must not survive inside the script element");
|
||||
assertTrue(out.contains("\\u003c"));
|
||||
assertTrue(out.contains("\\u003e"));
|
||||
assertTrue(out.contains("\\u0026"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putOmitsBlanksAndPutListCollapsesSingletons() {
|
||||
Map<String, Object> node = Ld.node("Organization", null);
|
||||
Ld.put(node, "name", " ");
|
||||
Ld.put(node, "url", null);
|
||||
assertFalse(node.containsKey("name"));
|
||||
assertFalse(node.containsKey("url"));
|
||||
Ld.putList(node, "sameAs", List.of("https://x.test"));
|
||||
assertEquals("https://x.test", node.get("sameAs"), "a single sameAs is a scalar");
|
||||
Ld.putList(node, "sameAs", List.of("https://a", "https://b"));
|
||||
assertEquals(List.of("https://a", "https://b"), node.get("sameAs"), "multiple is an array");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* /llms.txt: opt-in (geo.enabled) Markdown index of the host's published listing, in the site's default locale;
|
||||
* disabled ⇒ 404. The listing (published only, safe paths, reserved paths dropped) is the host's; what this
|
||||
* endpoint adds is the selection (noindex out), the labels, the summary and the absolute URLs.
|
||||
*/
|
||||
class LlmsTxtEndpointTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
|
||||
private final SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
private final FakePluginSettings settings = TestSettings.declared();
|
||||
private final FakeContentCatalog catalog = new FakeContentCatalog().site("acme");
|
||||
private final LlmsTxtEndpoint endpoint = new LlmsTxtEndpoint(catalog, settings);
|
||||
|
||||
private static final ContentRef ABOUT = ContentRef.of("about", "/about", Map.of(), List.of(EN),
|
||||
Map.of("en", "About"), Map.of("en", "Who we are."), "__site__/acme/about", null);
|
||||
private static final ContentRef ENTRY = ContentRef.of("my-post", "/blog/my-post", Map.of(), List.of(EN),
|
||||
Map.of("en", "My post"), Map.of("en", "A fine read."), "__plugin__/blog/entry", null);
|
||||
/** Published in Spanish only, on an English-default site. */
|
||||
private static final ContentRef SPANISH_ONLY = ContentRef.of("solo", "/solo", Map.of("es", "/solo-es"),
|
||||
List.of(ES), Map.of("es", "Sólo en español"), Map.of(), "__site__/acme/solo", null);
|
||||
private static final ContentRef HIDDEN = new ContentRef("hidden", "/hidden", Map.of(), List.of(EN),
|
||||
Map.of("en", "Hidden"), Map.of(), null, "__site__/acme/hidden", true, null, true, null, null, Map.of());
|
||||
|
||||
@BeforeEach
|
||||
@org.junit.jupiter.api.AfterEach
|
||||
void freshValidators() {
|
||||
CrawlConditional.reset(); // also restores the system clock a test may have stepped
|
||||
}
|
||||
|
||||
private RouteRequest req(SiteView s, Map<String, String> headers, String origin) {
|
||||
return new RouteRequest(s, EN, "GET", "/llms.txt", Map.of(), headers, new byte[0], Map.of(), null, origin);
|
||||
}
|
||||
|
||||
private String body(RouteResponse r) {
|
||||
assertEquals(200, r.status());
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void geo(Map<String, Object> extra) {
|
||||
Map<String, Object> cfg = new java.util.HashMap<>(Map.of("geo.enabled", true));
|
||||
cfg.putAll(extra);
|
||||
settings.site("acme", cfg);
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesMarkdownIndexWhenGeoEnabled() {
|
||||
geo(Map.of("geo.summary", "We build things."));
|
||||
catalog.entry("acme", Entries.page(ABOUT, site)).entry("acme", Entries.of("blog", ENTRY, site));
|
||||
|
||||
RouteResponse r = endpoint.handle(req(site, Map.of(), "http://ignored.test"));
|
||||
assertEquals("text/plain; charset=utf-8", r.headers().get("Content-Type"));
|
||||
assertEquals("""
|
||||
# Acme
|
||||
|
||||
> We build things.
|
||||
|
||||
## Pages
|
||||
|
||||
- [About](https://acme.test/about): Who we are.
|
||||
- [My post](https://acme.test/blog/my-post): A fine read.
|
||||
""", body(r), "the exact 1.x document shape; plugin content is a first-class citizen");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledReturns404WhenGeoOff() {
|
||||
settings.site("acme", Map.of("geo.enabled", false));
|
||||
RouteResponse r = endpoint.handle(req(site, Map.of(), ""));
|
||||
assertEquals(404, r.status());
|
||||
assertEquals("no-store", r.headers().get("Cache-Control"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void geoIsOffByDefault() {
|
||||
assertEquals(404, endpoint.handle(req(site, Map.of(), "")).status(), "GEO is opt-in");
|
||||
}
|
||||
|
||||
/**
|
||||
* An intended change: an item that does not exist in the default locale is linked where it exists
|
||||
* (its primary locale's real URL), never at the unprefixed default path that 1.x produced and the site 404s.
|
||||
*/
|
||||
@Test
|
||||
void anItemMissingFromTheDefaultLocaleIsLinkedWhereItExists() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(SPANISH_ONLY, site));
|
||||
|
||||
String md = body(endpoint.handle(req(site, Map.of(), "")));
|
||||
assertTrue(md.contains("- [Sólo en español](https://acme.test/es/solo-es)"), md);
|
||||
assertFalse(md.contains("https://acme.test/solo)"), "never the default path, which 404s: " + md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noindexContentIsNotAdvertised() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site)).entry("acme", Entries.page(HIDDEN, site));
|
||||
String md = body(endpoint.handle(req(site, Map.of(), "")));
|
||||
assertTrue(md.contains("[About]"));
|
||||
assertFalse(md.contains("Hidden"), md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsAreOneLineWithoutLinkMetacharactersAndFallBackToTheId() {
|
||||
geo(Map.of("geo.summary", "Line one\nline two"));
|
||||
ContentRef bracketed = ContentRef.of("faq", "/faq", Map.of(), List.of(EN), Map.of("en", "FAQ [updated]\nnow"),
|
||||
Map.of("en", "Two\nlines"), "__site__/acme/faq", null);
|
||||
ContentRef untitled = ContentRef.of("no-title", "/no-title", Map.of(), List.of(EN), Map.of(), Map.of(),
|
||||
"__site__/acme/nt", null);
|
||||
catalog.entry("acme", Entries.page(bracketed, site)).entry("acme", Entries.page(untitled, site));
|
||||
|
||||
String md = body(endpoint.handle(req(site, Map.of(), "")));
|
||||
assertTrue(md.contains("> Line one line two\n"), md);
|
||||
assertTrue(md.contains("- [FAQ (updated) now](https://acme.test/faq): Two lines\n"), md);
|
||||
assertTrue(md.contains("- [no-title](https://acme.test/no-title)\n"), md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutABaseUrlTheTrustedOriginIsUsed() {
|
||||
geo(Map.of());
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
catalog.entry("acme", Entries.page(ABOUT, noBase));
|
||||
String md = body(endpoint.handle(req(noBase, Map.of("Host", "spoofed.test"), "http://acme.test:8080")));
|
||||
assertTrue(md.contains("(http://acme.test:8080/about)"), md);
|
||||
assertFalse(md.contains("spoofed"), md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalGetRevalidatesWith304() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
String lastModified = fresh.headers().get("Last-Modified");
|
||||
assertEquals("no-cache", fresh.headers().get("Cache-Control"));
|
||||
RouteResponse again = endpoint.handle(req(site, Map.of("if-modified-since", lastModified), ""));
|
||||
assertEquals(304, again.status());
|
||||
assertEquals(0, again.body().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownSiteListsNothingButStillAnswers() {
|
||||
geo(Map.of());
|
||||
SiteView ghost = new SiteView("ghost", "Ghost", EN, List.of(EN), "https://ghost.test");
|
||||
settings.site("ghost", Map.of("geo.enabled", true));
|
||||
assertEquals("# Ghost\n\n## Pages\n\n", body(endpoint.handle(req(ghost, Map.of(), ""))));
|
||||
}
|
||||
|
||||
// --- the validator folds what the document prints besides the items (2.1.0) -----------------------------
|
||||
|
||||
private RouteResponse revalidate(SiteView s, RouteResponse fresh) {
|
||||
return endpoint.handle(req(s, Map.of("If-Modified-Since", fresh.headers().get("Last-Modified")), ""));
|
||||
}
|
||||
|
||||
/** Stepping the validator's clock past HTTP-date granularity, so an advance is observable. */
|
||||
private static void tick(int seconds) {
|
||||
java.time.Instant at = java.time.Instant.now().plusSeconds(seconds);
|
||||
CrawlConditional.clock = () -> at;
|
||||
}
|
||||
|
||||
@Test
|
||||
void editingTheSummaryAdvancesLastModified() {
|
||||
geo(Map.of("geo.summary", "We build things."));
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
assertEquals(304, revalidate(site, fresh).status(), "unchanged: 304");
|
||||
|
||||
tick(5);
|
||||
geo(Map.of("geo.summary", "We build better things."));
|
||||
RouteResponse after = revalidate(site, fresh);
|
||||
assertEquals(200, after.status(), "a crawler holding the old summary refetches");
|
||||
assertTrue(body(after).contains("> We build better things."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamingTheSiteAdvancesLastModified() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
|
||||
tick(5);
|
||||
SiteView renamed = new SiteView("acme", "Acme Industries", EN, List.of(EN, ES), "https://acme.test");
|
||||
RouteResponse after = revalidate(renamed, fresh);
|
||||
assertEquals(200, after.status(), "the H1 is the site name: a rename is a document change");
|
||||
assertTrue(body(after).startsWith("# Acme Industries\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewBaseUrlAdvancesLastModified() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
|
||||
tick(5);
|
||||
SiteView moved = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://www.acme.test");
|
||||
RouteResponse after = revalidate(moved, fresh);
|
||||
assertEquals(200, after.status(), "every link starts with the base URL");
|
||||
assertTrue(body(after).contains("(https://www.acme.test/about)"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A host-less site reached under two names serves each its own links; the request origin is deliberately NOT
|
||||
* folded, so each crawler's copy stays valid for the address it fetched and the validator does not advance on
|
||||
* every alternate request.
|
||||
*/
|
||||
@Test
|
||||
void theRequestOriginOfAHostlessSiteDoesNotMoveTheValidator() {
|
||||
geo(Map.of());
|
||||
SiteView hostless = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
catalog.entry("acme", Entries.page(ABOUT, hostless));
|
||||
RouteResponse first = endpoint.handle(req(hostless, Map.of(), "http://one.test"));
|
||||
tick(5);
|
||||
RouteResponse second = endpoint.handle(req(hostless, Map.of(), "http://two.test"));
|
||||
assertTrue(body(second).contains("(http://two.test/about)"));
|
||||
assertEquals(first.headers().get("Last-Modified"), second.headers().get("Last-Modified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void editingTheSummaryDoesNotMoveTheSitemapsValidator() {
|
||||
geo(Map.of("geo.summary", "One."));
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
SitemapEndpoint sitemap = new SitemapEndpoint(catalog, settings);
|
||||
RouteRequest sitemapReq = new RouteRequest(site, EN, "GET", "/sitemap.xml", Map.of(), Map.of(), new byte[0],
|
||||
Map.of(), null, "");
|
||||
String sitemapValidator = sitemap.handle(sitemapReq).headers().get("Last-Modified");
|
||||
endpoint.handle(req(site, Map.of(), ""));
|
||||
tick(5);
|
||||
geo(Map.of("geo.summary", "Two."));
|
||||
endpoint.handle(req(site, Map.of(), ""));
|
||||
assertEquals(sitemapValidator, sitemap.handle(sitemapReq).headers().get("Last-Modified"),
|
||||
"the sitemap does not print the summary");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.Severity;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The page editor's structured-data line says what the page is and where that comes from. */
|
||||
class PageTypeCheckTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final PageTypeCheck check = new PageTypeCheck(config, DiscoverabilityConfig.schemaTypes(), null);
|
||||
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
|
||||
private List<Finding> inspect(String path, Map<String, Object> cfg) {
|
||||
return inspect(path, cfg, false, List.of(Locale.ENGLISH));
|
||||
}
|
||||
|
||||
private List<Finding> inspect(String path, Map<String, Object> cfg, boolean noindex, List<Locale> languages) {
|
||||
config.site("acme", cfg);
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, languages, "https://acme.test");
|
||||
PageMeta page = new PageMeta(path.substring(1), "T", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
noindex);
|
||||
return check.inspect(new PageView(site, page, Locale.ENGLISH, "https://acme.test" + path, "<p>x</p>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultIsNamedAsTheSitesDefaultPageType() {
|
||||
List<Finding> f = inspect("/about", Map.of());
|
||||
assertEquals(1, f.size());
|
||||
assertEquals(Severity.INFO, f.get(0).severity());
|
||||
assertEquals("Structured data: this page is a WebPage, the site's Default page type.", f.get(0).message());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPerPageTypeNamesItsPatternAndWhatElseItAdds() {
|
||||
List<Finding> f = inspect("/pricing", Map.of("content.schema",
|
||||
"/pri*:\n - type: FAQPage\n faq: []\n - type: Service\n name: S\n"));
|
||||
assertEquals("Structured data: this page is a FAQPage, set by Per-page types (pattern /pri*). "
|
||||
+ "Per-page types also add: Service.", f.get(0).message());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownTypeAndASecondPageTypeAreWarnings() {
|
||||
List<Finding> f = inspect("/x", Map.of("content.schema",
|
||||
"/x:\n - type: AboutPage\n - type: ContactPage\n - type: Typo\n"));
|
||||
assertEquals(3, f.size(), f.toString());
|
||||
assertTrue(f.stream().anyMatch(x -> x.severity() == Severity.WARNING && x.message().contains("Typo")), f.toString());
|
||||
assertTrue(f.stream().anyMatch(x -> x.severity() == Severity.WARNING && x.message().contains("ContactPage is ignored")),
|
||||
f.toString());
|
||||
}
|
||||
|
||||
/** The head emits nothing on a noindex page, before anything else; the line says so, whatever else is set. */
|
||||
@Test
|
||||
void aNoindexPageIsSaidToCarryNoStructuredData() {
|
||||
List<Finding> f = inspect("/faq", Map.of("content.schema", "/faq:\n - type: FAQPage\n - type: Typo\n"),
|
||||
true, List.of(Locale.ENGLISH));
|
||||
assertEquals(1, f.size(), f.toString());
|
||||
assertEquals(Severity.INFO, f.get(0).severity());
|
||||
assertEquals("Structured data: this page is excluded from search engines (noindex), so it carries no "
|
||||
+ "structured data.", f.get(0).message());
|
||||
assertEquals(1, inspect("/x", Map.of("jsonld.enabled", false), true, List.of(Locale.ENGLISH)).size());
|
||||
assertTrue(inspect("/x", Map.of("jsonld.enabled", false), true, List.of(Locale.ENGLISH)).get(0).message()
|
||||
.contains("noindex"), "noindex is checked first, as the head does");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anFaqPageWithNoCompleteQuestionIsAWarning() {
|
||||
List<Finding> f = inspect("/faq", Map.of("content.schema",
|
||||
"/faq:\n type: FAQPage\n faq:\n - { question: Q, answer: A }\n"));
|
||||
assertEquals(2, f.size(), f.toString());
|
||||
assertEquals(Severity.WARNING, f.get(1).severity());
|
||||
assertEquals(PageTypeCheck.CODE_GAP, f.get(1).code());
|
||||
assertEquals("FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.",
|
||||
f.get(1).message());
|
||||
assertEquals(1, inspect("/faq", Map.of("content.schema",
|
||||
"/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n")).size(), "a complete pair is enough");
|
||||
List<Finding> list = inspect("/c", Map.of("content.schema",
|
||||
"/c:\n - type: AboutPage\n - type: ItemList\n items:\n - { name: A }\n"));
|
||||
assertTrue(list.stream().anyMatch(x -> x.severity() == Severity.WARNING
|
||||
&& x.message().equals("ItemList has no item with a url:, so no list is published.")), list.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTranslatedPageIsToldTheDefaultLanguagesEntryDoesNotReachIt() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n");
|
||||
List<Finding> f = inspect("/es/faq", cfg, false, List.of(Locale.ENGLISH, ES));
|
||||
assertEquals(2, f.size(), f.toString());
|
||||
assertEquals("Structured data: this page is a WebPage, the site's Default page type.", f.get(0).message());
|
||||
assertEquals(Severity.INFO, f.get(1).severity());
|
||||
assertEquals("Per-page types: /faq describes the default language's page, not this one; a page in another "
|
||||
+ "language is matched only by its own path. To describe this page, add /es/faq.", f.get(1).message());
|
||||
assertEquals(1, inspect("/faq", cfg, false, List.of(Locale.ENGLISH, ES)).size(), "the default language's page");
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchedOffSaysSo() {
|
||||
List<Finding> f = inspect("/x", Map.of("jsonld.enabled", false));
|
||||
assertTrue(f.get(0).message().startsWith("Structured data is switched off"), f.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* A page type declared in Per-page types replaces the site's Default page type on the page's own node;
|
||||
* every other type adds an entity. The head and the editor ask {@link PageTypes} the same question.
|
||||
*/
|
||||
class PageTypesTest {
|
||||
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH, ES),
|
||||
"https://acme.test");
|
||||
private static final Map<String, SchemaType> TYPES = DiscoverabilityConfig.schemaTypes();
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final StructuredDataHead head = new StructuredDataHead(config, TYPES);
|
||||
|
||||
private String render(String path, String title, Map<String, Object> cfg) {
|
||||
config.site("acme", cfg);
|
||||
PageMeta page = new PageMeta(path.substring(1), title, "d", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
false);
|
||||
String canonical = "https://acme.test" + path;
|
||||
return head.render(new HeadContext(SITE, page, Locale.ENGLISH, canonical, canonical, List.of(), false, false));
|
||||
}
|
||||
|
||||
private static int count(String haystack, String needle) {
|
||||
int n = 0;
|
||||
for (int i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + needle.length())) {
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutAPageTypeThePageHasTheSiteDefault() {
|
||||
PageTypes.Description d = PageTypes.describe(Map.of(), "/about", TYPES);
|
||||
assertEquals("WebPage", d.type());
|
||||
assertEquals(PageTypes.Source.DEFAULT, d.source());
|
||||
assertEquals("Article", PageTypes.describe(Map.of("jsonld.type", "Article"), "/x", TYPES).type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArticleEntryIsThePagesOwnTypeNotASecondArticle() {
|
||||
String out = render("/news/one", "One", Map.of("jsonld.type", "Article",
|
||||
"content.schema", "/news/*:\n type: BlogPosting\n author: Ed\n"));
|
||||
assertEquals(1, count(out, "\"@type\":\"BlogPosting\""), out);
|
||||
assertEquals(0, count(out, "\"@type\":\"Article\""), "no second article beside the page: " + out);
|
||||
assertTrue(out.contains("\"@id\":\"https://acme.test/news/one#webpage\""), out);
|
||||
assertTrue(out.contains("\"headline\":\"One\"") && out.contains("\"name\":\"Ed\""), out);
|
||||
assertFalse(out.contains("mainEntityOfPage"), "nothing points back at itself: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anFaqEntryMakesThePageAnFaqPageWithItsQuestions() {
|
||||
String out = render("/faq", "FAQ", Map.of("content.schema",
|
||||
"/faq:\n type: FAQPage\n faq:\n - { q: \"Why?\", a: \"Because.\" }\n"));
|
||||
assertEquals(1, count(out, "\"@type\":\"FAQPage\""), out);
|
||||
assertEquals(0, count(out, "\"@type\":\"WebPage\""), out);
|
||||
assertTrue(out.contains("\"mainEntity\":[{\"@type\":\"Question\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCollectionPageIsThePageAndItsListIsItsMainEntity() {
|
||||
String out = render("/coffees", "Coffees", Map.of("content.schema",
|
||||
"/coffees:\n type: CollectionPage\n items:\n - { name: A, url: /a }\n"));
|
||||
assertTrue(out.contains("\"@type\":\"CollectionPage\",\"@id\":\"https://acme.test/coffees#webpage\""), out);
|
||||
assertTrue(out.contains("\"mainEntity\":{\"@id\":\"https://acme.test/coffees#itemlist\"}"), out);
|
||||
assertEquals(1, count(out, "\"@type\":\"ItemList\""), out);
|
||||
// ItemList alone still only adds the list.
|
||||
String list = render("/coffees", "Coffees", Map.of("content.schema",
|
||||
"/coffees:\n type: ItemList\n items:\n - { name: A, url: /a }\n"));
|
||||
assertTrue(list.contains("\"@type\":\"WebPage\""), list);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSimplePageTypeOnlyNamesThePage() {
|
||||
String out = render("/contact", "Contact", Map.of("jsonld.type", "Article",
|
||||
"content.schema", "/contact:\n type: ContactPage\n"));
|
||||
assertTrue(out.contains("\"@type\":\"ContactPage\""), out);
|
||||
assertTrue(out.contains("\"name\":\"Contact\""), "a non-article page keeps its name: " + out);
|
||||
assertEquals(0, count(out, "\"@type\":\"Article\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherTypesStillAddEntitiesBesideThePageType() {
|
||||
PageTypes.Description d = PageTypes.describe(Map.of("content.schema",
|
||||
"/pricing:\n - type: FAQPage\n faq: []\n - type: Service\n name: S\n - type: Nope\n"
|
||||
+ " - type: AboutPage\n"), "/pricing", TYPES);
|
||||
assertEquals("FAQPage", d.type());
|
||||
assertEquals(PageTypes.Source.SCHEMA, d.source());
|
||||
assertEquals("/pricing", d.pattern());
|
||||
assertEquals(List.of("Service"), d.addedTypes());
|
||||
assertEquals(List.of("Nope"), d.unknown());
|
||||
assertEquals(List.of("AboutPage"), d.extraPageTypes(), "a page has one type; the second is reported");
|
||||
}
|
||||
|
||||
/** An entry's text is in one language, so a translated page is matched only by its own path. */
|
||||
@Test
|
||||
void aPageBehindALanguagePrefixIsNotMatchedByTheDefaultLanguagesKey() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"Do you ship abroad?\", a: \"Yes.\" }\n/blog/*:\n type: BlogPosting\n"
|
||||
+ "/coffees/*:\n type: Product\n name: Ethiopia Guji\n breadcrumb: { name: Coffees, url: /coffees }\n");
|
||||
PageTypes.Description d = PageTypes.describe(cfg, "/es/faq", TYPES);
|
||||
assertEquals("WebPage", d.type());
|
||||
assertEquals(PageTypes.Source.DEFAULT, d.source());
|
||||
assertNull(d.pattern(), "/faq does not reach /es/faq");
|
||||
assertEquals("WebPage", PageTypes.describe(cfg, "/es/blog/post", TYPES).type());
|
||||
assertNull(PageTypes.entry(cfg, "/es/coffees/guji"));
|
||||
|
||||
String faq = render("/es/faq", "Preguntas frecuentes", cfg);
|
||||
assertFalse(faq.contains("FAQPage") || faq.contains("Do you ship abroad?"), "no English questions: " + faq);
|
||||
String product = render("/es/coffees/guji", "Guji", cfg);
|
||||
assertFalse(product.contains("Ethiopia Guji") || product.contains("\"Product\""), product);
|
||||
assertFalse(product.contains("\"name\":\"Coffees\""), "no English breadcrumb parent: " + product);
|
||||
// The default language's pages are unchanged.
|
||||
assertTrue(render("/faq", "FAQ", cfg).contains("Do you ship abroad?"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyWrittenForTheTranslatedPathApplies() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"Do you ship abroad?\", a: \"Yes.\" }\n/es/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"¿Envían al extranjero?\", a: \"Sí.\" }\n/es/blog/*:\n type: BlogPosting\n");
|
||||
PageTypes.Description d = PageTypes.describe(cfg, "/es/faq", TYPES);
|
||||
assertEquals("FAQPage", d.type());
|
||||
assertEquals("/es/faq", d.pattern());
|
||||
String out = render("/es/faq", "Preguntas frecuentes", cfg);
|
||||
assertTrue(out.contains("¿Envían al extranjero?"), out);
|
||||
assertFalse(out.contains("Do you ship abroad?"), out);
|
||||
assertEquals("BlogPosting", PageTypes.describe(cfg, "/es/blog/hola", TYPES).type());
|
||||
// A catch-all reaches every language's page, as it always did.
|
||||
assertEquals("AboutPage", PageTypes.describe(Map.of("content.schema", "/*:\n type: AboutPage\n"),
|
||||
"/es/x", TYPES).type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEditorIsToldWhichDefaultLanguageEntryDoesNotReachATranslatedPage() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n/blog/*:\n type: BlogPosting\n"
|
||||
+ "/:\n type: WebPage\n/team:\n type: AboutPage\n/es/team:\n type: AboutPage\n");
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/faq", "/es/faq"), PageTypes.otherLanguageEntry(cfg, "/es/faq", SITE));
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/blog/*", "/es/blog/*"),
|
||||
PageTypes.otherLanguageEntry(cfg, "/es/blog/x", SITE));
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/", "/es"), PageTypes.otherLanguageEntry(cfg, "/es", SITE));
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/es/team", SITE), "it has its own key");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/faq", SITE), "a default-language page has no prefix");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/en/faq", SITE), "the default language is never a prefix");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/fr/faq", SITE), "fr is not a language of this site");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/es/acerca", SITE), "nothing matches /acerca either");
|
||||
Map<String, Object> catchAll = Map.of("content.schema", "/*:\n type: WebPage\n/es/*:\n type: WebPage\n"
|
||||
+ "/about:\n type: AboutPage\n");
|
||||
assertNull(PageTypes.otherLanguageEntry(catchAll, "/es/x", SITE), "/es/* is at least as specific as /*");
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/about", "/es/about"),
|
||||
PageTypes.otherLanguageEntry(catchAll, "/es/about", SITE), "/es/* is less specific than /about");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockWithoutATypeIsNotReportedAsUnknown() {
|
||||
PageTypes.Description d = PageTypes.describe(Map.of("content.schema",
|
||||
"/p:\n - breadcrumb: { name: Shop, url: /shop }\n - type: Product\n name: P\n"), "/p", TYPES);
|
||||
assertTrue(d.unknown().isEmpty(), d.unknown().toString());
|
||||
assertEquals(List.of("Product"), d.addedTypes());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The plugin-owned {@code /robots.txt}: a general allow-all group + the {@code Sitemap:} line, with a
|
||||
* configurable AI/LLM-crawler policy (per-site {@code robots.ai-policy} over the app-level {@code robots.ai-default}),
|
||||
* tenant extra Disallow paths, and a full-body custom override.
|
||||
*/
|
||||
class RobotsTxtEndpointTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
|
||||
private static PluginSettings config(Map<String, Object> cfg) {
|
||||
return TestSettings.declared().site("acme", cfg);
|
||||
}
|
||||
|
||||
private static DiscoverabilityProperties props(String aiDefault) {
|
||||
DiscoverabilityProperties p = new DiscoverabilityProperties();
|
||||
p.getRobots().setAiDefault(aiDefault);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers) {
|
||||
return req(site, headers, "");
|
||||
}
|
||||
|
||||
/** A request as the kernel builds it: the trusted origin, no forwarded headers. */
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers, String origin) {
|
||||
return new RouteRequest(site, EN, "GET", "/robots.txt", Map.of(), headers, new byte[0], Map.of(), null,
|
||||
origin);
|
||||
}
|
||||
|
||||
private static String bodyOf(Map<String, Object> cfg, String aiDefault, SiteView site, Map<String, String> headers) {
|
||||
return bodyOf(cfg, aiDefault, req(site, headers));
|
||||
}
|
||||
|
||||
private static String bodyOf(Map<String, Object> cfg, String aiDefault, RouteRequest req) {
|
||||
RouteResponse r = new RobotsTxtEndpoint(config(cfg), props(aiDefault)).handle(req);
|
||||
assertEquals(200, r.status());
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultAllowsEveryoneAndPointsAtTheSitemap() {
|
||||
String out = bodyOf(Map.of(), "allow", SITE, Map.of());
|
||||
assertTrue(out.contains("User-agent: *"), out);
|
||||
assertTrue(out.contains("Allow: /"), out);
|
||||
assertTrue(out.contains("Sitemap: https://acme.test/sitemap.xml"), out);
|
||||
// The AI/LLM posture is stated EXPLICITLY: a named group is emitted even on allow, with Allow — not
|
||||
// Disallow — so nothing is actually blocked.
|
||||
assertTrue(out.contains("User-agent: GPTBot"), "explicit AI-crawler group even on allow: " + out);
|
||||
assertFalse(out.contains("Disallow: /"), "allow posture disallows nothing: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void perSiteDisallowEmitsAiCrawlerGroups() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of());
|
||||
assertTrue(out.contains("User-agent: GPTBot"), out);
|
||||
assertTrue(out.contains("User-agent: ClaudeBot"), out);
|
||||
assertTrue(out.contains("User-agent: Google-Extended"), out);
|
||||
assertTrue(out.contains("Disallow: /"), out);
|
||||
assertTrue(out.contains("User-agent: *"), "classic crawlers are still allowed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void inheritsAppLevelDisallowDefault() {
|
||||
String out = bodyOf(Map.of(), "disallow", SITE, Map.of()); // policy defaults to inherit
|
||||
assertTrue(out.contains("User-agent: GPTBot"), "inherit → app default disallow: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void perSiteAllowOverridesAppLevelDisallowDefault() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "allow"), "disallow", SITE, Map.of());
|
||||
// Per-site allow wins over the app default: the named group is still present (explicit posture) but as
|
||||
// Allow, never Disallow: /.
|
||||
assertTrue(out.contains("User-agent: GPTBot"), out);
|
||||
assertFalse(out.contains("Disallow: /"), "per-site allow wins over the app default: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowedAiGroupMirrorsTenantExtraDisallows() {
|
||||
// On the allow posture the named AI group MIRRORS the general group's exclusions, so a most-specific
|
||||
// robots.txt match cannot let AI crawlers bypass the tenant's own Disallow paths. /private thus appears
|
||||
// twice: once under the AI group, once under the * group.
|
||||
String out = bodyOf(Map.of("robots.extra-disallow", List.of("/private")), "allow", SITE, Map.of());
|
||||
long count = out.lines().filter(l -> l.equals("Disallow: /private")).count();
|
||||
assertEquals(2, count, "AI group mirrors the tenant exclusion: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void omitsSitemapLineWhenSitemapDisabled() {
|
||||
String out = bodyOf(Map.of("sitemap.enabled", false), "allow", SITE, Map.of());
|
||||
assertFalse(out.contains("Sitemap:"), out);
|
||||
assertTrue(out.contains("Allow: /"), "still serves the allow group");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsTenantExtraDisallowPathsNormalized() {
|
||||
String out = bodyOf(Map.of("robots.extra-disallow", List.of("/private", "search")), "allow", SITE, Map.of());
|
||||
assertTrue(out.contains("Disallow: /private"), out);
|
||||
assertTrue(out.contains("Disallow: /search"), "a bare path is normalized to /search: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void customBodyReplacesEverythingVerbatim() {
|
||||
String out = bodyOf(Map.of("robots.custom", "User-agent: *\nDisallow: /"), "allow", SITE, Map.of());
|
||||
assertEquals("User-agent: *\nDisallow: /\n", out);
|
||||
assertFalse(out.contains("Sitemap:"), "the custom body is verbatim — no generated additions");
|
||||
}
|
||||
|
||||
@Test
|
||||
void takesTheSitemapOriginFromTheTrustedRequestOriginWhenBaseUrlUnset() {
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN), null);
|
||||
String out = bodyOf(Map.of(), "allow", req(noBase, Map.of("Host", "acme.test"), "http://acme.test:8080"));
|
||||
assertTrue(out.contains("Sitemap: http://acme.test:8080/sitemap.xml"), "the origin as the kernel gated it, "
|
||||
+ "scheme and port included — never a guessed https from the Host header: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConfiguredBaseUrlWinsOverTheRequestOrigin() {
|
||||
String out = bodyOf(Map.of(), "allow", req(SITE, Map.of(), "http://internal:8080"));
|
||||
assertTrue(out.contains("Sitemap: https://acme.test/sitemap.xml"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noBaseUrlAndNoOriginMeansNoSitemapLineRatherThanARelativeOne() {
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN), null);
|
||||
String out = bodyOf(Map.of(), "allow", req(noBase, Map.of("Host", "acme.test"), ""));
|
||||
assertFalse(out.contains("Sitemap:"), "a Host header alone is no longer trusted: " + out);
|
||||
}
|
||||
|
||||
/**
|
||||
* The exact regression the SEO/GEO compliance audit found in 1.3.0: {@code ClaudeBot} was listed but
|
||||
* {@code Claude-User} and {@code Claude-SearchBot} were not, so a site set to {@code disallow} was still
|
||||
* reachable by two of the three Anthropic agents — an opt-out the owner believed was complete and was not.
|
||||
*
|
||||
* <p>Asserted per-vendor across all three CLASSES the article distinguishes (training / live retrieval /
|
||||
* user-triggered fetch), because the failure mode is one missing name, not a missing feature — a test that
|
||||
* only checked "some AI agent is present" would have passed against the bug.
|
||||
*/
|
||||
@Test
|
||||
void everyAgentClassIsCoveredForEachMajorVendor() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of());
|
||||
for (String agent : List.of(
|
||||
"GPTBot", "OAI-SearchBot", "ChatGPT-User", // OpenAI: train / retrieve / user
|
||||
"ClaudeBot", "Claude-SearchBot", "Claude-User", // Anthropic: train / retrieve / user
|
||||
"PerplexityBot", "Perplexity-User", // Perplexity: retrieve / user
|
||||
"Google-Extended", "Applebot-Extended")) { // training opt-outs, NOT the search bots
|
||||
assertTrue(out.contains("User-agent: " + agent + "\n"), "missing agent: " + agent);
|
||||
}
|
||||
// The training opt-out must never take the SEARCH crawler with it — that would deindex the site.
|
||||
assertFalse(out.contains("User-agent: Googlebot\n"), "Googlebot must never be in the AI opt-out group");
|
||||
assertFalse(out.contains("User-agent: Applebot\n"), "Applebot must never be in the AI opt-out group");
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator escape hatch: the built-in list is a compile-time constant that goes stale silently, so
|
||||
* {@code robots.ai-agents-extra} must be able to cover a newly announced agent without a plugin release.
|
||||
*
|
||||
* <p>Also pins the injection guard. An operator-supplied name lands in a {@code User-agent:} line, so a value
|
||||
* carrying CR/LF or a colon could forge extra robots directives into every tenant's file — the same class of
|
||||
* hole already closed for tenant exclusion paths.
|
||||
*/
|
||||
@Test
|
||||
void operatorAddedAgentsAreAppendedDedupedAndSanitised() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of(
|
||||
"BrandNewBot", // the point of the feature
|
||||
"gptbot", // already built in, different case → must not duplicate
|
||||
"Evil\nUser-agent: *\nDisallow: /", // injection attempt via CR/LF
|
||||
" Spaced Bot ")); // whitespace stripped
|
||||
RouteResponse r = new RobotsTxtEndpoint(config(Map.of("robots.ai-policy", "disallow")), p)
|
||||
.handle(req(SITE, Map.of()));
|
||||
String out = new String(r.body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(out.contains("User-agent: BrandNewBot\n"), "operator addition must be emitted");
|
||||
assertEquals(1, out.split("(?i)User-agent: GPTBot\n", -1).length - 1, "must not duplicate a built-in");
|
||||
assertTrue(out.contains("User-agent: SpacedBot\n"), "whitespace stripped: " + out);
|
||||
// The injected directive must not survive as its own line.
|
||||
assertFalse(out.contains("\nDisallow: /\nUser-agent: *"), "CR/LF injection must be neutralised");
|
||||
assertTrue(out.contains("User-agent: EvilUser-agent:*Disallow:/\n")
|
||||
|| out.contains("User-agent: EvilUser-agent"),
|
||||
"the payload is flattened into one inert token: " + out);
|
||||
}
|
||||
|
||||
// ---- the three AI classes are separately governable -----------------------------------------------
|
||||
|
||||
/** The group a named agent falls in: the lines from its {@code User-agent:} to the next blank line. */
|
||||
private static String groupContaining(String robots, String agent) {
|
||||
for (String group : robots.split("\n\n")) {
|
||||
if (group.contains("User-agent: " + agent + "\n") || group.endsWith("User-agent: " + agent)) {
|
||||
return group;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The case the split exists for: decline training, stay citable.
|
||||
*
|
||||
* <p>Before this a site had one AI switch, so the only way to refuse training was to refuse the answer
|
||||
* engines too — which removes the site from generated answers, the opposite of what a site optimising for
|
||||
* them wants. The three classes carry opposite consequences and now carry opposite settings.
|
||||
*/
|
||||
@Test
|
||||
void aSiteCanDeclineTrainingWhileStayingCitable() {
|
||||
String out = bodyOf(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "allow"),
|
||||
"allow", SITE, Map.of());
|
||||
|
||||
assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), out);
|
||||
assertTrue(groupContaining(out, "ClaudeBot").contains("Disallow: /"), out);
|
||||
assertTrue(groupContaining(out, "OAI-SearchBot").contains("Allow: /"), out);
|
||||
assertTrue(groupContaining(out, "Claude-SearchBot").contains("Allow: /"), out);
|
||||
}
|
||||
|
||||
/** A user-triggered fetch is its own decision: someone asked for this page. */
|
||||
@Test
|
||||
void theUserTriggeredClassIsGovernedSeparately() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "disallow", "robots.ai-user", "allow"),
|
||||
"allow", SITE, Map.of());
|
||||
|
||||
assertTrue(groupContaining(out, "ChatGPT-User").contains("Allow: /"), out);
|
||||
assertTrue(groupContaining(out, "Claude-User").contains("Allow: /"), out);
|
||||
assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), "training still declined: " + out);
|
||||
}
|
||||
|
||||
/**
|
||||
* A site that sets no per-class override gets exactly the file it got before classes existed.
|
||||
*
|
||||
* <p>Byte-for-byte, agent order included. Splitting a site that expressed no such preference into three
|
||||
* identical groups would churn every crawler's copy of a file to say precisely the same thing.
|
||||
*/
|
||||
@Test
|
||||
void aSiteWithNoPerClassOverrideGetsTheIdenticalSingleGroup() {
|
||||
String withoutClasses = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of());
|
||||
String allInherit = bodyOf(Map.of("robots.ai-policy", "disallow", "robots.ai-training", "inherit",
|
||||
"robots.ai-retrieval", "inherit", "robots.ai-user", "inherit"), "allow", SITE, Map.of());
|
||||
|
||||
assertEquals(withoutClasses, allInherit);
|
||||
assertEquals(1, withoutClasses.split("Disallow: /\n", -1).length - 1,
|
||||
"one AI group, not three: " + withoutClasses);
|
||||
}
|
||||
|
||||
/** Three overrides that happen to agree also collapse to one group — the test is the OUTPUT, not the keys. */
|
||||
@Test
|
||||
void perClassOverridesThatAgreeStillCollapseToOneGroup() {
|
||||
String out = bodyOf(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "disallow",
|
||||
"robots.ai-user", "disallow"), "allow", SITE, Map.of());
|
||||
|
||||
assertEquals(bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of()), out);
|
||||
}
|
||||
|
||||
/** A per-class override beats the site policy; an unset class still inherits it. */
|
||||
@Test
|
||||
void aClassOverrideBeatsTheSitePolicyAndAnUnsetClassInheritsIt() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "allow", "robots.ai-training", "disallow"),
|
||||
"disallow", SITE, Map.of());
|
||||
|
||||
assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), "the override wins: " + out);
|
||||
assertTrue(groupContaining(out, "OAI-SearchBot").contains("Allow: /"),
|
||||
"an unset class follows the SITE policy, not the app default: " + out);
|
||||
}
|
||||
|
||||
/**
|
||||
* An operator-added agent with no declared class follows the site's overall policy.
|
||||
*
|
||||
* <p>Exactly what it did before classes existed. Guessing a class for a name the plugin does not recognise
|
||||
* would apply a policy the operator never chose — and would do it silently.
|
||||
*/
|
||||
@Test
|
||||
void anUnclassifiedOperatorAgentFollowsTheOverallPolicy() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of("BrandNewBot"));
|
||||
String out = new String(new RobotsTxtEndpoint(
|
||||
config(Map.of("robots.ai-policy", "disallow", "robots.ai-user", "allow")), p)
|
||||
.handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(groupContaining(out, "BrandNewBot").contains("Disallow: /"), out);
|
||||
assertTrue(groupContaining(out, "Claude-User").contains("Allow: /"), out);
|
||||
}
|
||||
|
||||
/** …and an operator can classify a newly-announced agent the day it is announced. */
|
||||
@Test
|
||||
void anOperatorCanDeclareTheClassOfANewAgent() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of("retrieval=BrandNewSearchBot"));
|
||||
String out = new String(new RobotsTxtEndpoint(
|
||||
config(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "allow")), p)
|
||||
.handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(out.contains("User-agent: BrandNewSearchBot"), out);
|
||||
assertTrue(groupContaining(out, "BrandNewSearchBot").contains("Allow: /"),
|
||||
"declared retrieval, so it follows the retrieval policy: " + out);
|
||||
assertFalse(out.contains("retrieval=BrandNewSearchBot"), "the prefix must not leak into the file");
|
||||
}
|
||||
|
||||
/**
|
||||
* A misspelt class still lists the agent, and the prefix is not an injection vector.
|
||||
*
|
||||
* <p>The alternative — folding the bad prefix into the name — yields a user-agent token that matches
|
||||
* nothing, so the operator believes they covered an agent they did not. That is the silent failure the
|
||||
* whole extra-agents list exists to prevent, so a typo is reported and the agent is honoured under the
|
||||
* site's overall policy.
|
||||
*/
|
||||
@Test
|
||||
void aMisspeltClassStillListsTheAgentAndCannotInject() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of("nonsense=EvilBot", "x\nDisallow: /secret\nUser-agent: Y"));
|
||||
String out = new String(new RobotsTxtEndpoint(config(Map.of()), p)
|
||||
.handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(out.contains("User-agent: EvilBot"), "the agent the operator named is listed: " + out);
|
||||
assertFalse(out.contains("nonsense"), "the bad prefix must not become part of the name: " + out);
|
||||
assertFalse(out.contains("Disallow: /secret"), "CR/LF injection stays closed: " + out);
|
||||
}
|
||||
|
||||
/** Every built-in agent has a class, or the split silently sends it to the catch-all group. */
|
||||
@Test
|
||||
void everyBuiltInAgentIsClassified() {
|
||||
for (String agent : RobotsTxtEndpoint.AI_CRAWLERS) {
|
||||
assertTrue(RobotsTxtEndpoint.AI_CLASSES.containsKey(agent),
|
||||
agent + " has no class — it would quietly fall under the overall policy instead");
|
||||
}
|
||||
assertEquals(RobotsTxtEndpoint.AI_CRAWLERS.size(), RobotsTxtEndpoint.AI_CLASSES.size(),
|
||||
"a class map entry naming an agent that is not in the list does nothing and will rot");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Mistakes in Per-page types never break a page, so the settings screen lists them instead. */
|
||||
class SchemaProblemsTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final DiscoverAdminModel model = new DiscoverAdminModel(config, null);
|
||||
|
||||
private List<String> problems(String schema) {
|
||||
config.site("acme", Map.of("content.schema", schema));
|
||||
return model.schemaProblems("acme");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCleanOrBlankSchemaHasNone() {
|
||||
assertEquals(List.of(), problems(""));
|
||||
assertEquals(List.of(), problems("/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n"
|
||||
+ "/shop/*:\n - type: Product\n name: P\n/p:\n type: Product\n"));
|
||||
}
|
||||
|
||||
/** A block that applies but publishes nothing of its own is listed; a product's name defaults to the title. */
|
||||
@Test
|
||||
void aBlockThatPublishesNothingOfItsOwnIsListed() {
|
||||
List<String> p = problems("/faq:\n type: FAQPage\n faq: []\n/help:\n type: FAQPage\n faq:\n"
|
||||
+ " - { question: Q, answer: A }\n/c:\n type: CollectionPage\n items:\n - { name: A }\n"
|
||||
+ "/l:\n - type: AboutPage\n - type: ItemList\n/two:\n - type: AboutPage\n - type: FAQPage\n");
|
||||
assertEquals(List.of(
|
||||
"/faq: FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.",
|
||||
"/help: FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.",
|
||||
"/c: CollectionPage has no item with a url:, so no list is published.",
|
||||
"/l: ItemList has no item with a url:, so no list is published.",
|
||||
"/two: more than one page type; only the first applies."), p);
|
||||
}
|
||||
|
||||
/** Google requires a mainEntity on both, which a type with no keys cannot give; they are not offered. */
|
||||
@Test
|
||||
void qaPageAndProfilePageAreNotTypes() {
|
||||
assertEquals(List.of("/qa: QAPage is not a type this plugin knows; ignored.",
|
||||
"/me: ProfilePage is not a type this plugin knows; ignored."),
|
||||
problems("/qa:\n type: QAPage\n/me:\n type: ProfilePage\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableYamlIsOneProblemNamingTheError() {
|
||||
List<String> p = problems("/faq: [unclosed\n");
|
||||
assertEquals(1, p.size(), p.toString());
|
||||
assertTrue(p.get(0).startsWith("Per-page types cannot be read"), p.toString());
|
||||
assertEquals(1, problems("- just\n- a list\n").size(), "a list root is not a pattern map");
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachMistakeIsNamedWithItsPattern() {
|
||||
List<String> p = problems("about:\n type: AboutPage\n/a*b:\n type: WebPage\n/x:\n type: Prodcut\n"
|
||||
+ "/y:\n - type: AboutPage\n - type: ContactPage\n/z: just text\n");
|
||||
assertTrue(p.contains("about: a pattern starts with / and matches page paths."), p.toString());
|
||||
assertTrue(p.contains("/a*b: * works only at the end of a pattern; here it is matched as a character."),
|
||||
p.toString());
|
||||
assertTrue(p.contains("/x: Prodcut is not a type this plugin knows; ignored."), p.toString());
|
||||
assertTrue(p.contains("/y: more than one page type; only the first applies."), p.toString());
|
||||
assertTrue(p.contains("/z: the value must be a type block (type: ...) or a list of them; ignored."),
|
||||
p.toString());
|
||||
assertEquals(5, p.size(), p.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Keeps the settings form's layout honest. The kernel deliberately <b>tolerates</b> a broken presentation key —
|
||||
* an unknown group, a {@code showWhen} on a missing switch, a dangling {@code inheritsFrom}, an unresolved
|
||||
* message key — by quietly rendering the plain field, so a typo here would never fail anything at runtime: the
|
||||
* tenant would simply lose the section, the hiding or the help line. This test is where such a typo fails.
|
||||
*
|
||||
* <p>Reads {@code plugin.yml} as plain YAML (the plugin links only the SPI, so the kernel's descriptor parser is not
|
||||
* on the default test classpath); the {@code host-it} profile additionally parses it with the kernel's own
|
||||
* {@code PluginDescriptor} ({@code HostDescriptorTest}).
|
||||
*/
|
||||
class SettingsDescriptorTest {
|
||||
|
||||
/** The plugin project root — the working directory when the module's tests run. */
|
||||
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
|
||||
|
||||
/** One setting definition as the YAML holds it. */
|
||||
private record Def(String key, String type, String group, String help, String label, String helpAnchor,
|
||||
String showWhen, String inheritsFrom, String requiresPlatform, String range) {
|
||||
|
||||
static Def of(Map<String, Object> raw) {
|
||||
return new Def(str(raw, "key"), str(raw, "type"), str(raw, "group"), str(raw, "help"), str(raw, "label"),
|
||||
str(raw, "helpAnchor"), str(raw, "showWhen"), str(raw, "inheritsFrom"),
|
||||
str(raw, "requiresPlatform"), str(raw, "range"));
|
||||
}
|
||||
|
||||
private static String str(Map<String, Object> raw, String key) {
|
||||
Object value = raw.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> descriptor() {
|
||||
return TestSettings.descriptor();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Def> defs(String section) {
|
||||
List<Def> out = new ArrayList<>();
|
||||
Object list = descriptor().get(section);
|
||||
if (list != null) {
|
||||
for (Map<String, Object> raw : (List<Map<String, Object>>) list) {
|
||||
out.add(Def.of(raw));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Map<String, Object>> groups() {
|
||||
return (List<Map<String, Object>>) descriptor().get("settingGroups");
|
||||
}
|
||||
|
||||
private static Properties bundle(String name) throws IOException {
|
||||
Properties props = new Properties();
|
||||
try (Reader reader = Files.newBufferedReader(ROOT.resolve("i18n").resolve(name), StandardCharsets.UTF_8)) {
|
||||
props.load(reader);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
private static Map<String, Def> byKey(List<Def> schema) {
|
||||
Map<String, Def> map = new HashMap<>();
|
||||
schema.forEach(def -> map.put(def.key(), def));
|
||||
return map;
|
||||
}
|
||||
|
||||
private static List<Def> all() {
|
||||
List<Def> all = new ArrayList<>(defs("settings"));
|
||||
all.addAll(defs("siteSettings"));
|
||||
return all;
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyFieldIsInADeclaredSectionAndEverySectionIsUsed() {
|
||||
Set<String> groups = new TreeSet<>();
|
||||
groups().forEach(g -> groups.add(String.valueOf(g.get("id"))));
|
||||
Set<String> used = new TreeSet<>();
|
||||
for (Def def : all()) {
|
||||
assertTrue(groups.contains(def.group()), def.key() + " names an undeclared group '" + def.group() + "'");
|
||||
used.add(def.group());
|
||||
}
|
||||
assertEquals(groups, used, "a declared section with no fields would never show");
|
||||
assertEquals(6, groups.size(), "the six sections of the 1.6.0 layout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDependencyPointsAtARealSwitch() {
|
||||
for (List<Def> schema : List.of(defs("settings"), defs("siteSettings"))) {
|
||||
Map<String, Def> keys = byKey(schema);
|
||||
for (Def def : schema) {
|
||||
if (def.showWhen() != null) {
|
||||
Def gate = keys.get(def.showWhen());
|
||||
assertTrue(gate != null && "boolean".equals(gate.type()),
|
||||
def.key() + ": showWhen must name a boolean in the same schema, got " + def.showWhen());
|
||||
}
|
||||
if (def.inheritsFrom() != null) {
|
||||
String ref = def.inheritsFrom();
|
||||
Def source = ref.startsWith("app:")
|
||||
? byKey(defs("settings")).get(ref.substring(4)) : keys.get(ref);
|
||||
assertTrue(source != null, def.key() + ": inheritsFrom names nothing: " + ref);
|
||||
assertTrue(def.range().contains("inherit"), def.key() + ": inheritsFrom without an inherit choice");
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Def def : defs("siteSettings")) {
|
||||
if (def.requiresPlatform() != null) {
|
||||
Def platform = byKey(defs("settings")).get(def.requiresPlatform());
|
||||
assertTrue(platform != null && "boolean".equals(platform.type()),
|
||||
def.key() + ": requiresPlatform must name an app-level boolean");
|
||||
}
|
||||
}
|
||||
assertEquals("app:robots.ai-default", byKey(defs("siteSettings")).get("robots.ai-policy").inheritsFrom(),
|
||||
"the AI policy still inherits the platform default");
|
||||
assertEquals("indexnow.enabled", byKey(defs("siteSettings")).get("indexnow.enabled").requiresPlatform());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyFieldHasAHelpLineAndEveryKeyResolvesInEnglishAndSpanish() throws IOException {
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (Def def : all()) {
|
||||
assertNotNull(def.help(), def.key() + " has no help line");
|
||||
keys.add(def.label());
|
||||
keys.add(def.help());
|
||||
}
|
||||
for (Map<String, Object> g : groups()) {
|
||||
keys.add(String.valueOf(g.get("label")));
|
||||
keys.add(String.valueOf(g.get("help")));
|
||||
}
|
||||
Properties en = bundle("messages.properties");
|
||||
Properties es = bundle("messages_es.properties");
|
||||
for (String key : keys) {
|
||||
assertTrue(en.containsKey(key), "missing in messages.properties: " + key);
|
||||
assertTrue(es.containsKey(key), "missing in messages_es.properties: " + key);
|
||||
}
|
||||
assertEquals(new TreeSet<>(en.stringPropertyNames()), new TreeSet<>(es.stringPropertyNames()),
|
||||
"the English and Spanish bundles carry the same keys");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyLearnMoreLinkLandsOnASectionOfTheHelpPage() throws IOException {
|
||||
assertEquals("/__plugin/discoverability/static/discoverability-help.html", descriptor().get("helpUrl"));
|
||||
String page = Files.readString(ROOT.resolve("static").resolve("discoverability-help.html"));
|
||||
List<String> anchors = new ArrayList<>();
|
||||
groups().forEach(g -> anchors.add(g.get("helpAnchor") == null ? null : String.valueOf(g.get("helpAnchor"))));
|
||||
all().forEach(def -> anchors.add(def.helpAnchor()));
|
||||
for (String anchor : anchors) {
|
||||
if (anchor != null) {
|
||||
assertTrue(page.contains("id=\"" + anchor + "\""), "the help page has no #" + anchor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.charset.StandardCharsets;
|
||||
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.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* /sitemap.xml over the host's {@code ContentCatalogView}: the whole published content surface — pages AND plugin
|
||||
* content — with the hreflang alternates and {@code x-default} the host computed, {@code <lastmod>} from
|
||||
* {@code updatedAt}, noindex and canonicalised-elsewhere items left out, the index/shards past 10,000 URLs, and the
|
||||
* conditional GET. Disabled ⇒ 404; base from the trusted origin when the site has none.
|
||||
*
|
||||
* <p>The listing itself (published only, safe and unreserved paths, a throwing source contributing nothing) and the
|
||||
* URL computation are the host's, tested in the kernel; the host-it profile runs this endpoint over the real kernel
|
||||
* catalog ({@code HostCatalogParityTest}), including the head-vs-sitemap agreement.
|
||||
*/
|
||||
class SitemapEndpointTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final Instant UPDATED = Instant.parse("2026-07-17T10:00:00Z");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
|
||||
@BeforeEach
|
||||
void freshValidators() {
|
||||
CrawlConditional.reset(); // per-site validator state is static — isolate from sibling tests
|
||||
}
|
||||
|
||||
/** The endpoint over a listing of {@code refs} (as pages) for {@link #SITE}'s locales, sitemap on. */
|
||||
private static SitemapEndpoint endpoint(SiteView site, ContentRef... refs) {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().site("acme");
|
||||
for (ContentRef ref : refs) {
|
||||
catalog.entry("acme", Entries.page(ref, site));
|
||||
}
|
||||
return new SitemapEndpoint(catalog, TestSettings.declared());
|
||||
}
|
||||
|
||||
private static SitemapEndpoint endpoint(ContentRef... refs) {
|
||||
return endpoint(SITE, refs);
|
||||
}
|
||||
|
||||
private static final ContentRef ABOUT = ContentRef.of("about", "/about", Map.of(), List.of(EN, ES),
|
||||
Map.of("en", "About", "es", "Acerca"), Map.of("en", "About page"), "__site__/acme/about", UPDATED);
|
||||
private static final ContentRef ENTRY = ContentRef.of("my-post", "/blog/my-post",
|
||||
Map.of("es", "/blog/mi-entrada"), List.of(EN, ES), Map.of("en", "My post"), Map.of(),
|
||||
"__plugin__/blog/entry", UPDATED);
|
||||
|
||||
/** Published, but the site tells robots not to index it — must not be advertised. */
|
||||
private static final ContentRef NOINDEXED = new ContentRef("hidden", "/hidden", Map.of(), List.of(EN),
|
||||
Map.of("en", "Hidden"), Map.of(), null, "__site__/acme/hidden", true, UPDATED, true, null, null,
|
||||
Map.of());
|
||||
/** Published and indexable, but declares a DIFFERENT canonical — it is not the authoritative URL. */
|
||||
private static final ContentRef DUPLICATE = new ContentRef("dupe", "/dupe", Map.of(), List.of(EN),
|
||||
Map.of("en", "Dupe"), Map.of(), null, "__site__/acme/dupe", true, UPDATED, false,
|
||||
"https://acme.test/about", null, Map.of());
|
||||
/** Published with a SELF-referential canonical — the ordinary case, which must still be listed. */
|
||||
private static final ContentRef SELF_CANONICAL = new ContentRef("self", "/self", Map.of(), List.of(EN),
|
||||
Map.of("en", "Self"), Map.of(), null, "__site__/acme/self", true, UPDATED, false,
|
||||
"https://acme.test/self", null, Map.of());
|
||||
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers) {
|
||||
return req(site, headers, "/sitemap.xml");
|
||||
}
|
||||
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers, String path) {
|
||||
return new RouteRequest(site, EN, "GET", path, Map.of(), headers, new byte[0], Map.of(), null, "");
|
||||
}
|
||||
|
||||
/** {@code n} trivial published pages — the fixture for the sharding tests. */
|
||||
private static ContentRef[] pages(int n) {
|
||||
ContentRef[] many = new ContentRef[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
many[i] = new ContentRef("p" + i, "/p" + i, Map.of(), List.of(EN), Map.of("en", "P" + i), Map.of(),
|
||||
null, "__site__/acme/p" + i, true, UPDATED, false, null, null, Map.of());
|
||||
}
|
||||
return many;
|
||||
}
|
||||
|
||||
private static String body(RouteResponse r) {
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesTheWholeContentSurfaceWithHreflangAndLastmod() {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", Entries.page(ABOUT, SITE))
|
||||
.entry("acme", Entries.of("blog", ENTRY, SITE));
|
||||
RouteResponse r = new SitemapEndpoint(catalog, TestSettings.declared()).handle(req(SITE, Map.of()));
|
||||
|
||||
assertEquals(200, r.status());
|
||||
assertEquals("application/xml; charset=utf-8", r.headers().get("Content-Type"));
|
||||
String xml = body(r);
|
||||
// Page-like items, both locales, the default unprefixed.
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), "default locale is unprefixed");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/about</loc>"), "other locale is /<lang>-prefixed");
|
||||
assertTrue(xml.contains("hreflang=\"en\"") && xml.contains("hreflang=\"es\""));
|
||||
assertTrue(xml.contains("hreflang=\"x-default\""));
|
||||
// PLUGIN content is a first-class sitemap citizen — with its LOCALIZED slug.
|
||||
assertTrue(xml.contains("<loc>https://acme.test/blog/my-post</loc>"), "virtual entry listed");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/blog/mi-entrada</loc>"), "its localized slug too");
|
||||
assertTrue(xml.contains("<lastmod>" + UPDATED + "</lastmod>"), "lastmod emitted from updatedAt");
|
||||
}
|
||||
|
||||
/**
|
||||
* The exact document — every byte — for a small bilingual site. 2.0.0 reads its URLs from the host's listing
|
||||
* instead of computing them; this pins the document so that move cannot change what a crawler receives.
|
||||
*/
|
||||
@Test
|
||||
void theDocumentIsByteForByteWhatOnePointSixServed() {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", Entries.of("blog", ENTRY, SITE))
|
||||
.entry("acme", Entries.page(ABOUT, SITE));
|
||||
String xml = body(new SitemapEndpoint(catalog, TestSettings.declared()).handle(req(SITE, Map.of())));
|
||||
String about = """
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://acme.test/about"/>
|
||||
<xhtml:link rel="alternate" hreflang="es" href="https://acme.test/es/about"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://acme.test/about"/>
|
||||
""";
|
||||
String post = """
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://acme.test/blog/my-post"/>
|
||||
<xhtml:link rel="alternate" hreflang="es" href="https://acme.test/es/blog/mi-entrada"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://acme.test/blog/my-post"/>
|
||||
""";
|
||||
String lastmod = " <lastmod>2026-07-17T10:00:00Z</lastmod>\n";
|
||||
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
||||
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" "
|
||||
+ "xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n"
|
||||
+ " <url>\n <loc>https://acme.test/about</loc>\n" + lastmod + about + " </url>\n"
|
||||
+ " <url>\n <loc>https://acme.test/blog/my-post</loc>\n" + lastmod + post + " </url>\n"
|
||||
+ " <url>\n <loc>https://acme.test/es/about</loc>\n" + lastmod + about + " </url>\n"
|
||||
+ " <url>\n <loc>https://acme.test/es/blog/mi-entrada</loc>\n" + lastmod + post + " </url>\n"
|
||||
+ "</urlset>\n", xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalGetRevalidatesWith304AndTheHeadersMatch() {
|
||||
SitemapEndpoint endpoint = endpoint(ABOUT);
|
||||
|
||||
RouteResponse fresh = endpoint.handle(req(SITE, Map.of()));
|
||||
assertEquals(200, fresh.status());
|
||||
String lastModified = fresh.headers().get("Last-Modified");
|
||||
assertTrue(lastModified != null && !lastModified.isBlank(), "the 200 carries Last-Modified");
|
||||
assertEquals("no-cache", fresh.headers().get("Cache-Control"), "cache-but-revalidate posture");
|
||||
|
||||
RouteResponse revalidated = endpoint.handle(req(SITE, Map.of("If-Modified-Since", lastModified)));
|
||||
assertEquals(304, revalidated.status(), "an unchanged sitemap revalidates without re-serializing");
|
||||
assertEquals(0, revalidated.body().length, "the 304 carries no body");
|
||||
assertEquals(lastModified, revalidated.headers().get("Last-Modified"), "same validator");
|
||||
|
||||
RouteResponse older = endpoint.handle(req(SITE,
|
||||
Map.of("If-Modified-Since", "Mon, 01 Jan 2001 00:00:00 GMT")));
|
||||
assertEquals(200, older.status(), "an outdated copy gets the full document again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledReturns404() {
|
||||
FakePluginSettings off = TestSettings.declared().site("acme", Map.of("sitemap.enabled", false));
|
||||
RouteResponse r = new SitemapEndpoint(new FakeContentCatalog().entry("acme", Entries.page(ABOUT, SITE)), off)
|
||||
.handle(req(SITE, Map.of()));
|
||||
assertEquals(404, r.status());
|
||||
assertEquals("no-store", r.headers().get("Cache-Control"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledByDefault() {
|
||||
assertEquals(200, endpoint(ABOUT).handle(req(SITE, Map.of())).status(), "sitemap.enabled defaults on");
|
||||
}
|
||||
|
||||
/**
|
||||
* Without a configured base URL the absolute URLs use the request's TRUSTED origin (scheme, host and port as
|
||||
* the kernel's trusted-proxy gate left them). 1.x read the raw Host header and guessed {@code https}.
|
||||
*/
|
||||
@Test
|
||||
void takesTheBaseFromTheTrustedOriginWhenBaseUrlUnset() {
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
RouteRequest request = new RouteRequest(noBase, EN, "GET", "/sitemap.xml", Map.of(),
|
||||
Map.of("Host", "spoofed.test"), new byte[0], Map.of(), null, "http://acme.test:8080");
|
||||
String xml = body(endpoint(noBase, ABOUT).handle(request));
|
||||
assertTrue(xml.contains("<loc>http://acme.test:8080/about</loc>"), xml);
|
||||
assertFalse(xml.contains("spoofed") || xml.contains("https://"), "never the Host header, never a guess");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrailingSlashOnTheConfiguredBaseIsDropped() {
|
||||
SiteView slash = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test/");
|
||||
String xml = body(endpoint(slash, ABOUT).handle(req(slash, Map.of())));
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* A sitemap is a list of URLs the site RECOMMENDS for indexing, so listing a page it separately tells robots
|
||||
* not to index contradicts itself — sitemaps.org treats such a file as a quality signal against the site.
|
||||
*
|
||||
* <p>Filtered in the plugin rather than in {@code ContentCatalog} on purpose: the router, the search indexer
|
||||
* and llms.txt all legitimately need the full published set, so narrowing the catalog would break them.
|
||||
*/
|
||||
@Test
|
||||
void noindexContentIsPublishedButNeverAdvertised() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, ABOUT, NOINDEXED).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), "indexable content still listed");
|
||||
assertFalse(xml.contains("/hidden"), "noindex content must not appear in the sitemap");
|
||||
}
|
||||
|
||||
/**
|
||||
* An item declaring a canonical elsewhere has said it is not the authoritative URL; advertising it would put
|
||||
* a self-declared non-canonical address in the sitemap. A canonical equal to the item's OWN url is the normal
|
||||
* self-referential case and must not be swept up by the same rule — that is the half a naive check breaks.
|
||||
*/
|
||||
@Test
|
||||
void anItemCanonicalisedElsewhereIsOmittedButASelfCanonicalOneIsKept() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, ABOUT, DUPLICATE, SELF_CANONICAL).handle(req(site, Map.of())));
|
||||
|
||||
assertFalse(xml.contains("/dupe"), "an item canonicalised elsewhere is not the authoritative URL");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/self</loc>"), "a SELF-referential canonical stays listed");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), "an item with no canonical stays listed");
|
||||
}
|
||||
|
||||
/**
|
||||
* A ROOT-RELATIVE canonical names an address on this site and is resolved against the base before comparing, as
|
||||
* the kernel resolves it for the {@code <head>}. 1.x compared the raw {@code /self} with the absolute URLs, so a
|
||||
* page whose canonical was its own path was dropped from the sitemap.
|
||||
*/
|
||||
@Test
|
||||
void aRootRelativeSelfCanonicalIsKeptAndARootRelativeElsewhereOneIsOmitted() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
ContentRef self = new ContentRef("self", "/self", Map.of(), List.of(EN, ES), Map.of("en", "Self"), Map.of(),
|
||||
null, "__site__/acme/self", true, UPDATED, false, "/self", null, Map.of());
|
||||
ContentRef elsewhere = new ContentRef("copy", "/copy", Map.of(), List.of(EN), Map.of("en", "Copy"), Map.of(),
|
||||
null, "__site__/acme/copy", true, UPDATED, false, "/self", null, Map.of());
|
||||
String xml = body(endpoint(site, self, elsewhere).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<loc>https://acme.test/self</loc>"), xml);
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/self</loc>"), "every locale of a self-canonical item");
|
||||
assertFalse(xml.contains("/copy"), "a root-relative canonical naming ANOTHER page still points elsewhere");
|
||||
}
|
||||
|
||||
/**
|
||||
* An item that exists only in a non-default locale: its one address and its x-default are the host's (the
|
||||
* Spanish URL), never the unprefixed default path, which the site does not serve.
|
||||
*/
|
||||
@Test
|
||||
void aNonDefaultLocaleOnlyItemUsesTheHostsAddressesForLocAndXDefault() {
|
||||
ContentRef solo = ContentRef.of("solo", "/solo", Map.of("es", "/solo-es"), List.of(ES), Map.of("es", "Solo"),
|
||||
Map.of(), "__site__/acme/solo", UPDATED);
|
||||
String xml = body(endpoint(solo).handle(req(SITE, Map.of())));
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/solo-es</loc>"), xml);
|
||||
assertTrue(xml.contains("hreflang=\"x-default\" href=\"https://acme.test/es/solo-es\""), xml);
|
||||
assertFalse(xml.contains("https://acme.test/solo\""), "the unprefixed default path does not serve: " + xml);
|
||||
assertFalse(xml.contains("hreflang=\"en\""), "no alternate for a locale the item does not exist in");
|
||||
}
|
||||
|
||||
/** A canonical naming one of the item's OTHER locales' addresses is still self-referential. */
|
||||
@Test
|
||||
void aCanonicalNamingAnotherLocaleOfTheSameItemIsSelf() {
|
||||
ContentRef ref = new ContentRef("about", "/about", Map.of(), List.of(EN, ES), Map.of("en", "About"), Map.of(),
|
||||
null, "__site__/acme/about", true, UPDATED, false, "https://acme.test/es/about", null, Map.of());
|
||||
String xml = body(endpoint(ref).handle(req(SITE, Map.of())));
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), xml);
|
||||
}
|
||||
|
||||
// ---- sitemap index -------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A small site keeps a single {@code <urlset>} — no index, no second round trip.
|
||||
*
|
||||
* <p>This is the shape almost every tenant has, and splitting a 40-URL site across an index would cost a
|
||||
* crawler two fetches to learn nothing.
|
||||
*/
|
||||
@Test
|
||||
void asmallSiteIsStillASinglePlainUrlset() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, pages(40)).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<urlset"), xml.substring(0, Math.min(200, xml.length())));
|
||||
assertFalse(xml.contains("<sitemapindex"), "no index for a site that fits in one file");
|
||||
assertEquals(40, xml.split("<loc>", -1).length - 1);
|
||||
}
|
||||
|
||||
/** …and its shard paths 404 rather than serving the same document at a second address. */
|
||||
@Test
|
||||
void aSmallSiteAnswers404OnTheShardPaths() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
|
||||
RouteResponse response = endpoint(site, pages(40)).handle(req(site, Map.of(), "/sitemap-1.xml"));
|
||||
|
||||
assertEquals(404, response.status(),
|
||||
"two URLs serving one document is the duplicate-content shape this plugin exists to avoid");
|
||||
}
|
||||
|
||||
/**
|
||||
* Past one shard's worth, {@code /sitemap.xml} becomes an index naming exactly the shards that exist.
|
||||
*
|
||||
* <p>25,000 URLs is three shards of 10,000 — the third holding 5,000 — so the count catches both an
|
||||
* off-by-one in the ceiling division and an index that advertises a shard with nothing in it.
|
||||
*/
|
||||
@Test
|
||||
void aLargeSiteGetsAnIndexNamingExactlyTheShardsThatExist() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, pages(25_000)).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<sitemapindex"), "over one shard's worth, the entry point is an index");
|
||||
assertEquals(3, xml.split("<loc>", -1).length - 1, "25,000 URLs is 3 shards, not 2 and not 4");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/sitemap-1.xml</loc>"), xml);
|
||||
assertTrue(xml.contains("<loc>https://acme.test/sitemap-3.xml</loc>"), xml);
|
||||
assertFalse(xml.contains("/sitemap-4.xml"), "an empty shard must never be advertised");
|
||||
}
|
||||
|
||||
/** Each shard carries its own slice, full shards first, and the last one holds the remainder. */
|
||||
@Test
|
||||
void eachShardCarriesItsOwnSliceAndTheLastHoldsTheRemainder() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
SitemapEndpoint endpoint = endpoint(site, pages(25_000));
|
||||
|
||||
String first = body(endpoint.handle(req(site, Map.of(), "/sitemap-1.xml")));
|
||||
String last = body(endpoint.handle(req(site, Map.of(), "/sitemap-3.xml")));
|
||||
|
||||
assertEquals(10_000, first.split("<loc>", -1).length - 1);
|
||||
assertEquals(5_000, last.split("<loc>", -1).length - 1);
|
||||
assertTrue(first.contains("<urlset") && last.contains("<urlset"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shards partition the URL set: every URL appears in exactly one, and none is lost at a boundary.
|
||||
*
|
||||
* <p>Asserted as a set rather than by counting, because a boundary bug that drops one URL and duplicates
|
||||
* another leaves the totals right.
|
||||
*/
|
||||
@Test
|
||||
void theShardsPartitionTheUrlSetWithNoGapOrOverlap() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
SitemapEndpoint endpoint = endpoint(site, pages(25_000));
|
||||
|
||||
List<String> all = new java.util.ArrayList<>();
|
||||
for (int shard = 1; shard <= 3; shard++) {
|
||||
all.addAll(locs(body(endpoint.handle(req(site, Map.of(), "/sitemap-" + shard + ".xml")))));
|
||||
}
|
||||
|
||||
assertEquals(25_000, all.size(), "no URL is served twice");
|
||||
assertEquals(25_000, new java.util.HashSet<>(all).size(), "…and none is served twice under two names");
|
||||
assertTrue(all.contains("https://acme.test/p0") && all.contains("https://acme.test/p24999"),
|
||||
"the first and last items both survive the split");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shard membership is a function of the CONTENT, not of source-registration order.
|
||||
*
|
||||
* <p>The host's listing is grouped by source in an order it does not promise, which says nothing across
|
||||
* restarts or across the nodes of a cluster. If shard boundaries followed it, two nodes behind one load
|
||||
* balancer would serve <b>different content for the same shard number</b>, and a crawler alternating
|
||||
* between them would watch URLs appear and vanish with nothing in the response to explain it.
|
||||
*/
|
||||
@Test
|
||||
void shardMembershipDoesNotDependOnSourceOrder() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
ContentRef[] refs = pages(25_000);
|
||||
ContentRef[] reversed = new ContentRef[refs.length];
|
||||
for (int i = 0; i < refs.length; i++) {
|
||||
reversed[i] = refs[refs.length - 1 - i];
|
||||
}
|
||||
|
||||
String oneWay = body(endpoint(site, refs).handle(req(site, Map.of(), "/sitemap-2.xml")));
|
||||
String other = body(endpoint(site, reversed).handle(req(site, Map.of(), "/sitemap-2.xml")));
|
||||
|
||||
assertEquals(oneWay, other, "the same shard number must mean the same URLs on every node");
|
||||
}
|
||||
|
||||
/** A shard number past the end 404s — nothing links to it, so the only way there is to type it. */
|
||||
@Test
|
||||
void aShardBeyondTheEndIs404() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
SitemapEndpoint endpoint = endpoint(site, pages(25_000));
|
||||
|
||||
assertEquals(404, endpoint.handle(req(site, Map.of(), "/sitemap-4.xml")).status());
|
||||
assertEquals(200, endpoint.handle(req(site, Map.of(), "/sitemap-3.xml")).status());
|
||||
}
|
||||
|
||||
/** Every shard route is declared, because the host matches routes by exact path — no patterns. */
|
||||
@Test
|
||||
void theIndexAndEveryShardAreDeclaredRoutes() {
|
||||
List<String> paths = endpoint().routes().stream()
|
||||
.map(mx.quest.runway.spi.model.Route::pathPattern).toList();
|
||||
|
||||
assertTrue(paths.contains("/sitemap.xml"));
|
||||
assertTrue(paths.contains("/sitemap-1.xml"));
|
||||
assertTrue(paths.contains("/sitemap-20.xml"));
|
||||
assertFalse(paths.contains("/sitemap-21.xml"), "the ceiling is real and must be visible in the routes");
|
||||
}
|
||||
|
||||
/** The {@code <loc>} values of a sitemap document. */
|
||||
private static List<String> locs(String xml) {
|
||||
List<String> found = new java.util.ArrayList<>();
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("<loc>([^<]+)</loc>").matcher(xml);
|
||||
while (m.find()) {
|
||||
found.add(m.group(1));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.Provenance;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** SEO+ structured-data head: emits the WebSite/WebPage(/Organization) graph, and nothing when it shouldn't. */
|
||||
class StructuredDataHeadTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final StructuredDataHead head = new StructuredDataHead(config, Map.of());
|
||||
private final StructuredDataHead typed = new StructuredDataHead(config, Map.ofEntries(
|
||||
Map.entry("FAQPage", new FaqPageSchema()),
|
||||
Map.entry("Product", new ProductSchema()),
|
||||
Map.entry("Article", new ArticleSchema()),
|
||||
Map.entry("BlogPosting", new ArticleSchema()),
|
||||
Map.entry("LocalBusiness", new LocalBusinessSchema()),
|
||||
Map.entry("CafeOrCoffeeShop", new LocalBusinessSchema()),
|
||||
Map.entry("Service", new ServiceSchema()),
|
||||
Map.entry("ProfessionalService", new ServiceSchema()),
|
||||
Map.entry("Person", new PersonSchema()),
|
||||
Map.entry("ItemList", new CollectionSchema()),
|
||||
Map.entry("CollectionPage", new CollectionSchema())));
|
||||
|
||||
private static HeadContext pageAt(String path, String title) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta(path.substring(1), title, "",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
String canonical = "https://acme.test" + path;
|
||||
return new HeadContext(site, page, Locale.ENGLISH, canonical, canonical, List.of(), false, false);
|
||||
}
|
||||
|
||||
private void cfg(Map<String, Object> map) {
|
||||
config.site("acme", map);
|
||||
}
|
||||
|
||||
private HeadContext ctx(boolean preview, boolean noindex) {
|
||||
SiteView site = new SiteView("acme", "Acme Corp", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("about", "About Acme", "We build things.",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, noindex);
|
||||
return new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about",
|
||||
"https://acme.test/about", List.of(), preview, noindex);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsWebSiteAndWebPageByDefault() {
|
||||
cfg(Map.of()); // all defaults → jsonld.enabled true
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("application/ld+json"));
|
||||
assertTrue(out.contains("\"@type\":\"WebSite\""));
|
||||
assertTrue(out.contains("\"@type\":\"WebPage\""));
|
||||
assertTrue(out.contains("https://acme.test/about"), "the WebPage is anchored on the canonical");
|
||||
assertTrue(out.contains("About Acme"));
|
||||
assertTrue(out.contains("\"isPartOf\""), "the WebPage references the WebSite");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsOrganizationWithSameAsWhenConfigured() {
|
||||
cfg(Map.of("org.name", "Acme Corp", "org.logo", "https://acme.test/logo.png",
|
||||
"org.sameas", List.of("https://social.example/acme", "https://network.example/acme")));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"@type\":\"Organization\""));
|
||||
assertTrue(out.contains("Acme Corp"));
|
||||
assertTrue(out.contains("logo.png"));
|
||||
assertTrue(out.contains("social.example/acme") && out.contains("network.example/acme"), "sameAs profiles emitted");
|
||||
assertTrue(out.contains("\"publisher\""), "the WebPage names the Organization as publisher");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesARootRelativeOrgLogoToAbsolute() {
|
||||
cfg(Map.of("org.name", "Acme", "org.logo", "/static/img/logo.svg"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"logo\":\"https://acme.test/static/img/logo.svg\""),
|
||||
"a root-relative org.logo resolves against the site base: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsArticleHeadlineWhenTypeIsArticle() {
|
||||
cfg(Map.of("jsonld.type", "Article"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"@type\":\"Article\""));
|
||||
assertTrue(out.contains("\"headline\":\"About Acme\""), "Article uses headline, not name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsNothingOnNoindexPreviewOrWhenDisabled() {
|
||||
cfg(Map.of());
|
||||
assertEquals("", head.render(ctx(false, true)), "no structured data on a noindex page");
|
||||
assertEquals("", head.render(ctx(true, false)), "no structured data on a preview render");
|
||||
cfg(Map.of("jsonld.enabled", false));
|
||||
assertEquals("", head.render(ctx(false, false)), "disabled by the tenant");
|
||||
}
|
||||
|
||||
@Test
|
||||
void breadcrumbsAppearForAChildPageAndNotTheHome() {
|
||||
cfg(Map.of());
|
||||
assertTrue(head.render(ctx(false, false)).contains("\"@type\":\"BreadcrumbList\""), "child page has a trail");
|
||||
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta home = new PageMeta("index", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext homeCtx = new HeadContext(site, home, Locale.ENGLISH, "https://acme.test/",
|
||||
"https://acme.test/", List.of(), false, false);
|
||||
assertFalse(head.render(homeCtx).contains("BreadcrumbList"), "the home page needs no breadcrumb");
|
||||
}
|
||||
|
||||
// --- GEO signals, now folded into the single @graph (was AnswerSchemaHead) --------------------------
|
||||
|
||||
@Test
|
||||
void foldsGeoSignalsIntoTheSameNodesWhenEnabled() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertEquals(1, countOccurrences(out, "application/ld+json"), "exactly one ld+json block: " + out);
|
||||
// WebSite/WebPage each defined exactly once, carrying the GEO signals inline (not a second block by @id)
|
||||
assertEquals(1, countOccurrences(out, "\"@type\":\"WebSite\""), out);
|
||||
assertEquals(1, countOccurrences(out, "\"@type\":\"WebPage\""), out);
|
||||
assertTrue(out.contains("\"potentialAction\"") && out.contains("SearchAction"), out);
|
||||
assertTrue(out.contains("\"speakable\"") && out.contains("SpeakableSpecification"), out);
|
||||
assertTrue(out.contains("{search_term_string}"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void speakableDefaultsToRealSelectorsNotPhantomArticle() {
|
||||
cfg(Map.of("geo.enabled", true));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("SpeakableSpecification"), out);
|
||||
assertTrue(out.contains("\"h1\"") && out.contains("\"main\""), out);
|
||||
assertFalse(out.contains("\"article\""), "the default no longer emits the phantom 'article' selector: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void geoSignalsAbsentWhenGeoDisabled() {
|
||||
cfg(Map.of()); // geo.enabled default false
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"@type\":\"WebSite\""), "the SEO graph still emits");
|
||||
assertFalse(out.contains("speakable"), "no GEO speakable when geo disabled");
|
||||
assertFalse(out.contains("SearchAction"), "no GEO SearchAction when geo disabled");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsCurlyQueryPlaceholderToSchemaVariable() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/find?q={query}"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("q={search_term_string}"), out);
|
||||
assertFalse(out.contains("{query}"), "the {query} placeholder is rewritten");
|
||||
}
|
||||
|
||||
// --- SoftwareApplication (item 4): homepage-only, @id-linked ---------------------------------------
|
||||
|
||||
private HeadContext homeCtx(String canonical) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta home = new PageMeta("index", "Home", "The home page.",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
return new HeadContext(site, home, Locale.ENGLISH, canonical, canonical, List.of(), false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsSoftwareApplicationOnTheHomepageOnly() {
|
||||
cfg(Map.of("software.enabled", true, "software.name", "Acme App", "software.category", "WebApplication",
|
||||
"software.price", "0", "org.name", "Acme Corp"));
|
||||
assertFalse(head.render(ctx(false, false)).contains("SoftwareApplication"),
|
||||
"not emitted on an interior page");
|
||||
String out = head.render(homeCtx("https://acme.test/"));
|
||||
assertTrue(out.contains("\"@type\":\"SoftwareApplication\""), out);
|
||||
assertTrue(out.contains("acme.test/#software"), "carries a stable @id: " + out);
|
||||
assertTrue(out.contains("Acme App"), out);
|
||||
assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"0\""), "free offer: " + out);
|
||||
assertTrue(out.contains("\"publisher\""), "references the Organization as publisher");
|
||||
assertEquals(1, countOccurrences(out, "\"@type\":\"SoftwareApplication\""), "emitted exactly once: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void softwareApplicationAlsoFiresOnALocalizedHome() {
|
||||
cfg(Map.of("software.enabled", true, "software.name", "Acme App"));
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH,
|
||||
List.of(Locale.ENGLISH, Locale.forLanguageTag("es")), "https://acme.test");
|
||||
PageMeta page = new PageMeta("index", "Inicio", "",
|
||||
List.of(Locale.ENGLISH), Locale.forLanguageTag("es"), true, false);
|
||||
HeadContext esHome = new HeadContext(site, page, Locale.forLanguageTag("es"), "https://acme.test/es",
|
||||
"https://acme.test/", List.of(), false, false);
|
||||
assertTrue(head.render(esHome).contains("SoftwareApplication"), "the localized home /es carries the entity");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCrossDomainCanonicalOverrideDoesNotLeakSoftwareApplication() {
|
||||
// A per-page canonical pointing at ANOTHER host must not be mistaken for the home (which would leak the
|
||||
// homepage-only SoftwareApplication) — the pathOf() prefix guard returns a non-"/" path so isHome is false.
|
||||
cfg(Map.of("software.enabled", true, "software.name", "Acme App"));
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("syndicated", "Syndicated", "",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://ex.test/x",
|
||||
"https://ex.test/x", List.of(), false, false);
|
||||
String out = head.render(ctx);
|
||||
assertFalse(out.contains("SoftwareApplication"), "no homepage entity on a cross-domain canonical: " + out);
|
||||
assertTrue(out.contains("\"@type\":\"WebPage\""), "the WebPage node still emits: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noSoftwareApplicationWhenDisabled() {
|
||||
cfg(Map.of("software.name", "Acme App")); // software.enabled defaults false
|
||||
assertFalse(head.render(homeCtx("https://acme.test/")).contains("SoftwareApplication"));
|
||||
}
|
||||
|
||||
// --- type-aware structured data (item 5): FAQPage from content.schema, path-matched -----------------
|
||||
|
||||
@Test
|
||||
void emitsFaqPageForAPathDeclaredInContentSchema() {
|
||||
String schema = "/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"Is this real?\", a: \"No, it is a demo.\" }\n"
|
||||
+ " - { q: \"Where based?\", a: \"Portland.\" }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("faq", "FAQ", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext faqCtx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/faq",
|
||||
"https://acme.test/faq", List.of(), false, false);
|
||||
|
||||
String out = typed.render(faqCtx);
|
||||
assertTrue(out.contains("\"@type\":\"FAQPage\""), out);
|
||||
assertTrue(out.contains("\"@type\":\"Question\"") && out.contains("\"@type\":\"Answer\""), out);
|
||||
assertTrue(out.contains("Is this real?") && out.contains("No, it is a demo."), out);
|
||||
assertTrue(out.contains("acme.test/faq#webpage"), "FAQPage is mainEntityOfPage-linked to the WebPage: " + out);
|
||||
// still ONE ld+json block — the typed node joins the same @graph
|
||||
assertEquals(1, countOccurrences(out, "application/ld+json"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noTypedNodesWhenPathDoesNotMatchOrTypeUnregistered() {
|
||||
cfg(Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n - { q: \"Q\", a: \"A\" }\n"));
|
||||
// ctx() is /about — no content.schema entry matches → no FAQPage
|
||||
assertFalse(typed.render(ctx(false, false)).contains("FAQPage"), "path /about matches no pattern");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsProductWithOfferForASectionPrefixPattern() {
|
||||
cfg(Map.of("content.schema",
|
||||
"/coffee-*:\n type: Product\n price: \"22.00\"\n currency: USD\n availability: InStock\n",
|
||||
"org.name", "Roasters"));
|
||||
String out = typed.render(pageAt("/coffee-guji", "Ethiopia Guji"));
|
||||
assertTrue(out.contains("\"@type\":\"Product\""), out);
|
||||
assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"22.00\""), out);
|
||||
assertTrue(out.contains("schema.org/InStock"), "availability expanded to a URL: " + out);
|
||||
assertTrue(out.contains("\"brand\""), "brand references the Organization");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsOneLocalBusinessNodePerLocation() {
|
||||
String schema = "/cafes:\n type: CafeOrCoffeeShop\n locations:\n"
|
||||
+ " - { name: \"Roastery\", street: \"14 Lamplight Lane\", locality: Portland, region: OR, postalCode: \"97201\" }\n"
|
||||
+ " - { name: \"Downtown\", street: \"88 Meridian St\", locality: Portland, region: OR }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/cafes", "Cafes"));
|
||||
assertEquals(2, countOccurrences(out, "\"@type\":\"CafeOrCoffeeShop\""), "one node per location: " + out);
|
||||
assertTrue(out.contains("Roastery") && out.contains("Downtown"), out);
|
||||
assertTrue(out.contains("\"@type\":\"PostalAddress\"") && out.contains("14 Lamplight Lane"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsAPersonPerTeamMember() {
|
||||
String schema = "/team:\n type: Person\n people:\n"
|
||||
+ " - { name: \"Theo Vance\", jobTitle: \"Head Roaster\" }\n"
|
||||
+ " - { name: \"Mara Okafor\", jobTitle: \"Cafe Director\" }\n";
|
||||
cfg(Map.of("content.schema", schema, "org.name", "Nocturne"));
|
||||
String out = typed.render(pageAt("/team", "Team"));
|
||||
assertEquals(2, countOccurrences(out, "\"@type\":\"Person\""), out);
|
||||
assertTrue(out.contains("Theo Vance") && out.contains("Mara Okafor"), out);
|
||||
assertTrue(out.contains("\"worksFor\""), "worksFor references the Organization");
|
||||
}
|
||||
|
||||
// --- ItemList on a collection page ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void emitsAnItemListForACollectionPage() {
|
||||
String schema = "/coffees:\n type: ItemList\n items:\n"
|
||||
+ " - { name: \"Ethiopia Guji\", url: \"/coffee-ethiopia-guji\" }\n"
|
||||
+ " - { name: \"Colombia Huila\", url: \"/coffee-colombia-huila\" }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/coffees", "Our Coffees"));
|
||||
assertTrue(out.contains("\"@type\":\"ItemList\""), out);
|
||||
// The two members appear as positioned ListItems inside itemListElement (the page's breadcrumb also uses
|
||||
// ListItem, so assert on the member payloads rather than a raw ListItem count).
|
||||
assertTrue(out.contains("Ethiopia Guji") && out.contains("Colombia Huila"), out);
|
||||
assertTrue(out.contains("https://acme.test/coffee-ethiopia-guji")
|
||||
&& out.contains("https://acme.test/coffee-colombia-huila"),
|
||||
"root-relative member urls are absolutized against the base: " + out);
|
||||
assertTrue(out.contains("acme.test/coffees#itemlist"), "the ItemList carries a stable @id: " + out);
|
||||
assertTrue(out.contains("\"mainEntityOfPage\""), "the ItemList is linked to the page: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectionPageAliasAlsoEmitsAnItemList() {
|
||||
cfg(Map.of("content.schema", "/index:\n type: CollectionPage\n items:\n - { name: A, url: /a }\n"));
|
||||
assertTrue(typed.render(pageAt("/index", "Index")).contains("\"@type\":\"ItemList\""),
|
||||
"CollectionPage is an alias for the ItemList emitter");
|
||||
}
|
||||
|
||||
// --- several type-blocks on one path ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void emitsEveryTypeBlockWhenAPathDeclaresAList() {
|
||||
// A pricing page that is BOTH an FAQPage AND a Service — the list form yields both nodes in one @graph.
|
||||
String schema = "/pricing:\n"
|
||||
+ " - type: FAQPage\n faq:\n - { q: \"Why ranges?\", a: \"Scope drives cost.\" }\n"
|
||||
+ " - { q: \"Discounts?\", a: \"For non-profits.\" }\n"
|
||||
+ " - type: Service\n name: \"Advisory Sprint\"\n offers:\n"
|
||||
+ " - { name: \"Sprint\", price: \"18000\", currency: USD }\n";
|
||||
cfg(Map.of("content.schema", schema, "org.name", "Northbeam"));
|
||||
String out = typed.render(pageAt("/pricing", "Pricing"));
|
||||
assertTrue(out.contains("\"@type\":\"FAQPage\""), "first block emitted: " + out);
|
||||
assertTrue(out.contains("\"@type\":\"Service\""), "second block emitted: " + out);
|
||||
assertTrue(out.contains("Why ranges?") && out.contains("Advisory Sprint"), out);
|
||||
assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"18000\""),
|
||||
"the priced tier is a machine-readable Offer: " + out);
|
||||
assertEquals(1, countOccurrences(out, "application/ld+json"), "still one ld+json block: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecurringServiceOfferBecomesAUnitPriceSpecification() {
|
||||
String schema = "/pricing:\n type: Service\n name: \"Northbeam\"\n offers:\n"
|
||||
+ " - { name: \"Growth Retainer\", price: \"32000\", currency: USD, unit: month }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/pricing", "Pricing"));
|
||||
assertTrue(out.contains("\"@type\":\"UnitPriceSpecification\""), "a per-unit price is a spec: " + out);
|
||||
assertTrue(out.contains("\"unitText\":\"month\"") && out.contains("\"price\":\"32000\""), out);
|
||||
}
|
||||
|
||||
// --- breadcrumb @id link + collection parent level --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void webPageLinksToTheBreadcrumbById() {
|
||||
cfg(Map.of());
|
||||
String out = head.render(ctx(false, false)); // /about — a child page
|
||||
assertTrue(out.contains("acme.test/about#breadcrumb"), "the BreadcrumbList has a stable @id: " + out);
|
||||
assertTrue(out.contains("\"breadcrumb\":{\"@id\":\"https://acme.test/about#breadcrumb\"}"),
|
||||
"the WebPage points at the BreadcrumbList by @id: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertsTheDeclaredCollectionParentAsAMiddleBreadcrumbLevel() {
|
||||
// A product detail page declares its parent collection — the trail reads Home → Coffees → Guji.
|
||||
String schema = "/coffee-*:\n type: Product\n price: \"22.00\"\n currency: USD\n"
|
||||
+ " breadcrumb: { name: \"Coffees\", url: \"/coffees\" }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/coffee-guji", "Ethiopia Guji"));
|
||||
assertTrue(out.contains("\"@type\":\"BreadcrumbList\""), out);
|
||||
assertEquals(3, countOccurrences(out, "\"@type\":\"ListItem\""), "Home + Coffees + the page = 3 levels: " + out);
|
||||
assertTrue(out.contains("Coffees") && out.contains("https://acme.test/coffees"),
|
||||
"the parent collection is a middle level: " + out);
|
||||
assertTrue(out.contains("\"position\":1") && out.contains("\"position\":2") && out.contains("\"position\":3"),
|
||||
"positions run 1..3: " + out);
|
||||
}
|
||||
|
||||
// --- LocalBusiness @id + page link ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void localBusinessNodesCarryAnIdAndLinkToThePage() {
|
||||
String schema = "/cafes:\n type: CafeOrCoffeeShop\n locations:\n"
|
||||
+ " - { name: \"Roastery\", locality: Portland }\n"
|
||||
+ " - { name: \"Downtown\", locality: Portland }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/cafes", "Cafes"));
|
||||
assertTrue(out.contains("acme.test/cafes#business-1") && out.contains("acme.test/cafes#business-2"),
|
||||
"each location gets a distinct @id: " + out);
|
||||
assertEquals(2, countOccurrences(out, "\"mainEntityOfPage\""), "each business is linked to the page: " + out);
|
||||
}
|
||||
|
||||
private static int countOccurrences(String haystack, String needle) {
|
||||
int count = 0;
|
||||
int from = 0;
|
||||
int at;
|
||||
while ((at = haystack.indexOf(needle, from)) >= 0) {
|
||||
count++;
|
||||
from = at + needle.length();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* The defect this fixed: {@code datePublished} and {@code author} could ONLY come from the shared
|
||||
* {@code content.schema} block, which matches by {@code *}-prefix. A blog is therefore covered by one
|
||||
* {@code /blog/*} entry for EVERY post, so a site could assert only one date and one author across all of
|
||||
* them — false of nearly every page it appeared on, which is exactly what structured-data policy prohibits.
|
||||
* Per-item provenance must win so each entry states its own truth.
|
||||
*/
|
||||
@Test
|
||||
void perItemProvenanceWinsOverTheSharedContentSchemaBlock() {
|
||||
cfg(Map.of("content.schema", "/blog/*:\n type: BlogPosting\n"
|
||||
+ " author: Shared Fallback Author\n datePublished: 2020-01-01\n"));
|
||||
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("blog:post-1", "Real Post", "", List.of(Locale.ENGLISH), Locale.ENGLISH,
|
||||
true, false, "blog",
|
||||
new Provenance("Ada Lovelace", Instant.parse("2026-03-04T00:00:00Z"),
|
||||
Instant.parse("2026-05-06T12:34:56Z")));
|
||||
HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/blog/post-1",
|
||||
"https://acme.test/blog/post-1", List.of(), false, false);
|
||||
|
||||
String out = typed.render(ctx);
|
||||
assertTrue(out.contains("\"name\":\"Ada Lovelace\""), "the item's own author must win: " + out);
|
||||
assertFalse(out.contains("Shared Fallback Author"), "the shared block must not override the item");
|
||||
assertTrue(out.contains("\"datePublished\":\"2026-03-04\""), "the item's own date must win: " + out);
|
||||
assertFalse(out.contains("2020-01-01"), "the shared date must not be asserted on this post");
|
||||
// dateModified comes from the host-derived updatedAt, rendered at DAY precision (not second).
|
||||
assertTrue(out.contains("\"dateModified\":\"2026-05-06\""), out);
|
||||
}
|
||||
|
||||
/** With no per-item provenance the configured values still apply — existing sites keep working unchanged. */
|
||||
@Test
|
||||
void theSharedBlockStillAppliesWhenTheItemHasNoProvenance() {
|
||||
cfg(Map.of("content.schema", "/about:\n type: Article\n"
|
||||
+ " author: Editorial Team\n datePublished: 2024-02-03\n"));
|
||||
|
||||
String out = typed.render(pageAt("/about", "About Acme"));
|
||||
assertTrue(out.contains("\"name\":\"Editorial Team\""), out);
|
||||
assertTrue(out.contains("\"datePublished\":\"2024-02-03\""), out);
|
||||
}
|
||||
|
||||
/**
|
||||
* The emitted JSON-LD must be <b>byte-reproducible</b>, so the same inputs always render the same bytes.
|
||||
*
|
||||
* <p>This is a regression guard with a real history. {@code SearchAction.target} was built with
|
||||
* {@code Map.of(...)}, and {@code java.util.Map.of} randomizes iteration order <b>per JVM instance</b>
|
||||
* ({@code ImmutableCollections.SALT}) — so the key order was stable within one run and flipped on roughly
|
||||
* every other restart. An operator diffing live homepages across an upgrade found it and reasonably
|
||||
* concluded it was a one-off change between builds; it was not, it was every restart, indefinitely.
|
||||
*
|
||||
* <p>Semantically harmless — the graphs are equal key-sorted — but it made rendered output
|
||||
* non-reproducible, and the page's strong ETag folds metadata and templates rather than the body, so the
|
||||
* validator did <b>not</b> change when the bytes did.
|
||||
*
|
||||
* <p>Asserted on the exact ordered substring rather than by parsing, because parsing would compare the
|
||||
* graphs and pass under exactly the defect this exists to catch.
|
||||
*/
|
||||
@Test
|
||||
void theSearchActionTargetHasADeterministicKeyOrder() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}"));
|
||||
String out = head.render(ctx(false, false));
|
||||
|
||||
assertTrue(out.contains("\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":"),
|
||||
() -> "SearchAction.target must serialize @type first, deterministically; got:\n" + out);
|
||||
}
|
||||
|
||||
/** Same inputs, same bytes — the general property, asserted over repeated renders. */
|
||||
@Test
|
||||
void repeatedRendersOfTheSameInputProduceIdenticalBytes() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}"));
|
||||
String first = head.render(ctx(false, false));
|
||||
for (int i = 0; i < 20; i++) {
|
||||
assertEquals(first, head.render(ctx(false, false)), "structured data must be byte-reproducible");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A DETERMINISTIC guard that no serialized JSON-LD node is built with a multi-entry {@code Map.of(...)}.
|
||||
*
|
||||
* <h2>Why a source check and not just the behavioural test above</h2>
|
||||
* The behavioural test is the right description of intent, but it is a <b>weak</b> guard on its own,
|
||||
* because the defect it guards is probabilistic: {@code Map.of} picks one of the two orders per JVM
|
||||
* instance, so a reintroduction passes roughly half the time — and Maven reuses forked JVMs, so it can
|
||||
* pass for many consecutive runs. Measured: reverting the fix and re-running six times produced five
|
||||
* passes and one failure. A guard that reports green five times out of six is not a guard.
|
||||
*
|
||||
* <p>So this asserts the property at the only place it is reliably observable: the source. A single-entry
|
||||
* {@code Map.of("@id", …)} is fine — one key cannot be misordered — and an empty {@code Map.of()} is fine.
|
||||
* Only two-or-more entries can vary, and those must use an insertion-ordered map.
|
||||
*
|
||||
* <p>If this fails: build the node with {@code Ld.node(...)} or a {@link java.util.LinkedHashMap}. The
|
||||
* requirement is byte-reproducible output, not any particular key order.
|
||||
*/
|
||||
@Test
|
||||
void noSerializedNodeIsBuiltWithAMultiEntryMapOf() throws Exception {
|
||||
for (String file : SCANNED_SOURCES) {
|
||||
java.nio.file.Path path = java.nio.file.Path.of("src/main/java/mx/quest/discover", file);
|
||||
if (!java.nio.file.Files.exists(path)) {
|
||||
continue;
|
||||
}
|
||||
String source = stripCommentsAndStrings(java.nio.file.Files.readString(path));
|
||||
int at = 0;
|
||||
while ((at = source.indexOf("Map.of(", at)) >= 0) {
|
||||
int entries = topLevelArgumentsFrom(source, at + "Map.of(".length());
|
||||
int offending = at;
|
||||
assertTrue(entries <= 2, () -> file + " builds a multi-entry Map.of near offset " + offending
|
||||
+ ", whose iteration order is randomized PER JVM INSTANCE and would make emitted "
|
||||
+ "JSON-LD non-reproducible across restarts. Use Ld.node(...) or a LinkedHashMap.");
|
||||
at += "Map.of(".length();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The sources whose output is serialized into JSON-LD, and so must be byte-reproducible. */
|
||||
private static final java.util.List<String> SCANNED_SOURCES = java.util.List.of(
|
||||
"StructuredDataHead.java", "Ld.java", "ArticleSchema.java", "ProductSchema.java",
|
||||
"LocalBusinessSchema.java", "FaqPageSchema.java", "PersonSchema.java", "ServiceSchema.java",
|
||||
"CollectionSchema.java");
|
||||
|
||||
/**
|
||||
* Blanks comments and string literals, preserving offsets and newlines.
|
||||
*
|
||||
* <p>Done before scanning rather than per line, because the previous version read the file LINE BY LINE
|
||||
* and therefore only ever saw the single-line form of {@code Map.of(...)}. A call whose arguments wrap
|
||||
* onto following lines — the natural formatting for three or more entries under a 120-column limit, which
|
||||
* is precisely the case at risk — left one comma or none on the opening line and sailed through. The
|
||||
* guard was reliable only for the shape the defect was least likely to take.
|
||||
*
|
||||
* <p>Blanking rather than deleting keeps every offset intact, so the failure message can point at a real
|
||||
* position in the file. Strings are blanked so a {@code Map.of} mentioned inside one, or a comma inside a
|
||||
* string argument, cannot be miscounted.
|
||||
*/
|
||||
private static String stripCommentsAndStrings(String source) {
|
||||
StringBuilder out = new StringBuilder(source.length());
|
||||
int i = 0;
|
||||
while (i < source.length()) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '/' && i + 1 < source.length() && source.charAt(i + 1) == '/') {
|
||||
while (i < source.length() && source.charAt(i) != '\n') {
|
||||
out.append(' ');
|
||||
i++;
|
||||
}
|
||||
} else if (c == '/' && i + 1 < source.length() && source.charAt(i + 1) == '*') {
|
||||
while (i < source.length() && !(source.charAt(i) == '*' && i + 1 < source.length()
|
||||
&& source.charAt(i + 1) == '/')) {
|
||||
out.append(source.charAt(i) == '\n' ? '\n' : ' ');
|
||||
i++;
|
||||
}
|
||||
for (int k = 0; k < 2 && i < source.length(); k++, i++) {
|
||||
out.append(' ');
|
||||
}
|
||||
} else if (c == '"' || c == '\'') {
|
||||
char quote = c;
|
||||
out.append(' ');
|
||||
i++;
|
||||
while (i < source.length() && source.charAt(i) != quote) {
|
||||
if (source.charAt(i) == '\\') {
|
||||
out.append(' ');
|
||||
i++;
|
||||
}
|
||||
if (i < source.length()) {
|
||||
out.append(source.charAt(i) == '\n' ? '\n' : ' ');
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (i < source.length()) {
|
||||
out.append(' ');
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
out.append(c);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** How many top-level arguments the call opening at {@code from} has (0 when it is empty). */
|
||||
private static int topLevelArgumentsFrom(String source, int from) {
|
||||
int depth = 0;
|
||||
int commas = 0;
|
||||
boolean any = false;
|
||||
for (int i = from; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '(' || c == '[' || c == '{') {
|
||||
depth++;
|
||||
} else if (c == ')' || c == ']' || c == '}') {
|
||||
if (depth == 0) {
|
||||
return any ? commas + 1 : 0;
|
||||
}
|
||||
depth--;
|
||||
} else if (c == ',' && depth == 0) {
|
||||
commas++;
|
||||
}
|
||||
if (!Character.isWhitespace(c)) {
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return any ? commas + 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The guard can actually fail — proven against synthetic sources rather than hoped for.
|
||||
*
|
||||
* <p>A source-level scan that silently matches nothing is indistinguishable from a codebase that is
|
||||
* clean, and this one WAS partly that: it could not see a wrapped call. So the scanner's two halves are
|
||||
* exercised directly, including the multi-line form it used to miss.
|
||||
*/
|
||||
@Test
|
||||
void theMapOfScannerCatchesBothTheSingleLineAndTheWrappedForm() {
|
||||
String singleLine = "var x = Map.of(\"a\", 1, \"b\", 2);";
|
||||
String wrapped = "var x = Map.of(\n \"a\", 1,\n \"b\", 2,\n \"c\", 3);";
|
||||
String safe = "var x = Map.of(\"only\", 1);";
|
||||
String inAComment = "// Map.of(\"a\", 1, \"b\", 2) is what NOT to do";
|
||||
String inAString = "var s = \"Map.of(a, 1, b, 2)\";";
|
||||
|
||||
assertEquals(4, argumentsOfFirstMapOf(singleLine), "two entries = four arguments");
|
||||
assertEquals(6, argumentsOfFirstMapOf(wrapped), "the wrapped form is the one it used to miss");
|
||||
assertEquals(2, argumentsOfFirstMapOf(safe), "a single entry is fine");
|
||||
assertEquals(-1, argumentsOfFirstMapOf(inAComment), "prose explaining the rule is not a violation");
|
||||
assertEquals(-1, argumentsOfFirstMapOf(inAString), "nor is a string that happens to contain it");
|
||||
}
|
||||
|
||||
/** Arguments of the first {@code Map.of(} in {@code source} after stripping, or {@code -1} if none. */
|
||||
private static int argumentsOfFirstMapOf(String source) {
|
||||
String stripped = stripCommentsAndStrings(source);
|
||||
int at = stripped.indexOf("Map.of(");
|
||||
return at < 0 ? -1 : topLevelArgumentsFrom(stripped, at + "Map.of(".length());
|
||||
}
|
||||
|
||||
/**
|
||||
* The declared head input names the very file this contributor reads.
|
||||
*
|
||||
* <p>{@code headInputs} is answered without any storage layout, so the path is a literal — and a literal
|
||||
* that does not match what the kernel reads folds a stable "absent" marker forever. The validator then
|
||||
* looks correct while covering nothing, and the symptom is a stale social card or organisation name on
|
||||
* every cached client, weeks later, with nothing pointing back here.
|
||||
*
|
||||
* <p>The kernel pins the other half of the convention ({@code <site>/plugins/<id>.yml}); this pins that
|
||||
* the id in the path is the id this contributor actually looks up its settings under, so renaming the
|
||||
* plugin cannot leave the declaration behind.
|
||||
*/
|
||||
@Test
|
||||
void theDeclaredHeadInputIsThisPluginsOwnSettingsFile() {
|
||||
assertEquals(List.of("plugins/" + StructuredDataHead.PLUGIN_ID + ".yml"), head.headInputs("acme"));
|
||||
assertEquals(List.of("plugins/discoverability.yml"), head.headInputs("acme"),
|
||||
"the kernel reads <site>/plugins/<id>.yml — see SitePluginConfigServiceTest");
|
||||
}
|
||||
|
||||
// --- a host-less site: absolute URLs from HeadContext.origin() (SPI 1.0.0, discoverability 2.1.0) ------------
|
||||
|
||||
/** A host-less site (no base URL, no host name — the platform's catch-all default): its canonical is relative. */
|
||||
private static HeadContext hostless(String path, String title, String origin) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "");
|
||||
PageMeta page = new PageMeta(path.substring(1), title, "", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
false);
|
||||
return new HeadContext(site, page, Locale.ENGLISH, path, path, List.of(), false, false, null, null, origin);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHostlessSitesGraphIsAbsoluteAgainstTheTrustedOrigin() {
|
||||
cfg(Map.of("org.name", "Acme", "org.logo", "/static/logo.svg"));
|
||||
String out = head.render(hostless("/about", "About", "http://10.0.0.5:8080"));
|
||||
assertTrue(out.contains("\"@id\":\"http://10.0.0.5:8080/#website\""), out);
|
||||
assertTrue(out.contains("\"url\":\"http://10.0.0.5:8080/\""), "WebSite/Organization url: " + out);
|
||||
assertTrue(out.contains("\"@id\":\"http://10.0.0.5:8080/about#webpage\""), out);
|
||||
assertTrue(out.contains("\"url\":\"http://10.0.0.5:8080/about\""), out);
|
||||
assertTrue(out.contains("\"logo\":\"http://10.0.0.5:8080/static/logo.svg\""), out);
|
||||
assertTrue(out.contains("\"@type\":\"BreadcrumbList\""), "a host-less deep page now has its trail: " + out);
|
||||
assertTrue(out.contains("\"item\":\"http://10.0.0.5:8080/\""), out);
|
||||
assertFalse(out.contains("\":\"/"), "no root-relative URL or @id is left: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHostlessSiteGainsItsSearchActionWithAnAbsoluteTemplate() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}"));
|
||||
String out = head.render(hostless("/about", "About", "https://example.test"));
|
||||
assertTrue(out.contains("\"urlTemplate\":\"https://example.test/search?q={search_term_string}\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHostlessHomeIsRecognisedAndCarriesNoTrail() {
|
||||
cfg(Map.of("software.enabled", true));
|
||||
String out = head.render(hostless("/", "Home", "https://example.test"));
|
||||
assertTrue(out.contains("\"@type\":\"SoftwareApplication\""), "the home is still the home: " + out);
|
||||
assertTrue(out.contains("\"@id\":\"https://example.test/#webpage\""), out);
|
||||
assertFalse(out.contains("BreadcrumbList"), out);
|
||||
}
|
||||
|
||||
/** A context with no origin (the constructor without one, or no request) renders exactly as 2.0.0 did. */
|
||||
@Test
|
||||
void withoutAnOriginAHostlessGraphStaysRootRelativeAsBefore() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search"));
|
||||
String out = head.render(hostless("/about", "About", ""));
|
||||
assertTrue(out.contains("\"@id\":\"/about#webpage\""), out);
|
||||
assertTrue(out.contains("\"@id\":\"/#website\""), out);
|
||||
assertFalse(out.contains("SearchAction"), "no base, no SearchAction — as 2.0.0: " + out);
|
||||
assertFalse(out.contains("BreadcrumbList"), out);
|
||||
}
|
||||
|
||||
/** The site's base URL wins over the request origin: a site with a host never takes the address it was reached at. */
|
||||
@Test
|
||||
void aConfiguredBaseUrlWinsOverTheOrigin() {
|
||||
cfg(Map.of());
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("about", "About", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about",
|
||||
"https://acme.test/about", List.of(), false, false, null, null, "http://10.0.0.5:8080");
|
||||
String out = head.render(ctx);
|
||||
assertTrue(out.contains("https://acme.test/#website"), out);
|
||||
assertFalse(out.contains("10.0.0.5"), out);
|
||||
HeadContext noOrigin = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about",
|
||||
"https://acme.test/about", List.of(), false, false);
|
||||
assertEquals(head.render(noOrigin), out, "byte-identical to the origin-less render of the same page");
|
||||
}
|
||||
|
||||
/** A cross-domain canonical override is absolute already and passes through untouched. */
|
||||
@Test
|
||||
void anAbsoluteCanonicalIsNeverRebased() {
|
||||
assertEquals("https://other.test/x", StructuredDataHead.absolute("https://other.test/x", "http://a.test"));
|
||||
assertEquals("//cdn.test/x", StructuredDataHead.absolute("//cdn.test/x", "http://a.test"),
|
||||
"a protocol-relative URL already names a host");
|
||||
assertEquals("/x", StructuredDataHead.absolute("/x", ""), "no base known: left as it is");
|
||||
assertEquals("http://a.test/x", StructuredDataHead.absolute("/x", "http://a.test"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* Test settings shaped the way the kernel's {@code PluginSettings} hands them to the plugin: the {@code default:}s
|
||||
* this plugin's descriptor declares, overlaid by what a test stores for a site.
|
||||
*
|
||||
* <p>Every unit test builds its settings here rather than from an empty map, so each assertion also proves that the
|
||||
* declared defaults change nothing a tenant sees (1.x read only the stored values and applied its code fallbacks;
|
||||
* since 2.0.0 the host applies the declared defaults first).
|
||||
*/
|
||||
final class TestSettings {
|
||||
|
||||
private TestSettings() {
|
||||
}
|
||||
|
||||
/** A fake {@code PluginSettings} carrying the descriptor's declared per-site defaults and no stored value. */
|
||||
static FakePluginSettings declared() {
|
||||
return new FakePluginSettings().defaults(declaredDefaults());
|
||||
}
|
||||
|
||||
/** A fake with NO declared defaults — what the plugin would see if the host stopped applying them. */
|
||||
static FakePluginSettings bare() {
|
||||
return new FakePluginSettings();
|
||||
}
|
||||
|
||||
/** The {@code default:} of every {@code siteSettings} key that declares one (secret-typed keys never). */
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> declaredDefaults() {
|
||||
Map<String, Object> defaults = new LinkedHashMap<>();
|
||||
for (Map<String, Object> def : (List<Map<String, Object>>) descriptor().get("siteSettings")) {
|
||||
if (def.containsKey("default") && def.get("default") != null && !"secret".equals(def.get("type"))) {
|
||||
defaults.put(String.valueOf(def.get("key")), def.get("default"));
|
||||
}
|
||||
}
|
||||
return defaults;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> descriptor() {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user