Skip to content
Closed
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
198 changes: 198 additions & 0 deletions src/Elastic.ApiExplorer/Infrastructure/HtmlWhitespace.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.Text;

namespace Elastic.ApiExplorer.Infrastructure;

/// <summary>
/// Drops the template indentation from a rendered page. The largest API pages repeat a nested row partial thousands of
/// times, and its tabs alone cost hundreds of kilobytes against Googlebot's 2 MB limit.
/// </summary>
/// <remarks>
/// A single pass over the page, not a regex: pages reach several megabytes and render in parallel, where a regex over
/// the whole page ran past its match timeout and failed the build.
/// </remarks>
public static class HtmlWhitespace
{
private static readonly string[] RawTextElements = ["pre", "textarea", "script", "style"];

/// <summary>
/// Turns each whitespace run that holds a line break in text into one line break, which renders the same under
/// <c>white-space: normal</c>. Raw-text and preformatted elements, comments and tags with their attribute values are
/// kept as they are. Only HTML's own whitespace counts, so a non-breaking space is never dropped.
/// </summary>
public static string Collapse(string html)
{
var output = new StringBuilder(html.Length);
var position = 0;
while (position < html.Length)
{
if (html[position] == '<')
{
var end = EndOfMarkup(html, position);
_ = output.Append(html, position, end - position);
position = end;
continue;
}

var next = html.IndexOf('<', position);
if (next < 0)
next = html.Length;
AppendText(output, html, position, next);
position = next;
}

return output.ToString();
}

/// <summary>Where the comment, raw-text element or tag starting at <paramref name="start"/> ends.</summary>
private static int EndOfMarkup(string html, int start)
{
if (string.CompareOrdinal(html, start, "<!--", 0, 4) == 0)
return EndAfter(html, html.IndexOf("-->", start + 4, StringComparison.Ordinal), 3);

if (RawTextElement(html, start) is { } name)
return EndOfElement(html, start, name);

// A '<' that opens no tag is text; encoded pages never hold one, but it must not swallow the page.
var opensTag = start + 1 < html.Length && (char.IsAsciiLetter(html[start + 1]) || html[start + 1] is '/' or '!' or '?');
return opensTag ? EndOfTag(html, start) : start + 1;
}

/// <summary>
/// The end of the element whose start tag begins at <paramref name="start"/>: after its own closing tag, which is the
/// name followed by whitespace, '/' or '>', so <c>&lt;/script-example&gt;</c> does not close a script. A
/// <c>pre</c> holds markup, so its tags are skipped whole, and a closing tag inside an attribute value does not count;
/// <c>script</c>, <c>style</c> and <c>textarea</c> hold raw text.
/// </summary>
private static int EndOfElement(string html, int start, string name)
{
var holdsMarkup = name == "pre";
// A pre inside the pre is counted, not recursed into, so no nesting depth can exhaust the stack.
var depth = 1;
var position = EndOfTag(html, start);
while (position < html.Length)
{
var next = html.IndexOf('<', position);
if (next < 0)
return html.Length;
if (IsClosingTag(html, next, name))
{
position = EndOfTag(html, next);
if (--depth == 0)
return position;
continue;
}

if (holdsMarkup && RawTextElement(html, next) == "pre")
{
depth++;
position = EndOfTag(html, next);
continue;
}

position = holdsMarkup ? EndOfMarkupInPre(html, next) : next + 1;
}

return html.Length;
}

/// <summary>
/// Where the markup at <paramref name="index"/> inside a <c>pre</c> ends: a nested raw-text element through its own
/// closing tag, a comment through its <c>--&gt;</c> (so text such as <c>="</c> in it is not read as an attribute), a tag
/// whole, and anything else one character on.
/// </summary>
private static int EndOfMarkupInPre(string html, int index)
{
// A textarea, script or style inside the pre holds raw text, where "<!--" is not a comment. Raw text holds no
// elements, so this goes one level deep at most.
if (RawTextElement(html, index) is { } nested and not "pre")
return EndOfElement(html, index, nested);
if (string.CompareOrdinal(html, index, "<!--", 0, 4) == 0)
return EndAfter(html, html.IndexOf("-->", index + 4, StringComparison.Ordinal), 3);
Comment thread
infra-vault-gh-plugin-prod[bot] marked this conversation as resolved.
Resolved
var opensTag = index + 1 < html.Length && (char.IsAsciiLetter(html[index + 1]) || html[index + 1] is '/' or '!');
return opensTag ? EndOfTag(html, index) : index + 1;
}

private static bool IsClosingTag(string html, int index, string name)
{
var after = index + 2 + name.Length;
return after < html.Length
&& html[index + 1] == '/'
&& string.Compare(html, index + 2, name, 0, name.Length, StringComparison.OrdinalIgnoreCase) == 0
&& (IsHtmlWhitespace(html[after]) || html[after] is '>' or '/');
}

/// <summary>The end of the tag at <paramref name="start"/>, skipping a quoted attribute value that holds a '>'.</summary>
private static int EndOfTag(string html, int start)
{
for (var i = start + 1; i < html.Length; i++)
{
var c = html[i];
if (c == '>')
return i + 1;
if (c is '"' or '\'' && PreviousNonSpace(html, i, start) == '=')
i = html.IndexOf(c, i + 1) is var closing and >= 0 ? closing : html.Length;
}

return html.Length;
}

private static char PreviousNonSpace(string html, int index, int floor)
{
for (var i = index - 1; i > floor; i--)
{
if (!IsHtmlWhitespace(html[i]))
return html[i];
}

return '\0';
}

private static string? RawTextElement(string html, int start)
{
foreach (var name in RawTextElements)
{
var after = start + 1 + name.Length;
if (
after < html.Length
&& string.Compare(html, start + 1, name, 0, name.Length, StringComparison.OrdinalIgnoreCase) == 0
&& (IsHtmlWhitespace(html[after]) || html[after] is '>' or '/')
)
return name;
}

return null;
}

private static void AppendText(StringBuilder output, string html, int start, int end)
{
var i = start;
while (i < end)
{
if (!IsHtmlWhitespace(html[i]))
{
_ = output.Append(html[i]);
i++;
continue;
}

var runStart = i;
var hasLineBreak = false;
while (i < end && IsHtmlWhitespace(html[i]))
{
hasLineBreak |= html[i] == '\n';
i++;
}

_ = hasLineBreak ? output.Append('\n') : output.Append(html, runStart, i - runStart);
}
}

private static int EndAfter(string html, int index, int length) => index < 0 ? html.Length : index + length;

// ASCII whitespace as HTML defines it; char.IsWhiteSpace would also take a non-breaking space.
private static bool IsHtmlWhitespace(char c) => c is ' ' or '\t' or '\n' or '\r' or '\f';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.IO.Abstractions;
using System.Text;

namespace Elastic.ApiExplorer.Infrastructure;

/// <summary>A page renderer's stream that stays in memory, so the page can be rewritten before it is written to disk.</summary>
public sealed class MemoryFileSystemStream : FileSystemStream
{
private readonly MemoryStream _buffer;

public MemoryFileSystemStream(string path) : this(new MemoryStream(), path) { }

private MemoryFileSystemStream(MemoryStream buffer, string path) : base(buffer, path, isAsync: false) => _buffer = buffer;

/// <summary>What was written, decoded from the buffer in place rather than copied out first.</summary>
public string ReadAsUtf8()
{
Flush();
return Encoding.UTF8.GetString(_buffer.GetBuffer(), 0, (int)_buffer.Length);
}
}
5 changes: 4 additions & 1 deletion src/Elastic.ApiExplorer/OpenApiGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -977,7 +977,8 @@ Cancel ctx

var navigationRenderResult = await navigationRenderer.RenderNavigation(current.NavigationRoot, current, ctx);
renderContext = renderContext with { CurrentNavigation = current, NavigationHtml = navigationRenderResult.Html };
await using var stream = _writeFileSystem.FileStream.New(outputFile.FullName, FileMode.Create);
// Rendered in memory so the indentation can be dropped before the page reaches disk.
await using var stream = new MemoryFileSystemStream(outputFile.FullName);

// Build the expensive page model once and pass it to both render paths so that
// OperationPageModel.Create / SchemaPageModel.Create / StructuralViewModel.Create
Expand All @@ -993,6 +994,8 @@ Cancel ctx
await page.RenderAsync(stream, renderContext, ctx);
}

var html = HtmlWhitespace.Collapse(stream.ReadAsUtf8());
await _writeFileSystem.File.WriteAllTextAsync(outputFile.FullName, html, ctx).ConfigureAwait(false);
return outputFile;

IFileInfo OutputFile(INavigationItem currentNavigation)
Expand Down
100 changes: 100 additions & 0 deletions tests/Elastic.ApiExplorer.Tests/HtmlWhitespaceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using AwesomeAssertions;
using Elastic.ApiExplorer.Infrastructure;

namespace Elastic.ApiExplorer.Tests;

public class HtmlWhitespaceTests
{
[Test]
public void Collapse_IndentationBetweenTags_BecomesOneLineBreak() =>
HtmlWhitespace
.Collapse("<dl>\n\t\t<dt>\n\t\t\t<code>a</code> <span>or</span>\n\t\t</dt>\n</dl>\n")
.Should()
.Be("<dl>\n<dt>\n<code>a</code> <span>or</span>\n</dt>\n</dl>\n");

[Test]
public void Collapse_PreformattedAndRawText_StayAsTheyAre()
{
const string kept =
"<pre><code>{\n \"a\": 1\n}</code></pre><textarea>x\n\n y</textarea><script>\n\tlet a = `\n\t`\n</script><style>\n\ta {}\n</style><!--\n\tnote\n-->";
HtmlWhitespace.Collapse(kept).Should().Be(kept);
}

[Test]
public void Collapse_AttributeValues_StayAsTheyAre()
{
const string kept = "<span data-tooltip=\"line one\n\n line two > three\" title='a\n b'>x</span>";
HtmlWhitespace.Collapse(kept).Should().Be(kept);
}

[Test]
public void Collapse_NonBreakingSpace_IsKeptBesideALineBreak() =>
HtmlWhitespace.Collapse("<span>a</span>\u00A0\n\t<span>b</span>").Should().Be("<span>a</span>\u00A0\n<span>b</span>");

[Test]
public void Collapse_StrayLessThanInText_IsText() => HtmlWhitespace.Collapse("<p>a < b\n\t\tc</p>").Should().Be("<p>a < b\nc</p>");

[Test]
public void Collapse_ApostropheInUnquotedValue_DoesNotOpenAQuote() =>
HtmlWhitespace.Collapse("<a title=it's>x</a>\n\t<b>y</b>").Should().Be("<a title=it's>x</a>\n<b>y</b>");

[Test]
public void Collapse_LookalikeClosingTag_DoesNotEndTheScript()
{
const string kept = "<script>\n\tlet t = '</script-example>';\n\tlet u = 1;\n</script>";
HtmlWhitespace.Collapse(kept + "\n\t<p>x</p>").Should().Be(kept + "\n<p>x</p>");
}

[Test]
public void Collapse_ClosingTagInsideAnAttribute_DoesNotEndThePre()
{
const string kept = "<pre><span title=\"a </pre> b\">{\n \"a\": 1\n}</span></pre>";
HtmlWhitespace.Collapse(kept + "\n\t<p>x</p>").Should().Be(kept + "\n<p>x</p>");
}

[Test]
public void Collapse_CommentInsideAPre_DoesNotHideItsClosingTag() =>
// Read as a tag, the comment's quote would pair with the title's and hide </pre>, leaving the rest uncollapsed.
HtmlWhitespace
.Collapse("<pre><!-- a=\" --> x</pre>\n\t<p title=\"t\">y</p>\n\t<p>z</p>")
.Should()
.Be("<pre><!-- a=\" --> x</pre>\n<p title=\"t\">y</p>\n<p>z</p>");

[Test]
public void Collapse_CommentOpenerInATextareaInsideAPre_IsText() =>
// In a textarea "<!--" is text; read as a comment with no "-->", it would leave the rest of the page uncollapsed.
HtmlWhitespace
.Collapse("<pre><textarea><!-- a</textarea> x</pre>\n\t<p>y</p>")
.Should()
.Be("<pre><textarea><!-- a</textarea> x</pre>\n<p>y</p>");

[Test]
public void Collapse_NestedPre_EndsAtTheOutermostClosingTag() =>
HtmlWhitespace.Collapse("<pre><pre>a\n b</pre>\n c</pre>\n\t<p>y</p>").Should().Be("<pre><pre>a\n b</pre>\n c</pre>\n<p>y</p>");

[Test]
public void Collapse_DeeplyNestedPre_DoesNotExhaustTheStack()
{
const int depth = 200_000;
var nested = string.Concat(Enumerable.Repeat("<pre>", depth)) + "x" + string.Concat(Enumerable.Repeat("</pre>", depth));

HtmlWhitespace.Collapse(nested + "\n\t<p>y</p>").Should().Be(nested + "\n<p>y</p>");
}

[Test]
public void Collapse_LargePage_DropsEveryRowIndentation()
{
// The largest API pages reach about 7 MB; this is the row partial repeated at that scale.
var row =
"<div class=\"property-item depth-6\">\n\t\t<dt id=\"a\"><a aria-label=\"Link to a.&lt;string&gt;.b\"></a>\n\t\t\t<code>b</code></dt>\n\t</div>\n";
var page = string.Concat(Enumerable.Repeat(row, 70_000));

var collapsed = HtmlWhitespace.Collapse(page);

collapsed.Should().Be(string.Concat(Enumerable.Repeat(row.Replace("\t", ""), 70_000)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,34 @@ static OpenApiPathItem Get(string id, string tag) =>
};
}

[Test]
public async Task Generate_WritesPagesWithoutTemplateIndentation()
{
var outputRoot = Path.Join(Paths.WorkingDirectoryRoot.FullName, $"api-ws-{Guid.NewGuid():N}");
var context = CreateGenerateContext(outputRoot);
using var versionIndexClient = new VersionIndexClient(BaseUri, MainOnlyHandler(), sleep: (_, _) => Task.CompletedTask);
var generator = new OpenApiGenerator(
NullLoggerFactory.Instance,
context,
PassthroughMarkdownRenderer.Instance,
versionIndexClient,
CreateSequentialReader(fixture.Document)
);

await generator.Generate(TestContext.Current!.Execution.CancellationToken);
var html = await context
.WriteFileSystem
.File
.ReadAllTextAsync(
Path.Join(outputRoot, "api", "elasticsearch", "operation", "operation-search", "index.html"),
TestContext.Current!.Execution.CancellationToken
);

// The property row partial indents its dt with a tab in the view; the written rows start it on its own line, and
// folded rows still open on find.
html.Should().Contain("\n<dt id=").And.NotContain("\n\t<dt id=").And.Contain("hidden=\"until-found\"");
}

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