Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
@@ -0,0 +1,69 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<name>Runway SPI</name>
|
||||
<description>
|
||||
The dependency-free extension API: thin interfaces and immutable model records that
|
||||
plugins and core features alike implement. Depends on nothing in the host. This is
|
||||
RELEASED API — evolve only by ADDING default methods; never reorder/retype existing
|
||||
members; keep old-arity constructors on model records so an extension compiled against
|
||||
an earlier version keeps loading.
|
||||
</description>
|
||||
|
||||
<!--
|
||||
Intentionally NO compile/runtime dependencies. The SPI is the stable artifact
|
||||
extensions compile against; pulling in host code here would defeat its purpose.
|
||||
The only dependency is JUnit at TEST scope — not transitive, so the published
|
||||
artifact remains dependency-free for consumers.
|
||||
-->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
<!-- The license and the plugin permission travel inside the jar, so a jar fetched on its own
|
||||
still carries its terms. -->
|
||||
<resource>
|
||||
<directory>${project.basedir}/..</directory>
|
||||
<includes>
|
||||
<include>LICENSE</include>
|
||||
<include>LICENSE-EXCEPTION</include>
|
||||
</includes>
|
||||
<targetPath>META-INF</targetPath>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<!-- The sources jar ships as a release asset next to the jar (scripts/make-spi-assets.sh), so a plugin
|
||||
author's IDE shows this module's Javadoc and code. jar-no-fork: no second lifecycle run. -->
|
||||
<plugin>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-sources</id>
|
||||
<goals>
|
||||
<goal>jar-no-fork</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,77 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import java.io.IOException;
|
||||
import mx.quest.runway.spi.model.BackupReader;
|
||||
import mx.quest.runway.spi.model.BackupWriter;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.SiteRef;
|
||||
|
||||
/**
|
||||
* Lets a plugin's <b>per-site generated data</b> travel inside a site's backup — a search
|
||||
* index, carousel slides, a contact form's stored config. Code and assets belong to the
|
||||
* plugin (and are never copied into a site); but data a plugin <em>generates for a site</em>
|
||||
* belongs to that site, so it must be exported into and restored from the site's backup.
|
||||
*
|
||||
* <h2>Contract</h2>
|
||||
* <ul>
|
||||
* <li>{@link #export} writes this participant's data for one site into the host-provided
|
||||
* {@link BackupWriter}, which scopes everything under this participant's namespace.</li>
|
||||
* <li>{@link #importInto} reads it back during restore and must be <b>idempotent</b> —
|
||||
* importing the same backup twice yields the same state — and must tolerate a missing
|
||||
* entry (an older backup, or a feature unused when the backup was taken).</li>
|
||||
* <li>{@link #key()} is the stable archive-namespace key; a duplicate among kernel contributions fails startup; a plugin's
|
||||
* colliding contribution is refused (the later plugin's in load order) and reported (since SPI 0.4.0).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* An {@code export} failure — an exception of any kind — <b>fails the whole backup</b>: a backup is complete or it is
|
||||
* not a backup. The error names the participant and its plugin. An {@code importInto} that throws (a
|
||||
* {@code RuntimeException}, {@code LinkageError} or {@code IOException}) is contained: the site's files are still
|
||||
* restored, the failure is logged and counted, and the next participant runs. Entry names must be plain relative
|
||||
* paths — blank, absolute, backslashed or {@code ..} names are refused with {@code IllegalArgumentException}.
|
||||
* Transfer copies skip participants entirely.
|
||||
*
|
||||
* <p><b>Threading.</b> {@code export} and {@code importInto} run on the thread that performs the backup or the
|
||||
* restore — a console request's, or the scheduler's for an automatic backup — while the host holds that
|
||||
* site's backup lock: calls for one site never overlap, but calls for <em>different</em> sites can run at the same
|
||||
* time. An implementation must be stateless or synchronize whatever it shares across sites.
|
||||
*/
|
||||
public interface BackupParticipant {
|
||||
|
||||
/**
|
||||
* This participant's stable, unique key — also its namespace within a site's backup
|
||||
* archive.
|
||||
*
|
||||
* @return a non-{@code null}, non-empty identifier, stable across releases
|
||||
*/
|
||||
String key();
|
||||
|
||||
/**
|
||||
* Exports this participant's data for the given site.
|
||||
*
|
||||
* @param out the host-provided sink, scoped to this participant's namespace (never {@code null})
|
||||
* @param site the site whose data to export (never {@code null})
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
void export(BackupWriter out, SiteRef site) throws IOException;
|
||||
|
||||
/**
|
||||
* Restores this participant's data for the given site. Must be idempotent and tolerate
|
||||
* absent entries.
|
||||
*
|
||||
* @param in the host-provided source, scoped to this participant's namespace (never {@code null})
|
||||
* @param site the site whose data to restore (never {@code null})
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
void importInto(BackupReader in, SiteRef site) throws IOException;
|
||||
|
||||
/**
|
||||
* The capabilities this participant declares, so the host can branch on data rather than
|
||||
* type. Defaults to {@link Capabilities#none()}.
|
||||
*
|
||||
* @return the declared capabilities (never {@code null})
|
||||
*/
|
||||
default Capabilities capabilities() {
|
||||
return Capabilities.none();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
|
||||
/**
|
||||
* A reusable CAPTCHA seam for <b>site forms</b> — the contact form and any other plugin/page form that wants a
|
||||
* challenge. It exposes the two halves a form needs while keeping every provider detail (the provider — currently
|
||||
* Google reCAPTCHA v2 & v3 —, the site's keys, the score threshold) behind this interface:
|
||||
*
|
||||
* <ol>
|
||||
* <li>{@link #widgetForSite(String)} — the ready-to-embed {@link CaptchaWidget} for a site's currently-configured
|
||||
* challenge (or an inactive one when none is set);</li>
|
||||
* <li>{@link #verify(String, String, String)} — server-side verification of the token the widget posted back.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p><b>Provided by the platform, armed by a plugin.</b> The kernel ships a permissive default (no challenge is
|
||||
* ever configured, so widgets are inactive and verification always accepts) so a form works with or without a
|
||||
* CAPTCHA provider installed. The essential <b>protection</b> plugin supplies the real implementation
|
||||
* ({@code @Primary}), reading each site's own per-site CAPTCHA settings — so a form gets a live challenge exactly
|
||||
* when the tenant has configured one, and nothing otherwise. A consumer therefore depends only on this SPI, never
|
||||
* on the protection plugin.
|
||||
*
|
||||
* <p><b>Fail-safe.</b> When a site has no active challenge, {@link #widgetForSite} returns
|
||||
* {@link CaptchaWidget#inactive()} and {@link #verify} returns {@code true} — a form is never blocked by a CAPTCHA
|
||||
* it did not ask for.
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* {@link #verify} contacts the configured provider (currently Google reCAPTCHA v2/v3) and may block for several seconds
|
||||
* (the protection plugin allows 5 s to connect and 5 s for the answer, so up to about 10 s);
|
||||
* when the provider cannot be reached it <b>fails open</b> (returns {@code true}) — a provider outage must not take
|
||||
* every site form down with it. Implementations are thread-safe.
|
||||
*
|
||||
* <p><b>Threading.</b> The host calls this concurrently from many request threads; an implementation must be
|
||||
* stateless or internally synchronized.
|
||||
*/
|
||||
public interface CaptchaService {
|
||||
|
||||
/**
|
||||
* The challenge widget for {@code siteId}'s current configuration, or {@link CaptchaWidget#inactive()} when the
|
||||
* site has no active CAPTCHA. Safe to call per render.
|
||||
*
|
||||
* @param siteId the tenant whose CAPTCHA settings apply
|
||||
* @return the embeddable widget (never {@code null})
|
||||
*/
|
||||
CaptchaWidget widgetForSite(String siteId);
|
||||
|
||||
/**
|
||||
* Verifies a solved CAPTCHA token for {@code siteId} server-side.
|
||||
*
|
||||
* @param siteId the tenant whose CAPTCHA settings (provider, secret, threshold) apply
|
||||
* @param token the token the widget posted back (the {@link CaptchaWidget#tokenField()} request parameter);
|
||||
* may be {@code null}/blank if the challenge was not solved
|
||||
* @param clientIp the requester's IP to pass as the provider's optional {@code remoteip} hint, or {@code null}
|
||||
* @return {@code true} if the site has no active challenge OR the token is valid (including a provider-outage
|
||||
* fail-open); {@code false} if a challenge is active and the token is missing or rejected
|
||||
*/
|
||||
boolean verify(String siteId, String token, String clientIp);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* Contributes <b>routable content</b> to a site — pages that are not kernel {@code Page}s: blog entries,
|
||||
* product pages, any plugin-owned content that deserves its own public URL. This is the kernel's content
|
||||
* noun: <b>routing</b> serves a source's content through the exact same locale-dispatch ladder, tenant master
|
||||
* chrome, and head treatment as a real page; <b>a sitemap plugin</b> lists it in sitemap.xml (per-locale
|
||||
* {@code hreflang} alternates, {@code <lastmod>}) and llms.txt; <b>search</b> indexes it. Kernel pages
|
||||
* themselves are exposed through this same interface (the built-in pages source) — a plugin source is a
|
||||
* first-class peer, never a second-class citizen.
|
||||
*
|
||||
* <h2>The enumeration-first contract</h2>
|
||||
* <ul>
|
||||
* <li>{@link #enumerate(SiteView)} is the primary method: the source's <b>published</b> content as cheap,
|
||||
* <b>metadata-only</b> {@link ContentRef}s. It MUST NOT read content bodies — it runs on public,
|
||||
* anonymous requests (the sitemap), so an eager-body implementation turns {@code /sitemap.xml} into a
|
||||
* full-corpus disk/database read. Keep metadata separate from bodies in storage so this is trivially
|
||||
* honest.</li>
|
||||
* <li>{@link #body(SiteView, String, Locale)} is fetched <b>lazily, only for an actual {@code 200}
|
||||
* render</b> — never for a conditional-request ({@code 304}) revalidation, never during
|
||||
* enumeration.</li>
|
||||
* <li>{@link #resolve(SiteView, String, Locale)} answers "do you serve this path?" on a routing miss (real
|
||||
* pages always win first). The default implementation is a correct-by-construction linear scan of
|
||||
* {@link #enumerate}; a real source SHOULD override it with an index probe — with
|
||||
* {@link #CAP_ARBITRARY_PATHS} declared it runs on <em>every</em> unmatched request of an enabled site,
|
||||
* so it must be cheap (an in-memory {@code path|lang → id} map, rebuilt on the source's own mutations
|
||||
* and on site-restore events).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Isolation and discipline</h2>
|
||||
* A source is <b>site-scoped and self-contained</b>: it reads only its own per-tenant subtree
|
||||
* ({@code sites/<id>/plugins/<key>/}) plus its per-tenant settings — never another plugin's data, never the
|
||||
* site's {@code templates/}, never application configuration. Content a source generates for a tenant belongs
|
||||
* to the tenant (it lives in the tenant folder and travels in the tenant's backup). Two contract points the
|
||||
* kernel cannot enforce and therefore <b>re-checks fail-closed</b> (dropping violations rather than serving
|
||||
* them): enumerate/resolve must return <b>published</b> content with <b>safe paths</b> only — the kernel
|
||||
* re-filters published, path safety, and reserved prefixes on every source output, so a misbehaving source
|
||||
* results in omission, never disclosure.
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* A {@code enumerate}/{@code resolve}/{@code body}/{@code indexableText} that throws a {@code RuntimeException} or
|
||||
* {@code LinkageError} is logged (the first time with the stack, then at most once a minute), counted in
|
||||
* {@code runway.plugin.contribution.failures} and treated as empty/miss (degrade-don't-crash): a broken source
|
||||
* disappears from routing and listings but never 500s a tenant's request surface; a page whose {@code body} failed
|
||||
* renders its chrome around an empty body, uncacheable.
|
||||
*
|
||||
* <h2>Freshness: announce every change</h2>
|
||||
* The host cannot see a source's storage change. After every mutation — an item created, edited, deleted,
|
||||
* published or unpublished, or the whole corpus replaced — call
|
||||
* {@link mx.quest.runway.spi.service.ContentChanges#changed} (since SPI 0.6.0; the host's internal event is not
|
||||
* part of the contract, and a plugin that links it is refused from 1.0.0). The call evicts
|
||||
* routing, the listing, the sitemap and search on every node and notifies every
|
||||
* {@link mx.quest.runway.spi.service.SiteEventListener}. A source that keeps its own index drops it from a
|
||||
* {@link mx.quest.runway.spi.service.SiteEventListener.Phase#SOURCE SOURCE}-phase listener (its own content
|
||||
* changes, site lifecycle events, its own settings), so consumers never rebuild from a stale index.
|
||||
*
|
||||
* <h2>The body template's render model (contract)</h2>
|
||||
* The template named by {@link ContentRef#bodyTemplate()} renders with exactly these variables, and nothing else
|
||||
* is promised:
|
||||
* <ul>
|
||||
* <li>{@code master} — the logical name of the site master template to wrap the body in
|
||||
* ({@code th:replace="~{${master} :: …}"}); the ref's {@code master} param picks another master the tenant
|
||||
* ships, else {@code _master};</li>
|
||||
* <li>{@code content} — a map with {@code id}, {@code sourceKey}, {@code title} and {@code description} (in the
|
||||
* rendered locale), {@code bodyHtml} and {@code attributes} (from {@link #body}), and {@code updatedAt}
|
||||
* (ISO-8601, or {@code ""} when unknown);</li>
|
||||
* <li>{@code locale} — the rendered {@link Locale};</li>
|
||||
* <li>{@code urls} — link targets: a page's bare slug, or {@code <sourceKey>:<id>} for a source item, mapped to
|
||||
* its root-relative URL in the rendered locale ({@code ${urls['blog:hello']}}).</li>
|
||||
* </ul>
|
||||
* The master itself renders with the full page model the tenant's templates use; that model is the tenant's
|
||||
* contract, not a plugin's. The render is the <b>site's</b> render, with the tenant's isolation: the body
|
||||
* template (and anything it pulls) reaches only that site's {@code __site__/<siteId>/…} templates, and Spring bean
|
||||
* references ({@code ${@…}}) are not available — feed the body through {@link #body} instead.
|
||||
*
|
||||
* <h2>Capability flags</h2>
|
||||
* By convention a flag constant ({@code CAP_*}) lives on the interface whose behaviour it changes, and its value is
|
||||
* namespaced by the axis ({@code content.…}). The host branches on one flag today, {@link #CAP_INDEXABLE_TEXT}
|
||||
* (search calls {@code indexableText} only on a source that declares it). {@link #CAP_ARBITRARY_PATHS} is
|
||||
* <b>reserved</b>: the kernel currently consults every source's {@code resolve} on a routing miss whether or not it
|
||||
* is declared; a later kernel may skip undeclared sources for paths outside their prefix, so declare it if your
|
||||
* source serves arbitrary paths. A flag the host does not recognise is ignored.
|
||||
*
|
||||
* <h2>Threading</h2>
|
||||
* Implementations must be <b>stateless or internally synchronized and thread-safe</b>; all three methods are
|
||||
* called concurrently from request threads.
|
||||
*/
|
||||
public interface ContentSource {
|
||||
|
||||
/**
|
||||
* Declares that this source implements {@link #indexableText} — the search integration opts in per
|
||||
* source, so an engine never calls a default that silently returns nothing and indexes hollow documents.
|
||||
*/
|
||||
String CAP_INDEXABLE_TEXT = "content.indexable-text";
|
||||
|
||||
/**
|
||||
* Declares that this source serves content at <b>arbitrary site paths</b> (not only under a stable
|
||||
* prefix), so the kernel must consult {@link #resolve} on every routing miss of a site where the source
|
||||
* is active. Without this capability the kernel may skip the source for paths it can prove the source
|
||||
* cannot serve.
|
||||
*/
|
||||
String CAP_ARBITRARY_PATHS = "content.arbitrary-paths";
|
||||
|
||||
/**
|
||||
* This source's stable, unique key — the namespace of its content identities ({@code <key>:<id>} in URL
|
||||
* maps and head metadata) and of its per-tenant data folder. Persisted contract. A duplicate among kernel
|
||||
* sources fails startup; a plugin source whose key is blank or collides with another's is refused and reported
|
||||
* (an ERROR naming both sides, the plugin marked degraded, its other contributions still loaded) — against
|
||||
* a kernel source (such as {@code pages}) the plugin's is refused, between two plugins the later one's in load
|
||||
* order.
|
||||
*
|
||||
* @return a non-{@code null}, non-blank identifier, stable across releases
|
||||
*/
|
||||
String key();
|
||||
|
||||
/**
|
||||
* The source's <b>published</b> content for {@code site}, as metadata only. Called on public request
|
||||
* paths (sitemap, llms.txt, URL maps) — see the class contract: cheap, body-free, published-only. Order
|
||||
* is the source's choice but should be stable.
|
||||
*
|
||||
* @param site the site being served (never {@code null})
|
||||
* @return the published content's metadata (never {@code null}; may be empty)
|
||||
*/
|
||||
List<ContentRef> enumerate(SiteView site);
|
||||
|
||||
/**
|
||||
* The render payload of one piece of content, in one locale. Called <b>only</b> for an actual {@code 200}
|
||||
* render of a ref this source returned; {@code id} is a {@link ContentRef#id()} from this source and
|
||||
* {@code locale} one the ref declares.
|
||||
*
|
||||
* <p><b>Freshness contract:</b> the render ETag is computed from the ref's <em>metadata</em> — this method
|
||||
* is never consulted for a conditional-request revalidation. Any change to what this method returns MUST
|
||||
* be reflected in the ref (bump {@link ContentRef#updatedAt()}), or revalidating clients receive stale
|
||||
* {@code 304}s indefinitely. {@link mx.quest.runway.spi.service.ContentChanges#changed} refreshes
|
||||
* <em>server-side</em> derived state (indexes, caches) — it does NOT affect HTTP validators.
|
||||
*
|
||||
* @param site the site being served (never {@code null})
|
||||
* @param id the content identity (never {@code null})
|
||||
* @param locale the locale being rendered (never {@code null})
|
||||
* @return the body payload; {@link ContentBody#empty()} when the content has none (never {@code null})
|
||||
*/
|
||||
ContentBody body(SiteView site, String id, Locale locale);
|
||||
|
||||
/**
|
||||
* Resolves a request path (locale-prefix already stripped by the kernel) to this source's content, for
|
||||
* the locale the URL implies. Consulted only after real pages miss. The default scans
|
||||
* {@link #enumerate}; override with an index probe — see the class contract for the cost obligation.
|
||||
*
|
||||
* @param site the site being served (never {@code null})
|
||||
* @param path the request path, leading {@code /}, no locale prefix (never {@code null})
|
||||
* @param locale the locale the URL implies (the site default for a bare path; never {@code null})
|
||||
* @return the matching ref, or empty when this source does not serve {@code path}
|
||||
*/
|
||||
default Optional<ContentRef> resolve(SiteView site, String path, Locale locale) {
|
||||
for (ContentRef ref : enumerate(site)) {
|
||||
if (ref.published() && path.equals(ref.pathFor(locale))) {
|
||||
return Optional.of(ref);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The content's <b>indexable material</b> for one locale — what a search engine folds into its index
|
||||
* beyond the ref's title/description. Return it as <b>HTML or plain text</b>: engines strip HTML markup
|
||||
* (they were built to index page HTML bodies) and index the remaining prose, so a source whose native
|
||||
* format is not HTML must render it first — a Markdown-backed source returns rendered HTML, not raw
|
||||
* Markdown, or heading/emphasis/link syntax would leak into the index terms and result snippets. Called
|
||||
* only by search indexing (never on a routing/listing path), and only when {@link #CAP_INDEXABLE_TEXT} is
|
||||
* declared — the default returns empty for sources that predate or skip the search integration.
|
||||
*
|
||||
* @param site the site being indexed (never {@code null})
|
||||
* @param id the content identity (a {@link ContentRef#id()} of this source; never {@code null})
|
||||
* @param locale the locale being indexed (never {@code null})
|
||||
* @return the material as HTML or plain text, or empty when this content/locale has none (never
|
||||
* {@code null})
|
||||
*/
|
||||
default String indexableText(SiteView site, String id, Locale locale) {
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The capabilities this source declares, so the host can branch on data rather than type. Defaults to
|
||||
* {@link Capabilities#none()}.
|
||||
*
|
||||
* @return the declared capabilities (never {@code null})
|
||||
*/
|
||||
default Capabilities capabilities() {
|
||||
return Capabilities.none();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.RenderFragment;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
|
||||
/**
|
||||
* A renderable piece of body content a page or master pulls in at an anchor — a carousel, a
|
||||
* search box, a recent-posts list. The host finds the anchor in the page markup (a
|
||||
* {@code data-widget="<plugin>/<instance>"} attribute), resolves the instance's configuration,
|
||||
* and asks the matching widget to render.
|
||||
*
|
||||
* <h2>Contract</h2>
|
||||
* <ul>
|
||||
* <li>{@link #render(WidgetView)} is a <b>pure function</b> of its {@link WidgetView};
|
||||
* implementations are <b>stateless and thread-safe</b>.</li>
|
||||
* <li><b>Soft-degrade:</b> when there is nothing to show (missing instance, disabled
|
||||
* feature), return {@link RenderFragment#empty()} — the page still renders, just without
|
||||
* this widget. Never throw to signal "nothing to show".</li>
|
||||
* <li>{@link #key()} is the stable widget-type key referenced by the {@code data-widget}
|
||||
* attribute; a duplicate among kernel contributions fails startup; a plugin's
|
||||
* colliding contribution is refused (the later plugin's in load order) and reported (since SPI 0.4.0).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* A {@code render} that throws a {@code RuntimeException} or {@code LinkageError}, or returns {@code null}, renders
|
||||
* as {@link RenderFragment#empty()}; the page carrying the hole is served {@code Cache-Control: no-store} without
|
||||
* validators. The failure is logged (with the stack the first time, then at most once a minute), counted in
|
||||
* {@code runway.plugin.contribution.failures} and shown on the plugins screen.
|
||||
*
|
||||
* <p><b>Threading.</b> The host calls this concurrently from many request threads; an implementation must be
|
||||
* stateless or internally synchronized.
|
||||
*/
|
||||
public interface ContentWidget {
|
||||
|
||||
/**
|
||||
* This widget type's stable, unique key — the {@code <type>} half of a
|
||||
* {@code data-widget="<type>/<instance>"} anchor.
|
||||
*
|
||||
* @return a non-{@code null}, non-empty identifier, stable across releases
|
||||
*/
|
||||
String key();
|
||||
|
||||
/**
|
||||
* Renders this widget for the given page/instance context.
|
||||
*
|
||||
* @param view the immutable, host-materialized context including the instance config
|
||||
* (never {@code null})
|
||||
* @return the fragment to splice at the anchor; {@link RenderFragment#empty()} to
|
||||
* soft-degrade. Never {@code null}.
|
||||
*/
|
||||
RenderFragment render(WidgetView view);
|
||||
|
||||
/**
|
||||
* The capabilities this widget declares (for example whether it is configurable), so the
|
||||
* host can branch on data rather than type. Defaults to {@link Capabilities#none()}.
|
||||
*
|
||||
* @return the declared capabilities (never {@code null})
|
||||
*/
|
||||
default Capabilities capabilities() {
|
||||
return Capabilities.none();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
|
||||
/**
|
||||
* Adds server routes — {@code robots.txt}, {@code sitemap.xml}, {@code llms.txt},
|
||||
* {@code /search}, a contact endpoint. The host reads {@link #routes()} at load time, checks
|
||||
* for collisions, and refuses any route that shadows a reserved kernel prefix; matching
|
||||
* requests are then dispatched to {@link #handle(RouteRequest)}.
|
||||
*
|
||||
* <h2>Contract</h2>
|
||||
* <ul>
|
||||
* <li>{@link #routes()} is declared once at load and must be stable for the life of the
|
||||
* process; each route carries the {@link mx.quest.runway.spi.model.SurfacePosture} the
|
||||
* host applies to its responses (fail-safe: {@code noindex}, not in sitemap, no-store).</li>
|
||||
* <li>{@link #handle(RouteRequest)} is a <b>pure function</b> of its frozen
|
||||
* {@link RouteRequest} — no servlet/Spring types reach it; implementations are
|
||||
* <b>stateless and thread-safe</b>.</li>
|
||||
* <li>{@link #key()} is a stable, unique identifier; a duplicate among kernel contributions fails startup; a plugin's
|
||||
* colliding contribution is refused (the later plugin's in load order) and reported (since SPI 0.4.0).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* <ul>
|
||||
* <li>A request body over the host's cap ({@code runway.endpoints.max-body-bytes}, 10 MiB by default) is answered
|
||||
* {@code 413} without calling {@code handle}.</li>
|
||||
* <li>A {@code handle} that throws a {@code RuntimeException} or {@code LinkageError}, or returns {@code null}, is
|
||||
* answered {@code 500} with {@code Cache-Control: no-store}; logged and counted. Any other {@code Error}
|
||||
* propagates.</li>
|
||||
* <li>A route the host cannot serve is refused on its own at load: a realm other than {@code TENANT}, a path with
|
||||
* {@code *}, <code>{</code> or <code>}</code>, a reserved prefix, or a collision. The plugin's other routes
|
||||
* still load.</li>
|
||||
* <li>A handler may have side effects (storing a submission, sending mail) — that is what endpoints are for — but
|
||||
* must not retain the {@link RouteRequest} beyond the call.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>Threading.</b> The host calls this concurrently from many request threads; an implementation must be
|
||||
* stateless or internally synchronized.
|
||||
*/
|
||||
public interface EndpointContributor {
|
||||
|
||||
/**
|
||||
* This contributor's stable, unique key (for diagnostics and collision detection).
|
||||
*
|
||||
* @return a non-{@code null}, non-empty identifier, stable across releases
|
||||
*/
|
||||
String key();
|
||||
|
||||
/**
|
||||
* The routes this contributor serves. Read once at load; collision- and reserved-prefix-
|
||||
* checked by the host.
|
||||
*
|
||||
* @return the declared routes (never {@code null}; may be empty)
|
||||
*/
|
||||
List<Route> routes();
|
||||
|
||||
/**
|
||||
* Handles a request matched to one of this contributor's {@link #routes()}.
|
||||
*
|
||||
* @param request the immutable, host-materialized request (never {@code null})
|
||||
* @return the response to send back (never {@code null})
|
||||
*/
|
||||
RouteResponse handle(RouteRequest request);
|
||||
|
||||
/**
|
||||
* The capabilities this contributor declares, so the host can branch on data rather than
|
||||
* type. Defaults to {@link Capabilities#none()}.
|
||||
*
|
||||
* @return the declared capabilities (never {@code null})
|
||||
*/
|
||||
default Capabilities capabilities() {
|
||||
return Capabilities.none();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
/**
|
||||
* The five conceptual request-pipeline bands. A plugin filter contribution declares its
|
||||
* <b>band</b> — never a raw order — and the host maps that to a concrete order clamped to the band's window, so
|
||||
* a plugin can never escape its band to preempt the protection floor or run before the security chain. This is
|
||||
* the released, dependency-free identity plugins compile against; the concrete integer windows and clamp live
|
||||
* host-side.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #EDGE_INGRESS} — raw request, pre-security (reject/normalize); never before the kernel floor.</li>
|
||||
* <li>{@link #EDGE_EGRESS} — response rewriting (post-phase).</li>
|
||||
* <li>{@link #TENANT} — after the site is resolved, before security.</li>
|
||||
* <li>{@link #SECURITY} — <b>not contributable</b>: the kernel's realm security chains own it. A plugin cannot
|
||||
* add a security chain instead either — since SPI 1.0.0 a non-essential plugin that declares a
|
||||
* {@code SecurityFilterChain} bean is blocked (the Spring-context rules of the plugin contract).</li>
|
||||
* <li>{@link #APPLICATION} — feature filters; the default, inner of security.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum FilterBand {
|
||||
|
||||
EDGE_INGRESS(true),
|
||||
EDGE_EGRESS(true),
|
||||
TENANT(true),
|
||||
SECURITY(false),
|
||||
APPLICATION(true);
|
||||
|
||||
private final boolean contributable;
|
||||
|
||||
FilterBand(boolean contributable) {
|
||||
this.contributable = contributable;
|
||||
}
|
||||
|
||||
/** Whether a plugin filter may target this band (false for {@link #SECURITY}). */
|
||||
public boolean contributable() {
|
||||
return contributable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Contributes markup to a page's {@code <head>}. The host collects every {@code HeadContributor}
|
||||
* (core and plugin alike) and splices their output before {@code </head>} at the response edge,
|
||||
* <b>independently of the site's templates</b> — this is how SEO/GEO/analytics markup lands on
|
||||
* every page without requiring any code inside a tenant's template.
|
||||
*
|
||||
* <h2>Contract</h2>
|
||||
* <ul>
|
||||
* <li>{@link #render(HeadContext)} is a <b>pure function</b> of its {@link HeadContext}: it
|
||||
* reads no request, no store, no other tenant, and returns plain markup. Implementations
|
||||
* must be <b>stateless and thread-safe</b> — one instance serves many concurrent requests.</li>
|
||||
* <li>Return the markup to inject, or an <b>empty string</b> to contribute nothing for this
|
||||
* request (a no-op is always valid).</li>
|
||||
* <li>{@link #key()} is a stable, unique identifier for this contributor; a duplicate among kernel contributions fails startup; a plugin's
|
||||
* colliding contribution is refused (the later plugin's in load order) and reported (since SPI 0.4.0).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* A {@code render} or {@code headInputs} that throws a {@code RuntimeException} or {@code LinkageError} contributes
|
||||
* nothing for that request; the page is then served {@code Cache-Control: no-store} without {@code ETag} or
|
||||
* {@code Last-Modified}, so the degraded copy is never cached. {@code headInputs} returning {@code null} counts as a
|
||||
* failure. The failure is logged (with the stack the first time per contributor, then at most once a minute),
|
||||
* counted in {@code runway.plugin.contribution.failures} and shown on the plugins screen. A page body larger than
|
||||
* the host's head-injection buffer (8 MiB by default) streams through without any injection.
|
||||
*
|
||||
* <p><b>Threading.</b> The host calls this concurrently from many request threads; an implementation must be
|
||||
* stateless or internally synchronized.
|
||||
*/
|
||||
public interface HeadContributor {
|
||||
|
||||
/**
|
||||
* This contributor's stable, unique key (used for diagnostics and collision detection).
|
||||
*
|
||||
* @return a non-{@code null}, non-empty identifier, stable across releases
|
||||
*/
|
||||
String key();
|
||||
|
||||
/**
|
||||
* Produces the {@code <head>} markup to inject for the given request context.
|
||||
*
|
||||
* @param context the immutable, host-materialized request context (never {@code null})
|
||||
* @return the markup to splice before {@code </head>}; an empty string contributes nothing.
|
||||
* Never {@code null}.
|
||||
*/
|
||||
String render(HeadContext context);
|
||||
|
||||
/**
|
||||
* The capabilities this contributor declares, so the host can branch on data rather than
|
||||
* type. Defaults to {@link Capabilities#none()}.
|
||||
*
|
||||
* @return the declared capabilities (never {@code null})
|
||||
*/
|
||||
default Capabilities capabilities() {
|
||||
return Capabilities.none();
|
||||
}
|
||||
|
||||
/**
|
||||
* The <b>site-relative</b> files and folders whose change alters this contributor's markup, so the host
|
||||
* can fold them into a page's {@code ETag}.
|
||||
*
|
||||
* <h2>Why a contributor has to say this</h2>
|
||||
* A page's strong {@code ETag} is a promise of <b>byte identity</b>, and head markup is spliced in at the
|
||||
* response edge, after the validator has already been computed and possibly answered {@code 304}. So
|
||||
* anything read here that the host cannot see is invisible to the validator: a site manager edits their
|
||||
* organisation name, reloads, sees it correct on a fresh fetch — and every client and CDN holding the old
|
||||
* validator keeps the previous head <b>indefinitely</b>, until some unrelated input happens to change.
|
||||
* That is a wrong answer that looks right from the one place anybody checks.
|
||||
*
|
||||
* <p>The host cannot infer this. It does not know which file a plugin reads, and must not learn any
|
||||
* particular plugin's layout — so the dependency travels with the code that has it.
|
||||
*
|
||||
* <h2>What to return</h2>
|
||||
* Paths <b>relative to the site folder</b> of files you read yourself ({@code "myplugin/feed.yml"}, a
|
||||
* folder you list). A folder folds its listing, so adding or removing a file in it moves the ETag; a
|
||||
* regular file folds its content — so read it when you render, or cache it only while the file is unchanged.
|
||||
* A path that escapes the site folder is ignored, and an absent path folds a stable "absent" marker, so
|
||||
* creating it later changes the ETag.
|
||||
*
|
||||
* <p>Your own settings need no declaration: the host folds every running plugin's app-level settings and, for a
|
||||
* plugin that declares {@code siteSettings:}, its per-site settings ({@link mx.quest.runway.spi.service.PluginSettings})
|
||||
* as loaded. A declared file the host
|
||||
* loads itself — {@code plugins/<id>.yml}, {@code seo.yml}, {@code manifest.yml}, {@code icons} — is folded
|
||||
* as loaded too, not as bytes, so the ETag moves when a change applies (a save or a site reload), with the
|
||||
* markup, rather than on a hand edit the markup does not show yet.
|
||||
*
|
||||
* <p>List only what genuinely shapes the markup. These are read on <b>every</b> conditional request for
|
||||
* every page of the site, so a large or numerous set is a per-request cost paid forever.
|
||||
*
|
||||
* <p>Anything derived from the {@link HeadContext} — the page, the site record, the locale, the canonical
|
||||
* URL — is already folded by the host and must not be listed. A contributor whose output is a pure
|
||||
* function of its context declares nothing, which is why the default is empty and every contributor
|
||||
* written before this method existed keeps working.
|
||||
*
|
||||
* @param siteId the site being rendered, for a contributor whose inputs are named per site (rare — most
|
||||
* return the same constant list for every site)
|
||||
* @return site-relative paths; never {@code null}
|
||||
*/
|
||||
default java.util.List<String> headInputs(String siteId) {
|
||||
return java.util.List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
|
||||
/**
|
||||
* An <b>advisory</b> on-page content/SEO/GEO check. The core ships structural checks (title
|
||||
* and description length, heading structure, alt text, …); SEO/GEO plugins add domain checks.
|
||||
* A check <b>reports findings, it never edits the page</b>. Findings are advisory by default;
|
||||
* only where a site opts into enforcement do they gate publishing.
|
||||
*
|
||||
* <h2>Contract</h2>
|
||||
* <ul>
|
||||
* <li>{@link #inspect(PageView)} is a <b>pure function</b> of its read-only {@link PageView};
|
||||
* implementations are <b>stateless and thread-safe</b> and must not mutate anything.</li>
|
||||
* <li>Return the findings (an <b>empty list</b> means "nothing to report"); <b>never
|
||||
* {@code null}</b> — non-null is the contract. (The reference host coerces a stray
|
||||
* {@code null} to empty defensively, but that tolerance is <em>not</em> part of the SPI
|
||||
* contract; an alternative host may treat a {@code null} return as a fault.)</li>
|
||||
* <li>{@link #key()} is a stable, unique identifier; a duplicate among kernel contributions fails startup; a plugin's
|
||||
* colliding contribution is refused (the later plugin's in load order) and reported (since SPI 0.4.0).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* An {@code inspect} that throws a {@code RuntimeException} or {@code LinkageError} is replaced by one
|
||||
* {@code WARNING} finding with the code {@code check.failed} — never an {@code ERROR}, so a broken check can never
|
||||
* block a publish on an Enforced or Reviewed site. The failure is logged and counted. A check may run several times
|
||||
* per request (once per locale the page is offered in); keep it fast.
|
||||
*
|
||||
* <p><b>Threading.</b> The host calls this concurrently from many request threads; an implementation must be
|
||||
* stateless or internally synchronized.
|
||||
*/
|
||||
public interface PageQualityCheck {
|
||||
|
||||
/**
|
||||
* This check's stable, unique key (for diagnostics and collision detection).
|
||||
*
|
||||
* @return a non-{@code null}, non-empty identifier, stable across releases
|
||||
*/
|
||||
String key();
|
||||
|
||||
/**
|
||||
* Inspects the page and reports findings, without modifying anything.
|
||||
*
|
||||
* @param page the immutable, read-only page view (never {@code null})
|
||||
* @return the findings (empty when the page is clean); never {@code null}
|
||||
*/
|
||||
List<Finding> inspect(PageView page);
|
||||
|
||||
/**
|
||||
* The capabilities this check declares, so the host can branch on data rather than type.
|
||||
* Defaults to {@link Capabilities#none()}.
|
||||
*
|
||||
* @return the declared capabilities (never {@code null})
|
||||
*/
|
||||
default Capabilities capabilities() {
|
||||
return Capabilities.none();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
/**
|
||||
* Marker and version anchor for the Runway extension API.
|
||||
*
|
||||
* <p>{@link #VERSION} is the SPI contract version an extension compiles against. The SPI is
|
||||
* <b>binary API</b>: it evolves only by <i>adding</i> {@code default} methods to interfaces and
|
||||
* keeping old-arity constructors on model records, so an extension built against an earlier
|
||||
* version keeps loading on a later one. Bump {@link #VERSION} on each additive evolution; a
|
||||
* value that no longer parses as {@code MAJOR.MINOR.PATCH} is a mistake (see the compatibility
|
||||
* rules in {@code docs/SPI-STABILITY.md}).
|
||||
*
|
||||
* <p>A plugin declares the level it needs with {@code requiresSpi: ">=X.Y.Z"} in its
|
||||
* {@code plugin.yml}, and the loader compares that floor against exactly this value — not against the
|
||||
* kernel's release version, which moves for reasons that have nothing to do with the extension
|
||||
* contract. A plugin whose floor is not met is blocked at startup with an operator-readable
|
||||
* reason, and the kernel still boots its other plugins. The protection runs one way only: a
|
||||
* kernel older than the one that introduced the key <b>ignores</b> it, because descriptors
|
||||
* parse with unknown properties ignored on purpose (forward/backward compatibility). So the
|
||||
* floor guards upgrades from {@code 0.5.0-beta10} onward, not the upgrade that introduces it.
|
||||
* That is also why the evolution log on {@link #VERSION} has to stay accurate: it is what an
|
||||
* author reads to pick a floor.
|
||||
*/
|
||||
public final class RunwaySpi {
|
||||
|
||||
private RunwaySpi() {}
|
||||
|
||||
/**
|
||||
* The SPI contract version <b>this code was compiled against</b>. It is a compile-time constant, so the Java
|
||||
* compiler copies its value into every class that reads it: in a plugin, {@code RunwaySpi.VERSION} is the
|
||||
* version the plugin was <i>built</i> against, not the one it is running on. Use {@link #runtimeVersion()} for
|
||||
* the running kernel's SPI version. The loader compares a plugin's {@code requiresSpi} floor against the
|
||||
* running version.
|
||||
*
|
||||
* <p>Evolution log (one line per SPI version from 0.4.0 on — it is what an author reads to pick a floor):
|
||||
* <ul>
|
||||
* <li><b>0.4.0</b> — the service tier begins: {@link mx.quest.runway.spi.service.PluginSettings}
|
||||
* with {@link mx.quest.runway.spi.model.SettingsView}, {@link mx.quest.runway.spi.model.PluginInfo},
|
||||
* {@link mx.quest.runway.spi.service.PluginLifecycle}, and {@link #runtimeVersion()}. <b>Removed</b>
|
||||
* {@code model.Permission} (it moved host-side; no plugin used it). Javadoc contracts: {@code Route} (exact
|
||||
* paths, tenant realm only), {@code WidgetView} (frozen config), and a "Limits & failure" paragraph
|
||||
* on every axis.</li>
|
||||
* <li><b>0.5.0</b> — site-facing services: {@link mx.quest.runway.spi.service.PluginSiteFiles} with
|
||||
* {@link mx.quest.runway.spi.model.FileEntry} (the plugin's own per-site subtree),
|
||||
* {@link mx.quest.runway.spi.service.Sites}, {@link mx.quest.runway.spi.service.RequestContext},
|
||||
* {@link mx.quest.runway.spi.service.AccessCheck}, {@link mx.quest.runway.spi.service.Messages},
|
||||
* {@link mx.quest.runway.spi.service.SitePages} with {@link mx.quest.runway.spi.model.StarterPage} and
|
||||
* {@link mx.quest.runway.spi.model.InstallResult}. {@link mx.quest.runway.spi.model.RouteRequest} gains
|
||||
* {@code form}, {@code clientIp}, {@code origin} and {@code param(name)}; its {@code query} is the URL
|
||||
* query only, its {@code locale} is negotiated against the site's locales, and header names are
|
||||
* lowercase. {@link mx.quest.runway.spi.model.Route} gains {@code anonymous} (CSRF-exempt public form
|
||||
* routes). The {@code siteData.personal} descriptor key (left out of transfer copies).</li>
|
||||
* <li><b>0.6.0</b> — the content and event tier:
|
||||
* {@link mx.quest.runway.spi.service.ContentCatalogView} with {@link mx.quest.runway.spi.model.CatalogEntry}
|
||||
* and {@link mx.quest.runway.spi.model.LocalizedUrl} (the published content surface with host-computed
|
||||
* URLs), {@link mx.quest.runway.spi.service.ContentChanges} (announce a source's change; replaces publishing
|
||||
* the host's {@code ContentChangedEvent}), {@link mx.quest.runway.spi.service.SiteEventListener} with
|
||||
* {@link mx.quest.runway.spi.model.SiteLifecycleEvent}, {@link mx.quest.runway.spi.model.SettingsChange}
|
||||
* and {@link mx.quest.runway.spi.model.CatalogChange} (phased, isolated, after the kernel's caches and
|
||||
* outside every host lock; change events carry the item's URLs before and after, and a {@code local}
|
||||
* flag), and {@link mx.quest.runway.spi.service.ConsoleScreen} (a plugin screen inside the console
|
||||
* shell without host classes). {@link ContentSource}'s body-template render model is now documented
|
||||
* contract.</li>
|
||||
* <li><b>1.0.0</b> (1.0.0-rc1) — <b>the contract is frozen</b>: from here the SPI evolves only additively
|
||||
* within the 1.x line (see {@code docs/SPI-STABILITY.md}). One addition:
|
||||
* {@link mx.quest.runway.spi.model.HeadContext#origin()} (the trusted origin, so a site with no configured
|
||||
* base URL still gets absolute URLs in its JSON-LD). One behaviour fix:
|
||||
* {@link mx.quest.runway.spi.model.CatalogEntry#xDefaultPath()} and
|
||||
* {@link mx.quest.runway.spi.model.CatalogEntry#pathFor} never name an address the item is not served at.
|
||||
* The loader now <b>requires</b> a {@code requiresSpi} floor of at least {@code 0.4.0} on every plugin
|
||||
* with a {@code mainClass} (an older or missing floor marks a plugin built for the pre-1.0 contract, which
|
||||
* is blocked), and blocks host linkage and Spring-surface violations instead of warning. A {@code 0.4.0}
|
||||
* – {@code 0.6.0} floor is a 1.x floor: the service tier those versions introduced is the 1.0
|
||||
* contract.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Before 0.4.0: 0.3.4 added {@link HeadContributor#headInputs(String)} (a {@code default} method returning an empty list:
|
||||
* the site-relative paths a contributor reads, so a page's {@code ETag} can cover head markup that is
|
||||
* spliced in at the response edge, after the validator has been computed). It also carries two additions
|
||||
* that landed <i>after</i> the 0.3.3 bump and so were never published under it —
|
||||
* {@link mx.quest.runway.spi.model.PageMeta#nosnippet()} (ask engines not to quote a page while it stays
|
||||
* indexed) and {@link mx.quest.runway.spi.model.Alternate#hreflang()} (the one BCP 47 formatter the head
|
||||
* and the sitemap now share, so the two surfaces cannot drift apart on a regional locale). A plugin using
|
||||
* either must declare {@code >=0.3.4}: kernels {@code 0.5.0-beta7} through {@code -beta9} report 0.3.3 and
|
||||
* do not have them. 0.3.3 added {@link mx.quest.runway.spi.model.PageMeta#provenance()} and the
|
||||
* {@link mx.quest.runway.spi.model.Provenance} record it returns, plus {@code author} and
|
||||
* {@code publishedAt} components (and a {@code provenance()} accessor) on
|
||||
* {@link mx.quest.runway.spi.model.ContentRef} — editorial authorship and publication date; before this
|
||||
* the boundary carried neither, so no {@link HeadContributor} could emit a byline or a date at all — all
|
||||
* with old-arity constructors kept. 0.3.2 added {@link ContentSource#indexableText} (a {@code default}
|
||||
* method gated by the {@code content.indexable-text} capability — the search integration's read side).
|
||||
* 0.3.1 added a {@code sourceKey} component to
|
||||
* {@link mx.quest.runway.spi.model.PageMeta} (identifies the serving content source; {@code null} = kernel
|
||||
* page) and a {@code path} component to {@link mx.quest.runway.spi.model.WidgetView} (the public request
|
||||
* path — the correct way for a widget to reference "the current page's URL"), both with old-arity
|
||||
* constructors kept. 0.3.0 added the content-source axis — {@link ContentSource} plus the
|
||||
* {@link mx.quest.runway.spi.model.ContentRef} and {@link mx.quest.runway.spi.model.ContentBody} boundary
|
||||
* records. 0.2.1 added {@link CaptchaService} and
|
||||
* {@link SiteLoginProtectionControl} (new interfaces) and a {@code query} component to
|
||||
* {@link mx.quest.runway.spi.model.WidgetView} (with the old-arity constructor kept). All additive and
|
||||
* binary-compatible (no existing member changed).
|
||||
*/
|
||||
public static final String VERSION = "1.0.0";
|
||||
|
||||
/**
|
||||
* The SPI version of the <b>running</b> kernel — unlike {@link #VERSION}, which the compiler inlines into the
|
||||
* caller and therefore reports the version a plugin was built against. A plugin that wants to adapt to (or
|
||||
* report) the kernel it runs on calls this.
|
||||
*
|
||||
* @return the running {@code runway-spi}'s version, plain {@code MAJOR.MINOR.PATCH}
|
||||
* @since SPI 0.4.0
|
||||
*/
|
||||
public static String runtimeVersion() {
|
||||
return VERSION;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
/**
|
||||
* An <b>application-realm</b> control over a single site's login protection — the operator's rescue seam for a
|
||||
* tenant that has locked itself out of its own console with a misconfigured CAPTCHA.
|
||||
*
|
||||
* <p>A site manager configures its own login CAPTCHA from the site console; if those keys are wrong (an invalid
|
||||
* or provider-mismatched site key), the challenge can never be solved and the manager can no longer sign in to
|
||||
* fix it. Because per-site login protection is honeypot + CAPTCHA only (the per-IP lockout and IP blocklist are
|
||||
* application-scope, already operator-managed), the <b>only</b> site-level lock-out vector is CAPTCHA — so this
|
||||
* seam lets an application operator switch a specific site's CAPTCHA off from the app-realm Sites screen, without
|
||||
* needing to authenticate into that tenant.
|
||||
*
|
||||
* <p><b>Provided by the platform, armed by a plugin.</b> The kernel ships a no-op default (no protection plugin ⇒
|
||||
* a site never has a CAPTCHA to disable), so the Sites screen compiles and runs with or without the protection
|
||||
* plugin installed. The essential <b>protection</b> plugin supplies the real implementation ({@code @Primary}),
|
||||
* reading and rewriting each site's own per-site protection config. The app console therefore depends only on this
|
||||
* SPI, never on the protection plugin.
|
||||
*
|
||||
* <p><b>Non-destructive.</b> {@link #disableCaptcha(String)} only flips the site's CAPTCHA <i>off</i>; it preserves
|
||||
* the site's stored provider and keys (the secret stays in its encrypted form), so once the manager is back in they
|
||||
* can correct the keys and re-enable. It does not touch the honeypot, the app-scope lockout, or the IP blocklist.
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* Thread-safe: the app console may call it from several operator requests at once. A failure to persist the change
|
||||
* surfaces as an exception to the calling console action; nothing is half-written.
|
||||
*
|
||||
* <p><b>Threading.</b> The host calls this concurrently from many request threads; an implementation must be
|
||||
* stateless or internally synchronized.
|
||||
*/
|
||||
public interface SiteLoginProtectionControl {
|
||||
|
||||
/**
|
||||
* Whether {@code siteId}'s login CAPTCHA is switched on (it may still be misconfigured — this reflects the
|
||||
* enable flag, not whether the keys are valid). Drives the app Sites screen's rescue affordance.
|
||||
*
|
||||
* @param siteId the tenant to inspect
|
||||
* @return {@code true} if the site has login CAPTCHA enabled; {@code false} otherwise (including when no
|
||||
* protection plugin is installed)
|
||||
*/
|
||||
boolean captchaEnabled(String siteId);
|
||||
|
||||
/**
|
||||
* Force {@code siteId}'s login CAPTCHA off — an operator rescue for a site locked out by a broken CAPTCHA.
|
||||
* Preserves the site's stored provider/keys and every other protection setting; a no-op when the site already
|
||||
* has CAPTCHA off, has no protection config, or no protection plugin is installed. Applies without a restart.
|
||||
*
|
||||
* @param siteId the tenant to rescue
|
||||
*/
|
||||
void disableCaptcha(String siteId);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A localized alternate of a page — one {@code (locale, url)} pair, the raw material for an
|
||||
* {@code hreflang} link. The set of alternates a page has is derived from its own available
|
||||
* locales, not the site's.
|
||||
*
|
||||
* @param locale the locale this alternate is for (never {@code null})
|
||||
* @param url the absolute or root-relative URL of the page in that locale (never {@code null})
|
||||
*/
|
||||
public record Alternate(Locale locale, String url) {
|
||||
|
||||
public Alternate {
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
Objects.requireNonNull(url, "url");
|
||||
}
|
||||
|
||||
/**
|
||||
* The value for an {@code hreflang} attribute — a <b>BCP 47 language tag</b>.
|
||||
*
|
||||
* <p>Exists so the two surfaces that emit alternates cannot disagree. The head contributor formatted with
|
||||
* {@code locale.getLanguage()} and the sitemap with {@code locale.toLanguageTag()}: identical for a plain
|
||||
* {@code es}, divergent the moment a region appears ({@code pt} versus {@code pt-BR}). Two surfaces
|
||||
* describing the same page with different tags is precisely the kind of inconsistency that makes an engine
|
||||
* discard the whole annotation set, and nothing would have failed — they simply drift.
|
||||
*
|
||||
* <p>{@code toLanguageTag()} is the correct one: {@code hreflang} takes a language tag, optionally with a
|
||||
* region, and dropping the region silently mislabels a regional variant as the base language.
|
||||
*
|
||||
* <p><b>Not the same thing as the URL prefix.</b> The path prefix is the LANGUAGE only ({@code /es/…}) —
|
||||
* one directory per language, regardless of region — so a difference there is by design, not drift.
|
||||
*/
|
||||
public String hreflang() {
|
||||
return locale.toLanguageTag();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* A host-provided source a {@link mx.quest.runway.spi.BackupParticipant} reads its per-site
|
||||
* data from during a restore. As with {@link BackupWriter}, the host scopes every entry under
|
||||
* the participant's own namespace. Restore should be idempotent — importing the same backup
|
||||
* twice yields the same state.
|
||||
*/
|
||||
public interface BackupReader {
|
||||
|
||||
/**
|
||||
* Whether the backup contains the given participant-relative entry. A restore should
|
||||
* tolerate a missing entry (an older backup, or a feature not yet used when it was taken).
|
||||
*
|
||||
* @param entry the participant-relative entry name (never {@code null})
|
||||
* @return {@code true} if the entry is present
|
||||
*/
|
||||
boolean has(String entry);
|
||||
|
||||
/**
|
||||
* Opens a stream to read one named entry.
|
||||
*
|
||||
* @param entry the participant-relative entry name (never {@code null})
|
||||
* @return an open stream to read the entry's bytes; the caller must close it
|
||||
* @throws IOException if the entry is absent or cannot be opened
|
||||
*/
|
||||
InputStream open(String entry) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* A host-provided sink a {@link mx.quest.runway.spi.BackupParticipant} writes its per-site
|
||||
* data into during a backup. The host owns the archive and scopes every entry under the
|
||||
* participant's own namespace, so participants cannot collide or read each other's data.
|
||||
*
|
||||
* <p>The participant writes one or more named entries and is responsible for closing each
|
||||
* stream it opens (use try-with-resources). Closing a per-entry stream finalizes that entry
|
||||
* only; the host manages the lifecycle of the outer archive (and the safe handling that keeps
|
||||
* a multi-entry container from being closed prematurely).
|
||||
*/
|
||||
public interface BackupWriter {
|
||||
|
||||
/**
|
||||
* Opens a stream for one named entry of this participant's backup data.
|
||||
*
|
||||
* @param entry a participant-relative entry name (for example {@code "slides.yml"});
|
||||
* never {@code null}
|
||||
* @return an open stream to write the entry's bytes; the caller must close it
|
||||
* @throws IOException if the entry cannot be opened for writing
|
||||
*/
|
||||
OutputStream put(String entry) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The immutable set of capability flags an SPI implementation <b>declares</b> about itself,
|
||||
* so the host can be <b>capability-driven</b>: every host surface branches on a declared
|
||||
* capability (data), never on a concrete implementation type or an {@code instanceof}/
|
||||
* {@code switch} over a known catalog. The acceptance test of the model is that a brand-new
|
||||
* implementation lights up across the platform with no host edit.
|
||||
*
|
||||
* <p>Flags are free-form string identifiers, by convention lowercase dotted keys (for example
|
||||
* {@code "widget.configurable"} or {@code "head.per-locale"}). They are a <em>convention the
|
||||
* kernel owns</em> — only the host calls {@link #has(String)} to decide behaviour, so an
|
||||
* implementation built against an older SPI never needs to know a flag a newer host added,
|
||||
* and a host that doesn't recognise a flag simply doesn't branch on it. This is deliberately
|
||||
* a string vocabulary (not a closed enum) so the catalog grows additively without an SPI
|
||||
* binary change and without the "old binary lacks the new enum constant" trap.
|
||||
*
|
||||
* <p>Instances are immutable; {@link #flags()} returns an unmodifiable set.
|
||||
*
|
||||
* @param flags the declared capability identifiers (never {@code null}; defensively copied)
|
||||
*/
|
||||
public record Capabilities(Set<String> flags) {
|
||||
|
||||
private static final Capabilities NONE = new Capabilities(Set.of());
|
||||
|
||||
/**
|
||||
* Canonical constructor — null-normalizes to the empty set and stores an unmodifiable
|
||||
* copy. Rejects a {@code null} flag element.
|
||||
*/
|
||||
public Capabilities {
|
||||
flags = (flags == null) ? Set.of() : Set.copyOf(flags);
|
||||
}
|
||||
|
||||
/** The empty capability set — the default an implementation advertises when it declares nothing. */
|
||||
public static Capabilities none() {
|
||||
return NONE;
|
||||
}
|
||||
|
||||
/**
|
||||
* A capability set from the given flags. Duplicates collapse; a {@code null} flag is
|
||||
* rejected. No arguments (or {@code null}) yields {@link #none()}.
|
||||
*/
|
||||
public static Capabilities of(String... flags) {
|
||||
if (flags == null || flags.length == 0) {
|
||||
return NONE;
|
||||
}
|
||||
LinkedHashSet<String> set = new LinkedHashSet<>(Arrays.asList(flags));
|
||||
return new Capabilities(set);
|
||||
}
|
||||
|
||||
/** Whether this set declares the given capability flag. A {@code null} flag is never present. */
|
||||
public boolean has(String flag) {
|
||||
return flag != null && flags.contains(flag);
|
||||
}
|
||||
|
||||
/** Whether no capability is declared. */
|
||||
public boolean isEmpty() {
|
||||
return flags.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* This set plus the given flags (a new instance; this one is unchanged). Useful for an
|
||||
* implementation composing its capabilities.
|
||||
*/
|
||||
public Capabilities with(String... more) {
|
||||
if (more == null || more.length == 0) {
|
||||
return this;
|
||||
}
|
||||
LinkedHashSet<String> set = new LinkedHashSet<>(flags);
|
||||
set.addAll(Arrays.asList(more));
|
||||
for (String f : set) {
|
||||
Objects.requireNonNull(f, "capability flag");
|
||||
}
|
||||
return new Capabilities(set);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
/**
|
||||
* A ready-to-embed CAPTCHA challenge for one site's form — the output of
|
||||
* {@link mx.quest.runway.spi.CaptchaService#widgetForSite(String)}. A consuming form (the contact form, or any
|
||||
* plugin/page form) just drops {@link #html()} into its markup and, on submit, reads the token from the
|
||||
* {@link #tokenField()} request parameter to verify it. Everything provider-specific (which vendor, the public
|
||||
* site key, the widget CSS class, the script URL, the invisible-v3 handling) is already baked into {@link #html()}
|
||||
* by the implementation, so the consumer needs no CAPTCHA-provider knowledge.
|
||||
*
|
||||
* @param active whether a challenge is actually configured for the site — when {@code false}, {@link #html()}
|
||||
* is empty and {@link mx.quest.runway.spi.CaptchaService#verify verify} accepts any request, so a
|
||||
* form can render + verify unconditionally and simply has no CAPTCHA when none is set
|
||||
* @param tokenField the request-parameter name the widget posts its solved token under (empty when inactive)
|
||||
* @param html the self-contained widget markup to insert into the form (the challenge div/hidden field plus
|
||||
* the provider script); empty when inactive. Contains only operator-configured values, safe to
|
||||
* embed as trusted markup
|
||||
*/
|
||||
public record CaptchaWidget(boolean active, String tokenField, String html) {
|
||||
|
||||
public CaptchaWidget {
|
||||
tokenField = tokenField == null ? "" : tokenField;
|
||||
html = html == null ? "" : html;
|
||||
}
|
||||
|
||||
/** The "no challenge configured" widget: renders nothing and never blocks a submission. */
|
||||
public static CaptchaWidget inactive() {
|
||||
return new CaptchaWidget(false, "", "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Something that may reshape a site's content surface changed — what
|
||||
* {@link mx.quest.runway.spi.service.SiteEventListener#onCatalogChanged} receives. Immutable.
|
||||
*
|
||||
* <p>What each {@link Cause} carries:
|
||||
* <table>
|
||||
* <caption>Components by cause</caption>
|
||||
* <tr><th>cause</th><th>{@code sourceKey}</th><th>{@code id}</th><th>{@code pluginId}</th><th>URLs</th></tr>
|
||||
* <tr><td>{@code PAGE}</td><td>{@code "pages"}</td><td>the page slug, or {@code null} for the whole site</td>
|
||||
* <td>{@code null}</td><td>previous and current</td></tr>
|
||||
* <tr><td>{@code CONTENT}</td><td>the publishing source's key</td><td>the item id, or {@code null} for the
|
||||
* source's whole corpus</td><td>the plugin that owns the source ({@code null} for a kernel source)</td>
|
||||
* <td>previous and current</td></tr>
|
||||
* <tr><td>{@code SITE}</td><td>{@code null}</td><td>{@code null}</td><td>{@code null}</td><td>both empty</td></tr>
|
||||
* <tr><td>{@code SETTINGS}</td><td>{@code null}</td><td>{@code null}</td><td>the plugin whose per-site settings
|
||||
* were saved</td><td>both empty</td></tr>
|
||||
* </table>
|
||||
*
|
||||
* <p><b>The URLs.</b> {@code previousUrls} are the item's addresses as the host last listed them, captured before
|
||||
* any cache was evicted — so a <b>deleted</b> or <b>moved</b> item still reports where it used to be. They are empty
|
||||
* when the item is new, when the event names no item, or when the host has not listed the site since it started.
|
||||
* {@code currentUrls} are the item's addresses after the change, from a fresh listing; empty when the item is gone,
|
||||
* unpublished or names no item. A consumer that tells the outside world about changed URLs (an IndexNow submitter)
|
||||
* uses the union of both. <b>A {@code SOURCE}-phase listener always receives {@code currentUrls} empty</b>: the
|
||||
* current listing cannot be resolved before the sources themselves have dropped their state.
|
||||
*
|
||||
* @param siteId the site (never {@code null})
|
||||
* @param cause what happened (never {@code null}); may gain constants in a MINOR release
|
||||
* @param sourceKey see the table (nullable)
|
||||
* @param id see the table (nullable)
|
||||
* @param pluginId see the table (nullable)
|
||||
* @param previousUrls the item's addresses before the change (never {@code null}; copied, unmodifiable)
|
||||
* @param currentUrls the item's addresses after the change (never {@code null}; copied, unmodifiable)
|
||||
* @param local {@code true} on the node where the change happened; {@code false} for a peer's replayed
|
||||
* change. A listener with an external side effect acts only on local changes, so a cluster of N
|
||||
* nodes does not repeat it N times
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public record CatalogChange(String siteId, Cause cause, String sourceKey, String id, String pluginId,
|
||||
List<LocalizedUrl> previousUrls, List<LocalizedUrl> currentUrls, boolean local) {
|
||||
|
||||
/** Why the content surface may have changed. */
|
||||
public enum Cause {
|
||||
/** A real page was created, saved, renamed, deleted, published or unpublished. */
|
||||
PAGE,
|
||||
/** A content source announced a change to its content. */
|
||||
CONTENT,
|
||||
/** A site lifecycle event (see {@link SiteLifecycleEvent}). */
|
||||
SITE,
|
||||
/** A plugin's per-site settings were saved (any plugin: settings can reshape a source's output). */
|
||||
SETTINGS
|
||||
}
|
||||
|
||||
public CatalogChange {
|
||||
Objects.requireNonNull(siteId, "siteId");
|
||||
Objects.requireNonNull(cause, "cause");
|
||||
previousUrls = (previousUrls == null) ? List.of() : List.copyOf(previousUrls);
|
||||
currentUrls = (currentUrls == null) ? List.of() : List.copyOf(currentUrls);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* One item of a site's published content surface — a real page or a content source's item — as
|
||||
* {@link mx.quest.runway.spi.service.ContentCatalogView} lists it: the item's metadata plus the URLs the host
|
||||
* computed for it. Immutable.
|
||||
*
|
||||
* @param sourceKey the {@link mx.quest.runway.spi.ContentSource#key()} that contributed the item;
|
||||
* {@code "pages"} ({@link mx.quest.runway.spi.service.ContentCatalogView#PAGES_SOURCE}) for a
|
||||
* real page. Never {@code null}
|
||||
* @param ref the item's metadata as its source declared it (for a page, the id is the page's slug).
|
||||
* Never {@code null}
|
||||
* @param urls one {@link LocalizedUrl} per <b>available</b> locale — the locales the item declares that the
|
||||
* site also serves, or the site's default locale alone when none survive. Never empty for an
|
||||
* entry the host built; copied and unmodifiable
|
||||
* @param xDefaultPath the root-relative {@code x-default} address: the URL of the item's primary locale, or — when
|
||||
* the site does not serve the primary — of the item's first <b>available</b> locale (the first
|
||||
* of {@code urls}), so it is always an address the site serves for this item. Never
|
||||
* {@code null}. (Before SPI 1.0.0 the fallback was the site's default locale, which could name
|
||||
* an unprefixed path the item does not exist at.)
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public record CatalogEntry(String sourceKey, ContentRef ref, List<LocalizedUrl> urls, String xDefaultPath) {
|
||||
|
||||
public CatalogEntry {
|
||||
Objects.requireNonNull(sourceKey, "sourceKey");
|
||||
Objects.requireNonNull(ref, "ref");
|
||||
urls = (urls == null) ? List.of() : List.copyOf(urls);
|
||||
if (xDefaultPath == null || xDefaultPath.isBlank()) {
|
||||
xDefaultPath = urls.isEmpty() ? ref.path() : urls.get(0).path();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The item's identity across sources: {@code <sourceKey>:<id>} ({@code pages:<slug>} for a page). Stable,
|
||||
* collision-free (a {@code :} never appears in a page slug or a source id), and the key the change events of
|
||||
* {@link mx.quest.runway.spi.service.SiteEventListener} name items by. Never a file name.
|
||||
*/
|
||||
public String compositeId() {
|
||||
return sourceKey + ":" + ref.id();
|
||||
}
|
||||
|
||||
/** Whether this entry is a real page (its source is {@code "pages"}). */
|
||||
public boolean isPage() {
|
||||
return "pages".equals(sourceKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* The root-relative URL to link this item from content rendered in {@code locale}: that locale's address when
|
||||
* the item is available in it, else {@link #xDefaultPath()} when that is one of {@link #urls()} (always so for
|
||||
* an entry the host built), else the first of {@link #urls()}. An item that does not exist in the requested
|
||||
* locale is therefore linked where it does exist, never to a URL that 404s — even for an entry built by hand
|
||||
* with an {@code xDefaultPath} outside its own URLs. With no URLs at all, {@link #xDefaultPath()}.
|
||||
*
|
||||
* @param locale the locale of the linking context (never {@code null})
|
||||
* @return a root-relative URL (never {@code null})
|
||||
*/
|
||||
public String pathFor(Locale locale) {
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
for (LocalizedUrl url : urls) {
|
||||
if (url.locale().equals(locale)) {
|
||||
return url.path();
|
||||
}
|
||||
}
|
||||
if (urls.isEmpty()) {
|
||||
return xDefaultPath;
|
||||
}
|
||||
for (LocalizedUrl url : urls) {
|
||||
if (url.path().equals(xDefaultPath)) {
|
||||
return xDefaultPath;
|
||||
}
|
||||
}
|
||||
return urls.get(0).path();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The lazily-fetched <b>render payload</b> of one piece of content, for one locale — the counterpart of the
|
||||
* always-cheap {@link ContentRef} metadata. The kernel calls
|
||||
* {@link mx.quest.runway.spi.ContentSource#body(SiteView, String, java.util.Locale)} <em>only</em> for an
|
||||
* actual {@code 200} render: the conditional-request ({@code 304}) path, the sitemap, llms.txt and search
|
||||
* enumeration never see this type.
|
||||
*
|
||||
* <p>The payload reaches the content's body template (the {@link ContentRef#bodyTemplate()}) under the
|
||||
* <b>{@code ${content.*}} namespace</b> — {@code ${content.bodyHtml}}, {@code ${content.attributes['...']}} —
|
||||
* alongside the standard page-render model. The namespace is a <em>clobber guard</em> (source values can never
|
||||
* shadow kernel model variables), not a security boundary: the template renders with the full evaluation
|
||||
* context under the same first-party trust as any plugin code.
|
||||
*
|
||||
* @param bodyHtml the content's main body markup, ready to splice into the body template ({@code null}
|
||||
* normalized to empty). The source owns the markup's safety exactly as a widget owns its
|
||||
* {@link RenderFragment} — sources render/escape their raw material (e.g. Markdown) before
|
||||
* returning it
|
||||
* @param attributes additional per-render string values for the template (e.g. a formatted publication date),
|
||||
* insertion order preserved; never {@code null} after normalization
|
||||
*/
|
||||
public record ContentBody(String bodyHtml, Map<String, String> attributes) {
|
||||
|
||||
private static final ContentBody EMPTY = new ContentBody("", Map.of());
|
||||
|
||||
public ContentBody {
|
||||
bodyHtml = (bodyHtml == null) ? "" : bodyHtml;
|
||||
attributes = normalize(attributes);
|
||||
}
|
||||
|
||||
/** A body of just markup, no extra attributes. */
|
||||
public static ContentBody of(String bodyHtml) {
|
||||
return (bodyHtml == null || bodyHtml.isEmpty()) ? EMPTY : new ContentBody(bodyHtml, Map.of());
|
||||
}
|
||||
|
||||
/** The empty body — a source's honest answer when the content has no renderable payload. */
|
||||
public static ContentBody empty() {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
/** Trimmed keys, blank keys dropped, null values coerced to "", order preserved (the params convention). */
|
||||
private static Map<String, String> normalize(Map<String, String> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> clean = new LinkedHashMap<>();
|
||||
raw.forEach((key, value) -> {
|
||||
if (key != null) {
|
||||
String trimmedKey = key.trim();
|
||||
if (!trimmedKey.isEmpty()) {
|
||||
clean.put(trimmedKey, value == null ? "" : value);
|
||||
}
|
||||
}
|
||||
});
|
||||
return Collections.unmodifiableMap(clean);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The <b>metadata</b> of one piece of content a {@link mx.quest.runway.spi.ContentSource} serves — everything
|
||||
* routing, the sitemap, llms.txt, search, and the {@code <head>} need <em>without ever fetching the body</em>.
|
||||
* The body itself ({@link ContentBody}) is fetched lazily, only for an actual {@code 200} render; keeping this
|
||||
* record body-free is what makes enumerating every source safe on a public, anonymous request (a sitemap must
|
||||
* never become a full-corpus disk/database read).
|
||||
*
|
||||
* <p>The dispatch surface deliberately mirrors the kernel page's, so virtual content participates in locale
|
||||
* dispatch <em>exactly</em> like a page: {@link #pathFor(Locale)} keeps the localized-override-else-default
|
||||
* fallback, {@link #hasLocale(Locale, Locale)} treats an empty {@link #locales()} as "site default only", and
|
||||
* {@link #primaryLocale(Locale)} prefers the site default. A localized path resolves to exactly one
|
||||
* (content, locale) pair and never doubles as another locale's URL.
|
||||
*
|
||||
* <p><b>Shape-only normalization.</b> This is a dependency-free boundary record: it trims and drops blank map
|
||||
* entries but performs no path-safety or reserved-prefix validation — the <b>kernel re-filters every source
|
||||
* output fail-closed</b> (published, path safety, reserved prefixes) before routing or enumeration consumes
|
||||
* it, so a misbehaving source results in omission, never disclosure.
|
||||
*
|
||||
* @param id the source-scoped stable identity of this content (never {@code null}/blank). Like an
|
||||
* SPI {@code key()}, it is a persisted contract — URLs, search hits and internal links
|
||||
* ({@code ${urls['<sourceKey>:<id>']}}) survive a refactor only if it is stable
|
||||
* @param path the default-locale public path, leading {@code /} (never {@code null}/blank)
|
||||
* @param localizedPaths per-language path overrides ({@code lang → path}); blank values are dropped so the
|
||||
* locale falls back to {@link #path} (never {@code null} after normalization)
|
||||
* @param locales the locales this content is published in; <b>empty means the site default only</b>
|
||||
* (the page convention)
|
||||
* @param title per-language titles ({@code lang → text}); {@link #titleFor(Locale)} falls back to any
|
||||
* present value
|
||||
* @param description per-language descriptions, same fallback rule
|
||||
* @param activeNav the navigation id this content highlights, or {@code null}
|
||||
* @param bodyTemplate the full logical name of the Thymeleaf template that renders this content's body
|
||||
* (e.g. {@code __plugin__/blog/entry-classic}; never {@code null}/blank). Carried in
|
||||
* metadata — not on {@link ContentBody} — so a conditional-request ({@code 304}) can fold
|
||||
* the template into its validator <em>without</em> fetching the body, and so the kernel
|
||||
* can namespace-validate before rendering
|
||||
* @param published whether this content is publicly visible. Sources must enumerate published content
|
||||
* only; the kernel drops unpublished refs fail-closed as the backstop
|
||||
* @param updatedAt when the content last changed — drives the sitemap {@code <lastmod>} AND is
|
||||
* <b>load-bearing for HTTP revalidation</b>: the render ETag folds this record's state,
|
||||
* never the body payload, so ANY change to what {@code body()} returns (body files
|
||||
* included) MUST change {@code updatedAt} (or other ref metadata) — otherwise
|
||||
* revalidating clients receive stale {@code 304}s indefinitely. {@code null} if unknown
|
||||
* (then only metadata/template edits refresh caches)
|
||||
* @param author display name credited for this content, or {@code null} when unattributed. An
|
||||
* EDITORIAL fact the source owns — unlike {@code updatedAt}, which the host derives
|
||||
* @param publishedAt when this content was first published, or {@code null} if unknown. Editorial, and
|
||||
* deliberately NOT derived from a file mtime: a backup/restore or a redeploy rewrites
|
||||
* mtimes, and a publication date that moves is an untrue assertion
|
||||
* @param noindex whether robots must be told not to index this content (same semantics as a page)
|
||||
* @param canonical an absolute canonical URL override for the {@code <head>}, or {@code null}. The
|
||||
* sitemap deliberately ignores it — a sitemap lists real URLs
|
||||
* @param cacheControl a {@code Cache-Control} override for responses, or {@code null} for the default
|
||||
* @param params free-form per-content parameters for the body template (insertion order preserved;
|
||||
* never {@code null} after normalization)
|
||||
*/
|
||||
public record ContentRef(String id, String path, Map<String, String> localizedPaths, List<Locale> locales,
|
||||
Map<String, String> title, Map<String, String> description, String activeNav,
|
||||
String bodyTemplate, boolean published, Instant updatedAt, boolean noindex,
|
||||
String canonical, String cacheControl, Map<String, String> params,
|
||||
String author, Instant publishedAt) {
|
||||
|
||||
/**
|
||||
* Canonical constructor — validates the required identity fields and shape-normalizes the collections
|
||||
* (defensive copies; trimmed keys; blank localized paths dropped). See the class contract for what is
|
||||
* deliberately <em>not</em> validated here.
|
||||
*/
|
||||
public ContentRef {
|
||||
id = requireNonBlank(id, "id");
|
||||
path = requireNonBlank(path, "path");
|
||||
bodyTemplate = requireNonBlank(bodyTemplate, "bodyTemplate");
|
||||
localizedPaths = normalizeLocalized(localizedPaths);
|
||||
locales = (locales == null) ? List.of() : List.copyOf(locales);
|
||||
title = normalizeText(title);
|
||||
description = normalizeText(description);
|
||||
params = normalizeParams(params);
|
||||
// Blank byline == no byline: a form posts "" for an untouched field, and an empty author must not
|
||||
// serialize as a present-but-meaningless value or render as an empty byline.
|
||||
author = (author == null || author.isBlank()) ? null : author.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The pre-provenance canonical form, kept for binary compatibility (SPI evolution rule) so a
|
||||
* {@link mx.quest.runway.spi.ContentSource} compiled against an earlier SPI keeps loading: content with no
|
||||
* author and no publication date.
|
||||
*/
|
||||
public ContentRef(String id, String path, Map<String, String> localizedPaths, List<Locale> locales,
|
||||
Map<String, String> title, Map<String, String> description, String activeNav,
|
||||
String bodyTemplate, boolean published, Instant updatedAt, boolean noindex,
|
||||
String canonical, String cacheControl, Map<String, String> params) {
|
||||
this(id, path, localizedPaths, locales, title, description, activeNav, bodyTemplate, published,
|
||||
updatedAt, noindex, canonical, cacheControl, params, null, null);
|
||||
}
|
||||
|
||||
/** A minimal published ref — the common construction for straightforward sources; overrides default off. */
|
||||
public static ContentRef of(String id, String path, Map<String, String> localizedPaths, List<Locale> locales,
|
||||
Map<String, String> title, Map<String, String> description, String bodyTemplate,
|
||||
Instant updatedAt) {
|
||||
return new ContentRef(id, path, localizedPaths, locales, title, description, null, bodyTemplate,
|
||||
true, updatedAt, false, null, null, Map.of(), null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* A minimal published ref that carries a byline and a publication date — the shape a blog or article source
|
||||
* wants, so its entries can produce truthful {@code datePublished}/{@code author} rather than leaving the
|
||||
* schema layer to guess one value for every entry.
|
||||
*/
|
||||
public static ContentRef of(String id, String path, Map<String, String> localizedPaths, List<Locale> locales,
|
||||
Map<String, String> title, Map<String, String> description, String bodyTemplate,
|
||||
Instant updatedAt, String author, Instant publishedAt) {
|
||||
return new ContentRef(id, path, localizedPaths, locales, title, description, null, bodyTemplate,
|
||||
true, updatedAt, false, null, null, Map.of(), author, publishedAt);
|
||||
}
|
||||
|
||||
/** This ref's authorship and timestamps as one value for the SPI boundary. */
|
||||
public Provenance provenance() {
|
||||
return new Provenance(author, publishedAt, updatedAt);
|
||||
}
|
||||
|
||||
/** The public path for {@code locale}: the localized override if any, else the default {@link #path}. */
|
||||
public String pathFor(Locale locale) {
|
||||
String localized = localizedPaths.get(locale.getLanguage());
|
||||
return localized != null ? localized : path;
|
||||
}
|
||||
|
||||
/** Whether this content is available in {@code locale} (an empty {@link #locales} means site-default only). */
|
||||
public boolean hasLocale(Locale locale, Locale siteDefault) {
|
||||
return locales.isEmpty() ? locale.equals(siteDefault) : locales.contains(locale);
|
||||
}
|
||||
|
||||
/** The primary locale: the site default if available, else the first declared locale. */
|
||||
public Locale primaryLocale(Locale siteDefault) {
|
||||
return (locales.isEmpty() || locales.contains(siteDefault)) ? siteDefault : locales.get(0);
|
||||
}
|
||||
|
||||
/** The title for {@code locale}, falling back to any present title, else empty. */
|
||||
public String titleFor(Locale locale) {
|
||||
return localized(title, locale);
|
||||
}
|
||||
|
||||
/** The description for {@code locale}, falling back to any present value, else empty. */
|
||||
public String descriptionFor(Locale locale) {
|
||||
return localized(description, locale);
|
||||
}
|
||||
|
||||
// --- normalization (shape only — the kernel validates safety) ----------------------------------------------
|
||||
|
||||
private static String requireNonBlank(String value, String name) {
|
||||
Objects.requireNonNull(value, name);
|
||||
String trimmed = value.trim();
|
||||
if (trimmed.isEmpty()) {
|
||||
throw new IllegalArgumentException(name + " must not be blank");
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** Trims entries; drops null/blank keys and values (a blank override must fall back, not route to ""). */
|
||||
private static Map<String, String> normalizeLocalized(Map<String, String> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> safe = new LinkedHashMap<>();
|
||||
raw.forEach((lang, value) -> {
|
||||
if (lang != null && value != null && !lang.isBlank()) {
|
||||
String trimmed = value.trim();
|
||||
if (!trimmed.isEmpty()) {
|
||||
safe.put(lang.trim(), trimmed);
|
||||
}
|
||||
}
|
||||
});
|
||||
return Collections.unmodifiableMap(safe);
|
||||
}
|
||||
|
||||
/** Null → empty; null keys/values dropped; values kept verbatim (text may legitimately lead with space). */
|
||||
private static Map<String, String> normalizeText(Map<String, String> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> clean = new LinkedHashMap<>();
|
||||
raw.forEach((lang, value) -> {
|
||||
if (lang != null && !lang.isBlank() && value != null) {
|
||||
clean.put(lang.trim(), value);
|
||||
}
|
||||
});
|
||||
return Collections.unmodifiableMap(clean);
|
||||
}
|
||||
|
||||
/** The page convention: trimmed keys, blank keys dropped, null values coerced to "", order preserved. */
|
||||
private static Map<String, String> normalizeParams(Map<String, String> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> clean = new LinkedHashMap<>();
|
||||
raw.forEach((key, value) -> {
|
||||
if (key != null) {
|
||||
String trimmedKey = key.trim();
|
||||
if (!trimmedKey.isEmpty()) {
|
||||
clean.put(trimmedKey, value == null ? "" : value);
|
||||
}
|
||||
}
|
||||
});
|
||||
return Collections.unmodifiableMap(clean);
|
||||
}
|
||||
|
||||
private static String localized(Map<String, String> map, Locale locale) {
|
||||
String value = map.get(locale.getLanguage());
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
return map.isEmpty() ? "" : map.values().iterator().next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* One entry of a plugin's per-site file subtree, as {@link mx.quest.runway.spi.service.PluginSiteFiles} reports
|
||||
* it. Immutable.
|
||||
*
|
||||
* @param name the entry's own name (one path segment, never {@code null})
|
||||
* @param directory whether it is a folder
|
||||
* @param size the size in bytes; {@code 0} for a folder
|
||||
* @param lastModified the last-modified time ({@code null} normalized to {@link Instant#EPOCH})
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public record FileEntry(String name, boolean directory, long size, Instant lastModified) {
|
||||
|
||||
public FileEntry {
|
||||
Objects.requireNonNull(name, "name");
|
||||
size = directory ? 0 : Math.max(0, size);
|
||||
lastModified = lastModified == null ? Instant.EPOCH : lastModified;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* One advisory result from a {@link mx.quest.runway.spi.PageQualityCheck} — a single
|
||||
* observation about a page. A finding never mutates anything; it is surfaced to the author
|
||||
* and, only where a site opts into enforcement, may gate publishing.
|
||||
*
|
||||
* @param severity the advisory level (never {@code null})
|
||||
* @param code a stable, machine-readable identifier for the kind of finding, for i18n and
|
||||
* deduplication (for example {@code "title.too-long"}; never {@code null})
|
||||
* @param message a human-readable description ({@code null} normalized to empty); typically a
|
||||
* resolved message, since the host owns i18n
|
||||
*/
|
||||
public record Finding(Severity severity, String code, String message) {
|
||||
|
||||
public Finding {
|
||||
Objects.requireNonNull(severity, "severity");
|
||||
Objects.requireNonNull(code, "code");
|
||||
message = (message == null) ? "" : message;
|
||||
}
|
||||
|
||||
/** An {@link Severity#INFO} finding. */
|
||||
public static Finding info(String code, String message) {
|
||||
return new Finding(Severity.INFO, code, message);
|
||||
}
|
||||
|
||||
/** A {@link Severity#WARNING} finding. */
|
||||
public static Finding warning(String code, String message) {
|
||||
return new Finding(Severity.WARNING, code, message);
|
||||
}
|
||||
|
||||
/** A {@link Severity#ERROR} finding. */
|
||||
public static Finding error(String code, String message) {
|
||||
return new Finding(Severity.ERROR, code, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The immutable input to a {@link mx.quest.runway.spi.HeadContributor} — everything resolved
|
||||
* for the current request that a contributor needs to produce {@code <head>} markup, without
|
||||
* touching the request or any store. The host injects the rendered markup before
|
||||
* {@code </head>} at the response edge, independently of the site's templates.
|
||||
*
|
||||
* <p>Facts available through {@link #site()} (for example its base URL and full locale set) and
|
||||
* through {@link #page()} (title, description, available locales) are not duplicated here.
|
||||
*
|
||||
* @param site the site being served (never {@code null})
|
||||
* @param page the page being served (never {@code null})
|
||||
* @param locale the resolved request locale (never {@code null})
|
||||
* @param canonical the resolved canonical URL for this page+locale, or {@code null} when not
|
||||
* applicable
|
||||
* @param xDefault the resolved {@code hreflang x-default} URL (the page's primary-locale URL),
|
||||
* or {@code null} when not applicable
|
||||
* @param alternates the page's localized alternates for {@code hreflang} (never {@code null};
|
||||
* defensively copied, unmodifiable; may be empty)
|
||||
* @param preview whether this is a draft/preview render (preview surfaces are never indexable)
|
||||
* @param noindex the <em>effective</em> indexability for this render — the host has already
|
||||
* folded in the page's setting and preview, so a contributor can emit the
|
||||
* robots directive directly from this flag
|
||||
* @param seo the site's core SEO tags (social cards + verification + extra head), resolved by
|
||||
* the host; never {@code null} (an unconfigured site yields {@link SeoTags#empty()})
|
||||
* @param icons the site's icon/manifest discovery hints, resolved by the host; never {@code null}
|
||||
* (a site with no icons yields {@link IconHints#NONE})
|
||||
* @param origin the <b>trusted origin</b> the page is served under — {@code scheme://host[:port]}, no
|
||||
* trailing slash, default port omitted — for building absolute URLs (JSON-LD {@code @id}s, social
|
||||
* card images) that must never be relative: the site's base URL when it has one (configured,
|
||||
* or derived from its primary host — {@link SiteView#baseUrl()}), else — a host-less site, such as
|
||||
* the platform's catch-all default — the request's own origin as the host's trusted-proxy gate
|
||||
* left it (a configured trusted
|
||||
* proxy's forwarded scheme and host applied, raw values otherwise — never a raw
|
||||
* {@code X-Forwarded-*} header). Never {@code null}; {@code ""} when unknown (a context built
|
||||
* with an older constructor, or a render with no request). {@link #canonical()},
|
||||
* {@link #xDefault()} and {@link #alternates()} keep their own rule (prefixed with the configured
|
||||
* base URL only), so a host-less site's head links stay root-relative as before; {@code ""}
|
||||
* for a draft preview; since SPI 1.0.0
|
||||
*/
|
||||
public record HeadContext(SiteView site, PageMeta page, Locale locale, String canonical,
|
||||
String xDefault, List<Alternate> alternates, boolean preview, boolean noindex,
|
||||
SeoTags seo, IconHints icons, String origin) {
|
||||
|
||||
public HeadContext {
|
||||
Objects.requireNonNull(site, "site");
|
||||
Objects.requireNonNull(page, "page");
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
alternates = (alternates == null) ? List.of() : List.copyOf(alternates);
|
||||
seo = (seo == null) ? SeoTags.empty() : seo;
|
||||
icons = (icons == null) ? IconHints.NONE : icons;
|
||||
origin = (origin == null) ? "" : (origin.endsWith("/") ? origin.substring(0, origin.length() - 1) : origin);
|
||||
}
|
||||
|
||||
/**
|
||||
* The SPI 0.6.0 form, before the {@code origin} component: {@link #origin()} is {@code ""}. (Kept per the SPI
|
||||
* evolution rule.)
|
||||
*/
|
||||
public HeadContext(SiteView site, PageMeta page, Locale locale, String canonical, String xDefault,
|
||||
List<Alternate> alternates, boolean preview, boolean noindex, SeoTags seo, IconHints icons) {
|
||||
this(site, page, locale, canonical, xDefault, alternates, preview, noindex, seo, icons, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compatible constructor for callers predating the {@code icons} component: defaults it to
|
||||
* {@link IconHints#NONE}. (Kept per the SPI evolution rule.)
|
||||
*/
|
||||
public HeadContext(SiteView site, PageMeta page, Locale locale, String canonical, String xDefault,
|
||||
List<Alternate> alternates, boolean preview, boolean noindex, SeoTags seo) {
|
||||
this(site, page, locale, canonical, xDefault, alternates, preview, noindex, seo, IconHints.NONE, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compatible constructor for callers predating the {@code seo} and {@code icons} components:
|
||||
* defaults both. (Kept per the SPI evolution rule — an extension compiled against the earlier shape
|
||||
* keeps constructing a valid context.)
|
||||
*/
|
||||
public HeadContext(SiteView site, PageMeta page, Locale locale, String canonical, String xDefault,
|
||||
List<Alternate> alternates, boolean preview, boolean noindex) {
|
||||
this(site, page, locale, canonical, xDefault, alternates, preview, noindex, SeoTags.empty(), IconHints.NONE,
|
||||
"");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The site's icon/manifest facts the host has resolved for the current render, handed to a
|
||||
* {@link mx.quest.runway.spi.HeadContributor} so it can emit the discovery {@code <link>}/{@code <meta>}
|
||||
* tags without reading a store. Derived from which icon slots the site actually provides, so nothing missing
|
||||
* is ever advertised.
|
||||
*
|
||||
* @param iconKeys the stable keys of the icon slots the site provides (the contributor maps each to its
|
||||
* link); never {@code null} (defensively copied)
|
||||
* @param hasManifest whether a Web App Manifest is worth linking (the site declared manifest fields or has a
|
||||
* manifest-eligible icon)
|
||||
* @param themeColor the browser-UI theme color to emit as {@code <meta name="theme-color">}, or {@code null}
|
||||
*/
|
||||
public record IconHints(List<String> iconKeys, boolean hasManifest, String themeColor) {
|
||||
|
||||
/** The "nothing to emit" value — a site with no icons and no manifest. */
|
||||
public static final IconHints NONE = new IconHints(List.of(), false, null);
|
||||
|
||||
public IconHints {
|
||||
iconKeys = (iconKeys == null) ? List.of() : List.copyOf(iconKeys);
|
||||
}
|
||||
|
||||
/** Whether there is nothing for the contributor to emit. */
|
||||
public boolean isEmpty() {
|
||||
return iconKeys.isEmpty() && !hasManifest && (themeColor == null || themeColor.isBlank());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* What {@link mx.quest.runway.spi.service.SitePages#install} did. Immutable.
|
||||
*
|
||||
* @param outcome what happened (never {@code null})
|
||||
* @param path the page's path: the new page's, or the existing page's for {@link Outcome#ALREADY_EXISTS}
|
||||
* (never {@code null})
|
||||
* @param blocking the quality findings that kept the page a draft, for {@link Outcome#DRAFT_BLOCKED}; empty
|
||||
* otherwise (copied, never {@code null})
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public record InstallResult(Outcome outcome, String path, List<Finding> blocking) {
|
||||
|
||||
public InstallResult {
|
||||
Objects.requireNonNull(outcome, "outcome");
|
||||
Objects.requireNonNull(path, "path");
|
||||
blocking = blocking == null ? List.of() : List.copyOf(blocking);
|
||||
}
|
||||
|
||||
/**
|
||||
* The four install outcomes. This enum may gain constants in a MINOR release: a {@code switch} over it needs a
|
||||
* {@code default} branch.
|
||||
*/
|
||||
public enum Outcome {
|
||||
/** The page was created and is live. */
|
||||
PUBLISHED,
|
||||
/** The page was created as a draft and submitted to the site's review queue (a Reviewed site). */
|
||||
PENDING_REVIEW,
|
||||
/** The page was created but stays a draft: the site's quality checks blocked publishing it. */
|
||||
DRAFT_BLOCKED,
|
||||
/** A page with the slug already exists; nothing was changed. */
|
||||
ALREADY_EXISTS
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* One locale's address of a {@link CatalogEntry}, as the host's single URL authority computes it — the same
|
||||
* computation the page {@code <head>} alternates, the sitemap and llms.txt use, so a plugin that lists content
|
||||
* cannot disagree with them. A plugin receives these values; it never applies the URL scheme itself.
|
||||
*
|
||||
* @param locale the locale this address serves (never {@code null})
|
||||
* @param path the <b>root-relative routing URL</b> in that locale ({@code /about}, {@code /es/acerca-de}): the
|
||||
* localized path under the locale prefix (none for the site's default locale). A real address the
|
||||
* site serves; never {@code null} or blank
|
||||
* @param canonical the canonical address for this locale: the content's own canonical override <b>as given</b>
|
||||
* (an absolute URL, or a root-relative {@code /…} value), else {@code path}. Never {@code null}.
|
||||
* An entry whose canonical differs from its {@code path} "points elsewhere" (a syndicated or
|
||||
* consolidated original) — a sitemap lists the real {@code path}, the {@code <head>} names this
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public record LocalizedUrl(Locale locale, String path, String canonical) {
|
||||
|
||||
public LocalizedUrl {
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
Objects.requireNonNull(path, "path");
|
||||
if (path.isBlank()) {
|
||||
throw new IllegalArgumentException("path must not be blank");
|
||||
}
|
||||
canonical = (canonical == null || canonical.isBlank()) ? path : canonical;
|
||||
}
|
||||
|
||||
/**
|
||||
* The absolute routing URL: {@code origin + path}.
|
||||
*
|
||||
* @param origin {@code scheme://host[:port]} with no trailing slash (a trailing {@code /} is tolerated and
|
||||
* dropped), or {@code ""} for a root-relative result; never {@code null}
|
||||
* @return the absolute URL (never {@code null})
|
||||
*/
|
||||
public String absolute(String origin) {
|
||||
return trimOrigin(origin) + path;
|
||||
}
|
||||
|
||||
/**
|
||||
* This address as an {@code hreflang} {@link Alternate}: {@code (locale, origin + path)} — the real URL, never
|
||||
* the canonical override (an alternate must be an address that serves).
|
||||
*
|
||||
* @param origin as for {@link #absolute(String)}
|
||||
* @return the alternate (never {@code null})
|
||||
*/
|
||||
public Alternate alternate(String origin) {
|
||||
return new Alternate(locale, absolute(origin));
|
||||
}
|
||||
|
||||
private static String trimOrigin(String origin) {
|
||||
Objects.requireNonNull(origin, "origin");
|
||||
return origin.endsWith("/") ? origin.substring(0, origin.length() - 1) : origin;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Immutable metadata about a page, independent of the locale a given request renders it in
|
||||
* (the request locale is passed separately to each SPI). Carries the author-level facts an SPI
|
||||
* needs to reason about a page without touching the page store.
|
||||
*
|
||||
* <p>These are the kernel-owned page facts. Domain-feature SEO content (social-card images,
|
||||
* structured data, verification tags) is owned by the SEO/GEO plugin, not carried here; the
|
||||
* plugin composes it from these facts plus its own per-page configuration.
|
||||
*
|
||||
* @param slug the page's stable slug / identifier within its site (never {@code null})
|
||||
* @param title the page title ({@code null} normalized to empty)
|
||||
* @param description the page meta description ({@code null} normalized to empty)
|
||||
* @param availableLocales the locales this page is published in (never {@code null};
|
||||
* defensively copied, unmodifiable; may be empty). Canonical/hreflang
|
||||
* and locale listings derive from this set, not the site's.
|
||||
* @param primaryLocale the page's primary locale — the site default if it is in
|
||||
* {@code availableLocales}, else the first declared — used for
|
||||
* {@code hreflang x-default}; {@code null} when the site default applies
|
||||
* @param published whether the page is published (versus draft-only)
|
||||
* @param noindex the author's "do not index" setting for this page (the <em>effective</em>
|
||||
* indexability for a given render, which also accounts for preview, is
|
||||
* carried by {@link HeadContext#noindex()})
|
||||
* @param nosnippet whether engines are asked not to quote this page's text ({@code nosnippet}).
|
||||
* Independent of {@link #noindex}: the page stays indexed and keeps its ranking,
|
||||
* it simply is not excerpted — which is also the documented control over whether
|
||||
* generative features may use its text
|
||||
* @param provenance who wrote this and when — never {@code null} ({@link Provenance#NONE} when nothing
|
||||
* is known). The carrier that lets a {@code HeadContributor} emit a byline or a
|
||||
* publication date; before it existed, no contributor could emit either at all
|
||||
* @param sourceKey the {@link mx.quest.runway.spi.ContentSource#key()} serving this content, or
|
||||
* {@code null} for a kernel page. When set, {@link #slug()} is the composite
|
||||
* {@code <sourceKey>:<id>} identity — an identity, never a file/template name; an SPI
|
||||
* that needs the current page's real URL must use its view's request path, not build
|
||||
* one from the slug
|
||||
*/
|
||||
public record PageMeta(String slug, String title, String description, List<Locale> availableLocales,
|
||||
Locale primaryLocale, boolean published, boolean noindex, String sourceKey,
|
||||
Provenance provenance, boolean nosnippet) {
|
||||
|
||||
public PageMeta {
|
||||
Objects.requireNonNull(slug, "slug");
|
||||
title = (title == null) ? "" : title;
|
||||
description = (description == null) ? "" : description;
|
||||
availableLocales = (availableLocales == null) ? List.of() : List.copyOf(availableLocales);
|
||||
provenance = (provenance == null) ? Provenance.NONE : provenance;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pre-{@code provenance} constructor, kept for binary compatibility (SPI evolution rule): content with
|
||||
* no known author or dates, i.e. {@link Provenance#NONE}.
|
||||
*/
|
||||
public PageMeta(String slug, String title, String description, List<Locale> availableLocales,
|
||||
Locale primaryLocale, boolean published, boolean noindex, String sourceKey) {
|
||||
this(slug, title, description, availableLocales, primaryLocale, published, noindex, sourceKey,
|
||||
Provenance.NONE, false);
|
||||
}
|
||||
|
||||
/** The pre-{@code nosnippet} 9-arg form, kept for binary compatibility (SPI evolution rule). */
|
||||
public PageMeta(String slug, String title, String description, List<Locale> availableLocales,
|
||||
Locale primaryLocale, boolean published, boolean noindex, String sourceKey,
|
||||
Provenance provenance) {
|
||||
this(slug, title, description, availableLocales, primaryLocale, published, noindex, sourceKey,
|
||||
provenance, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* The pre-{@code sourceKey} constructor, kept for binary compatibility so an extension or host compiled
|
||||
* against an earlier SPI keeps loading on this one — a kernel page ({@code sourceKey} {@code null}).
|
||||
*/
|
||||
public PageMeta(String slug, String title, String description, List<Locale> availableLocales,
|
||||
Locale primaryLocale, boolean published, boolean noindex) {
|
||||
this(slug, title, description, availableLocales, primaryLocale, published, noindex, null,
|
||||
Provenance.NONE, false);
|
||||
}
|
||||
|
||||
/** Whether this view describes a content source's page rather than a kernel page. */
|
||||
public boolean isVirtual() {
|
||||
return sourceKey != null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The immutable input to a {@link mx.quest.runway.spi.PageQualityCheck} — a fully resolved,
|
||||
* read-only page for advisory inspection, including its rendered HTML for the given locale.
|
||||
* A check inspects this view and returns findings; it never edits anything.
|
||||
*
|
||||
* <p>Page facts such as title, description, and available locales are reachable through
|
||||
* {@link #page()}, and the site's full locale set through {@link #site()}, so a check can audit
|
||||
* (for example) that {@code hreflang} only points to locales the page and site actually offer.
|
||||
*
|
||||
* @param site the site being inspected (never {@code null})
|
||||
* @param page the page metadata (never {@code null})
|
||||
* @param locale the locale the {@code resolvedHtml} was rendered in (never {@code null})
|
||||
* @param canonical the resolved canonical URL for this page+locale, for duplicate/correctness
|
||||
* checks, or {@code null} when not applicable
|
||||
* @param resolvedHtml the page's rendered HTML for that locale ({@code null} normalized to
|
||||
* empty), so checks can examine the actual delivered markup
|
||||
*/
|
||||
public record PageView(SiteView site, PageMeta page, Locale locale, String canonical, String resolvedHtml) {
|
||||
|
||||
public PageView {
|
||||
Objects.requireNonNull(site, "site");
|
||||
Objects.requireNonNull(page, "page");
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
resolvedHtml = (resolvedHtml == null) ? "" : resolvedHtml;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Who the calling plugin is, as the host loaded it. Injectable into plugin code (it is bound to the plugin
|
||||
* whose jar the injecting class came from — see {@link mx.quest.runway.spi.service.PluginSettings}) and handed
|
||||
* to {@link mx.quest.runway.spi.service.PluginLifecycle#started(PluginInfo)}.
|
||||
*
|
||||
* @param id the plugin id from {@code plugin.yml} (= its install folder name)
|
||||
* @param version the plugin version from {@code plugin.yml} (plain {@code MAJOR.MINOR.PATCH})
|
||||
* @param installDir the plugin's install folder ({@code external/plugins/<id>/}) — read-only by convention: it is
|
||||
* replaced wholesale on upgrade, so a plugin keeps nothing it writes there
|
||||
* @since SPI 0.4.0
|
||||
*/
|
||||
public record PluginInfo(String id, String version, Path installDir) {
|
||||
|
||||
public PluginInfo {
|
||||
Objects.requireNonNull(id, "id");
|
||||
Objects.requireNonNull(version, "version");
|
||||
Objects.requireNonNull(installDir, "installDir");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Who wrote a piece of content and when — the <b>provenance</b> a page carries across the SPI boundary.
|
||||
*
|
||||
* <p><b>Why this exists as its own type.</b> Before it, {@link PageMeta} carried identity, titles and
|
||||
* indexability but nothing about authorship or time, and {@link HeadContext} carried none either. The
|
||||
* consequence was structural rather than cosmetic: <b>no {@code HeadContributor} could emit a publication date
|
||||
* or an author at all</b>, because the boundary did not carry the values. Two things fell out of that, and both
|
||||
* were found by auditing the platform against its own SEO guidance:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Trust markers were unimplementable.</b> Named authors, visible publication dates and visible update
|
||||
* dates are the concrete, machine-legible form of "a real, accountable entity stands behind this". A
|
||||
* platform that cannot express them cannot help a tenant be a credible source.</li>
|
||||
* <li><b>Structured data was pushed toward a policy violation.</b> A blog whose entries each knew their own
|
||||
* publication date could not pass it to the schema layer, so {@code datePublished} and {@code author} had
|
||||
* to come from hand-written per-site config matched by URL pattern. One pattern covers every entry, so the
|
||||
* honest outcomes were "no dates at all" or "one date asserted identically on every post" — the second
|
||||
* being an assertion that is false of nearly every page it appears on, reached by <i>trying</i> to
|
||||
* comply.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>Grouped rather than three loose components</b> so the concept has a name, so a contributor can pass it
|
||||
* around as one value, and so it can gain fields later (an author URL or affiliation) without changing the arity
|
||||
* of every record that carries it.
|
||||
*
|
||||
* <p><b>Every field is optional.</b> Most content legitimately has no byline — a landing page, a contact page, a
|
||||
* pricing table. {@link #NONE} is the "nothing known" value and is what a page without provenance carries;
|
||||
* consumers must treat absence as normal and simply emit nothing, never a placeholder or a fabricated date. A
|
||||
* wrong date is worse than no date: it is an assertion, and search engines and readers both treat it as one.
|
||||
*
|
||||
* <p><b>The division of ownership between the three fields is deliberate.</b> {@link #author()} and
|
||||
* {@link #publishedAt()} are <i>editorial facts</i> — a human asserts them and they do not change when a typo is
|
||||
* fixed. {@link #updatedAt()} is a <i>system fact</i> the platform derives. Letting an author hand-maintain a
|
||||
* "last updated" stamp guarantees it drifts out of truth, and an untruthful timestamp is worse than an absent
|
||||
* one because consumers are told to trust it.
|
||||
*
|
||||
* @param author display name of the human or organisation credited, or {@code null}/blank when unattributed.
|
||||
* A free-text display name on purpose: a real identity model (accounts, profiles, affiliations)
|
||||
* is a larger design, and blocking bylines on it would leave content unattributable meanwhile.
|
||||
* @param publishedAt when the content was first published, or {@code null} if unknown. An editorial fact: set by
|
||||
* the author, not the file system, so it survives a backup/restore and a re-deploy — the
|
||||
* reason it is not derived from a file timestamp.
|
||||
* @param updatedAt when the content last changed, or {@code null} if unknown. Derived by the host (typically a
|
||||
* file mtime) rather than authored.
|
||||
*/
|
||||
public record Provenance(String author, Instant publishedAt, Instant updatedAt) {
|
||||
|
||||
/** Nothing known — the value for content with no byline and no dates. Never {@code null}. */
|
||||
public static final Provenance NONE = new Provenance(null, null, null);
|
||||
|
||||
public Provenance {
|
||||
// Blank is the same as absent: a form posts "" for an untouched field, and an empty byline must not
|
||||
// render as an empty author element or serialize as a present-but-meaningless value.
|
||||
author = (author == null || author.isBlank()) ? null : author.trim();
|
||||
}
|
||||
|
||||
/** Whether anything at all is known — {@code false} for {@link #NONE}. Lets a consumer skip a whole block. */
|
||||
public boolean isPresent() {
|
||||
return author != null || publishedAt != null || updatedAt != null;
|
||||
}
|
||||
|
||||
/** This provenance with {@code updatedAt} replaced — the host derives that field after the fact. */
|
||||
public Provenance withUpdatedAt(Instant instant) {
|
||||
return new Provenance(author, publishedAt, instant);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
/**
|
||||
* One of Runway's two isolated identity domains. The realms never cross: authenticating in
|
||||
* one never grants access to the other, and a contribution (a permission, a menu entry, an
|
||||
* endpoint route) always declares which realm it belongs to.
|
||||
*/
|
||||
public enum Realm {
|
||||
|
||||
/**
|
||||
* The platform-operator realm — the people who run the Runway server itself (configure
|
||||
* the platform, manage plugins, create and suspend sites, manage application users).
|
||||
*/
|
||||
APPLICATION,
|
||||
|
||||
/**
|
||||
* The per-site (tenant) realm — the people who manage an individual site (its pages,
|
||||
* users, content, and plugin configuration). A tenant-realm actor can never reach another
|
||||
* site's data or the platform's configuration.
|
||||
*/
|
||||
TENANT
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
/**
|
||||
* The HTML a {@link mx.quest.runway.spi.ContentWidget} produces to fill its anchor on a page.
|
||||
* An {@linkplain #empty() empty} fragment is the <b>soft-degrade</b> result — when a widget
|
||||
* has nothing to render (missing instance, disabled feature) the page still renders, just
|
||||
* without the widget's content.
|
||||
*
|
||||
* @param html the markup to splice in at the widget's anchor ({@code null} normalized to empty)
|
||||
*/
|
||||
public record RenderFragment(String html) {
|
||||
|
||||
private static final RenderFragment EMPTY = new RenderFragment("");
|
||||
|
||||
public RenderFragment {
|
||||
html = (html == null) ? "" : html;
|
||||
}
|
||||
|
||||
/** The empty fragment — the soft-degrade result (renders nothing). */
|
||||
public static RenderFragment empty() {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
/** A fragment of the given markup; {@code null} or empty yields {@link #empty()}. */
|
||||
public static RenderFragment of(String html) {
|
||||
return (html == null || html.isEmpty()) ? EMPTY : new RenderFragment(html);
|
||||
}
|
||||
|
||||
/** Whether this fragment has no markup (the soft-degrade case). */
|
||||
public boolean isEmpty() {
|
||||
return html.isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* One route an {@link mx.quest.runway.spi.EndpointContributor} declares it will serve. The
|
||||
* host registers routes at load time, checking for collisions and refusing any that shadow a
|
||||
* reserved kernel prefix; each route carries the {@link SurfacePosture} the host applies to
|
||||
* its responses.
|
||||
*
|
||||
* <p><b>What the host serves</b> (enforced at registration since SPI 0.4.0; a plugin route that breaks a rule is
|
||||
* refused on its own, with a logged reason, while the plugin's other routes load):
|
||||
* <ul>
|
||||
* <li>{@code pathPattern} is an <b>exact</b>, absolute path, matched literally. The characters {@code *},
|
||||
* <code>{</code> and <code>}</code> are <b>reserved</b> for a future pattern syntax and refused now, so that a
|
||||
* route written today can never change meaning later.</li>
|
||||
* <li>{@code realm} must be {@link Realm#TENANT}: endpoints are dispatched on a site's public host only.</li>
|
||||
* <li>An {@code anonymous} route must use {@code POST} (since SPI 0.5.0).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Anonymous form routes (since SPI 0.5.0)</h2>
|
||||
* Every {@code POST} on a site's host needs a CSRF token from the visitor's session — the defence against another
|
||||
* web site making a visitor's browser submit a form on their behalf. A public form placed on a cacheable page
|
||||
* (a contact form) cannot carry one: the page is shared by every visitor, and an anonymous visitor has no session.
|
||||
* A route declared {@code anonymous} opts out of the CSRF check, and the host makes that safe by taking away
|
||||
* everything such a forged submission could use:
|
||||
* <ul>
|
||||
* <li>it is dispatched <b>with no principal</b>, even when the visitor is signed in: an
|
||||
* {@link mx.quest.runway.spi.service.AccessCheck} answers {@code false}, so the route cannot perform anything
|
||||
* a signed-in user could and an anonymous visitor could not;</li>
|
||||
* <li>it accepts only {@code POST} with an {@code application/x-www-form-urlencoded} body (any other content type
|
||||
* is answered {@code 415}); the fields arrive in {@link RouteRequest#form()};</li>
|
||||
* <li>the exemption covers exactly that method and path on a site's host, and nothing else.</li>
|
||||
* </ul>
|
||||
* Use it only for a form any visitor may submit with no account (contact, newsletter sign-up), and keep the
|
||||
* form's own abuse guards (a CAPTCHA, a honeypot field, a rate limit by {@link RouteRequest#clientIp()}). Never use
|
||||
* it for an action that changes anything a signed-in user owns.
|
||||
*
|
||||
* @param method the HTTP method (for example {@code "GET"}; never {@code null})
|
||||
* @param pathPattern the exact path this route matches (never {@code null}; see above)
|
||||
* @param realm which realm the route belongs to (never {@code null}; must be {@code TENANT})
|
||||
* @param posture how the route's responses are treated for indexing/sitemap/cache
|
||||
* ({@code null} normalized to {@link SurfacePosture#safeDefault()})
|
||||
* @param anonymous whether this is an anonymous form route: CSRF-exempt, dispatched with no principal, form
|
||||
* body only (see above; since SPI 0.5.0)
|
||||
*/
|
||||
public record Route(String method, String pathPattern, Realm realm, SurfacePosture posture, boolean anonymous) {
|
||||
|
||||
public Route {
|
||||
Objects.requireNonNull(method, "method");
|
||||
Objects.requireNonNull(pathPattern, "pathPattern");
|
||||
Objects.requireNonNull(realm, "realm");
|
||||
posture = (posture == null) ? SurfacePosture.safeDefault() : posture;
|
||||
}
|
||||
|
||||
/** The pre-0.5.0 form: an ordinary (not anonymous) route. */
|
||||
public Route(String method, String pathPattern, Realm realm, SurfacePosture posture) {
|
||||
this(method, pathPattern, realm, posture, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* An anonymous form route ({@code POST}, tenant realm): CSRF-exempt, dispatched with no principal, accepting
|
||||
* only an {@code application/x-www-form-urlencoded} body.
|
||||
*
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public static Route anonymousPost(String pathPattern, SurfacePosture posture) {
|
||||
return new Route("POST", pathPattern, Realm.TENANT, posture, true);
|
||||
}
|
||||
|
||||
/** A {@code GET} route in the given realm with the fail-safe {@link SurfacePosture}. */
|
||||
public static Route get(String pathPattern, Realm realm) {
|
||||
return new Route("GET", pathPattern, realm, SurfacePosture.safeDefault());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* The immutable input to {@link mx.quest.runway.spi.EndpointContributor#handle}. It is a
|
||||
* frozen, host-built view of the request — never the raw servlet objects — so a handler is a
|
||||
* pure function of these inputs and stays free of any servlet/Spring type.
|
||||
*
|
||||
* <p>The {@code site} is the full {@link SiteView} (not just a {@link SiteRef}), so endpoint
|
||||
* handlers that build absolute links or enumerate locales (robots, sitemap, feeds) have the
|
||||
* site's base URL and locale set directly.
|
||||
*
|
||||
* <h2>What the host puts in it (since SPI 0.5.0)</h2>
|
||||
* <ul>
|
||||
* <li>{@code locale} is negotiated the way a page's is: an explicit {@code ?lang=} in the query, then the
|
||||
* visitor's language cookie for the site, then {@code Accept-Language}, then the site default. It is always
|
||||
* one of the site's locales.</li>
|
||||
* <li>{@code query} holds the URL query string only; the fields of a form body are in {@code form}. Use
|
||||
* {@link #param(String)} to read a field from either.</li>
|
||||
* <li>{@code headers} are keyed by <b>lowercase</b> name ({@code "user-agent"}); lookups ignore case, so
|
||||
* {@code headers().get("User-Agent")} still finds it. Forwarded headers ({@code X-Forwarded-*},
|
||||
* {@code Forwarded}) are never present: the host has already applied them for a trusted proxy and hidden them
|
||||
* from anyone else.</li>
|
||||
* <li>{@code clientIp} is the client address after the host's trusted-proxy gate: the forwarded address when the
|
||||
* connection came from a configured trusted proxy, the connection's own address otherwise. Use it for rate
|
||||
* limits and abuse decisions, never a header.</li>
|
||||
* <li>{@code origin} is the request's {@code scheme://host[:port]} as the trusted-proxy gate leaves it (a trusted
|
||||
* proxy's forwarded scheme and host applied; raw values otherwise), with the default port omitted. Use it to
|
||||
* build absolute URLs when the site has no configured base URL.</li>
|
||||
* </ul>
|
||||
* A record built with the pre-0.5.0 seven-argument constructor (in a plugin's own tests) has an empty
|
||||
* {@code form}, no {@code clientIp} and an empty {@code origin}.
|
||||
*
|
||||
* <p>All collection and array components are defensively copied; {@link #body()} returns a
|
||||
* fresh copy on each call. (Because the body is an array, the record-generated
|
||||
* {@code equals}/{@code hashCode} compare it by <em>reference</em>, not content, so they are
|
||||
* unreliable for an instance carrying a body — do not rely on record equality for such
|
||||
* instances.)
|
||||
*
|
||||
* @param site the site the request resolved to (never {@code null})
|
||||
* @param locale the negotiated request locale, one of the site's (never {@code null})
|
||||
* @param method the HTTP method (never {@code null})
|
||||
* @param path the request path (never {@code null})
|
||||
* @param query the URL query parameters, multi-valued (never {@code null}; deeply copied, unmodifiable; may be
|
||||
* empty)
|
||||
* @param headers request headers by lowercase name, case-insensitive lookup (never {@code null}; copied,
|
||||
* unmodifiable; may be empty)
|
||||
* @param body the raw request body (never {@code null}; defensively copied; empty when none)
|
||||
* @param form the fields of an {@code application/x-www-form-urlencoded} body, multi-valued (never
|
||||
* {@code null}; deeply copied, unmodifiable; empty for any other body); since SPI 0.5.0
|
||||
* @param clientIp the gated client IP, or {@code null} when unknown; since SPI 0.5.0
|
||||
* @param origin {@code scheme://host[:port]} of the request (never {@code null}; empty when unknown); since SPI
|
||||
* 0.5.0
|
||||
*/
|
||||
public record RouteRequest(SiteView site, Locale locale, String method, String path,
|
||||
Map<String, List<String>> query, Map<String, String> headers, byte[] body,
|
||||
Map<String, List<String>> form, String clientIp, String origin) {
|
||||
|
||||
public RouteRequest {
|
||||
Objects.requireNonNull(site, "site");
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
Objects.requireNonNull(method, "method");
|
||||
Objects.requireNonNull(path, "path");
|
||||
query = copyParams(query, "query key");
|
||||
headers = copyHeaders(headers);
|
||||
body = (body == null) ? new byte[0] : body.clone();
|
||||
form = copyParams(form, "form key");
|
||||
clientIp = (clientIp == null || clientIp.isBlank()) ? null : clientIp;
|
||||
origin = (origin == null) ? "" : origin;
|
||||
}
|
||||
|
||||
/** The pre-0.5.0 form: no form fields, no client IP, no origin. */
|
||||
public RouteRequest(SiteView site, Locale locale, String method, String path,
|
||||
Map<String, List<String>> query, Map<String, String> headers, byte[] body) {
|
||||
this(site, locale, method, path, query, headers, body, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The first value of field {@code name}: from the query string, else from the form body.
|
||||
*
|
||||
* @return the value (possibly empty text); empty when neither carries the field
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public Optional<String> param(String name) {
|
||||
Objects.requireNonNull(name, "name");
|
||||
List<String> values = query.get(name);
|
||||
if (values == null || values.isEmpty()) {
|
||||
values = form.get(name);
|
||||
}
|
||||
return (values == null || values.isEmpty()) ? Optional.empty() : Optional.ofNullable(values.get(0));
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> copyParams(Map<String, List<String>> params, String what) {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, List<String>> copy = new LinkedHashMap<>();
|
||||
params.forEach((key, values) -> copy.put(
|
||||
Objects.requireNonNull(key, what),
|
||||
(values == null) ? List.of() : values.stream().filter(Objects::nonNull).toList()));
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lowercase keys (the first of two names differing only in case wins), case-insensitive lookup, {@code null}
|
||||
* names and values dropped.
|
||||
*/
|
||||
private static Map<String, String> copyHeaders(Map<String, String> headers) {
|
||||
if (headers == null || headers.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
TreeMap<String, String> copy = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
headers.forEach((name, value) -> {
|
||||
if (name != null && value != null) {
|
||||
copy.putIfAbsent(name.toLowerCase(Locale.ROOT), value);
|
||||
}
|
||||
});
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
/** A defensive copy of the raw request body (callers cannot mutate the stored bytes). */
|
||||
@Override
|
||||
public byte[] body() {
|
||||
return body.clone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The immutable result an {@link mx.quest.runway.spi.EndpointContributor} returns from
|
||||
* {@code handle} — a plain {@code (status, headers, body)} tuple the host sends back to the
|
||||
* client. Carrying no servlet types keeps handlers pure and testable.
|
||||
*
|
||||
* <p>The body is defensively copied; {@link #body()} returns a fresh copy on each call.
|
||||
* (As with {@link RouteRequest}, the record-generated {@code equals}/{@code hashCode} compare the
|
||||
* body array by <em>reference</em>, not content, so they are unreliable for an instance carrying a
|
||||
* body — do not rely on record equality for such instances.)
|
||||
*
|
||||
* @param status the HTTP status code
|
||||
* @param headers the response headers (never {@code null}; defensively copied, unmodifiable;
|
||||
* may be empty)
|
||||
* @param body the response body (never {@code null}; defensively copied; empty when none)
|
||||
*/
|
||||
public record RouteResponse(int status, Map<String, String> headers, byte[] body) {
|
||||
|
||||
public RouteResponse {
|
||||
headers = (headers == null) ? Map.of() : Map.copyOf(headers);
|
||||
body = (body == null) ? new byte[0] : body.clone();
|
||||
}
|
||||
|
||||
/** A defensive copy of the response body. */
|
||||
@Override
|
||||
public byte[] body() {
|
||||
return body.clone();
|
||||
}
|
||||
|
||||
/** A {@code 200 OK} with the given body and no extra headers. */
|
||||
public static RouteResponse ok(byte[] body) {
|
||||
return new RouteResponse(200, Map.of(), body);
|
||||
}
|
||||
|
||||
/** A {@code 404 Not Found} with an empty body. */
|
||||
public static RouteResponse notFound() {
|
||||
return new RouteResponse(404, Map.of(), new byte[0]);
|
||||
}
|
||||
|
||||
/** A UTF-8 {@code text/plain} response with the given status and text. */
|
||||
public static RouteResponse text(int status, String body) {
|
||||
byte[] bytes = (body == null) ? new byte[0] : body.getBytes(StandardCharsets.UTF_8);
|
||||
return new RouteResponse(status, Map.of("Content-Type", "text/plain; charset=utf-8"), bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
/**
|
||||
* A site's core social-card and verification metadata, resolved by the host and handed to a
|
||||
* {@link mx.quest.runway.spi.HeadContributor} through the {@link HeadContext}. These are the lean
|
||||
* <em>kernel</em> SEO fields; richer concerns (analytics tags, consent, Content-Security-Policy) are
|
||||
* deliberately left to SEO/GEO/analytics plugins rather than baked into the core context.
|
||||
*
|
||||
* <p>Every field is optional: a blank or {@code null} value is normalized to {@code null} and means
|
||||
* "not set" (the host emits no tag for it). {@link #extraHead()} is a verbatim, operator-trusted
|
||||
* escape hatch — the host injects it as-is into the site's own {@code <head>} — whereas the structured
|
||||
* fields are attribute values a contributor must HTML-escape.
|
||||
*
|
||||
* @param ogImage {@code og:image} URL, or {@code null}
|
||||
* @param ogType {@code og:type} (e.g. {@code website}, {@code article}), or {@code null}
|
||||
* @param twitterCard {@code twitter:card} (e.g. {@code summary_large_image}), or {@code null}
|
||||
* @param twitterSite {@code twitter:site} handle (e.g. {@code @quest}), or {@code null}
|
||||
* @param googleVerification {@code google-site-verification} token, or {@code null}
|
||||
* @param bingVerification Bing {@code msvalidate.01} token, or {@code null}
|
||||
* @param extraHead verbatim markup appended inside {@code <head>} (operator-trusted), or {@code null}
|
||||
*/
|
||||
public record SeoTags(String ogImage, String ogType, String twitterCard, String twitterSite,
|
||||
String googleVerification, String bingVerification, String extraHead) {
|
||||
|
||||
private static final SeoTags EMPTY = new SeoTags(null, null, null, null, null, null, null);
|
||||
|
||||
public SeoTags {
|
||||
ogImage = blankToNull(ogImage);
|
||||
ogType = blankToNull(ogType);
|
||||
twitterCard = blankToNull(twitterCard);
|
||||
twitterSite = blankToNull(twitterSite);
|
||||
googleVerification = blankToNull(googleVerification);
|
||||
bingVerification = blankToNull(bingVerification);
|
||||
extraHead = blankToNull(extraHead);
|
||||
}
|
||||
|
||||
/** The shared "nothing set" instance — the host uses this when a site has no SEO configuration. */
|
||||
public static SeoTags empty() {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
/** Whether any field is set (so a contributor can skip emitting anything when nothing is configured). */
|
||||
public boolean hasAny() {
|
||||
return ogImage != null || ogType != null || twitterCard != null || twitterSite != null
|
||||
|| googleVerification != null || bingVerification != null || extraHead != null;
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The listening plugin's own per-site settings were saved — what
|
||||
* {@link mx.quest.runway.spi.service.SiteEventListener#onSettingsChanged} receives. By the time it is delivered the
|
||||
* host's settings cache has been evicted, so {@link mx.quest.runway.spi.service.PluginSettings#site} returns the new
|
||||
* values. Immutable.
|
||||
*
|
||||
* @param siteId the site whose settings changed (never {@code null})
|
||||
* @param pluginId the plugin whose settings changed — always the receiving listener's own plugin (never
|
||||
* {@code null})
|
||||
* @param local {@code true} on the node where the save happened; {@code false} for a peer's replayed save
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public record SettingsChange(String siteId, String pluginId, boolean local) {
|
||||
|
||||
public SettingsChange {
|
||||
Objects.requireNonNull(siteId, "siteId");
|
||||
Objects.requireNonNull(pluginId, "pluginId");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A plugin's effective per-site settings, as {@link mx.quest.runway.spi.service.PluginSettings#site(String)}
|
||||
* builds them: the descriptor's {@code siteSettings:} defaults overlaid by the values stored for the site, plus any
|
||||
* preserved keys the schema does not declare. Secret-typed keys are never present (read them with
|
||||
* {@link mx.quest.runway.spi.service.PluginSettings#secret(String, String)}).
|
||||
*
|
||||
* <p><b>Immutable and deep-frozen.</b> The compact constructor copies {@code values}, drops {@code null} keys and
|
||||
* values, and freezes nested {@link List}s and {@link Map}s recursively (their {@code null} elements dropped too),
|
||||
* so a view can be cached and shared between threads, and nothing a caller does to it — or to the map it was built
|
||||
* from — is visible to anyone else.
|
||||
*
|
||||
* <p><b>Precedence</b> for a value: the stored value, else the descriptor's {@code default}, else the
|
||||
* {@code fallback} argument of the accessor. The host applies the first two when it builds the view, so the
|
||||
* code fallback only matters for keys the schema does not declare (or declares without a default). Every
|
||||
* accessor is <b>lenient</b>: a value that does not parse as the requested type yields the fallback, never an
|
||||
* exception — a hand-edited settings file must not break a public page.
|
||||
*
|
||||
* <p>Nested structures (a list of maps, for example) are not interpreted here; read them from {@link #values()}
|
||||
* and parse them in the plugin.
|
||||
*
|
||||
* @param values the effective key → value map (never {@code null} after construction; {@code null} = empty)
|
||||
* @since SPI 0.4.0
|
||||
*/
|
||||
public record SettingsView(Map<String, Object> values) {
|
||||
|
||||
public SettingsView {
|
||||
values = freezeMap(values);
|
||||
}
|
||||
|
||||
/** An empty view: every accessor answers its fallback. */
|
||||
public static SettingsView empty() {
|
||||
return new SettingsView(Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as a string, or {@code fallback} when the key is absent or its value is blank. A list value is
|
||||
* joined with {@code ", "}.
|
||||
*/
|
||||
public String string(String key, String fallback) {
|
||||
Object value = values.get(key);
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
String text = value instanceof List<?> list
|
||||
? String.join(", ", list.stream().map(String::valueOf).toList())
|
||||
: String.valueOf(value);
|
||||
return text.isBlank() ? fallback : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as a boolean: a {@link Boolean} as is; the strings {@code true}/{@code on}/{@code yes}/{@code 1}
|
||||
* as {@code true} and {@code false}/{@code off}/{@code no}/{@code 0} as {@code false} (case-insensitive,
|
||||
* trimmed); a number as {@code != 0}. Anything else — absent, blank, unrecognised — yields {@code fallback}.
|
||||
*/
|
||||
public boolean bool(String key, boolean fallback) {
|
||||
Object value = values.get(key);
|
||||
if (value instanceof Boolean b) {
|
||||
return b;
|
||||
}
|
||||
if (value instanceof Number n) {
|
||||
return n.doubleValue() != 0;
|
||||
}
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
String text = String.valueOf(value).trim().toLowerCase(Locale.ROOT);
|
||||
return switch (text) {
|
||||
case "true", "on", "yes", "1" -> true;
|
||||
case "false", "off", "no", "0" -> false;
|
||||
default -> fallback;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as a whole number: an integral {@link Number}, or a string that parses as a {@code long}
|
||||
* (trimmed). A fractional number, an unparsable string, or an absent key yields {@code fallback}.
|
||||
*/
|
||||
public long integer(String key, long fallback) {
|
||||
Object value = values.get(key);
|
||||
if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
|
||||
return ((Number) value).longValue();
|
||||
}
|
||||
if (value instanceof Number n) {
|
||||
try {
|
||||
return new BigDecimal(n.toString()).longValueExact();
|
||||
} catch (ArithmeticException | NumberFormatException notIntegral) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(String.valueOf(value).trim());
|
||||
} catch (NumberFormatException bad) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #integer(String, long)}, then clamped into {@code [min, max]} — the fallback included, so the
|
||||
* result is always in range.
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code min > max}
|
||||
*/
|
||||
public long integer(String key, long fallback, long min, long max) {
|
||||
if (min > max) {
|
||||
throw new IllegalArgumentException("min " + min + " > max " + max);
|
||||
}
|
||||
return Math.max(min, Math.min(max, integer(key, fallback)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as a decimal: a {@link Number} (converted through its string form, so {@code 1.1} stays
|
||||
* {@code 1.1}) or a string that parses as a {@link BigDecimal}; otherwise {@code fallback} (which may be
|
||||
* {@code null}).
|
||||
*/
|
||||
public BigDecimal decimal(String key, BigDecimal fallback) {
|
||||
Object value = values.get(key);
|
||||
if (value instanceof BigDecimal d) {
|
||||
return d;
|
||||
}
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return new BigDecimal(String.valueOf(value).trim());
|
||||
} catch (NumberFormatException bad) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as a list of non-blank, trimmed strings: a YAML list element by element, or a string split on
|
||||
* commas and newlines. An absent key yields an empty list. Never {@code null}; the list is unmodifiable.
|
||||
*/
|
||||
public List<String> list(String key) {
|
||||
Object value = values.get(key);
|
||||
List<String> out = new ArrayList<>();
|
||||
if (value instanceof List<?> items) {
|
||||
for (Object item : items) {
|
||||
String text = String.valueOf(item).trim();
|
||||
if (!text.isEmpty()) {
|
||||
out.add(text);
|
||||
}
|
||||
}
|
||||
} else if (value != null) {
|
||||
for (String token : String.valueOf(value).split("[,\\n]")) {
|
||||
String text = token.trim();
|
||||
if (!text.isEmpty()) {
|
||||
out.add(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
private static Map<String, Object> freezeMap(Map<?, ?> source) {
|
||||
if (source == null || source.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
source.forEach((key, value) -> {
|
||||
if (key != null && value != null) {
|
||||
out.put(String.valueOf(key), freeze(value));
|
||||
}
|
||||
});
|
||||
return Collections.unmodifiableMap(out);
|
||||
}
|
||||
|
||||
private static Object freeze(Object value) {
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
return freezeMap(map);
|
||||
}
|
||||
if (value instanceof List<?> list) {
|
||||
List<Object> out = new ArrayList<>(list.size());
|
||||
for (Object item : list) {
|
||||
if (item != null) {
|
||||
out.add(freeze(item));
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableList(out);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
/**
|
||||
* The advisory level of a {@link Finding} reported by a
|
||||
* {@link mx.quest.runway.spi.PageQualityCheck}. Findings are advisory by default — the
|
||||
* severity ranks importance for display and optional opt-in publish gating; it never forces
|
||||
* an edit or blocks publishing on its own.
|
||||
*/
|
||||
public enum Severity {
|
||||
|
||||
/** Informational — a suggestion or neutral observation. */
|
||||
INFO,
|
||||
|
||||
/** A likely problem worth attention, but not necessarily blocking. */
|
||||
WARNING,
|
||||
|
||||
/** A serious problem; the most likely candidate to gate on when a site opts into enforcement. */
|
||||
ERROR
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A site's lifecycle changed — what {@link mx.quest.runway.spi.service.SiteEventListener#onSiteLifecycle} receives.
|
||||
* Immutable.
|
||||
*
|
||||
* @param siteId the site (never {@code null})
|
||||
* @param kind what happened (never {@code null}). May gain constants in a MINOR release: a {@code switch} over
|
||||
* it needs a {@code default} branch
|
||||
* @param fromBackup on {@link Kind#CREATED}: the site was imported wholesale from a backup (it is a faithful copy;
|
||||
* a plugin should not seed defaults into it). {@code false} otherwise
|
||||
* @param local {@code true} on the node where the change happened; {@code false} when this node replays a
|
||||
* peer's change in a cluster. A listener with an external side effect acts only on local events
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public record SiteLifecycleEvent(String siteId, Kind kind, boolean fromBackup, boolean local) {
|
||||
|
||||
/** The kind of lifecycle change. */
|
||||
public enum Kind {
|
||||
/** A new site (fresh, or imported from a backup — see {@code fromBackup}). */
|
||||
CREATED,
|
||||
/** The site's record changed (name, locales, hosts, editorial level, maintenance), or it was reloaded. */
|
||||
UPDATED,
|
||||
/** An operator suspended the site. */
|
||||
SUSPENDED,
|
||||
/** An operator resumed the site. */
|
||||
RESUMED,
|
||||
/** The site and its whole folder were deleted. */
|
||||
DELETED,
|
||||
/** The site's whole folder was replaced from a backup. */
|
||||
RESTORED
|
||||
}
|
||||
|
||||
public SiteLifecycleEvent {
|
||||
Objects.requireNonNull(siteId, "siteId");
|
||||
Objects.requireNonNull(kind, "kind");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the site's files were replaced or removed as a whole ({@link Kind#DELETED} or {@link Kind#RESTORED}):
|
||||
* every per-site state a plugin derived from its files is now wrong and must be dropped.
|
||||
*/
|
||||
public boolean wholesale() {
|
||||
return kind == Kind.DELETED || kind == Kind.RESTORED;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A minimal, stable reference to a site (tenant) — just its identity. Used where an SPI needs
|
||||
* to name the site it is acting for without the fuller {@link SiteView} (for example a
|
||||
* {@link mx.quest.runway.spi.BackupParticipant} exporting a site's data, or the site behind a
|
||||
* routed request).
|
||||
*
|
||||
* @param id the site's stable identifier (never {@code null}); the same value the host uses to
|
||||
* scope the site's folder, cache keys, and backups
|
||||
*/
|
||||
public record SiteRef(String id) {
|
||||
|
||||
public SiteRef {
|
||||
Objects.requireNonNull(id, "id");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* An immutable, host-materialized view of the site (tenant) a request is being served for.
|
||||
* Carries the site identity and the stable, presentation-relevant facts an SPI commonly
|
||||
* needs; it is <b>not</b> the mutable domain model and exposes nothing of other tenants.
|
||||
*
|
||||
* <p>It deliberately carries only <em>rendering-level</em> facts the kernel owns. Domain-feature
|
||||
* configuration — SEO social/verification defaults, analytics ids, and the like — is owned by
|
||||
* the relevant plugin (via its own per-site settings), not exposed here.
|
||||
*
|
||||
* <p>The shape is intentionally minimal and grows additively as extension axes need more.
|
||||
*
|
||||
* @param id the site's stable identifier (never {@code null})
|
||||
* @param displayName the site's human-facing name (never {@code null}); used for branding and
|
||||
* {@code og:site_name}-style markup
|
||||
* @param defaultLocale the site's default locale (never {@code null}); drives {@code hreflang}
|
||||
* {@code x-default} and locale resolution
|
||||
* @param locales the locales the site offers (never {@code null}; defensively copied,
|
||||
* unmodifiable; may be empty)
|
||||
* @param baseUrl the site's base URL ({@code scheme://host[:port]}) for building absolute
|
||||
* links in head/endpoint markup, or {@code null} if not resolved
|
||||
*/
|
||||
public record SiteView(String id, String displayName, Locale defaultLocale, List<Locale> locales,
|
||||
String baseUrl) {
|
||||
|
||||
public SiteView {
|
||||
Objects.requireNonNull(id, "id");
|
||||
Objects.requireNonNull(displayName, "displayName");
|
||||
Objects.requireNonNull(defaultLocale, "defaultLocale");
|
||||
locales = (locales == null) ? List.of() : List.copyOf(locales);
|
||||
}
|
||||
|
||||
/** A minimal {@link SiteRef} for this site (its id). */
|
||||
public SiteRef ref() {
|
||||
return new SiteRef(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A page a plugin offers to install on a site ({@link mx.quest.runway.spi.service.SitePages#install}). Immutable.
|
||||
*
|
||||
* @param slug the page's stable id and file name (a safe identifier, never {@code null})
|
||||
* @param path its public path, starting with {@code /} (never {@code null})
|
||||
* @param titles the page title per language code ({@code "en" → "Contact"}); copied, {@code null} keys and
|
||||
* values dropped; may be empty
|
||||
* @param html the page body: decoupled-Thymeleaf markup (never {@code null})
|
||||
* @param logic the decoupled logic ({@code .th.xml}) for the body, or {@code null}/blank for none
|
||||
* @param noindex whether the page asks search engines not to index it
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public record StarterPage(String slug, String path, Map<String, String> titles, String html, String logic,
|
||||
boolean noindex) {
|
||||
|
||||
public StarterPage {
|
||||
Objects.requireNonNull(slug, "slug");
|
||||
Objects.requireNonNull(path, "path");
|
||||
Objects.requireNonNull(html, "html");
|
||||
Map<String, String> copy = new LinkedHashMap<>();
|
||||
if (titles != null) {
|
||||
titles.forEach((language, title) -> {
|
||||
if (language != null && title != null) {
|
||||
copy.put(language, title);
|
||||
}
|
||||
});
|
||||
}
|
||||
titles = Map.copyOf(copy);
|
||||
logic = (logic == null || logic.isBlank()) ? null : logic;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
/**
|
||||
* What a request-facing surface (an {@link mx.quest.runway.spi.EndpointContributor} route, a
|
||||
* widget-backed page) declares about how it should be treated for discoverability and
|
||||
* caching. The defaults are <b>fail-safe</b>: not indexed, not in the sitemap, not cached —
|
||||
* so a surface that declares nothing can never pollute the search index or poison a shared
|
||||
* cache. Opting into indexing or caching is a deliberate act.
|
||||
*
|
||||
* <p>Note: caching a surface whose content varies per-user, per-request, or over time is an
|
||||
* isolation/correctness failure, not merely a performance miss — only declare
|
||||
* {@code cacheable} when the response is a pure function of the routed inputs.
|
||||
*
|
||||
* @param indexable whether search/AI crawlers may index it (default {@code false})
|
||||
* @param inSitemap whether it should be listed in the sitemap (default {@code false}). <b>Advisory:</b> the
|
||||
* kernel itself builds no sitemap; a sitemap contributor (a plugin) may
|
||||
* honour it, and nothing guarantees one is installed
|
||||
* @param cacheable whether the response may be cached (default {@code false} = no-store)
|
||||
*/
|
||||
public record SurfacePosture(boolean indexable, boolean inSitemap, boolean cacheable) {
|
||||
|
||||
private static final SurfacePosture SAFE = new SurfacePosture(false, false, false);
|
||||
|
||||
/** The fail-safe default: not indexed, not in the sitemap, not cached. */
|
||||
public static SurfacePosture safeDefault() {
|
||||
return SAFE;
|
||||
}
|
||||
|
||||
/** A surface that is indexed and listed in the sitemap, but still not cached. */
|
||||
public static SurfacePosture discoverable() {
|
||||
return new SurfacePosture(true, true, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The immutable input to a {@link mx.quest.runway.spi.ContentWidget} — the page/instance
|
||||
* context plus the widget instance's resolved configuration. The host locates the anchor in
|
||||
* the page markup (a {@code data-widget="<plugin>/<instance>"} attribute), resolves the
|
||||
* instance's config, and hands the widget this frozen view.
|
||||
*
|
||||
* @param site the site being served (never {@code null})
|
||||
* @param page the page the widget appears on (never {@code null})
|
||||
* @param locale the resolved request locale (never {@code null})
|
||||
* @param instanceId the widget instance identifier from the anchor (never {@code null}); lets
|
||||
* one widget type render differently per placement
|
||||
* @param isChrome whether the anchor is in the site's master chrome (so the widget shows on
|
||||
* every page of that master) rather than in a single page's content — it
|
||||
* affects rendering scope and cache-invalidation reasoning
|
||||
* @param config the resolved configuration for this instance (never {@code null};
|
||||
* defensively copied, unmodifiable; may be empty). Absent keys mean "use the
|
||||
* widget's default". The host guarantees (since SPI 0.4.0) that no key or value is
|
||||
* {@code null} at any depth and that nested maps and lists are unmodifiable too, so a
|
||||
* widget may cache or share what it reads without copying.
|
||||
* @param query the request's query parameters (first value per name), so a widget can render
|
||||
* request-dependent output on a normal page — a search-results widget reading
|
||||
* {@code ?q=}, a form widget reading a {@code ?sent} confirmation flag. Never
|
||||
* {@code null} (empty when there is no query); defensively copied, unmodifiable.
|
||||
* The widget stays a <b>pure function</b> of this view: it may READ the query to
|
||||
* choose what to render, but must not mutate anything (side effects — storing a
|
||||
* submission, sending mail — belong to a request-handling endpoint, not to render).
|
||||
* @param path the public request path being rendered, exactly as served (locale prefix included — e.g.
|
||||
* {@code /es/blog/mi-entrada}); empty when unknown (a bare preview). A widget that needs
|
||||
* "the current page's URL" (a return path, a self-link) MUST use this — never build one from
|
||||
* {@link PageMeta#slug()}, which for a content source's page is a composite identity, not a
|
||||
* path.
|
||||
*/
|
||||
public record WidgetView(SiteView site, PageMeta page, Locale locale, String instanceId,
|
||||
boolean isChrome, Map<String, Object> config, Map<String, String> query,
|
||||
String path) {
|
||||
|
||||
public WidgetView {
|
||||
Objects.requireNonNull(site, "site");
|
||||
Objects.requireNonNull(page, "page");
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
Objects.requireNonNull(instanceId, "instanceId");
|
||||
config = (config == null) ? Map.of() : Map.copyOf(config);
|
||||
query = (query == null) ? Map.of() : Map.copyOf(query);
|
||||
path = (path == null) ? "" : path;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pre-{@code path} constructor, kept for binary compatibility so a widget or host compiled against an
|
||||
* earlier SPI keeps loading on this one. Materializes an empty path.
|
||||
*/
|
||||
public WidgetView(SiteView site, PageMeta page, Locale locale, String instanceId,
|
||||
boolean isChrome, Map<String, Object> config, Map<String, String> query) {
|
||||
this(site, page, locale, instanceId, isChrome, config, query, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The pre-{@code query} constructor, kept for binary compatibility so a widget or host compiled against an
|
||||
* earlier SPI keeps loading on this one. Materializes an empty query.
|
||||
*/
|
||||
public WidgetView(SiteView site, PageMeta page, Locale locale, String instanceId,
|
||||
boolean isChrome, Map<String, Object> config) {
|
||||
this(site, page, locale, instanceId, isChrome, config, Map.of(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Immutable boundary model for the Runway SPI — the host-materialized <em>views</em> that
|
||||
* {@linkplain mx.quest.runway.spi SPI implementations} receive as inputs and the plain value
|
||||
* types they return.
|
||||
*
|
||||
* <p>Every type here is immutable and built by the host. An SPI implementation is a
|
||||
* <b>pure function of its inputs</b>: it never reads persistence, never sees drafts, other
|
||||
* versions, other tenants, or other requests, and returns plain values. This keeps
|
||||
* implementations trivially unit-testable (no Spring, no I/O), preserves tenant isolation,
|
||||
* and lets the host evolve storage without touching a single implementation.
|
||||
*
|
||||
* <p>Records here defensively copy and null-normalize their collection/array components in
|
||||
* their compact constructors, so a view handed to an implementation cannot be mutated by it
|
||||
* or by whoever built it. These types are <b>released API</b>: evolve them only by
|
||||
* <i>adding</i> components while keeping an older-arity constructor/factory, never by
|
||||
* reordering, retyping, or removing existing components (see
|
||||
* {@link mx.quest.runway.spi.RunwaySpi}).
|
||||
*
|
||||
* <p><b>Record patterns are not source-stable across MINOR versions.</b> Adding a component keeps every existing
|
||||
* constructor and accessor working (binary compatibility), but a deconstruction pattern names <em>all</em>
|
||||
* components ({@code if (view instanceof WidgetView(var site, var page, ...))}), so it stops compiling when one is
|
||||
* added. Read components through their accessors; use record patterns only in code you rebuild with each SPI.
|
||||
*
|
||||
* <p>Field shapes are deliberately minimal for now and grow (add-only) as each extension
|
||||
* axis is built out.
|
||||
*/
|
||||
package mx.quest.runway.spi.model;
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Runway's extension API — the small set of capability-typed Service Provider Interfaces
|
||||
* (SPIs) the platform is built around.
|
||||
*
|
||||
* <p>Every "kind of X" in the domain — and the platform's own built-in features — is an
|
||||
* implementation of an SPI in this module, discovered and wired identically whether it ships
|
||||
* in the core or in a plugin (the no-two-class rule). The host is <b>capability-driven</b>: an
|
||||
* implementation declares what it can do as data, and host surfaces branch on a declared
|
||||
* capability, never on a concrete type.
|
||||
*
|
||||
* <p>This module depends on <b>nothing</b> in the host: only these interfaces and their
|
||||
* immutable model records (in {@link mx.quest.runway.spi.model}). It is RELEASED API — see
|
||||
* {@link mx.quest.runway.spi.RunwaySpi} for the compatibility contract.
|
||||
*
|
||||
* <p>The extension axes defined here ("Group A" — the JDK-only Java SPIs):
|
||||
* {@link mx.quest.runway.spi.HeadContributor}, {@link mx.quest.runway.spi.ContentWidget},
|
||||
* {@link mx.quest.runway.spi.PageQualityCheck}, {@link mx.quest.runway.spi.EndpointContributor},
|
||||
* and {@link mx.quest.runway.spi.BackupParticipant}. Each is a thin interface carrying a stable
|
||||
* {@code key()}, one lifecycle method over an immutable host-built view, and a default
|
||||
* {@code capabilities()} declaration. Host-coupled axes (servlet filters, Spring security
|
||||
* chains) and the declarative descriptor axes (settings, permissions, menu, dashboard cards)
|
||||
* live in the host module, not here.
|
||||
*/
|
||||
package mx.quest.runway.spi;
|
||||
@@ -0,0 +1,26 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
/**
|
||||
* Checks a permission for the principal of the request on the calling thread. The kernel's implementation is the
|
||||
* bean named {@value #BEAN_NAME}, so the same check is available in Spring Security expressions
|
||||
* ({@code @PreAuthorize("@authz.may('blog|manage')")}) and in Thymeleaf templates
|
||||
* ({@code ${@authz.may('blog|manage')}}), and by injection of this type in Java.
|
||||
*
|
||||
* <p>Thread-safe; never throws for a missing request or principal.
|
||||
*
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public interface AccessCheck {
|
||||
|
||||
/** The bean name the kernel registers its implementation under. */
|
||||
String BEAN_NAME = "authz";
|
||||
|
||||
/**
|
||||
* Whether the current principal holds {@code permissionKey} in the current realm and tenancy. A plugin's own
|
||||
* permission is named {@code <pluginId>|<permissionId>}; a kernel permission by its name
|
||||
* ({@code EDIT_PAGES}). <b>Fail-closed</b>: {@code false} with no request, no signed-in principal, an
|
||||
* undeclared key, or on an endpoint route dispatched anonymously
|
||||
* ({@link mx.quest.runway.spi.model.Route#anonymous()}).
|
||||
*/
|
||||
boolean may(String permissionKey);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Marks a plugin {@code @Controller} whose screens render <b>inside the operator console shell</b> — the topbar,
|
||||
* the menus, the language switcher and the footer, exactly as a kernel screen. The host's own advice fills the shell's
|
||||
* model for every request handled by a class carrying this annotation; the plugin needs no
|
||||
* {@code @ControllerAdvice} of its own and no host class.
|
||||
*
|
||||
* <h2>How a screen uses it</h2>
|
||||
* <pre>{@code
|
||||
* @Controller
|
||||
* @ConsoleScreen
|
||||
* public class BlogAdminController {
|
||||
* @GetMapping("/__admin/blog")
|
||||
* @PreAuthorize("@authz.may('blog|manage')")
|
||||
* public String list(Model model) {
|
||||
* model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/blog/admin-list");
|
||||
* model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "blog.admin.title");
|
||||
* return ConsoleScreen.LAYOUT_VIEW;
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* <h2>Rules</h2>
|
||||
* <ul>
|
||||
* <li>Every mapping lies under {@code /__admin/<pluginId>} (the tenant console) or {@code /__app/<pluginId>} (the
|
||||
* application console), so the console's realm security and CSRF protection apply unchanged. Gate each handler
|
||||
* with {@link AccessCheck} ({@code @PreAuthorize("@authz.may('…')")}).</li>
|
||||
* <li>The content template ({@code __plugin__/<pluginId>/<name>}) may rely on these model variables:
|
||||
* {@code tenantSiteId} (the bound site's id on the tenant console, {@code null} on the application console)
|
||||
* and {@code _csrf}; on the expressions {@code ${@<own bean>…}} and {@code ${@authz.may('…')}}; and on
|
||||
* {@code #{…}} messages from the plugin's bundle. Nothing else in the shell's model is promised.</li>
|
||||
* </ul>
|
||||
*
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface ConsoleScreen {
|
||||
|
||||
/** The view name a console screen returns: the shell layout that wraps the content template. */
|
||||
String LAYOUT_VIEW = "operator/op-layout";
|
||||
|
||||
/** The model attribute naming the screen's content template ({@code __plugin__/<pluginId>/<template>}). */
|
||||
String CONTENT_TEMPLATE = "contentTemplate";
|
||||
|
||||
/** The model attribute naming the message key of the screen's title (the browser tab and the heading). */
|
||||
String PAGE_TITLE_KEY = "pageTitleKey";
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
|
||||
/**
|
||||
* The read side of a site's <b>published content surface</b>: every real page and every content source's item, with
|
||||
* the URLs the host computed for each. What a sitemap, an llms.txt, a search index or an "is this path taken?" check
|
||||
* reads. A kernel singleton, injected by type.
|
||||
*
|
||||
* <h2>What the listing guarantees</h2>
|
||||
* The host re-filters every source's output <b>fail-closed</b> before it is listed: unpublished items, items with an
|
||||
* unsafe path, and items whose URL (in any locale) collides with the reserved kernel surface or an exact endpoint
|
||||
* route are dropped; a source that throws contributes nothing and never breaks the listing of the others. The URLs
|
||||
* come from the same computation as the page {@code <head>} alternates, so a listing cannot disagree with the
|
||||
* pages it lists.
|
||||
*
|
||||
* <h2>Freshness</h2>
|
||||
* {@link #entries} is cached per site and evicted by every change that can reshape the surface (a page write, a
|
||||
* {@link ContentChanges#changed} call, a site lifecycle event, any plugin's per-site settings save), with a 30-second
|
||||
* time-to-live as the backstop for changes nothing announces (a file edited by hand). {@link #refresh} drops the
|
||||
* cached listing on demand — a manual "reindex" button.
|
||||
*
|
||||
* <h2>Rules</h2>
|
||||
* Every method takes a <b>site id</b> and resolves the site on the host side (a caller can never fill the shared
|
||||
* cache from a stale or hand-built view). An unsafe id throws {@link IllegalArgumentException}; a well-formed id of
|
||||
* an unknown site answers empty, {@code ""} or {@code false}. Thread-safe; no method returns {@code null}.
|
||||
*
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public interface ContentCatalogView {
|
||||
|
||||
/** The {@link CatalogEntry#sourceKey()} of real pages. */
|
||||
String PAGES_SOURCE = "pages";
|
||||
|
||||
/**
|
||||
* Every published item of the site — real pages and every content source's items, grouped by source in a
|
||||
* stable order (do not rely on which source comes first) — re-filtered as described above. Metadata only: no body
|
||||
* is read, so this is safe on public, anonymous request paths.
|
||||
*
|
||||
* @param siteId the site
|
||||
* @return the entries (never {@code null}; unmodifiable; empty for an unknown site)
|
||||
*/
|
||||
List<CatalogEntry> entries(String siteId);
|
||||
|
||||
/**
|
||||
* The item's indexable material in {@code locale} — the text a search engine folds in beyond the title and
|
||||
* description, as HTML or plain text (strip markup before indexing). Only sources that declare the
|
||||
* {@code content.indexable-text} capability are asked; for the others, for an unknown site, and when the source
|
||||
* fails, the answer is {@code ""}.
|
||||
*
|
||||
* @param siteId the site
|
||||
* @param entry an entry from {@link #entries} of the same site
|
||||
* @param locale the locale to index
|
||||
* @return the material, or {@code ""} (never {@code null})
|
||||
*/
|
||||
String indexableText(String siteId, CatalogEntry entry, Locale locale);
|
||||
|
||||
/**
|
||||
* The slug of the <b>published real page</b> that serves {@code path} in {@code locale} — the question a content
|
||||
* source asks before it publishes an item at a path ("a page owns this URL; the page wins, so the entry would be
|
||||
* unreachable"). A draft page serves nothing and owns no path.
|
||||
*
|
||||
* @param siteId the site
|
||||
* @param path a root-relative path without a locale prefix ({@code /blog})
|
||||
* @param locale the locale whose URL space to check
|
||||
* @return the owning page's slug (when two pages wrongly claim the path, the first by slug), or empty when no
|
||||
* published page claims it
|
||||
*/
|
||||
Optional<String> pageAt(String siteId, String path, Locale locale);
|
||||
|
||||
/**
|
||||
* Whether the host would route content at {@code path} at all: a safe page path that is not part of the
|
||||
* reserved kernel surface ({@code /__…}, {@code /login}, {@code /error}, …) and not an exact endpoint route
|
||||
* ({@code /sitemap.xml}, …). No content source is consulted, so a path another item already uses still answers
|
||||
* {@code true} — this is the "is this prefix even allowed?" check, not an availability check.
|
||||
*
|
||||
* @param siteId the site ({@code false} for an unknown site)
|
||||
* @param path the root-relative path to check
|
||||
* @return whether content may be served at the path
|
||||
*/
|
||||
boolean servablePath(String siteId, String path);
|
||||
|
||||
/**
|
||||
* Drops the site's cached listing, so the next {@link #entries} re-reads every source. For a manual reindex of
|
||||
* changes no event announced; ordinary writes do not need it.
|
||||
*
|
||||
* @param siteId the site
|
||||
*/
|
||||
void refresh(String siteId);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
/**
|
||||
* Announces that the calling plugin's content changed, so every cache derived from it — the host's routing and
|
||||
* URL maps, the {@link ContentCatalogView} listing, a search index, a sitemap — is dropped, on every node of a
|
||||
* cluster. Every {@link mx.quest.runway.spi.ContentSource} calls it after each mutation of its content: the host
|
||||
* cannot see a plugin's files change.
|
||||
*
|
||||
* <h2>How a plugin gets one</h2>
|
||||
* Plugin-scoped, like {@link PluginSettings}: inject it into a class from the plugin's own jar and it is bound to
|
||||
* that plugin. The binding is what lets the host refuse an announcement for a source the plugin does not own.
|
||||
*
|
||||
* <h2>What a call does, in order</h2>
|
||||
* Synchronously, on the calling thread: the host's caches for the site are evicted; listeners that still use the
|
||||
* host's own change event run; the change is relayed to the other nodes of a cluster; then every
|
||||
* {@link SiteEventListener} receives {@link SiteEventListener#onCatalogChanged} (cause {@code CONTENT}). When
|
||||
* {@code changed} returns, every listener on this node has run.
|
||||
*
|
||||
* <p><b>It does not refresh HTTP validators.</b> A rendered item's {@code ETag} folds its {@code ContentRef}
|
||||
* metadata; a change to what {@code body()} returns must also change the ref (bump {@code updatedAt}).
|
||||
*
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public interface ContentChanges {
|
||||
|
||||
/**
|
||||
* Call after mutating the calling plugin's content.
|
||||
*
|
||||
* @param siteId the site whose content changed
|
||||
* @param sourceKey the {@link mx.quest.runway.spi.ContentSource#key()} whose content changed — one the calling
|
||||
* plugin contributes
|
||||
* @param id the changed item's {@code ContentRef.id()}; nullable: {@code null} means the source's whole
|
||||
* corpus for the site (a re-import, a prefix change)
|
||||
* @throws IllegalArgumentException if {@code siteId} is unsafe, or {@code sourceKey} is not a content source
|
||||
* contributed by the calling plugin
|
||||
* @throws IllegalStateException if called from inside a {@link SiteEventListener} callback (a change announced
|
||||
* while a change is being delivered would start a re-entrant storm)
|
||||
*/
|
||||
void changed(String siteId, String sourceKey, String id);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Looks up a localized message for a plugin's output. A kernel singleton, injected by type.
|
||||
*
|
||||
* <p>Two namespaces that never mix: <b>public</b> output (what a site's visitors read) resolves against the site's
|
||||
* own bundle first and then every plugin's {@code i18n/messages*.properties} (add-only: a plugin can never override
|
||||
* a site's key); <b>console</b> output resolves against the operator console's bundles, including every plugin's
|
||||
* operator bundle, in the operator's chosen UI language.
|
||||
*
|
||||
* <p>Arguments are applied with {@link java.text.MessageFormat}, to the found message or to the fallback. Thread-safe;
|
||||
* never returns {@code null}; never throws for a missing key.
|
||||
*
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public interface Messages {
|
||||
|
||||
/**
|
||||
* A message for public output on site {@code siteId}, in {@code locale}. Works off-request (the site is named,
|
||||
* not taken from the thread).
|
||||
*
|
||||
* @param fallback the text when no bundle has {@code code} (nullable: {@code null} yields the code itself)
|
||||
* @throws IllegalArgumentException if {@code siteId} is not a safe identifier
|
||||
*/
|
||||
String site(String siteId, Locale locale, String code, String fallback, Object... args);
|
||||
|
||||
/**
|
||||
* A message for console output, in the UI language of the operator making the current request.
|
||||
*
|
||||
* @param fallback the text when no bundle has {@code code} (nullable: {@code null} yields the code itself)
|
||||
* @return the message; off a request thread, the fallback (or the code)
|
||||
*/
|
||||
String console(String code, String fallback, Object... args);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
|
||||
/**
|
||||
* An optional start/stop hook. A plugin that only contributes beans needs none. Implement it on any bean from the
|
||||
* plugin's own jar to run code once the platform is up (warm a cache, open an index, schedule work) or when it
|
||||
* shuts down. The host collects every {@code PluginLifecycle} bean by type and matches each to its plugin by the
|
||||
* jar its class was loaded from — a {@code PluginLifecycle} defined in kernel code or a {@code lib/} jar is
|
||||
* ignored with a warning.
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* <ul>
|
||||
* <li>{@link #started} runs once, after the context has refreshed and every singleton exists, in plugin load
|
||||
* order (a plugin after the plugins it {@code requires:}). {@link #stopping} runs at shutdown in the
|
||||
* reverse order, and only for hooks whose {@code started} returned normally.</li>
|
||||
* <li>Both run on the host's startup/shutdown thread, which they block: keep them short and hand long work to
|
||||
* the plugin's own executor.</li>
|
||||
* <li>Each call is isolated: a {@link RuntimeException} or {@link LinkageError} it throws is logged (and
|
||||
* counted on the plugins screen) and the next hook still runs; the platform keeps booting.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Replaces the host-internal {@code RunwayPlugin}/{@code PluginContext} pair, which handed plugins the host's
|
||||
* {@code ApplicationContext}.
|
||||
*
|
||||
* @since SPI 0.4.0
|
||||
*/
|
||||
public interface PluginLifecycle {
|
||||
|
||||
/**
|
||||
* Called once the platform is up.
|
||||
*
|
||||
* @param self the plugin this hook belongs to
|
||||
*/
|
||||
default void started(PluginInfo self) {
|
||||
}
|
||||
|
||||
/** Called at shutdown, before the context closes. */
|
||||
default void stopping() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
|
||||
/**
|
||||
* The calling plugin's own per-site settings — the values an operator saves on the plugin's per-site settings
|
||||
* form ({@code siteSettings:} in {@code plugin.yml}), stored in {@code sites/<siteId>/plugins/<pluginId>.yml}.
|
||||
*
|
||||
* <h2>How a plugin gets one</h2>
|
||||
* By ordinary Spring injection into a class from the plugin's <b>own jar</b> — a constructor or {@code @Bean}
|
||||
* method parameter, a field, or an {@code ObjectProvider<PluginSettings>}. The host binds the instance to the
|
||||
* plugin <b>whose jar the injecting class was loaded from</b>; no method takes a plugin id, so a plugin can only
|
||||
* ever read its own settings. Injection fails fast (the plugin does not start) from a class in the plugin's
|
||||
* {@code lib/} folder, from kernel code, and through a bare {@code getBean(PluginSettings.class)} (which has no
|
||||
* injection point to bind by). Binding happens at injection, so the instance keeps answering for the right
|
||||
* plugin on any thread, later.
|
||||
*
|
||||
* <h2>Rules</h2>
|
||||
* <ul>
|
||||
* <li>Thread-safe. No method returns {@code null}.</li>
|
||||
* <li>An unsafe site id (one that could not be a folder name) throws {@link IllegalArgumentException} before
|
||||
* any I/O. A well-formed id of a site that does not exist answers the declared defaults.</li>
|
||||
* <li>Changes apply immediately: a save on the settings form evicts the cached view on every node, and the
|
||||
* next call returns the new values.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>App-level (platform-wide) plugin settings are not here: they bind through Spring
|
||||
* {@code @ConfigurationProperties} under {@code runway.plugin.<id>.*}, which is descriptor contract.
|
||||
*
|
||||
* @since SPI 0.4.0
|
||||
*/
|
||||
public interface PluginSettings {
|
||||
|
||||
/**
|
||||
* The calling plugin's effective settings for {@code siteId}: the declared {@code siteSettings:} defaults,
|
||||
* overlaid by the stored values (a stored blank string does not mask a declared default), plus any stored
|
||||
* keys the schema does not declare (preserved on purpose — a schema upgrade never wipes operator data).
|
||||
* Secret-typed keys are absent. Cached; never {@code null}.
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code siteId} is not a safe identifier
|
||||
*/
|
||||
SettingsView site(String siteId);
|
||||
|
||||
/**
|
||||
* A {@code secret}-typed setting in clear. A stored {@code ENC(...)} value is decrypted; any other value (a
|
||||
* hand-written plaintext) is returned unchanged. Empty when the key is not declared {@code type: secret} in
|
||||
* {@code siteSettings:}, when it is unset or blank, when it is encrypted but no platform secret key is
|
||||
* configured, or when decryption fails (logged once per site and key, never with the value).
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code siteId} is not a safe identifier
|
||||
*/
|
||||
Optional<String> secret(String siteId, String key);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.FileEntry;
|
||||
|
||||
/**
|
||||
* The calling plugin's own <b>per-site file subtree</b>, {@code sites/<siteId>/plugins/<pluginId>/}: the place a
|
||||
* plugin keeps the data it generates for a site (form submissions, blog entries, logs of visitor searches). The
|
||||
* folder lives inside the site's folder, so a full backup carries it and a deleted site takes it along.
|
||||
*
|
||||
* <h2>How a plugin gets one</h2>
|
||||
* By ordinary Spring injection into a class from the plugin's <b>own jar</b>, exactly like
|
||||
* {@link PluginSettings}: the host binds the instance to the plugin whose jar the injecting class was loaded from.
|
||||
* No method takes a plugin id, so a plugin can only ever reach its own subtree. Injection from a {@code lib/}
|
||||
* class, from kernel code, or through a bare {@code getBean} fails fast.
|
||||
*
|
||||
* <h2>Confinement</h2>
|
||||
* Every path is relative to the subtree root and uses {@code /}. An absolute path, a backslash, an empty segment,
|
||||
* a {@code .} or {@code ..} segment, or a control character throws {@link IllegalArgumentException} before any
|
||||
* I/O. Beyond that lexical rule, every operation checks the <b>real</b> (symbolic-link-resolved) path: a symbolic
|
||||
* link planted inside the subtree, or a link standing in for the subtree itself, can never carry a read or a write
|
||||
* outside {@code plugins/<pluginId>/} (to the site's {@code users.yml}, another plugin's data, or another site);
|
||||
* such an operation throws {@link IllegalArgumentException}. A symbolic link at the leaf reads as absent and is
|
||||
* never listed. The plugin's settings file ({@code plugins/<pluginId>.yml}) is a <em>sibling</em> of the subtree,
|
||||
* not inside it, so it cannot be written through this service.
|
||||
*
|
||||
* <h2>Limits & failure</h2>
|
||||
* <ul>
|
||||
* <li>One write is capped by {@code runway.plugins.site-files.max-write-bytes} (default 16 MiB): over the cap,
|
||||
* {@link IllegalArgumentException} and nothing is written. {@link #readText} refuses a file over the same
|
||||
* cap with an {@link IOException}, so a large file placed by hand is never read whole into the heap.</li>
|
||||
* <li>{@link #list} returns at most 10,000 entries (the first by name) and logs when it truncates.</li>
|
||||
* <li>An unsafe site id throws {@link IllegalArgumentException}; a well-formed id of a site that does not exist
|
||||
* simply has no files (reads are empty), and a write for it fails with {@link IOException} rather than
|
||||
* creating the site's folder — so a late write for a deleted site cannot leave a stray folder that a
|
||||
* new site with the same id would inherit.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Concurrency and freshness</h2>
|
||||
* Thread-safe. Each write is atomic (temporary file, {@code fsync}, rename), so a reader never sees a torn file;
|
||||
* a <b>read-modify-write</b> sequence (append a line) must be serialized by the plugin itself. Writing a file
|
||||
* announces nothing: a plugin whose files shape routable content tells the host afterwards (the content-change
|
||||
* service of a later SPI level).
|
||||
*
|
||||
* <h2>Personal data</h2>
|
||||
* A file that holds visitor or user input (names, emails, messages, search terms) must be declared in
|
||||
* {@code plugin.yml} under {@code siteData.personal}; a <b>transfer copy</b> of the site leaves it out. See the
|
||||
* plugin development guide.
|
||||
*
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public interface PluginSiteFiles {
|
||||
|
||||
/**
|
||||
* Reads a file as UTF-8 text.
|
||||
*
|
||||
* @return the text; empty when the file is absent, or the leaf is a directory or a symbolic link
|
||||
* @throws IllegalArgumentException if {@code siteId} or {@code relPath} is unsafe, or the path escapes the
|
||||
* subtree through a symbolic link
|
||||
* @throws IOException if the file is larger than the write cap, or cannot be read
|
||||
*/
|
||||
Optional<String> readText(String siteId, String relPath) throws IOException;
|
||||
|
||||
/**
|
||||
* Atomically writes {@code text} (UTF-8), creating parent folders as needed and replacing any existing file.
|
||||
*
|
||||
* @throws IllegalArgumentException if a path is unsafe or escapes the subtree, or the encoded text is over the
|
||||
* write cap (nothing is written)
|
||||
* @throws IOException if the site does not exist, the leaf is a directory, or the write fails
|
||||
*/
|
||||
void writeText(String siteId, String relPath, String text) throws IOException;
|
||||
|
||||
/**
|
||||
* Deletes one regular file.
|
||||
*
|
||||
* @return {@code true} if a file was deleted; {@code false} when it was absent, a directory or a symbolic link
|
||||
* @throws IllegalArgumentException if a path is unsafe or escapes the subtree
|
||||
* @throws IOException if the deletion fails
|
||||
*/
|
||||
boolean delete(String siteId, String relPath) throws IOException;
|
||||
|
||||
/**
|
||||
* Deletes a folder and everything in it (or a single regular file). Symbolic links inside it are removed as
|
||||
* links and <b>never followed</b>, so nothing outside the folder is touched. {@code relDir} must name
|
||||
* something below the root: the subtree root itself cannot be deleted this way.
|
||||
*
|
||||
* @return {@code true} if anything was deleted; {@code false} when it was absent or is a symbolic link
|
||||
* @throws IllegalArgumentException if a path is unsafe or escapes the subtree
|
||||
* @throws IOException if a deletion fails (what was already deleted stays deleted)
|
||||
*/
|
||||
boolean deleteTree(String siteId, String relDir) throws IOException;
|
||||
|
||||
/**
|
||||
* The direct children of a folder, sorted by name; symbolic links are omitted. {@code relDir} may be
|
||||
* {@code ""} for the subtree root.
|
||||
*
|
||||
* @return the entries; empty when the folder is absent, is a file, or is a symbolic link
|
||||
* @throws IllegalArgumentException if a path is unsafe or escapes the subtree
|
||||
* @throws IOException if the folder cannot be read
|
||||
*/
|
||||
List<FileEntry> list(String siteId, String relDir) throws IOException;
|
||||
|
||||
/**
|
||||
* What is at {@code relPath}: a regular file or a folder.
|
||||
*
|
||||
* @return the entry; empty when absent, a symbolic link, or another kind of file
|
||||
* @throws IllegalArgumentException if a path is unsafe or escapes the subtree
|
||||
* @throws IOException if its attributes cannot be read
|
||||
*/
|
||||
Optional<FileEntry> stat(String siteId, String relPath) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* The tenancy the request on the calling thread is bound to — what a plugin's console screen asks to learn which
|
||||
* site the signed-in user is managing. A kernel singleton, injected by type.
|
||||
*
|
||||
* <p>An endpoint does not need this: its {@link mx.quest.runway.spi.model.RouteRequest} already carries the site,
|
||||
* the locale, the client IP and the origin.
|
||||
*
|
||||
* <p>Thread-safe; never returns {@code null}; never throws.
|
||||
*
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public interface RequestContext {
|
||||
|
||||
/**
|
||||
* The site this request is bound to: the site whose public page or tenant console ({@code /__admin/…}) is
|
||||
* being served.
|
||||
*
|
||||
* @return the site; empty on the <b>application</b> realm ({@code /__app/…}, where the host would otherwise fall
|
||||
* back to the catch-all default site, which is not what an application-realm screen manages) and off a
|
||||
* request thread
|
||||
*/
|
||||
Optional<SiteView> site();
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.SettingsChange;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
|
||||
/**
|
||||
* Reacts to site, settings and content changes. Implement it on any bean from the plugin's own jar and override the
|
||||
* callbacks you need; the host collects every {@code SiteEventListener} bean by type. It replaces listening to the
|
||||
* host's internal Spring events (which plugins could not rely on: their order against the kernel's caches was not a
|
||||
* contract).
|
||||
*
|
||||
* <h2>What is delivered</h2>
|
||||
* <ul>
|
||||
* <li>{@link #onSiteLifecycle} — every site lifecycle event (created, updated, suspended, resumed, deleted,
|
||||
* restored).</li>
|
||||
* <li>{@link #onSettingsChanged} — a save of <b>this listener's own plugin's</b> per-site settings, and nothing
|
||||
* else.</li>
|
||||
* <li>{@link #onCatalogChanged} — anything that may reshape the content surface: a page write, a
|
||||
* {@link ContentChanges#changed} call, any lifecycle event, and any plugin's per-site settings save.</li>
|
||||
* </ul>
|
||||
* For one event and one listener the callbacks run in that order: lifecycle, then settings, then catalog.
|
||||
*
|
||||
* <h2>Guarantees</h2>
|
||||
* <ul>
|
||||
* <li><b>After the kernel.</b> When a callback runs, every kernel cache the change affects has been evicted:
|
||||
* reading {@link ContentCatalogView}, {@link PluginSettings} or {@link Sites} from a callback sees the new
|
||||
* state.</li>
|
||||
* <li><b>Phases.</b> All {@link Phase#SOURCE} listeners run first (a content source dropping its own index), then
|
||||
* the host evicts the content listing once more, then all {@link Phase#CONSUMER} listeners (a sitemap, a search
|
||||
* index) — so a consumer that re-reads the listing never sees a source's stale state. Within a phase the order
|
||||
* is plugin load order (a plugin after the plugins it {@code requires:}), then bean registration order:
|
||||
* deterministic, but not part of the contract.</li>
|
||||
* <li><b>No host lock is held.</b> A callback never runs while the host holds a write lock (a page's, a backup's).
|
||||
* A change made under a lock is delivered after the lock is released, still before the write call returns —
|
||||
* so "when the save returns, every listener has run" holds. Calling any service from a callback is therefore
|
||||
* safe, including one that writes; the events of such a write are delivered after the current callback
|
||||
* returns.</li>
|
||||
* <li><b>Thread.</b> The thread that made the change: the console request that saved, or the cluster's topic
|
||||
* thread for a change replayed from a peer ({@code local == false}).</li>
|
||||
* <li><b>Isolation.</b> A callback that throws a {@link RuntimeException} or {@link LinkageError} is logged (the
|
||||
* first time with the stack, then at most once a minute) and counted on the plugins screen; the change itself
|
||||
* and every other listener are unaffected.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Duty</h2>
|
||||
* Callbacks run on the writer's thread: <b>evict or enqueue, never do heavy work</b> — hand an index rebuild or a
|
||||
* network call to the plugin's own executor. {@link ContentChanges#changed} is refused from a callback (it would
|
||||
* start a re-entrant change storm).
|
||||
*
|
||||
* <h2>Not delivered</h2>
|
||||
* Changes nobody announces (a file edited by hand with no reload) and changes made before the platform finished
|
||||
* starting. The listing's time-to-live and the plugin's own time-to-live are the backstop.
|
||||
*
|
||||
* @since SPI 0.6.0
|
||||
*/
|
||||
public interface SiteEventListener {
|
||||
|
||||
/** When in a dispatch a listener runs. May gain constants in a MINOR release. */
|
||||
enum Phase {
|
||||
/** Content sources dropping their own state, before anything re-reads the listing. */
|
||||
SOURCE,
|
||||
/** Everything else: consumers of the listing (sitemaps, search indexes, change notifiers). */
|
||||
CONSUMER
|
||||
}
|
||||
|
||||
/**
|
||||
* This listener's phase; read once, when the platform starts. Default {@link Phase#CONSUMER}.
|
||||
*
|
||||
* @return the phase (a {@code null} answer counts as {@code CONSUMER})
|
||||
*/
|
||||
default Phase phase() {
|
||||
return Phase.CONSUMER;
|
||||
}
|
||||
|
||||
/**
|
||||
* A site's lifecycle changed.
|
||||
*
|
||||
* @param event what happened
|
||||
*/
|
||||
default void onSiteLifecycle(SiteLifecycleEvent event) {
|
||||
}
|
||||
|
||||
/**
|
||||
* This listener's own plugin's per-site settings were saved; {@link PluginSettings#site} already returns the new
|
||||
* values.
|
||||
*
|
||||
* @param change which site
|
||||
*/
|
||||
default void onSettingsChanged(SettingsChange change) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Something that may reshape the site's content surface changed. See {@link CatalogChange} for what each cause
|
||||
* carries, including the item's URLs before and after the change.
|
||||
*
|
||||
* @param change what changed
|
||||
*/
|
||||
default void onCatalogChanged(CatalogChange change) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
|
||||
/**
|
||||
* Installs a plugin's <b>starter page</b> on a site (the contact form's page, the search results page) and reports
|
||||
* where an existing one lives. A kernel singleton, injected by type.
|
||||
*
|
||||
* <p>Installing goes through the site's editorial rules, so a plugin can never publish around them:
|
||||
* <ol>
|
||||
* <li>An existing page with the slug (in any state) is never touched: {@link InstallResult.Outcome#ALREADY_EXISTS}.</li>
|
||||
* <li>Otherwise the page is created as a <b>draft</b>.</li>
|
||||
* <li>Then, by the site's editorial level:
|
||||
* <ul>
|
||||
* <li><b>Advisory</b>: published at once, {@link InstallResult.Outcome#PUBLISHED}.</li>
|
||||
* <li><b>Enforced</b>: published if the quality checks pass, else it stays a draft:
|
||||
* {@link InstallResult.Outcome#DRAFT_BLOCKED} with the blocking findings.</li>
|
||||
* <li><b>Reviewed</b>: if the current principal holds {@code APPROVE_PAGES}, as Enforced; otherwise it is
|
||||
* submitted to the review queue, {@link InstallResult.Outcome#PENDING_REVIEW}.</li>
|
||||
* </ul>
|
||||
* </li>
|
||||
* </ol>
|
||||
* The whole sequence holds the page's write lock, and each step is written to the site's audit log under the
|
||||
* current principal's name. The calling plugin is responsible for checking that the current principal may install
|
||||
* pages at all (with {@link AccessCheck}) before calling.
|
||||
*
|
||||
* <p>Thread-safe; never returns {@code null}.
|
||||
*
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public interface SitePages {
|
||||
|
||||
/**
|
||||
* The default path of the page with this slug, whatever its state (draft, published, in review) — so a plugin
|
||||
* can link to "its" page even after an operator moved it.
|
||||
*
|
||||
* @return the page's path; empty when no page has the slug or the site does not exist
|
||||
* @throws IllegalArgumentException if {@code siteId} or {@code slug} is not a safe identifier
|
||||
*/
|
||||
Optional<String> pathOf(String siteId, String slug);
|
||||
|
||||
/**
|
||||
* Installs {@code page} on site {@code siteId} once, following the editorial rules above. Idempotent: it never
|
||||
* overwrites.
|
||||
*
|
||||
* @return what happened, the page's path and, for {@link InstallResult.Outcome#DRAFT_BLOCKED}, the blocking
|
||||
* findings
|
||||
* @throws IllegalArgumentException if the site id or slug is unsafe, or the path is unsafe or reserved (a
|
||||
* kernel surface such as {@code /__admin} or {@code /login})
|
||||
* @throws IllegalStateException if the site does not exist, or the page could not be written (another page
|
||||
* already claims the path, the master template is missing, an I/O failure)
|
||||
*/
|
||||
InstallResult install(String siteId, StarterPage page);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package mx.quest.runway.spi.service;
|
||||
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* Looks a site up by id, off-request as well as on one: the way a background task, a listener or a console screen
|
||||
* gets the {@link SiteView} of a site it only knows by id. A kernel singleton, injected by type.
|
||||
*
|
||||
* <p>Thread-safe; never returns {@code null}.
|
||||
*
|
||||
* @since SPI 0.5.0
|
||||
*/
|
||||
public interface Sites {
|
||||
|
||||
/**
|
||||
* The view of site {@code siteId}. Suspended sites are included (a suspended site still exists and still owns
|
||||
* its data).
|
||||
*
|
||||
* @return the view, or empty when no site has this (well-formed) id
|
||||
* @throws IllegalArgumentException if {@code siteId} is not a safe identifier
|
||||
*/
|
||||
Optional<SiteView> find(String siteId);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* The SPI <b>service tier</b> (since SPI 0.4.0): narrow interfaces the <b>kernel implements</b> and a plugin
|
||||
* <b>receives by ordinary Spring injection</b>, plus the callbacks a plugin implements and the host calls. They
|
||||
* replace the host-internal classes plugins used to inject: since SPI 1.0.0 a plugin that links a {@code runway-app}
|
||||
* class is refused at load time (blocked, with the reason on the plugins screen).
|
||||
*
|
||||
* <h2>Rules that apply to every service</h2>
|
||||
* <ul>
|
||||
* <li><b>Nullability.</b> No method returns {@code null}. Every parameter is non-null unless documented
|
||||
* nullable.</li>
|
||||
* <li><b>Unsafe input.</b> An unsafe site id, slug or relative path throws {@link IllegalArgumentException}
|
||||
* before any I/O; a well-formed id of an unknown site is not an error.</li>
|
||||
* <li><b>Threading.</b> Every service is thread-safe. {@link mx.quest.runway.spi.service.RequestContext},
|
||||
* {@link mx.quest.runway.spi.service.AccessCheck} and {@link mx.quest.runway.spi.service.Messages#console}
|
||||
* read the request bound to the calling thread; off a request thread they answer empty, {@code false} or the
|
||||
* fallback, and never throw.</li>
|
||||
* <li><b>Isolation.</b> A plugin-scoped service ({@link mx.quest.runway.spi.service.PluginSettings},
|
||||
* {@link mx.quest.runway.spi.service.PluginSiteFiles}, {@link mx.quest.runway.spi.service.ContentChanges},
|
||||
* {@link mx.quest.runway.spi.model.PluginInfo}) is bound to the plugin whose own jar the injecting class came
|
||||
* from; no parameter can name another plugin. The other services ({@link mx.quest.runway.spi.service.Sites},
|
||||
* {@link mx.quest.runway.spi.service.RequestContext}, {@link mx.quest.runway.spi.service.AccessCheck},
|
||||
* {@link mx.quest.runway.spi.service.Messages}, {@link mx.quest.runway.spi.service.SitePages},
|
||||
* {@link mx.quest.runway.spi.service.ContentCatalogView}) are kernel singletons.</li>
|
||||
* <li><b>Callbacks</b> a plugin implements ({@link mx.quest.runway.spi.service.PluginLifecycle},
|
||||
* {@link mx.quest.runway.spi.service.SiteEventListener}) are collected by type and isolated: one that throws
|
||||
* is logged and counted, and never affects the host or another plugin.</li>
|
||||
* <li><b>Enums</b> in this tier may gain constants in a MINOR release; a {@code switch} over one needs a
|
||||
* {@code default} branch.</li>
|
||||
* </ul>
|
||||
*/
|
||||
package mx.quest.runway.spi.service;
|
||||
@@ -0,0 +1,65 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
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 java.util.Optional;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The {@link ContentSource} default methods: {@code resolve()} must be a correct-by-construction scan of
|
||||
* {@code enumerate()} — matching the locale-specific path ({@code pathFor}), skipping unpublished refs — and
|
||||
* {@code capabilities()} defaults to none. Pure unit tests over a tiny in-memory source.
|
||||
*/
|
||||
class ContentSourceDefaultsTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
private static final SiteView SITE = new SiteView("demo", "Demo", EN, List.of(EN, ES), null);
|
||||
|
||||
/** A minimal source over a fixed list — exercises only the interface defaults. */
|
||||
private record FixedSource(List<ContentRef> refs) implements ContentSource {
|
||||
@Override public String key() { return "fixed"; }
|
||||
@Override public List<ContentRef> enumerate(SiteView site) { return refs; }
|
||||
@Override public ContentBody body(SiteView site, String id, Locale locale) { return ContentBody.empty(); }
|
||||
}
|
||||
|
||||
private static ContentRef entry(String id, String path, Map<String, String> localized, boolean published) {
|
||||
return new ContentRef(id, path, localized, List.of(EN, ES), Map.of("en", id), Map.of(), null,
|
||||
"__plugin__/fixed/entry", published, null, false, null, null, Map.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultResolveMatchesTheLocaleSpecificPath() {
|
||||
ContentSource source = new FixedSource(List.of(
|
||||
entry("a", "/blog/a", Map.of("es", "/blog/a-es"), true),
|
||||
entry("b", "/blog/b", Map.of(), true)));
|
||||
|
||||
assertEquals("a", source.resolve(SITE, "/blog/a", EN).orElseThrow().id(), "default path, default locale");
|
||||
assertEquals("a", source.resolve(SITE, "/blog/a-es", ES).orElseThrow().id(), "localized slug, its locale");
|
||||
assertTrue(source.resolve(SITE, "/blog/a-es", EN).isEmpty(),
|
||||
"a localized slug never doubles as another locale's URL (the page rule)");
|
||||
assertTrue(source.resolve(SITE, "/blog/none", EN).isEmpty(), "unknown path → miss");
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultResolveSkipsUnpublishedContent() {
|
||||
ContentSource source = new FixedSource(List.of(entry("draft", "/blog/draft", Map.of(), false)));
|
||||
assertTrue(source.resolve(SITE, "/blog/draft", EN).isEmpty(),
|
||||
"an unpublished ref must never resolve (and the kernel re-filters as the backstop)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void capabilitiesDefaultToNone() {
|
||||
ContentSource source = new FixedSource(List.of());
|
||||
assertEquals(Capabilities.none(), source.capabilities());
|
||||
assertTrue(!source.capabilities().has(ContentSource.CAP_ARBITRARY_PATHS));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RunwaySpiTest {
|
||||
|
||||
@Test
|
||||
void versionParsesAsPlainMajorMinorPatch() {
|
||||
assertTrue(RunwaySpi.VERSION.matches("\\d+\\.\\d+\\.\\d+"),
|
||||
"RunwaySpi.VERSION must be plain MAJOR.MINOR.PATCH so the plugin resolver's "
|
||||
+ "segment-wise integer compare stays trivial; was: " + RunwaySpi.VERSION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void runtimeVersionReportsTheRunningSpi() {
|
||||
// Read reflectively, as a plugin compiled against an older SPI effectively does: the method body runs in the
|
||||
// running runway-spi, so it reports that jar's VERSION, never an inlined copy.
|
||||
assertTrue(RunwaySpi.runtimeVersion().equals(RunwaySpi.VERSION));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package mx.quest.runway.spi;
|
||||
|
||||
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.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.BackupReader;
|
||||
import mx.quest.runway.spi.model.BackupWriter;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.RenderFragment;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.Severity;
|
||||
import mx.quest.runway.spi.model.SiteRef;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Proves each Group A SPI is implementable as a pure, dependency-free unit — no Spring, no
|
||||
* real I/O — exactly as the design intends. Doubles as worked usage of each contract.
|
||||
*/
|
||||
class SpiContractTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
|
||||
private static SiteView site() {
|
||||
return new SiteView("s1", "Site", EN, List.of(EN), "https://example.test");
|
||||
}
|
||||
|
||||
private static PageMeta page() {
|
||||
return new PageMeta("home", "Home", "A page", List.of(EN), EN, true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void headContributorIsAPureFunction() {
|
||||
HeadContributor c = new HeadContributor() {
|
||||
@Override
|
||||
public String key() {
|
||||
return "test.meta";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String render(HeadContext ctx) {
|
||||
return "<meta name=\"slug\" content=\"" + ctx.page().slug() + "\">";
|
||||
}
|
||||
};
|
||||
assertEquals("test.meta", c.key());
|
||||
assertTrue(c.capabilities().isEmpty(), "default capabilities() is none()");
|
||||
HeadContext ctx = new HeadContext(site(), page(), EN, null, null, null, false, false);
|
||||
assertEquals("<meta name=\"slug\" content=\"home\">", c.render(ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contentWidgetRendersAndSoftDegrades() {
|
||||
ContentWidget present = new ContentWidget() {
|
||||
@Override
|
||||
public String key() {
|
||||
return "test.box";
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderFragment render(WidgetView view) {
|
||||
return RenderFragment.of("<div>" + view.instanceId() + "</div>");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("widget.configurable");
|
||||
}
|
||||
};
|
||||
ContentWidget absent = new ContentWidget() {
|
||||
@Override
|
||||
public String key() {
|
||||
return "test.absent";
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderFragment render(WidgetView view) {
|
||||
return RenderFragment.empty();
|
||||
}
|
||||
};
|
||||
WidgetView view = new WidgetView(site(), page(), EN, "hero", false, Map.of());
|
||||
assertEquals("<div>hero</div>", present.render(view).html());
|
||||
assertTrue(present.capabilities().has("widget.configurable"));
|
||||
assertTrue(absent.render(view).isEmpty(), "soft-degrade yields an empty fragment");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageQualityCheckReportsAdvisoryFindings() {
|
||||
PageQualityCheck check = new PageQualityCheck() {
|
||||
@Override
|
||||
public String key() {
|
||||
return "test.title-length";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Finding> inspect(PageView page) {
|
||||
if (page.page().title().length() > 60) {
|
||||
return List.of(Finding.warning("title.too-long", "Title exceeds 60 characters"));
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
};
|
||||
assertTrue(check.inspect(new PageView(site(), page(), EN, null, "<html>")).isEmpty());
|
||||
|
||||
PageMeta longTitle = new PageMeta("p", "x".repeat(61), "", List.of(EN), EN, true, false);
|
||||
List<Finding> findings = check.inspect(new PageView(site(), longTitle, EN, null, "<html>"));
|
||||
assertEquals(1, findings.size());
|
||||
assertEquals(Severity.WARNING, findings.get(0).severity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointContributorDeclaresRoutesAndHandles() {
|
||||
EndpointContributor endpoint = new EndpointContributor() {
|
||||
@Override
|
||||
public String key() {
|
||||
return "test.robots";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
return List.of(Route.get("/robots.txt", Realm.TENANT));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest request) {
|
||||
// A handler can build absolute links from the full SiteView it receives.
|
||||
return RouteResponse.text(200, "Sitemap: " + request.site().baseUrl() + "/sitemap.xml");
|
||||
}
|
||||
};
|
||||
assertEquals(1, endpoint.routes().size());
|
||||
assertEquals("/robots.txt", endpoint.routes().get(0).pathPattern());
|
||||
assertFalse(endpoint.routes().get(0).posture().indexable(), "fail-safe posture by default");
|
||||
|
||||
RouteRequest request = new RouteRequest(site(), EN, "GET", "/robots.txt", null, null, null);
|
||||
RouteResponse response = endpoint.handle(request);
|
||||
assertEquals(200, response.status());
|
||||
assertEquals("Sitemap: https://example.test/sitemap.xml", new String(response.body(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void backupParticipantRoundTripsAndImportIsIdempotent() throws IOException {
|
||||
BackupParticipant participant = new BackupParticipant() {
|
||||
@Override
|
||||
public String key() {
|
||||
return "test.notes";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void export(BackupWriter out, SiteRef siteRef) throws IOException {
|
||||
try (OutputStream os = out.put("note.txt")) {
|
||||
os.write(("note for " + siteRef.id()).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void importInto(BackupReader in, SiteRef siteRef) throws IOException {
|
||||
if (in.has("note.txt")) {
|
||||
try (InputStream is = in.open("note.txt")) {
|
||||
is.readAllBytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
InMemoryBackup store = new InMemoryBackup();
|
||||
participant.export(store, new SiteRef("s1"));
|
||||
assertTrue(store.has("note.txt"));
|
||||
assertEquals("note for s1", new String(store.bytes("note.txt"), StandardCharsets.UTF_8));
|
||||
|
||||
// Importing twice must not throw and must not change state (idempotent restore).
|
||||
participant.importInto(store, new SiteRef("s1"));
|
||||
participant.importInto(store, new SiteRef("s1"));
|
||||
assertEquals("note for s1", new String(store.bytes("note.txt"), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** A trivial in-memory {@link BackupWriter}+{@link BackupReader}, proving the contract needs no host. */
|
||||
private static final class InMemoryBackup implements BackupWriter, BackupReader {
|
||||
|
||||
private final Map<String, byte[]> entries = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public OutputStream put(String entry) {
|
||||
return new ByteArrayOutputStream() {
|
||||
@Override
|
||||
public void close() {
|
||||
entries.put(entry, toByteArray());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean has(String entry) {
|
||||
return entries.containsKey(entry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream open(String entry) throws IOException {
|
||||
byte[] bytes = entries.get(entry);
|
||||
if (bytes == null) {
|
||||
throw new IOException("no such entry: " + entry);
|
||||
}
|
||||
return new ByteArrayInputStream(bytes);
|
||||
}
|
||||
|
||||
byte[] bytes(String entry) {
|
||||
return entries.get(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Immutability, defensive copying, and null-normalization across the SPI boundary records. */
|
||||
class BoundaryRecordsTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale FR = Locale.FRENCH;
|
||||
|
||||
private static SiteView site() {
|
||||
return new SiteView("s1", "Site", EN, List.of(EN), "https://example.test");
|
||||
}
|
||||
|
||||
private static PageMeta page() {
|
||||
return new PageMeta("home", "Home", "A page", List.of(EN), EN, true, false);
|
||||
}
|
||||
|
||||
// --- SiteView ---
|
||||
|
||||
@Test
|
||||
void siteViewNullLocalesNormalizeToEmpty() {
|
||||
assertTrue(new SiteView("s", "n", EN, null, null).locales().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteViewLocalesUnmodifiable() {
|
||||
assertThrows(UnsupportedOperationException.class, () -> site().locales().add(FR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteViewDefensivelyCopiesLocales() {
|
||||
List<Locale> source = new ArrayList<>(List.of(EN));
|
||||
SiteView s = new SiteView("s", "n", EN, source, null);
|
||||
source.add(FR);
|
||||
assertEquals(1, s.locales().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteViewRequiresIdNameDefaultLocale() {
|
||||
assertThrows(NullPointerException.class, () -> new SiteView(null, "n", EN, List.of(), null));
|
||||
assertThrows(NullPointerException.class, () -> new SiteView("s", null, EN, List.of(), null));
|
||||
assertThrows(NullPointerException.class, () -> new SiteView("s", "n", null, List.of(), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteViewBaseUrlIsOptionalAndStored() {
|
||||
assertNull(new SiteView("s", "n", EN, List.of(), null).baseUrl());
|
||||
assertEquals("https://example.test", site().baseUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteViewRefCarriesId() {
|
||||
assertEquals("s1", site().ref().id());
|
||||
}
|
||||
|
||||
// --- SiteRef / Alternate ---
|
||||
|
||||
@Test
|
||||
void siteRefRequiresId() {
|
||||
assertThrows(NullPointerException.class, () -> new SiteRef(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void alternateRequiresLocaleAndUrl() {
|
||||
assertThrows(NullPointerException.class, () -> new Alternate(null, "/x"));
|
||||
assertThrows(NullPointerException.class, () -> new Alternate(EN, null));
|
||||
}
|
||||
|
||||
// --- PageMeta ---
|
||||
|
||||
@Test
|
||||
void pageMetaNullTextNormalizesToEmpty() {
|
||||
PageMeta p = new PageMeta("s", null, null, null, null, false, false);
|
||||
assertEquals("", p.title());
|
||||
assertEquals("", p.description());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageMetaNullLocalesNormalizeToEmpty() {
|
||||
assertTrue(new PageMeta("s", null, null, null, null, false, false).availableLocales().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageMetaPrimaryLocaleOptionalAndFlags() {
|
||||
assertNull(new PageMeta("s", "t", "d", List.of(), null, false, false).primaryLocale());
|
||||
assertEquals(EN, page().primaryLocale());
|
||||
assertTrue(page().published());
|
||||
assertFalse(page().noindex());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageMetaRequiresSlug() {
|
||||
assertThrows(NullPointerException.class, () -> new PageMeta(null, "t", "d", List.of(), EN, true, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageMetaLocalesUnmodifiable() {
|
||||
assertThrows(UnsupportedOperationException.class, () -> page().availableLocales().add(FR));
|
||||
}
|
||||
|
||||
// --- HeadContext ---
|
||||
|
||||
@Test
|
||||
void headContextNullAlternatesNormalizeToEmpty() {
|
||||
HeadContext h = new HeadContext(site(), page(), EN, null, null, null, false, false);
|
||||
assertTrue(h.alternates().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void headContextAlternatesUnmodifiableAndCopied() {
|
||||
List<Alternate> source = new ArrayList<>();
|
||||
source.add(new Alternate(EN, "/x"));
|
||||
HeadContext h = new HeadContext(site(), page(), EN, null, null, source, false, false);
|
||||
source.add(new Alternate(FR, "/y"));
|
||||
assertEquals(1, h.alternates().size());
|
||||
assertThrows(UnsupportedOperationException.class, () -> h.alternates().add(new Alternate(FR, "/z")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void headContextRequiresSitePageLocale() {
|
||||
assertThrows(NullPointerException.class, () -> new HeadContext(null, page(), EN, null, null, null, false, false));
|
||||
assertThrows(NullPointerException.class, () -> new HeadContext(site(), null, EN, null, null, null, false, false));
|
||||
assertThrows(NullPointerException.class, () -> new HeadContext(site(), page(), null, null, null, null, false, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void headContextAllowsNullCanonicalAndXDefault() {
|
||||
HeadContext h = new HeadContext(site(), page(), EN, null, null, null, false, false);
|
||||
assertNull(h.canonical());
|
||||
assertNull(h.xDefault());
|
||||
// base URL is reached through the site, not duplicated on the context
|
||||
assertEquals("https://example.test", h.site().baseUrl());
|
||||
}
|
||||
|
||||
// --- WidgetView ---
|
||||
|
||||
@Test
|
||||
void widgetViewNullConfigNormalizesToEmpty() {
|
||||
assertTrue(new WidgetView(site(), page(), EN, "inst", false, null).config().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void widgetViewConfigUnmodifiableAndCopied() {
|
||||
Map<String, Object> source = new HashMap<>();
|
||||
source.put("k", "v");
|
||||
WidgetView w = new WidgetView(site(), page(), EN, "inst", false, source);
|
||||
source.put("k2", "v2");
|
||||
assertEquals(1, w.config().size());
|
||||
assertThrows(UnsupportedOperationException.class, () -> w.config().put("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void widgetViewChromeFlagStored() {
|
||||
assertTrue(new WidgetView(site(), page(), EN, "inst", true, Map.of()).isChrome());
|
||||
assertFalse(new WidgetView(site(), page(), EN, "inst", false, Map.of()).isChrome());
|
||||
}
|
||||
|
||||
@Test
|
||||
void widgetViewRequiresInstanceId() {
|
||||
assertThrows(NullPointerException.class, () -> new WidgetView(site(), page(), EN, null, false, Map.of()));
|
||||
}
|
||||
|
||||
// --- PageView ---
|
||||
|
||||
@Test
|
||||
void pageViewNullHtmlNormalizesToEmpty() {
|
||||
assertEquals("", new PageView(site(), page(), EN, null, null).resolvedHtml());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageViewCanonicalOptional() {
|
||||
assertNull(new PageView(site(), page(), EN, null, "<html>").canonical());
|
||||
assertEquals("https://example.test/home", new PageView(site(), page(), EN, "https://example.test/home", "<html>").canonical());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageViewRequiresSite() {
|
||||
assertThrows(NullPointerException.class, () -> new PageView(null, page(), EN, null, "<html>"));
|
||||
}
|
||||
|
||||
// --- Route ---
|
||||
|
||||
@Test
|
||||
void routeNullPostureBecomesSafeDefault() {
|
||||
assertEquals(SurfacePosture.safeDefault(), new Route("GET", "/x", Realm.TENANT, null).posture());
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeRequiresMethodPathRealm() {
|
||||
assertThrows(NullPointerException.class, () -> new Route(null, "/x", Realm.TENANT, null));
|
||||
assertThrows(NullPointerException.class, () -> new Route("GET", null, Realm.TENANT, null));
|
||||
assertThrows(NullPointerException.class, () -> new Route("GET", "/x", null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeGetFactory() {
|
||||
Route r = Route.get("/sitemap.xml", Realm.APPLICATION);
|
||||
assertEquals("GET", r.method());
|
||||
assertEquals(Realm.APPLICATION, r.realm());
|
||||
assertEquals(SurfacePosture.safeDefault(), r.posture());
|
||||
}
|
||||
|
||||
// --- RouteRequest ---
|
||||
|
||||
@Test
|
||||
void routeRequestCarriesFullSiteView() {
|
||||
RouteRequest req = new RouteRequest(site(), EN, "GET", "/robots.txt", null, null, null);
|
||||
assertEquals("https://example.test", req.site().baseUrl());
|
||||
assertEquals("s1", req.site().id());
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeRequestBodyCopiedOnInput() {
|
||||
byte[] source = {1, 2, 3};
|
||||
RouteRequest req = new RouteRequest(site(), EN, "GET", "/x", null, null, source);
|
||||
source[0] = 9;
|
||||
assertArrayEquals(new byte[] {1, 2, 3}, req.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeRequestBodyCopiedOnAccess() {
|
||||
RouteRequest req = new RouteRequest(site(), EN, "GET", "/x", null, null, new byte[] {1, 2, 3});
|
||||
req.body()[0] = 9;
|
||||
assertArrayEquals(new byte[] {1, 2, 3}, req.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeRequestNullBodyBecomesEmpty() {
|
||||
assertEquals(0, new RouteRequest(site(), EN, "GET", "/x", null, null, null).body().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeRequestQueryDeeplyCopiedAndUnmodifiable() {
|
||||
Map<String, List<String>> query = new HashMap<>();
|
||||
query.put("k", new ArrayList<>(List.of("v")));
|
||||
RouteRequest req = new RouteRequest(site(), EN, "GET", "/x", query, null, null);
|
||||
query.get("k").add("v2");
|
||||
query.put("k2", List.of("x"));
|
||||
assertEquals(1, req.query().size());
|
||||
assertEquals(1, req.query().get("k").size());
|
||||
assertThrows(UnsupportedOperationException.class, () -> req.query().put("z", List.of()));
|
||||
assertThrows(UnsupportedOperationException.class, () -> req.query().get("k").add("w"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeRequestHeadersUnmodifiable() {
|
||||
RouteRequest req = new RouteRequest(site(), EN, "GET", "/x", null, Map.of("h", "v"), null);
|
||||
assertThrows(UnsupportedOperationException.class, () -> req.headers().put("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeRequestRequiresSiteLocaleMethodPath() {
|
||||
assertThrows(NullPointerException.class, () -> new RouteRequest(null, EN, "GET", "/x", null, null, null));
|
||||
assertThrows(NullPointerException.class, () -> new RouteRequest(site(), null, "GET", "/x", null, null, null));
|
||||
assertThrows(NullPointerException.class, () -> new RouteRequest(site(), EN, null, "/x", null, null, null));
|
||||
assertThrows(NullPointerException.class, () -> new RouteRequest(site(), EN, "GET", null, null, null, null));
|
||||
}
|
||||
|
||||
// --- RouteResponse ---
|
||||
|
||||
@Test
|
||||
void routeResponseBodyCopiedInAndOut() {
|
||||
byte[] source = {1, 2};
|
||||
RouteResponse resp = new RouteResponse(200, null, source);
|
||||
source[0] = 9;
|
||||
assertArrayEquals(new byte[] {1, 2}, resp.body());
|
||||
resp.body()[0] = 9;
|
||||
assertArrayEquals(new byte[] {1, 2}, resp.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeResponseNullHeadersBecomeEmpty() {
|
||||
assertTrue(new RouteResponse(200, null, null).headers().isEmpty());
|
||||
}
|
||||
|
||||
// --- SPI 0.3.1: PageMeta.sourceKey + WidgetView.path (old-arity ctors are binary API) -------------------
|
||||
|
||||
@org.junit.jupiter.api.Test
|
||||
void pageMetaOldArityYieldsAKernelPage() {
|
||||
PageMeta meta = new PageMeta("about", "About", "", java.util.List.of(), null, true, false);
|
||||
org.junit.jupiter.api.Assertions.assertNull(meta.sourceKey(), "old-arity ⇒ kernel page");
|
||||
org.junit.jupiter.api.Assertions.assertFalse(meta.isVirtual());
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.Test
|
||||
void pageMetaWithASourceKeyIsVirtualAndKeepsTheCompositeSlug() {
|
||||
PageMeta meta = new PageMeta("blog:my-post", "My post", "", java.util.List.of(), null, true, false, "blog");
|
||||
org.junit.jupiter.api.Assertions.assertTrue(meta.isVirtual());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("blog", meta.sourceKey());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("blog:my-post", meta.slug(), "the composite id is accepted verbatim");
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.Test
|
||||
void widgetViewPathNormalizesNullAndOldArityCtorsMaterializeEmpties() {
|
||||
SiteView site = new SiteView("acme", "Acme", java.util.Locale.ENGLISH, java.util.List.of(), null);
|
||||
PageMeta page = new PageMeta("home", "", "", java.util.List.of(), null, true, false);
|
||||
WidgetView full = new WidgetView(site, page, java.util.Locale.ENGLISH, "i", false,
|
||||
java.util.Map.of(), java.util.Map.of(), null);
|
||||
org.junit.jupiter.api.Assertions.assertEquals("", full.path(), "null path normalizes to empty");
|
||||
WidgetView preQuery = new WidgetView(site, page, java.util.Locale.ENGLISH, "i", false, java.util.Map.of());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("", preQuery.path());
|
||||
org.junit.jupiter.api.Assertions.assertEquals(java.util.Map.of(), preQuery.query());
|
||||
WidgetView prePath = new WidgetView(site, page, java.util.Locale.ENGLISH, "i", false,
|
||||
java.util.Map.of(), java.util.Map.of("q", "x"));
|
||||
org.junit.jupiter.api.Assertions.assertEquals("", prePath.path());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("x", prePath.query().get("q"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CapabilitiesTest {
|
||||
|
||||
@Test
|
||||
void noneIsEmpty() {
|
||||
assertTrue(Capabilities.none().isEmpty());
|
||||
assertFalse(Capabilities.none().has("anything"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ofHoldsFlags() {
|
||||
Capabilities c = Capabilities.of("a", "b");
|
||||
assertTrue(c.has("a"));
|
||||
assertTrue(c.has("b"));
|
||||
assertFalse(c.has("c"));
|
||||
assertEquals(2, c.flags().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ofWithNoArgsIsNoneInstance() {
|
||||
assertSame(Capabilities.none(), Capabilities.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ofDeduplicates() {
|
||||
assertEquals(1, Capabilities.of("a", "a").flags().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void flagsAreUnmodifiable() {
|
||||
Capabilities c = Capabilities.of("a");
|
||||
assertThrows(UnsupportedOperationException.class, () -> c.flags().add("b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructorDefensivelyCopies() {
|
||||
Set<String> source = new HashSet<>(Set.of("a"));
|
||||
Capabilities c = new Capabilities(source);
|
||||
source.add("b");
|
||||
assertFalse(c.has("b"));
|
||||
assertEquals(1, c.flags().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullSetNormalizesToEmpty() {
|
||||
assertTrue(new Capabilities(null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullFlagIsRejected() {
|
||||
assertThrows(NullPointerException.class, () -> Capabilities.of("a", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hasNullIsFalse() {
|
||||
assertFalse(Capabilities.of("a").has(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withAddsWithoutMutatingOriginal() {
|
||||
Capabilities a = Capabilities.of("a");
|
||||
Capabilities b = a.with("b");
|
||||
assertTrue(b.has("a"));
|
||||
assertTrue(b.has("b"));
|
||||
assertFalse(a.has("b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withNothingReturnsSameInstance() {
|
||||
Capabilities a = Capabilities.of("a");
|
||||
assertSame(a, a.with());
|
||||
}
|
||||
|
||||
@Test
|
||||
void equalityIsOrderIndependent() {
|
||||
assertEquals(Capabilities.of("a", "b"), Capabilities.of("b", "a"));
|
||||
assertEquals(Capabilities.of("a", "b").hashCode(), Capabilities.of("b", "a").hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* {@link ContentRef}'s dispatch surface and shape normalization. The dispatch helpers must mirror the kernel
|
||||
* page's semantics EXACTLY (localized-override-else-default path fallback, empty locales = site-default only,
|
||||
* primary-locale preference) — that parity is what lets virtual content run the same locale-dispatch ladder as
|
||||
* a real page. Pure unit tests: no Spring, no kernel.
|
||||
*/
|
||||
class ContentRefTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
private static final Locale FR = Locale.of("fr");
|
||||
|
||||
private static ContentRef ref(Map<String, String> localizedPaths, List<Locale> locales) {
|
||||
return ContentRef.of("my-post", "/blog/my-post", localizedPaths, locales,
|
||||
Map.of("en", "My post", "es", "Mi entrada"), Map.of("en", "A post"),
|
||||
"__plugin__/blog/entry-classic", Instant.parse("2026-07-16T12:00:00Z"));
|
||||
}
|
||||
|
||||
// --- dispatch-surface parity with Page ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void pathForReturnsLocalizedOverrideElseDefault() {
|
||||
ContentRef r = ref(Map.of("es", "/blog/mi-entrada"), List.of(EN, ES));
|
||||
assertEquals("/blog/mi-entrada", r.pathFor(ES), "localized override wins");
|
||||
assertEquals("/blog/my-post", r.pathFor(EN), "no override → the default path (the Page fallback rule)");
|
||||
assertEquals("/blog/my-post", r.pathFor(FR), "an unlisted locale also falls back — availability is hasLocale's job, not pathFor's");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyLocalesMeansSiteDefaultOnly() {
|
||||
ContentRef r = ref(Map.of(), List.of());
|
||||
assertTrue(r.hasLocale(EN, EN), "empty locales → available in the site default");
|
||||
assertFalse(r.hasLocale(ES, EN), "empty locales → NOT available in any other locale");
|
||||
}
|
||||
|
||||
@Test
|
||||
void declaredLocalesGovernAvailability() {
|
||||
ContentRef r = ref(Map.of(), List.of(EN, ES));
|
||||
assertTrue(r.hasLocale(ES, FR), "a declared locale is available regardless of the site default");
|
||||
assertFalse(r.hasLocale(FR, FR), "an undeclared locale is not available even as site default");
|
||||
}
|
||||
|
||||
@Test
|
||||
void primaryLocalePrefersTheSiteDefault() {
|
||||
assertEquals(EN, ref(Map.of(), List.of(EN, ES)).primaryLocale(EN), "default available → default");
|
||||
assertEquals(ES, ref(Map.of(), List.of(ES, FR)).primaryLocale(EN), "default unavailable → first declared");
|
||||
assertEquals(EN, ref(Map.of(), List.of()).primaryLocale(EN), "empty → default");
|
||||
}
|
||||
|
||||
@Test
|
||||
void titleAndDescriptionFallBackToAnyPresentValue() {
|
||||
// An ORDERED input map makes the "falls back to a present value" contract deterministic to assert
|
||||
// (Map.of is unordered; the fallback picks the map's first value, whichever that is).
|
||||
Map<String, String> titles = new LinkedHashMap<>();
|
||||
titles.put("en", "My post");
|
||||
titles.put("es", "Mi entrada");
|
||||
ContentRef r = ContentRef.of("my-post", "/blog/my-post", Map.of(), List.of(EN, ES, FR),
|
||||
titles, Map.of("en", "A post"), "__plugin__/blog/entry-classic", null);
|
||||
assertEquals("My post", r.titleFor(EN));
|
||||
assertEquals("Mi entrada", r.titleFor(ES));
|
||||
assertEquals("My post", r.titleFor(FR), "untranslated locale falls back to a present value");
|
||||
assertEquals("A post", r.descriptionFor(FR), "same rule for descriptions");
|
||||
}
|
||||
|
||||
// --- normalization (shape only) ------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void identityFieldsAreRequiredAndTrimmed() {
|
||||
assertThrows(NullPointerException.class, () -> ContentRef.of(null, "/p", Map.of(), List.of(),
|
||||
Map.of(), Map.of(), "t", null));
|
||||
assertThrows(IllegalArgumentException.class, () -> ContentRef.of(" ", "/p", Map.of(), List.of(),
|
||||
Map.of(), Map.of(), "t", null));
|
||||
assertThrows(IllegalArgumentException.class, () -> ContentRef.of("id", "/p", Map.of(), List.of(),
|
||||
Map.of(), Map.of(), " ", null));
|
||||
ContentRef r = ContentRef.of(" id ", " /p ", Map.of(), List.of(), Map.of(), Map.of(), " t ", null);
|
||||
assertEquals("id", r.id());
|
||||
assertEquals("/p", r.path());
|
||||
assertEquals("t", r.bodyTemplate());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankLocalizedPathsAreDroppedSoTheLocaleFallsBack() {
|
||||
// A blank override must NOT become a routing key for "" — it must fall back to the default path,
|
||||
// exactly as the page model drops unusable localized paths.
|
||||
Map<String, String> raw = new LinkedHashMap<>();
|
||||
raw.put("es", " ");
|
||||
raw.put("fr", "/blog/mon-billet");
|
||||
raw.put(null, "/x");
|
||||
ContentRef r = ref(raw, List.of(EN, ES, FR));
|
||||
assertEquals("/blog/my-post", r.pathFor(ES), "blank override dropped → default path");
|
||||
assertEquals("/blog/mon-billet", r.pathFor(FR), "real override kept (trimmed)");
|
||||
assertEquals(1, r.localizedPaths().size(), "null keys and blank values are gone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullCollectionsNormalizeToEmpty() {
|
||||
ContentRef r = new ContentRef("id", "/p", null, null, null, null, null, "t",
|
||||
true, null, false, null, null, null);
|
||||
assertEquals(Map.of(), r.localizedPaths());
|
||||
assertEquals(List.of(), r.locales());
|
||||
assertEquals(Map.of(), r.title());
|
||||
assertEquals(Map.of(), r.description());
|
||||
assertEquals(Map.of(), r.params());
|
||||
assertEquals("", r.titleFor(EN), "no titles → empty, never null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void paramsKeepInsertionOrderAndCoerceNullValues() {
|
||||
Map<String, String> raw = new LinkedHashMap<>();
|
||||
raw.put("zeta", "1");
|
||||
raw.put("alpha", null);
|
||||
raw.put(" ", "dropped");
|
||||
ContentRef r = new ContentRef("id", "/p", Map.of(), List.of(), Map.of(), Map.of(), null, "t",
|
||||
true, null, false, null, null, raw);
|
||||
assertEquals(List.of("zeta", "alpha"), List.copyOf(r.params().keySet()), "insertion order preserved");
|
||||
assertEquals("", r.params().get("alpha"), "null value coerced to empty (the params convention)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectionsAreImmutable() {
|
||||
ContentRef r = ref(Map.of("es", "/blog/mi-entrada"), List.of(EN, ES));
|
||||
assertThrows(UnsupportedOperationException.class, () -> r.localizedPaths().put("fr", "/x"));
|
||||
assertThrows(UnsupportedOperationException.class, () -> r.locales().add(FR));
|
||||
assertThrows(UnsupportedOperationException.class, () -> r.params().put("k", "v"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ofFactoryBuildsAPublishedRefWithSafeDefaults() {
|
||||
ContentRef r = ref(Map.of(), List.of(EN));
|
||||
assertTrue(r.published(), "the of() factory builds published refs");
|
||||
assertFalse(r.noindex());
|
||||
assertEquals(Instant.parse("2026-07-16T12:00:00Z"), r.updatedAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FactoriesTest {
|
||||
|
||||
// --- RenderFragment ---
|
||||
|
||||
@Test
|
||||
void renderFragmentEmptyVariantsAreEmptyAndShared() {
|
||||
assertTrue(RenderFragment.empty().isEmpty());
|
||||
assertTrue(RenderFragment.of(null).isEmpty());
|
||||
assertTrue(RenderFragment.of("").isEmpty());
|
||||
assertSame(RenderFragment.empty(), RenderFragment.of(null));
|
||||
assertSame(RenderFragment.empty(), RenderFragment.of(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void renderFragmentOfHoldsMarkup() {
|
||||
RenderFragment f = RenderFragment.of("<div>");
|
||||
assertEquals("<div>", f.html());
|
||||
assertFalse(f.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renderFragmentNullHtmlNormalizes() {
|
||||
assertEquals("", new RenderFragment(null).html());
|
||||
}
|
||||
|
||||
// --- RouteResponse factories ---
|
||||
|
||||
@Test
|
||||
void routeResponseOk() {
|
||||
RouteResponse r = RouteResponse.ok(new byte[] {1});
|
||||
assertEquals(200, r.status());
|
||||
assertEquals(1, r.body().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeResponseNotFound() {
|
||||
RouteResponse r = RouteResponse.notFound();
|
||||
assertEquals(404, r.status());
|
||||
assertEquals(0, r.body().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeResponseText() {
|
||||
RouteResponse r = RouteResponse.text(200, "hi");
|
||||
assertEquals("text/plain; charset=utf-8", r.headers().get("Content-Type"));
|
||||
assertEquals("hi", new String(r.body(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeResponseTextNullBody() {
|
||||
assertEquals(0, RouteResponse.text(204, null).body().length);
|
||||
}
|
||||
|
||||
// --- SurfacePosture ---
|
||||
|
||||
@Test
|
||||
void surfacePostureSafeDefaultIsAllFalse() {
|
||||
SurfacePosture p = SurfacePosture.safeDefault();
|
||||
assertFalse(p.indexable());
|
||||
assertFalse(p.inSitemap());
|
||||
assertFalse(p.cacheable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void surfacePostureDiscoverableIndexesButDoesNotCache() {
|
||||
SurfacePosture p = SurfacePosture.discoverable();
|
||||
assertTrue(p.indexable());
|
||||
assertTrue(p.inSitemap());
|
||||
assertFalse(p.cacheable());
|
||||
}
|
||||
|
||||
// --- Finding ---
|
||||
|
||||
@Test
|
||||
void findingSeverityFactories() {
|
||||
assertEquals(Severity.INFO, Finding.info("c", "m").severity());
|
||||
assertEquals(Severity.WARNING, Finding.warning("c", "m").severity());
|
||||
assertEquals(Severity.ERROR, Finding.error("c", "m").severity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findingNullMessageNormalizes() {
|
||||
assertEquals("", new Finding(Severity.INFO, "c", null).message());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findingRequiresSeverityAndCode() {
|
||||
assertThrows(NullPointerException.class, () -> new Finding(null, "c", "m"));
|
||||
assertThrows(NullPointerException.class, () -> new Finding(Severity.INFO, null, "m"));
|
||||
}
|
||||
|
||||
// --- enums ---
|
||||
|
||||
@Test
|
||||
void realmHasBothDomains() {
|
||||
assertEquals(2, Realm.values().length);
|
||||
assertNotNull(Realm.valueOf("APPLICATION"));
|
||||
assertNotNull(Realm.valueOf("TENANT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void severityHasThreeLevels() {
|
||||
assertEquals(3, Severity.values().length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The records SPI 0.5.0 adds or extends: frozen, null-normalized, and the old constructors keep their meaning. */
|
||||
class K2RecordsTest {
|
||||
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(), null);
|
||||
|
||||
// --- RouteRequest ----------------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void theOldSevenArgumentFormHasNoFormNoClientIpAndAnEmptyOrigin() {
|
||||
RouteRequest old = new RouteRequest(SITE, Locale.ENGLISH, "GET", "/x", null, null, null);
|
||||
assertEquals(Map.of(), old.form());
|
||||
assertNull(old.clientIp());
|
||||
assertEquals("", old.origin());
|
||||
}
|
||||
|
||||
@Test
|
||||
void headerNamesAreLowercasedAndLookupsIgnoreCase() {
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
headers.put("User-Agent", "UA");
|
||||
headers.put("user-agent", "second spelling loses");
|
||||
headers.put("X-A", "1");
|
||||
headers.put(null, "dropped");
|
||||
headers.put("X-Null", null);
|
||||
RouteRequest req = new RouteRequest(SITE, Locale.ENGLISH, "GET", "/x", null, headers, null);
|
||||
assertEquals(List.of("user-agent", "x-a"), new ArrayList<>(req.headers().keySet()));
|
||||
assertEquals("UA", req.headers().get("USER-AGENT"));
|
||||
assertTrue(req.headers().containsKey("x-A"));
|
||||
assertThrows(UnsupportedOperationException.class, () -> req.headers().put("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void formIsDeepCopiedAndParamPrefersTheQuery() {
|
||||
Map<String, List<String>> form = new HashMap<>();
|
||||
List<String> names = new ArrayList<>(List.of("Ana"));
|
||||
form.put("name", names);
|
||||
form.put("both", List.of("form"));
|
||||
form.put("none", List.of());
|
||||
RouteRequest req = new RouteRequest(SITE, Locale.ENGLISH, "POST", "/x", Map.of("both", List.of("query")),
|
||||
null, null, form, " ", null);
|
||||
names.add("mutated");
|
||||
assertEquals(List.of("Ana"), req.form().get("name"), "deep-copied");
|
||||
assertThrows(UnsupportedOperationException.class, () -> req.form().get("name").add("x"));
|
||||
assertEquals(Optional.of("query"), req.param("both"));
|
||||
assertEquals(Optional.of("Ana"), req.param("name"));
|
||||
assertEquals(Optional.empty(), req.param("none"));
|
||||
assertEquals(Optional.empty(), req.param("absent"));
|
||||
assertNull(req.clientIp(), "a blank client IP is unknown");
|
||||
assertEquals("", req.origin());
|
||||
assertThrows(NullPointerException.class, () -> req.param(null));
|
||||
}
|
||||
|
||||
// --- Route -----------------------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void routesAreNotAnonymousUnlessDeclared() {
|
||||
assertFalse(new Route("POST", "/x", Realm.TENANT, null).anonymous());
|
||||
assertFalse(Route.get("/x", Realm.TENANT).anonymous());
|
||||
Route anonymous = Route.anonymousPost("/contact/send", null);
|
||||
assertTrue(anonymous.anonymous());
|
||||
assertEquals("POST", anonymous.method());
|
||||
assertEquals(Realm.TENANT, anonymous.realm());
|
||||
assertEquals(SurfacePosture.safeDefault(), anonymous.posture());
|
||||
}
|
||||
|
||||
// --- FileEntry, StarterPage, InstallResult ---------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void fileEntryNormalizesSizeAndTime() {
|
||||
FileEntry dir = new FileEntry("d", true, 4096, null);
|
||||
assertEquals(0, dir.size(), "a folder has no size");
|
||||
assertEquals(Instant.EPOCH, dir.lastModified());
|
||||
assertEquals(0, new FileEntry("f", false, -5, Instant.EPOCH).size());
|
||||
assertThrows(NullPointerException.class, () -> new FileEntry(null, false, 1, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void starterPageFreezesTitlesAndNormalizesBlankLogic() {
|
||||
Map<String, String> titles = new HashMap<>();
|
||||
titles.put("en", "Contact");
|
||||
titles.put(null, "x");
|
||||
titles.put("es", null);
|
||||
StarterPage page = new StarterPage("contact", "/contact", titles, "<p/>", " ", true);
|
||||
assertEquals(Map.of("en", "Contact"), page.titles());
|
||||
assertNull(page.logic());
|
||||
assertThrows(UnsupportedOperationException.class, () -> page.titles().put("fr", "x"));
|
||||
assertEquals(Map.of(), new StarterPage("s", "/s", null, "", null, false).titles());
|
||||
assertThrows(NullPointerException.class, () -> new StarterPage(null, "/s", null, "", null, false));
|
||||
assertThrows(NullPointerException.class, () -> new StarterPage("s", "/s", null, null, null, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void installResultFreezesItsFindings() {
|
||||
List<Finding> findings = new ArrayList<>(List.of(Finding.error("x", "y")));
|
||||
InstallResult result = new InstallResult(InstallResult.Outcome.DRAFT_BLOCKED, "/c", findings);
|
||||
findings.clear();
|
||||
assertEquals(1, result.blocking().size());
|
||||
assertEquals(List.of(), new InstallResult(InstallResult.Outcome.PUBLISHED, "/c", null).blocking());
|
||||
assertThrows(NullPointerException.class, () -> new InstallResult(null, "/c", null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.RunwaySpi;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The records and contracts SPI 0.6.0 adds: frozen, null-normalized, and their small helpers. */
|
||||
class K3RecordsTest {
|
||||
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
|
||||
private static ContentRef ref(String id) {
|
||||
return ContentRef.of(id, "/" + id, Map.of(), List.of(), Map.of(), Map.of(), "__plugin__/x/t", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSpiIsAtOneZero() {
|
||||
assertEquals("1.0.0", RunwaySpi.VERSION);
|
||||
}
|
||||
|
||||
// --- LocalizedUrl ----------------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void aLocalizedUrlWithoutAnOverrideIsItsOwnCanonical() {
|
||||
LocalizedUrl url = new LocalizedUrl(Locale.ENGLISH, "/about", null);
|
||||
assertEquals("/about", url.canonical());
|
||||
assertEquals("/about", new LocalizedUrl(Locale.ENGLISH, "/about", " ").canonical());
|
||||
assertEquals("https://elsewhere.test/x", new LocalizedUrl(Locale.ENGLISH, "/about",
|
||||
"https://elsewhere.test/x").canonical(), "an override is kept as given");
|
||||
}
|
||||
|
||||
@Test
|
||||
void absoluteAndAlternateUseTheRealPathNeverTheCanonical() {
|
||||
LocalizedUrl url = new LocalizedUrl(ES, "/es/acerca", "https://elsewhere.test/x");
|
||||
assertEquals("https://acme.test/es/acerca", url.absolute("https://acme.test"));
|
||||
assertEquals("https://acme.test/es/acerca", url.absolute("https://acme.test/"), "a trailing slash is dropped");
|
||||
assertEquals("/es/acerca", url.absolute(""));
|
||||
Alternate alternate = url.alternate("https://acme.test");
|
||||
assertEquals(ES, alternate.locale());
|
||||
assertEquals("https://acme.test/es/acerca", alternate.url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLocalizedUrlNeedsALocaleAndAPath() {
|
||||
assertThrows(NullPointerException.class, () -> new LocalizedUrl(null, "/x", null));
|
||||
assertThrows(NullPointerException.class, () -> new LocalizedUrl(Locale.ENGLISH, null, null));
|
||||
assertThrows(IllegalArgumentException.class, () -> new LocalizedUrl(Locale.ENGLISH, " ", null));
|
||||
assertThrows(NullPointerException.class, () -> new LocalizedUrl(Locale.ENGLISH, "/x", null).absolute(null));
|
||||
}
|
||||
|
||||
// --- CatalogEntry ----------------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void anEntryIsFrozenAndNamesItselfByComposite() {
|
||||
List<LocalizedUrl> urls = new ArrayList<>(List.of(new LocalizedUrl(Locale.ENGLISH, "/hello", null)));
|
||||
CatalogEntry entry = new CatalogEntry("blog", ref("hello"), urls, "/hello");
|
||||
urls.clear();
|
||||
assertEquals(1, entry.urls().size(), "the list is copied");
|
||||
assertThrows(UnsupportedOperationException.class, () -> entry.urls().add(null));
|
||||
assertEquals("blog:hello", entry.compositeId());
|
||||
assertFalse(entry.isPage());
|
||||
assertTrue(new CatalogEntry(ContentCatalogView.PAGES_SOURCE, ref("about"), List.of(), null).isPage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pathForFallsBackToThePrimaryLocalesRealAddress() {
|
||||
// An item that exists only in Spanish on an English-default site (review n6): an English context links its
|
||||
// Spanish URL — never the unprefixed English path, which 404s.
|
||||
CatalogEntry entry = new CatalogEntry("blog", ref("hola"),
|
||||
List.of(new LocalizedUrl(ES, "/es/hola", null)), "/es/hola");
|
||||
assertEquals("/es/hola", entry.pathFor(ES));
|
||||
assertEquals("/es/hola", entry.pathFor(Locale.ENGLISH));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingXDefaultFallsBackToTheFirstUrlThenTheRefPath() {
|
||||
assertEquals("/es/hola", new CatalogEntry("blog", ref("hola"),
|
||||
List.of(new LocalizedUrl(ES, "/es/hola", null)), null).xDefaultPath());
|
||||
assertEquals("/hola", new CatalogEntry("blog", ref("hola"), null, "").xDefaultPath());
|
||||
assertEquals(List.of(), new CatalogEntry("blog", ref("hola"), null, null).urls());
|
||||
}
|
||||
|
||||
// --- events ----------------------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void lifecycleWholesaleIsDeletedOrRestoredOnly() {
|
||||
for (SiteLifecycleEvent.Kind kind : SiteLifecycleEvent.Kind.values()) {
|
||||
boolean expected = kind == SiteLifecycleEvent.Kind.DELETED || kind == SiteLifecycleEvent.Kind.RESTORED;
|
||||
assertEquals(expected, new SiteLifecycleEvent("acme", kind, false, true).wholesale(), kind.name());
|
||||
}
|
||||
assertThrows(NullPointerException.class, () -> new SiteLifecycleEvent(null, SiteLifecycleEvent.Kind.CREATED,
|
||||
false, true));
|
||||
assertThrows(NullPointerException.class, () -> new SiteLifecycleEvent("acme", null, false, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCatalogChangeNormalizesItsUrlLists() {
|
||||
List<LocalizedUrl> previous = new ArrayList<>(List.of(new LocalizedUrl(Locale.ENGLISH, "/old", null)));
|
||||
CatalogChange change = new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", "about", null, previous,
|
||||
null, true);
|
||||
previous.clear();
|
||||
assertEquals(1, change.previousUrls().size());
|
||||
assertEquals(List.of(), change.currentUrls());
|
||||
assertThrows(UnsupportedOperationException.class, () -> change.previousUrls().clear());
|
||||
assertThrows(NullPointerException.class, () -> new CatalogChange(null, CatalogChange.Cause.SITE, null, null,
|
||||
null, null, null, true));
|
||||
assertThrows(NullPointerException.class, () -> new CatalogChange("acme", null, null, null, null, null, null,
|
||||
true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSettingsChangeNamesSiteAndPlugin() {
|
||||
assertEquals("contact", new SettingsChange("acme", "contact", false).pluginId());
|
||||
assertThrows(NullPointerException.class, () -> new SettingsChange("acme", null, true));
|
||||
}
|
||||
|
||||
// --- listener and screen contracts -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void aListenerDefaultsToTheConsumerPhaseAndIgnoresEverything() {
|
||||
SiteEventListener listener = new SiteEventListener() { };
|
||||
assertEquals(SiteEventListener.Phase.CONSUMER, listener.phase());
|
||||
listener.onSiteLifecycle(new SiteLifecycleEvent("acme", SiteLifecycleEvent.Kind.UPDATED, false, true));
|
||||
listener.onSettingsChanged(new SettingsChange("acme", "x", true));
|
||||
listener.onCatalogChanged(new CatalogChange("acme", CatalogChange.Cause.SITE, null, null, null, null, null,
|
||||
true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConsoleScreenAnnotationIsVisibleAtRuntimeAndNamesTheShellContract() {
|
||||
Retention retention = ConsoleScreen.class.getAnnotation(Retention.class);
|
||||
assertEquals(RetentionPolicy.RUNTIME, retention.value(), "the host's advice selects by it at runtime");
|
||||
assertEquals("operator/op-layout", ConsoleScreen.LAYOUT_VIEW);
|
||||
assertEquals("contentTemplate", ConsoleScreen.CONTENT_TEMPLATE);
|
||||
assertEquals("pageTitleKey", ConsoleScreen.PAGE_TITLE_KEY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** What SPI 1.0.0 adds or fixes on the boundary records: {@code HeadContext.origin} and {@code CatalogEntry.pathFor}. */
|
||||
class K4RecordsTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
private static final Locale FR = Locale.FRENCH;
|
||||
|
||||
private static SiteView site() {
|
||||
return new SiteView("s1", "Site", EN, List.of(EN, ES), null);
|
||||
}
|
||||
|
||||
private static PageMeta page() {
|
||||
return new PageMeta("home", "Home", "A page", List.of(EN), EN, true, false);
|
||||
}
|
||||
|
||||
// --- HeadContext.origin -----------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void theOriginIsCarriedWithoutATrailingSlashAndNeverNull() {
|
||||
assertEquals("https://acme.test", new HeadContext(site(), page(), EN, "/", null, List.of(), false, false,
|
||||
null, null, "https://acme.test/").origin());
|
||||
assertEquals("http://localhost:8080", new HeadContext(site(), page(), EN, "/", null, List.of(), false, false,
|
||||
null, null, "http://localhost:8080").origin());
|
||||
assertEquals("", new HeadContext(site(), page(), EN, "/", null, List.of(), false, false, null, null, null)
|
||||
.origin());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyOlderConstructorLeavesTheOriginUnknown() {
|
||||
assertEquals("", new HeadContext(site(), page(), EN, "/", null, List.of(), false, false, SeoTags.empty(),
|
||||
IconHints.NONE).origin(), "the 0.6.0 form");
|
||||
assertEquals("", new HeadContext(site(), page(), EN, "/", null, List.of(), false, false, SeoTags.empty())
|
||||
.origin());
|
||||
assertEquals("", new HeadContext(site(), page(), EN, "/", null, List.of(), false, false).origin());
|
||||
}
|
||||
|
||||
// --- CatalogEntry.pathFor ---------------------------------------------------------------------------------
|
||||
|
||||
private static ContentRef ref(String id) {
|
||||
return ContentRef.of(id, "/" + id, Map.of(), List.of(), Map.of(), Map.of(), "__plugin__/x/t", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pathForNeverLinksAnXDefaultOutsideTheItemsOwnUrls() {
|
||||
// A hand-built entry (or one from a pre-1.0 kernel) whose x-default is the site-default path the item does
|
||||
// not exist at: a context in a locale the item lacks links the item's first real address instead.
|
||||
CatalogEntry entry = new CatalogEntry("blog", ref("salut"),
|
||||
List.of(new LocalizedUrl(ES, "/es/salut", null)), "/salut");
|
||||
assertEquals("/es/salut", entry.pathFor(EN), "never the unprefixed path the site does not serve");
|
||||
assertEquals("/es/salut", entry.pathFor(FR));
|
||||
assertEquals("/salut", entry.xDefaultPath(), "the component itself is reported as given");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pathForPrefersTheXDefaultWhenItIsOneOfTheUrls() {
|
||||
CatalogEntry entry = new CatalogEntry("blog", ref("hi"), List.of(new LocalizedUrl(ES, "/es/hola", null),
|
||||
new LocalizedUrl(EN, "/hi", null)), "/hi");
|
||||
assertEquals("/hi", entry.pathFor(FR), "x-default (the primary's address) wins over the first URL");
|
||||
assertEquals("/es/hola", entry.pathFor(ES));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pathForWithNoUrlsAnswersTheXDefault() {
|
||||
assertEquals("/hi", new CatalogEntry("blog", ref("hi"), List.of(), "/hi").pathFor(EN));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package mx.quest.runway.spi.model;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link SettingsView}: deep freezing, null normalisation, and the lenient typed accessors. */
|
||||
class SettingsViewTest {
|
||||
|
||||
private static SettingsView of(Object... keyValues) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
for (int i = 0; i < keyValues.length; i += 2) {
|
||||
map.put((String) keyValues[i], keyValues[i + 1]);
|
||||
}
|
||||
return new SettingsView(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullsAreDroppedAndNestedValuesAreDeepFrozen() {
|
||||
List<Object> inner = new ArrayList<>(Arrays.asList("a", null, "b"));
|
||||
Map<String, Object> nested = new HashMap<>();
|
||||
nested.put("k", "v");
|
||||
nested.put("gone", null);
|
||||
nested.put("list", inner);
|
||||
Map<String, Object> source = new HashMap<>();
|
||||
source.put("x", nested);
|
||||
source.put("dropped", null);
|
||||
source.put(null, "no key");
|
||||
|
||||
SettingsView view = new SettingsView(source);
|
||||
source.put("late", "added after");
|
||||
inner.add("c");
|
||||
|
||||
assertEquals(1, view.values().size(), view.values().toString());
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> frozen = (Map<String, Object>) view.values().get("x");
|
||||
assertEquals(Map.of("k", "v", "list", List.of("a", "b")), frozen,
|
||||
"null entries dropped at every level; later edits to the source are invisible");
|
||||
assertThrows(UnsupportedOperationException.class, () -> view.values().put("y", 1));
|
||||
assertThrows(UnsupportedOperationException.class, () -> frozen.put("y", 1));
|
||||
assertThrows(UnsupportedOperationException.class, () -> ((List<?>) frozen.get("list")).clear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNullMapIsEmpty() {
|
||||
assertTrue(new SettingsView(null).values().isEmpty());
|
||||
assertTrue(SettingsView.empty().values().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringUsesTheFallbackForAbsentAndBlankValuesAndJoinsLists() {
|
||||
SettingsView view = of("name", "Acme", "blank", " ", "n", 5, "tags", List.of("a", "b"));
|
||||
assertEquals("Acme", view.string("name", "x"));
|
||||
assertEquals("x", view.string("blank", "x"));
|
||||
assertEquals("x", view.string("absent", "x"));
|
||||
assertNull(view.string("absent", null));
|
||||
assertEquals("5", view.string("n", "x"));
|
||||
assertEquals("a, b", view.string("tags", "x"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void boolAcceptsBooleansWordsAndNumbersAndFallsBackOnAnythingElse() {
|
||||
SettingsView view = of("t", true, "f", false, "on", "ON", "yes", " yes ", "one", "1", "off", "off",
|
||||
"no", "No", "zero", "0", "num", 2, "numZero", 0, "junk", "maybe", "blank", "");
|
||||
assertTrue(view.bool("t", false));
|
||||
assertFalse(view.bool("f", true));
|
||||
assertTrue(view.bool("on", false));
|
||||
assertTrue(view.bool("yes", false));
|
||||
assertTrue(view.bool("one", false));
|
||||
assertFalse(view.bool("off", true));
|
||||
assertFalse(view.bool("no", true));
|
||||
assertFalse(view.bool("zero", true));
|
||||
assertTrue(view.bool("num", false));
|
||||
assertFalse(view.bool("numZero", true));
|
||||
assertTrue(view.bool("junk", true), "unrecognised → fallback");
|
||||
assertFalse(view.bool("junk", false));
|
||||
assertTrue(view.bool("blank", true));
|
||||
assertTrue(view.bool("absent", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void integerParsesIntegralValuesOnlyAndClamps() {
|
||||
SettingsView view = of("i", 42, "l", 7_000_000_000L, "s", " 13 ", "d", 2.0, "frac", 2.5, "junk", "x",
|
||||
"big", new BigDecimal("12"));
|
||||
assertEquals(42, view.integer("i", -1));
|
||||
assertEquals(7_000_000_000L, view.integer("l", -1));
|
||||
assertEquals(13, view.integer("s", -1));
|
||||
assertEquals(2, view.integer("d", -1), "an integral double is accepted");
|
||||
assertEquals(-1, view.integer("frac", -1), "a fractional number is not a whole number");
|
||||
assertEquals(-1, view.integer("junk", -1));
|
||||
assertEquals(12, view.integer("big", -1));
|
||||
assertEquals(-1, view.integer("absent", -1));
|
||||
assertEquals(10, view.integer("i", 0, 1, 10), "clamped to max");
|
||||
assertEquals(1, view.integer("absent", -5, 1, 10), "the fallback is clamped too");
|
||||
assertThrows(IllegalArgumentException.class, () -> view.integer("i", 0, 10, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void decimalParsesNumbersExactlyAndFallsBack() {
|
||||
SettingsView view = of("d", 1.1, "s", "2.50", "bd", new BigDecimal("3.3"), "junk", "x");
|
||||
assertEquals(new BigDecimal("1.1"), view.decimal("d", null));
|
||||
assertEquals(new BigDecimal("2.50"), view.decimal("s", null));
|
||||
assertEquals(new BigDecimal("3.3"), view.decimal("bd", null));
|
||||
assertEquals(BigDecimal.ONE, view.decimal("junk", BigDecimal.ONE));
|
||||
assertNull(view.decimal("absent", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReadsYamlListsAndSeparatedStrings() {
|
||||
SettingsView view = of("yaml", List.of(" a ", "", "b"), "csv", "x, y,,z", "lines", "p\nq", "one", "solo");
|
||||
assertEquals(List.of("a", "b"), view.list("yaml"));
|
||||
assertEquals(List.of("x", "y", "z"), view.list("csv"));
|
||||
assertEquals(List.of("p", "q"), view.list("lines"));
|
||||
assertEquals(List.of("solo"), view.list("one"));
|
||||
assertEquals(List.of(), view.list("absent"));
|
||||
assertThrows(UnsupportedOperationException.class, () -> view.list("yaml").add("c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pluginInfoRequiresEveryComponent() {
|
||||
assertEquals("blog", new PluginInfo("blog", "1.0.0", Path.of("plugins", "blog")).id());
|
||||
assertThrows(NullPointerException.class, () -> new PluginInfo(null, "1.0.0", Path.of("x")));
|
||||
assertThrows(NullPointerException.class, () -> new PluginInfo("a", null, Path.of("x")));
|
||||
assertThrows(NullPointerException.class, () -> new PluginInfo("a", "1.0.0", null));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user