Repository navigation
Drop template indentation from API pages before writing them #4959
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+355
−1
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
62d4d27
Drop template indentation from API pages before writing them
akira28 e5f0586
Match real closing tags and decode the page buffer in place
akira28 a1a7590
Skip comments whole inside a pre when collapsing whitespace
akira28 f7dea03
Skip raw-text elements nested in a pre when collapsing whitespace
akira28 9f473ab
Count nested pre elements instead of recursing into them
akira28 1d0fbf0
Read the written page from its new path in the whitespace generator test
akira28 0a3244d
Keep the System.Text import the tree-relative link hashing needs
akira28 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
198 changes: 198 additions & 0 deletions
198
src/Elastic.ApiExplorer/Infrastructure/HtmlWhitespace.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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></script-example></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>--></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); | ||
| 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'; | ||
| } | ||
25 changes: 25 additions & 0 deletions
25
src/Elastic.ApiExplorer/Infrastructure/MemoryFileSystemStream.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.<string>.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))); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.