Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions docs/data/openapi/api-explorer.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,9 @@ The numeric `9` entry is a frozen v9 snapshot. It is distinct from the moving `m
Search indexes the default version at `/api/<key>/` and older majors at `/api/<key>/vN/`, not `main` at `/next/` or the `/v9/` copy of the newest major. Search from a `/next/` page is the normal search with a lift for that API's default-version results. It does not filter by version, and operations that exist only in older majors stay hidden.
An API whose index lists no numeric major keeps `main` at `/api/<key>/` and has no `/next/`.
The default comes from the versions the index declares. If the newest major fails to load, nothing
renders at `/api/<key>/`, and no older major takes its place.
renders at `/api/<key>/`, and no older major takes its place. The API's card on the API landing page
then opens the newest older major that loaded. It never opens `/next/`, so an API with no released
version loaded has no card.
A version named `next` in the index is a build error, because `next` is the URL segment of `main`.

When a local spec file exists, it overrides only the `main` moniker. Older majors still resolve
Expand All @@ -216,8 +218,11 @@ remotely through the index. In `docs-builder serve`, a local spec edit therefore

Versionless products (`versioning: serverless` and similar) render only the unversioned
`/api/<key>/` path even when the index lists historical monikers. When more than one
version is rendered, the bar shows a version picker beside the API name. The unreleased tree is
labeled `Next (unreleased)`, and each frozen major is `v9`, `v8`. When the API has a numbered major, the unreleased tree is served at `/next`. Without one, it is the default and keeps the unversioned URL. The highest frozen major carries `(latest)`, as in `v9 (latest)`, and the unversioned URL serves it. Isolated builds put the same picker
released version is rendered, the bar shows a version picker beside the API name. Each frozen major is `v9`, `v8`. When the API has a numbered major, the unreleased tree is served at `/next`. Without one, it is the default and keeps the unversioned URL. The highest frozen major carries `(latest)`, as in `v9 (latest)`, and the unversioned URL serves it.

The `/next` tree is a preview that you open by its URL, `/api/<key>/next/`. No released page links to it, and the picker on a released page does not list it. On a `/next` page the picker lists it as `Next (unreleased)`, selected, above the released versions.

Isolated builds put the same picker
under the API name in the left navigation.
Picking a version opens the same page in that version when it has one, for example the same
operation, and that version's landing page otherwise. On a `/v9/` page, the `v9 (latest)` entry
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ public static class ApiVersionSwitcher
/// <summary>
/// One entry per version, for the page tree served at <paramref name="currentSuffix"/>. Each entry links to the
/// version's URL from <paramref name="routes"/>, except the selected one, which links to the current tree's own root,
/// so the numbered copy of the default major stays on its own URLs.
/// so the numbered copy of the default major stays on its own URLs. The unreleased tree is listed only on its own
/// pages: it is a preview opened by URL, so no released page links to it. An API with one released version keeps
/// that entry, because titles and the breadcrumb name the selected version; the menus need two entries to show.
/// </summary>
public static IReadOnlyList<ApiVersionSwitcherItem> Build(
string? urlPathPrefix,
Expand All @@ -26,6 +28,7 @@ public static IReadOnlyList<ApiVersionSwitcherItem> Build(

var latest = ApiVersions.LatestMajor(monikers);
return monikers
.Where(m => !routes.IsNext(m) || routes.Suffixes(m).Contains(currentSuffix))
.OrderByDescending(ApiVersions.Recency)
.Select(m => (Moniker: m, Selected: routes.Suffixes(m).Contains(currentSuffix)))
.Select(
Expand Down
15 changes: 9 additions & 6 deletions src/Elastic.ApiExplorer/OpenApiGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -505,18 +505,21 @@ private async Task<ResolvedProductDocuments> LoadDocuments(string apiKey, Resolv
}
}

/// <summary>The document that titles the API: the default version's, or the first that loaded when the default did not.</summary>
private static VersionedOpenApiDocument CanonicalDocument(ResolvedProductDocuments resolved) =>
resolved.Documents.FirstOrDefault(v => v.Version.Moniker == resolved.Routes.DefaultMoniker) ?? resolved.Documents[0];
/// <summary>
/// The document that titles the API: the default version's, or the newest released one that loaded when the default
/// did not. Never the unreleased tree, which no listing links to.
/// </summary>
private static VersionedOpenApiDocument? CanonicalDocument(ResolvedProductDocuments resolved) =>
resolved.Documents.FirstOrDefault(v => v.Version.Moniker == resolved.Routes.DefaultMoniker)
?? resolved.Documents.Where(v => !resolved.Routes.IsNext(v.Version.Moniker)).MaxBy(v => ApiVersions.Recency(v.Version.Moniker));

internal ApiCatalogEntry? CatalogEntry(string prefix, ResolvedApiConfiguration apiConfig, ResolvedProductDocuments resolved)
{
if (resolved.Documents.Count == 0)
if (CanonicalDocument(resolved) is not { } canonical)
return null;
Comment on lines +518 to 519

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

If /next is the only tree that renders in a build, omitting its card also suppresses the entire /api hub. The preview pages still link to /api in their breadcrumbs, so those links now lead to a missing page. Keep the hub available without the card, or omit its links when there is no hub.

Generated by Libra. React with 👍 or 👎 to give feedback on this comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No change here. The hub goes missing only when every API in the build lost all of its released versions and main alone loaded. The build reports that state for each API, and the search export stops on it. A hub page with no cards gives the reader nothing to open, and a card for the preview is the link this PR removes. If a degraded build should still write an empty hub, that is a separate change to Generate, which skips the catalog page when it has no entries.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One distinction: the search-export failure does not itself prevent the preview pages from being generated. Generate renders products and then skips the catalog only when there are no entries; GenerateProduct renders each resolved tree before returning its (possibly null) catalog entry (OpenApiGenerator.cs#L135-L140, OpenApiGenerator.cs#L368-L420). The separate search-export path reports the unresolved versions and stops the export (OpenApiGenerator.cs#L226-L248); that diagnostic does not address the /api link still emitted on non-catalog pages (ApiBreadcrumbs.cs#L14-L24). So the concern still applies to the generated /next pages in this degraded case. If an empty hub is intentionally out of scope, omitting that breadcrumb when there is no hub remains the alternative in the finding.

Generated by Libra. React with 👍 or 👎 to give feedback on this comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right about the export: it stops the search index and does not stop the /next pages from rendering. I withdraw that part of my reply. The dead APIs crumb is real in that build.

I still leave it out of this PR, for two reasons.

The state needs every API in the build to declare a numeric major and to lose all of them while main loads. An API with no numeric major keeps main as its default tree, so IsNext is false and it keeps its card. The assembled site has several such APIs, so its hub cannot go missing this way. That leaves an isolated build of one versioned API whose index resolves and whose released specs all fail to fetch, and that build already reports each missing version.

Neither fix is local. ApiBreadcrumbs.Build does not know whether a hub exists, and the render context's catalog entries are empty in contexts that do have a hub, such as PageContentsAsync, so that list cannot stand in for it. Writing an empty hub means that Generate and GenerateCatalog stop skipping on zero entries, which also changes what a build with no loadable spec writes.

The right shape is one fact, whether the build writes a hub, that the catalog step and the breadcrumb both read. That is a change of its own.


var canonical = CanonicalDocument(resolved);
var title = canonical.Document.Info?.Title ?? apiConfig.Product.DisplayName ?? prefix;
// The versionless URL when the default version rendered, else the tree that did, so the card never links to a page nothing wrote.
// The versionless URL when the default version rendered, else the released tree that did, so the card never links to a page nothing wrote.
var url = ApiUrlBuilder.ProductRoot(context.UrlPathPrefix, resolved.Routes.Suffix(canonical.Version.Moniker));
return new ApiCatalogEntry(prefix, title, url, apiConfig.Product.Id, canonical.Document.Info?.Description);
}
Expand Down
3 changes: 2 additions & 1 deletion src/Elastic.Documentation.Site/Layout/_ApiIdentity.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
@{
var hasVersions = Model.Versions.Count > 1;
var hasProducts = Model.ProductGroups.Count > 0;
var current = hasVersions ? Model.Versions.FirstOrDefault(static v => v.Selected) ?? Model.Versions[0] : null;
// One released version is not a choice, so it has no menu group, but the trigger still names it.
var current = Model.Versions.FirstOrDefault(static v => v.Selected) ?? (hasVersions ? Model.Versions[0] : null);
// The menu label can carry a hint such as "(latest)"; the trigger names just the version.
var currentLabel = current?.ShortLabel ?? current?.Label;
}
Expand Down
60 changes: 28 additions & 32 deletions tests/Elastic.ApiExplorer.Tests/ApiVersionSwitcherTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,32 @@ public void Build_SingleVersion_ReturnsEmpty()
}

[Test]
public void Build_MultipleVersions_OrdersCurrentMajorFirstAndMarksCurrent()
public void Build_ReleasedPage_ListsTheReleasedVersionsNewestFirstAndMarksCurrent()
{
var items = ApiVersionSwitcher.Build("", Es, ["main", "9", "8"], "elasticsearch/v8");

items.Should().HaveCount(3);
items.Select(i => i.Label).Should().Equal("Next (unreleased)", "v9 (latest)", "v8");
items.Select(i => i.Url).Should().Equal("/api/elasticsearch/next", "/api/elasticsearch", "/api/elasticsearch/v8");
items.Select(i => i.Label).Should().Equal(["v9 (latest)", "v8"], "the unreleased tree is opened by URL, not from a released page");
items.Select(i => i.Url).Should().Equal("/api/elasticsearch", "/api/elasticsearch/v8");
items.Single(i => i.Selected).Label.Should().Be("v8");
}

[Test]
public void Build_MainAndOneMajor_ReleasedPageKeepsItsOwnVersionAsTheOnlyEntry()
{
var routes = ApiVersionRoutes.For("elasticsearch", ["main", "9"]);

ApiVersionSwitcher
.Build("", routes, ["main", "9"], "elasticsearch")
.Select(i => $"{i.Label} {i.Selected}")
.Should()
.Equal(["v9 (latest) True"], "one entry is no picker, and the titles and the breadcrumb still name the version");
ApiVersionSwitcher
.Build("", routes, ["main", "9"], "elasticsearch/next")
.Select(i => i.Label)
.Should()
.Equal("Next (unreleased)", "v9 (latest)");
}

[Test]
public void Build_CurrentMain_LinksMainAtNextAndMarksTheHighestMajorLatest()
{
Expand All @@ -44,10 +60,7 @@ public void Build_NumberedCopyOfTheDefaultMajor_SelectedEntryLinksToItsOwnRoot()
{
var items = ApiVersionSwitcher.Build("", Es, ["main", "9", "8"], "elasticsearch/v9");

items
.Select(i => $"{i.Url} {i.Selected}")
.Should()
.Equal("/api/elasticsearch/next False", "/api/elasticsearch/v9 True", "/api/elasticsearch/v8 False");
items.Select(i => $"{i.Url} {i.Selected}").Should().Equal("/api/elasticsearch/v9 True", "/api/elasticsearch/v8 False");
}

[Test]
Expand Down Expand Up @@ -107,18 +120,11 @@ public void ForPage_PageMissingInOtherVersions_LinksToVersionRoots()
}

[Test]
public void ForPage_FromTheVersionlessDefault_LinksToSamePageInMain()
public void ForPage_FromTheVersionlessDefault_KeepsItsPageAndLinksOlderMajorsToTheirRoot()
{
var items = ApiVersionSwitcher.ForPage(Items("elasticsearch"), "/api/elasticsearch/operation/operation-ping");

items
.Select(i => i.Url)
.Should()
.Equal(
"/api/elasticsearch/next/operation/operation-ping",
"/api/elasticsearch/operation/operation-ping",
"/api/elasticsearch/v8"
);
items.Select(i => i.Url).Should().Equal("/api/elasticsearch/operation/operation-ping", "/api/elasticsearch/v8");
items.Single(i => i.Selected).Label.Should().Be("v9 (latest)");
}

Expand All @@ -127,14 +133,7 @@ public void ForPage_FromTheNumberedCopyOfTheDefault_StaysOnTheSamePage()
{
var items = ApiVersionSwitcher.ForPage(Items("elasticsearch/v9"), "/api/elasticsearch/v9/operation/operation-ping");

items
.Select(i => i.Url)
.Should()
.Equal(
"/api/elasticsearch/next/operation/operation-ping",
"/api/elasticsearch/v9/operation/operation-ping",
"/api/elasticsearch/v8"
);
items.Select(i => i.Url).Should().Equal("/api/elasticsearch/v9/operation/operation-ping", "/api/elasticsearch/v8");
}

[Test]
Expand Down Expand Up @@ -178,15 +177,12 @@ public void ForPage_CollapsedPageInTarget_LinksToItsCanonicalPath()
var items = ApiVersionSwitcher.ForPage(
ApiVersionSwitcher.Build(
"",
ApiVersionRoutes.For("elasticsearch", ["main", "8"]),
["main", "8"],
Es,
["main", "9", "8"],
"elasticsearch/v8",
new Dictionary<string, IReadOnlyDictionary<string, IReadOnlyList<string>>>
{
["main"] = Pages(
[""],
["/operation/operation-search", "/operation/operation-search-1", "/operation/operation-search-2"]
),
["9"] = Pages([""], ["/operation/operation-search", "/operation/operation-search-1", "/operation/operation-search-2"]),
["8"] = Pages([""], ["/operation/operation-search-2"])
}
),
Expand All @@ -196,6 +192,6 @@ public void ForPage_CollapsedPageInTarget_LinksToItsCanonicalPath()
items
.Select(i => i.Url)
.Should()
.Equal("/api/elasticsearch/next/operation/operation-search", "/api/elasticsearch/v8/operation/operation-search-2");
.Equal("/api/elasticsearch/operation/operation-search", "/api/elasticsearch/v8/operation/operation-search-2");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,13 @@ var path when path.EndsWith("index.json", StringComparison.Ordinal) => IndexResp
var errorsAfterRendering = context.Collector.Errors;
var export = () => generator.ResolveIndexedTrees(TestContext.Current!.Execution.CancellationToken);

entries.Should().ContainSingle("pages still render the trees that loaded");
entries.Should().BeEmpty("only the unreleased tree loaded, and no card links to it");
context
.WriteFileSystem
.File
.Exists(Path.Join(outputRoot, "api", "elasticsearch", "next", "index.html"))
.Should()
.BeTrue("pages still render the trees that loaded");
errorsAfterRendering.Should().Be(0, "rendering skips the missing tree with a warning");
(await export.Should().ThrowAsync<InvalidOperationException>()).WithMessage(
"The API search export stops: API 'elasticsearch': version '8' is declared in the version index but could not be loaded."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ public async Task CatalogEntry_MultiMajorIndex_OpensTheVersionlessUrlTitledByThe
}

[Test]
public async Task CatalogEntry_NewestMajorFailsToLoad_LinksToATreeThatRendered()
public async Task CatalogEntry_NewestMajorFailsToLoad_LinksToTheReleasedTreeThatRendered()
{
var collector = new DiagnosticsCollector([]);
var stack = TestHelpers.CreateStackVersionsConfiguration(currentMajor: 9);
Expand All @@ -260,7 +260,64 @@ public async Task CatalogEntry_NewestMajorFailsToLoad_LinksToATreeThatRendered()
entry!
.Url
.Should()
.Be("/api/elasticsearch/next", "nothing renders at /api/elasticsearch, so the card opens the first tree that did");
.Be("/api/elasticsearch/v8", "nothing renders at /api/elasticsearch, and the card never opens the unreleased tree");
}

[Test]
public async Task CatalogEntry_NewestMajorFailsToLoad_PrefersTheNewestSurvivorOverIndexOrder()
{
var collector = new DiagnosticsCollector([]);
var stack = TestHelpers.CreateStackVersionsConfiguration(currentMajor: 9);
var product = TestHelpers.CreateProduct("elasticsearch", stack.GetVersioningSystem(VersioningSystemId.Stack));
var context = TestHelpers.CreateScopedBuildContext(collector, stack, ProductsFor(product), GitForElasticsearch());
using var versionIndexClient = new VersionIndexClient(
BaseUri,
MultiVersionHandler(
elasticsearchVersions: /*lang=json,strict*/ """{ "main": { "version": "main" }, "7": { "version": "7.17" }, "8": { "version": "8.19" }, "9": { "version": "9.4" } }"""
),
sleep: (_, _) => Task.CompletedTask
);
var reader = CreateVersionedReader(
missingVersionsAreUnreadable: true,
("main", SpecDocument("Elasticsearch main")),
("7.17", SpecDocument("Elasticsearch 7")),
("8.19", SpecDocument("Elasticsearch 8"))
);
var generator = CreateGenerator(context, versionIndexClient, reader);
var apiConfig = ApiConfig(product);
var resolved = await generator.ResolveDocumentsForProduct(
"elasticsearch",
apiConfig,
TestContext.Current!.Execution.CancellationToken
);

var entry = generator.CatalogEntry("elasticsearch", apiConfig, resolved);

entry!.Url.Should().Be("/api/elasticsearch/v8", "the index lists 7 before 8, and the card opens the newest release that rendered");
entry.Title.Should().Be("Elasticsearch 8");
}

[Test]
public async Task CatalogEntry_OnlyTheUnreleasedTreeLoads_HasNoCard()
{
var collector = new DiagnosticsCollector([]);
var stack = TestHelpers.CreateStackVersionsConfiguration(currentMajor: 9);
var product = TestHelpers.CreateProduct("elasticsearch", stack.GetVersioningSystem(VersioningSystemId.Stack));
var context = TestHelpers.CreateScopedBuildContext(collector, stack, ProductsFor(product), GitForElasticsearch());
using var versionIndexClient = new VersionIndexClient(BaseUri, MultiVersionHandler(), sleep: (_, _) => Task.CompletedTask);
var reader = CreateVersionedReader(missingVersionsAreUnreadable: true, ("main", SpecDocument("Elasticsearch main")));
var generator = CreateGenerator(context, versionIndexClient, reader);
var apiConfig = ApiConfig(product);
var resolved = await generator.ResolveDocumentsForProduct(
"elasticsearch",
apiConfig,
TestContext.Current!.Execution.CancellationToken
);

var entry = generator.CatalogEntry("elasticsearch", apiConfig, resolved);

resolved.Documents.Should().ContainSingle("the unreleased tree still renders at /next");
entry.Should().BeNull("a card would be the only link to the unreleased tree");
}

[Test]
Expand Down Expand Up @@ -977,10 +1034,11 @@ public async Task Generate_VersionPickerKeepsTheSamePageWhenItExists()
var files = context.WriteFileSystem.File;
var shared = files.ReadAllText(Path.Join(outputRoot, "api", "elasticsearch", "operation", "operation-ping", "index.html"));
shared.Should().Contain("href=\"/api/elasticsearch/v8/operation/operation-ping\"");
shared.Should().Contain("href=\"/api/elasticsearch/next/operation/operation-ping\"");
shared.Should().NotContain("href=\"/api/elasticsearch/next", "a released page never links to the unreleased tree");
var mainOnly = files.ReadAllText(
Path.Join(outputRoot, "api", "elasticsearch", "next", "operation", "operation-newop", "index.html")
);
mainOnly.Should().Contain("href=\"/api/elasticsearch/next/operation/operation-newop\"", "the unreleased tree lists itself");
mainOnly.Should().Contain("href=\"/api/elasticsearch/v8\"");
mainOnly.Should().Contain("href=\"/api/elasticsearch\"");
mainOnly.Should().NotContain("/api/elasticsearch/v8/operation/operation-newop");
Expand All @@ -989,7 +1047,7 @@ public async Task Generate_VersionPickerKeepsTheSamePageWhenItExists()
// the numbered copy of the newest major keeps its reader on its own URLs
var numbered = files.ReadAllText(Path.Join(outputRoot, "api", "elasticsearch", "v9", "operation", "operation-ping", "index.html"));
numbered.Should().Contain("href=\"/api/elasticsearch/v9/operation/operation-ping\"");
numbered.Should().Contain("href=\"/api/elasticsearch/next/operation/operation-ping\"");
numbered.Should().NotContain("href=\"/api/elasticsearch/next");
}

[Test]
Expand Down Expand Up @@ -1299,7 +1357,14 @@ private static IOpenApiSpecificationReader CreateVersionedReader(
return reader;
}

private static HttpMessageHandler MultiVersionHandler(string repository = "elastic/elasticsearch") =>
private const string MainNineAndEight = /*lang=json,strict*/
"""{ "main": { "version": "main" }, "9": { "version": "9.4" }, "8": { "version": "8.19" } }""";

/// <param name="elasticsearchVersions">The versions the index declares for the Elasticsearch spec, in the order it lists them.</param>
private static HttpMessageHandler MultiVersionHandler(
string repository = "elastic/elasticsearch",
string elasticsearchVersions = MainNineAndEight
) =>
new StubHandler(request =>
{
if (request.RequestUri!.AbsolutePath.EndsWith("index.json", StringComparison.Ordinal))
Expand All @@ -1308,11 +1373,7 @@ private static HttpMessageHandler MultiVersionHandler(string repository = "elast
$$"""
{
"{{repository}}": {
"elasticsearch-openapi.json": {
"main": { "version": "main" },
"9": { "version": "9.4" },
"8": { "version": "8.19" }
},
"elasticsearch-openapi.json": {{elasticsearchVersions}},
"elastic-cloud-serverless.yml": {
"main": { "version": "main" },
"8": { "version": "8.19" }
Expand Down
18 changes: 18 additions & 0 deletions tests/Navigation.Tests/Rendering/SecondaryNavRenderingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,24 @@ public async Task ApiIdentityTriggerDropsTheLatestSuffixButTheMenuKeepsIt()
html.Should().MatchHtmlSnapshot(DocsHtml.Body());
}

[Test]
public async Task ApiIdentityWithOneVersionNamesItInTheTriggerAndOffersNoVersionMenu()
{
var bar = new ApiIdentity(
"Alpha API",
null,
[new ApiIdentityProductGroup(null, [new ApiIdentityProduct("Alpha API", "/a/", true, null)])],
"/docs/api/",
[new NavigationSelectOption("v9 (latest)", "/a/", true, "v9")],
new ApiSpecDownload("/a.json", "/a.yaml")
);

var html = await _ApiIdentity.Create(bar).RenderAsync(cancellationToken: TestContext.Current!.Execution.CancellationToken);

html.Should().Contain("<span class=\"api-identity-version-label\">v9</span>");
html.Should().NotContain("api-version-switcher", "one version is not a choice");
}

[Test]
public async Task ApiIdentityWithoutVersionsOrOtherApisIsPlainText()
{
Expand Down
Loading