返回提交历史
Modified
Source/XFESystem.Browser/BackgroundBrowserEditorSession.cs
+7
-1
Modified
Source/XFESystem.Browser/BrowserCssCascade.cs
+31
-24
Modified
Source/XFESystem.Browser/BrowserDocumentLoading.cs
+2
-1
Modified
Source/XFESystem.Browser/BrowserDomBootstrap.cs
+7
-0
Modified
Source/XFESystem.Browser/BrowserLayoutEngine.cs
+1
-0
Modified
Source/XFESystem.Browser/BrowserPageResources.cs
+4
-0
Added
Source/XFESystem.Browser/BrowserSelectorKey.cs
+54
-0
Modified
Source/XFESystem.Browser/BrowserService.cs
+4
-0
Modified
Source/XFESystem.Browser/DomBridge.cs
+2
-2
Added
Source/XFESystem.NativeRuntime/Application/Web/NativeHttpConnectionPool.cs
+37
-0
Modified
Source/XFESystem.NativeRuntime/Application/Web/NativeHttpProtocol.cs
+14
-2
Modified
Source/XFESystem.NativeRuntime/Application/Web/NativeWebTransport.cs
+65
-17
Modified
Tests/XFESystem.Browser.Tests/BackgroundPageTests.cs
+21
-1
Modified
Tests/XFESystem.Browser.Tests/BrowserCssCacheTests.cs
+3
-0
Added
Tests/XFESystem.Browser.Tests/MinifiedStylesheetTests.cs
+23
-0
Added
Tests/XFESystem.Browser.Tests/SelectorIndexTests.cs
+77
-0
Added
Tests/XFESystem.HttpProtocol.Tests/IndependentConnectionReuseTests.cs
+82
-0
Modified
Tests/XFESystem.HttpProtocol.Tests/XFESystem.HttpProtocol.Tests.csproj
+2
-0
Added
Tools/BrowserCompatibility/PreviewProfile/CompareLoading.ps1
+52
-0
Added
Tools/BrowserCompatibility/PreviewProfile/LoadingProfile.cs
+83
-0
Modified
Tools/BrowserCompatibility/PreviewProfile/Packages.lock.json
+4
-0
Modified
Tools/BrowserCompatibility/PreviewProfile/Program.cs
+1
-0
Added
Tools/IndependentKernel/TestLoadSpeed.py
+225
-0
XFEstudio/XFESystem
Speed up CSS loading and reuse native web connections
60fcee1
代码差异
23 个文件
+801
-48
@@ -178,8 +178,9 @@ public sealed class BackgroundBrowserEditorSession : IBackgroundEditorSession
178
178
private void Work()
179
179
{
180
180
var finishedReadbacks = new List<Completion>();
181
bool succeeded = false;
181
182
try
182
{ WorkCore(finishedReadbacks); }
183
{ WorkCore(finishedReadbacks); succeeded = true; }
183
184
catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
184
185
{
185
186
if(Volatile.Read(ref cancelled)==0)
@@ -195,6 +196,11 @@ public sealed class BackgroundBrowserEditorSession : IBackgroundEditorSession
195
196
// and the explicit Legacy runtime entry, which has limited unwinding.
196
197
Volatile.Write(ref scheduled, 0);
197
198
if(Volatile.Read(ref cancelled)!=0)RetireOnOwner();
199
// Continue finite loading work without waiting for the UI's 50 ms
200
// timer between every library. Each script remains a separate FIFO
201
// work item, so input and other pages can run between them. Never
202
// spin while waiting for the first actual presentation or after error.
203
else if (succeeded && page.DocumentEnhancementsPending && !page.NeedsDocumentFirstPresentation) EnsureQueued();
198
204
}
199
205
internal void RetireOnOwner()
200
206
{
@@ -26,28 +26,31 @@ internal sealed class BrowserCssCascade
26
26
private readonly record struct Declaration(string Name, string Value, bool Important);
27
27
private readonly record struct Winner(bool Important, bool Inline, int Specificity, long Order, string Value);
28
28
private readonly List<Rule> rules = [];
29
private readonly List<Rule> generalRules = [];
30
private readonly Dictionary<string, List<Rule>> classRules = new(StringComparer.OrdinalIgnoreCase);
31
private IEnumerable<Rule> Candidates(IElement element)
29
private sealed class RuleBucket
32
30
{
33
foreach (var rule in generalRules) yield return rule;
34
foreach (string name in element.ClassList)
35
if (classRules.TryGetValue(name, out var matching)) foreach (var rule in matching) yield return rule;
31
internal readonly List<Rule> General = [];
32
internal readonly Dictionary<string, List<Rule>> Ids = new(StringComparer.OrdinalIgnoreCase),
33
Classes = new(StringComparer.OrdinalIgnoreCase), Tags = new(StringComparer.OrdinalIgnoreCase);
34
}
35
private readonly Dictionary<string, RuleBucket> selectorBuckets = new(StringComparer.Ordinal);
36
private IEnumerable<Rule> Candidates(IElement element, string pseudo = "")
37
{
38
if (!selectorBuckets.TryGetValue(pseudo, out var bucket)) yield break;
39
foreach (var rule in bucket.General) yield return rule;
40
if (bucket.Tags.TryGetValue(element.LocalName, out var tags)) foreach (var rule in tags) yield return rule;
41
if (element.Id is { } id && bucket.Ids.TryGetValue(id, out var ids)) foreach (var rule in ids) yield return rule;
42
foreach (string name in element.ClassList.Distinct(StringComparer.OrdinalIgnoreCase))
43
if (bucket.Classes.TryGetValue(name, out var matching)) foreach (var rule in matching) yield return rule;
36
44
}
37
45
private void AddRule(Rule rule)
38
46
{
39
47
rules.Add(rule);
40
string selector = rule.Selector;
41
// Only a single unescaped ASCII class can enter the index. All complex
42
// selectors keep the full matcher, including :is/:not and combinators.
43
if (selector.Length > 1 && selector[0] == '.' &&
44
selector.AsSpan(1).IndexOfAnyExcept("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-".AsSpan()) < 0)
45
{
46
string name = selector[1..];
47
if (!classRules.TryGetValue(name, out var matching)) classRules[name] = matching = [];
48
matching.Add(rule);
49
}
50
else generalRules.Add(rule);
48
if (!selectorBuckets.TryGetValue(rule.Pseudo, out var bucket)) selectorBuckets[rule.Pseudo] = bucket = new();
49
var key = BrowserSelectorKey.Find(rule.Selector);
50
if (key is not { } found) { bucket.General.Add(rule); return; }
51
var index = found.Kind == '#' ? bucket.Ids : found.Kind == '.' ? bucket.Classes : bucket.Tags;
52
if (!index.TryGetValue(found.Value, out var matching)) index[found.Value] = matching = [];
53
matching.Add(rule);
51
54
}
52
55
private int characters, declarations, comparisons, order;
53
56
private int parsedDeclarations, parsedOrder;
@@ -59,6 +62,7 @@ internal sealed class BrowserCssCascade
59
62
private sealed class InteractionHolder { public BrowserInteractionState Value = new(); }
60
63
public long ParseGeneration { get; private set; }
61
64
public long ReuseCount { get; private set; }
65
public int SelectorEvaluations => comparisons;
62
66
internal bool InteractionChangesStyles(BrowserInteractionState before, BrowserInteractionState after, IEnumerable<IElement> elements)
63
67
{
64
68
var relevant = rules.Where(rule => rule.Selector.Contains(":hover", StringComparison.OrdinalIgnoreCase) ||
@@ -160,7 +164,7 @@ internal sealed class BrowserCssCascade
160
164
}
161
165
else
162
166
{
163
validSources = false; rules.Clear(); generalRules.Clear(); classRules.Clear(); sources.Clear(); parseMessages.Clear(); characters = declarations = order = 0;
167
validSources = false; rules.Clear(); selectorBuckets.Clear(); sources.Clear(); parseMessages.Clear(); characters = declarations = order = 0;
164
168
foreach (string source in currentSources) ParseSheet(source);
165
169
parsedDeclarations = declarations; parsedOrder = order; parsedViewport = viewport;
166
170
sources.AddRange(currentSources); parseMessages.AddRange(messages); validSources = true; ParseGeneration++;
@@ -175,7 +179,7 @@ internal sealed class BrowserCssCascade
175
179
}
176
180
public void ResetDocument()
177
181
{
178
validSources = false; rules.Clear(); generalRules.Clear(); classRules.Clear(); sources.Clear(); currentSources.Clear(); parseMessages.Clear(); complexTexts.Clear();
182
validSources = false; rules.Clear(); selectorBuckets.Clear(); sources.Clear(); currentSources.Clear(); parseMessages.Clear(); complexTexts.Clear();
179
183
styleOwners.Clear(); removedOwners.Clear(); textSegments.Clear(); messages.Clear(); interaction.Value = new();
180
184
selectorParser = CreateParser(interaction); characters = declarations = comparisons = order = parsedDeclarations = parsedOrder = 0;
181
185
}
@@ -265,9 +269,8 @@ internal sealed class BrowserCssCascade
265
269
// candidates before copying the inherited custom-property environment;
266
270
// the website's theme can otherwise be copied twice for every element.
267
271
Dictionary<string, Winner>? winning = null;
268
foreach (var rule in Candidates(element))
272
foreach (var rule in Candidates(element, pseudo))
269
273
{
270
if (rule.Pseudo!=pseudo) continue;
271
274
if (++comparisons > limits.MaximumSelectorEvaluations) throw new BrowserLimitException("CSS selector evaluation limit reached.");
272
275
if (rule.Matcher.Match(element, element.Owner?.DocumentElement ?? element))
273
276
{ winning ??= new(StringComparer.OrdinalIgnoreCase); Apply(rule.Declarations, false, rule.Specificity, rule.Order, winning); }
@@ -315,8 +318,11 @@ internal sealed class BrowserCssCascade
315
318
{
316
319
while (offset < css.Length && char.IsWhiteSpace(css[offset])) offset++;
317
320
int open = Find(css, offset, '{');
318
int semicolon = Find(css, offset, ';');
319
321
if (open < 0) break;
322
// Only an at-rule's prelude can end at this semicolon. Looking
323
// through the rest of the sheet made minified one-declaration
324
// rules (notably the icon font) quadratic when they omit ';'.
325
int semicolon = Find(css, offset, ';', open);
320
326
if (semicolon >= 0 && semicolon < open) { Note("Unsupported CSS at-rule: " + WithoutComments(css,offset,semicolon-offset)); offset = semicolon + 1; continue; }
321
327
int close = Matching(css, open, '{', '}');
322
328
if (close < 0) { Note("Malformed CSS block ignored"); break; }
@@ -583,10 +589,11 @@ internal sealed class BrowserCssCascade
583
589
}
584
590
return result.ToString();
585
591
}
586
private static int Find(string text, int offset, char target)
592
private static int Find(string text, int offset, char target, int limit = -1)
587
593
{
594
if (limit < 0) limit = text.Length;
588
595
char quote = '\0'; int parentheses = 0, brackets = 0;
589
for (int i = offset; i < text.Length; i++)
596
for (int i = offset; i < limit; i++)
590
597
{
591
598
char c = text[i]; if (quote != '\0') { if (c == quote && (i == 0 || text[i - 1] != '\\')) quote = '\0'; continue; }
592
599
if (c is '\'' or '"') { quote = c; continue; }
@@ -170,7 +170,8 @@ public sealed partial class BrowserService
170
170
",\"ExecutedScriptCount\":" + executedScripts.Count + ",\"ScalePercent\":" + documentPaintScale +
171
171
",\"FirstPaintPhases\":{\"ClockFrequency\":" + System.Diagnostics.Stopwatch.Frequency + ",\"MarkdownConvertTicks\":" + documentMarkdownTicks +
172
172
",\"HtmlParseTicks\":" + documentHtmlTicks + ",\"StylesheetFetchTicks\":" + documentStyleFetchTicks + ",\"StylesheetParseTicks\":" + documentStylesheetParseTicks +
173
",\"LayoutTicks\":" + documentLayoutTicks + ",\"LayoutIncludesStylesheetParsing\":true,\"RasterPaintTicks\":" + documentRasterTicks +
173
",\"LayoutTicks\":" + documentLayoutTicks + ",\"SelectorEvaluations\":" + layoutEngine.CssSelectorEvaluations +
174
",\"LayoutIncludesStylesheetParsing\":true,\"RasterPaintTicks\":" + documentRasterTicks +
174
175
",\"FrameCacheStoreTicks\":" + documentFrameCacheTicks + ",\"PresentationTicks\":" + documentPresentationTicks + "}" +
175
176
",\"Viewport\":{\"X\":" + documentPaintBounds.X + ",\"Y\":" + documentPaintBounds.Y + ",\"Width\":" + documentPaintBounds.Width +
176
177
",\"Height\":" + documentPaintBounds.Height + "},\"Heading\":" + Element(article?.QuerySelector("h1,h2,h3"), true) +
@@ -3,6 +3,13 @@ namespace XFESystem.Browser;
3
3
/// <summary>Trusted, interpreter-executed Web API prototypes. Host objects only expose explicit primitive callbacks.</summary>
4
4
internal static class BrowserDomBootstrap
5
5
{
6
// Syntax is reusable; each evaluation still creates fresh prototypes,
7
// WeakMaps, closures and globals belonging to its engine.
8
private static readonly Lazy<Jint.Prepared<Acornima.Ast.Script>> prepared = new(() =>
9
Jint.Engine.PrepareScript(Source, "xfesystem:dom-bootstrap", strict: false,
10
options: new Jint.ScriptPreparationOptions { FoldConstants = false }));
11
internal static Jint.Prepared<Acornima.Ast.Script> Prepared => prepared.Value;
12
internal static readonly Jint.Prepared<Acornima.Ast.Script> FlushJobs = Jint.Engine.PrepareScript("void 0");
6
13
internal const string Source = """
7
14
(function() {
8
15
const listenerAdded=__xfeListenerAdded,listenerRemoved=__xfeListenerRemoved,eventError=__xfeEventError,observerAdded=__xfeObserverAdded;
@@ -37,6 +37,7 @@ public sealed class BrowserLayoutEngine(BrowserCssLimits? limits = null)
37
37
private BrowserLayoutBox? canvasBackgroundOwner;
38
38
public long CssParseGeneration => cascade?.ParseGeneration ?? 0;
39
39
public long CssReuseCount => cascade?.ReuseCount ?? 0;
40
public int CssSelectorEvaluations => cascade?.SelectorEvaluations ?? 0;
40
41
public long LastStylesheetParseTicks { get; private set; }
41
42
internal bool InteractionChangesStyles(BrowserInteractionState before, BrowserInteractionState after) =>
42
43
cascade is null || cascade.InteractionChangesStyles(before, after, all.Where(box => box.Node is IElement).Select(box => (IElement)box.Node).Distinct());
@@ -54,11 +54,15 @@ public sealed partial class BrowserService
54
54
CheckOperationCancellation();
55
55
long previousRevision = Revision;
56
56
dom!.CurrentScript = script;
57
long scriptStarted = System.Diagnostics.Stopwatch.GetTimestamp();
57
58
var result = external && resourceLoader!.LastResponsePackaged
58
59
? runtime!.EvaluatePackaged(source, ResourceAddress(script.GetAttribute("src")!).AbsoluteUri)
59
60
: runtime!.Evaluate(source);
60
61
dom.CurrentScript = null;
61
62
Trace?.Invoke("XFE_BROWSER_SCRIPT_END|" + (script.GetAttribute("src") ?? "Inline") + "|Success|" + result.Success + "\n");
63
Trace?.Invoke("XFE_BROWSER_SCRIPT_TIMING|" + (script.GetAttribute("src") ?? "Inline") +
64
"|Ticks|" + (System.Diagnostics.Stopwatch.GetTimestamp() - scriptStarted) +
65
"|Frequency|" + System.Diagnostics.Stopwatch.Frequency + "\n");
62
66
CheckOperationCancellation();
63
67
if (result.ConsoleOutput.Length != 0) Diagnostic(result.ConsoleOutput);
64
68
if (!result.Success) Diagnostic("JavaScript error: " + result.Error);
@@ -0,0 +1,54 @@
1
namespace XFESystem.Browser;
2
3
/// <summary>A necessary positive key in the subject compound, never a substitute for selector matching.</summary>
4
internal static class BrowserSelectorKey
5
{
6
internal static (char Kind, string Value)? Find(string selector)
7
{
8
// Escapes, namespaces and non-ASCII identifiers stay on the general
9
// path. In particular, a prefix of an escaped/Unicode name is no key.
10
foreach (char c in selector) if (c == '\\' || c == '|' || c > 127) return null;
11
int start = 0, brackets = 0, parentheses = 0;
12
char quote = '\0';
13
for (int i = 0; i < selector.Length; i++)
14
{
15
char c = selector[i];
16
if (quote != '\0') { if (c == quote) quote = '\0'; continue; }
17
if (c is '\'' or '"') { quote = c; continue; }
18
if (c == '[') brackets++;
19
else if (c == ']') brackets--;
20
else if (brackets == 0 && c == '(') parentheses++;
21
else if (brackets == 0 && c == ')') parentheses--;
22
else if (brackets == 0 && parentheses == 0 && (char.IsWhiteSpace(c) || c is '>' or '+' or '~')) start = i + 1;
23
}
24
if (brackets != 0 || parentheses != 0 || quote != '\0') return null;
25
string? tag = null, name = null;
26
if (start < selector.Length && (char.IsAsciiLetter(selector[start]) || selector[start] is '_' or '-'))
27
{
28
int end = start;
29
while (end < selector.Length && Identifier(selector[end])) end++;
30
tag = selector[start..end];
31
}
32
for (int i = start; i < selector.Length; i++)
33
{
34
char c = selector[i];
35
if (quote != '\0') { if (c == quote) quote = '\0'; continue; }
36
if (c is '\'' or '"') { quote = c; continue; }
37
if (c == '[') brackets++;
38
else if (c == ']') brackets--;
39
else if (brackets == 0 && c == '(') parentheses++;
40
else if (brackets == 0 && c == ')') parentheses--;
41
else if (brackets == 0 && parentheses == 0 && c is '#' or '.')
42
{
43
int end = i + 1;
44
while (end < selector.Length && Identifier(selector[end])) end++;
45
if (end == i + 1) return null;
46
if (c == '#') return ('#', selector[(i + 1)..end]);
47
name ??= selector[(i + 1)..end];
48
i = end - 1;
49
}
50
}
51
return name is not null ? ('.', name) : tag is not null ? ('t', tag) : null;
52
}
53
private static bool Identifier(char c) => char.IsAsciiLetterOrDigit(c) || c is '_' or '-';
54
}
@@ -297,6 +297,7 @@ public sealed partial class BrowserService : IJavaScriptPreviewService, IInterac
297
297
} : limits;
298
298
ResetDocumentLoading();
299
299
documentHtmlTicks = htmlTicks;
300
long runtimeStarted = System.Diagnostics.Stopwatch.GetTimestamp();
300
301
runtime = deferDocumentScripts ? null : new(activeLimits);
301
302
CheckOperationCancellation();
302
303
resourceLoader = new(transport, resources, target, activeLimits, trustedDocument);
@@ -306,6 +307,9 @@ public sealed partial class BrowserService : IJavaScriptPreviewService, IInterac
306
307
tracePumps = tracePaints = 0;
307
308
pageDiagnostics = new(activeLimits.MaximumOutputCharacters);
308
309
dom = deferDocumentScripts ? null : new DomBridge(runtime!, document, target, activeLimits, CreateDomHost());
310
long runtimeTicks = System.Diagnostics.Stopwatch.GetTimestamp() - runtimeStarted;
311
Trace?.Invoke("XFE_BROWSER_LOAD_TIMING|HtmlParseTicks|" + htmlTicks + "|RuntimeAndDomTicks|" + runtimeTicks +
312
"|Frequency|" + System.Diagnostics.Stopwatch.Frequency + "\n");
309
313
var scripts = document.QuerySelectorAll("script").ToArray();
310
314
if (scripts.Length > limits.MaximumScripts)
311
315
throw new BrowserLimitException("The document exceeds its script count limit.");
@@ -49,7 +49,7 @@ public sealed partial class DomBridge
49
49
}));
50
50
InstallEncodingCallbacks();
51
51
InstallCssomCallbacks();
52
bootstrap = engine.Evaluate(BrowserDomBootstrap.Source).AsObject();
52
bootstrap = engine.Evaluate(BrowserDomBootstrap.Prepared).AsObject();
53
53
engine.SetValue("document", Wrap(document));
54
54
InstallWindow();
55
55
}
@@ -75,7 +75,7 @@ public sealed partial class DomBridge
75
75
Data(values, "data", init.Data); Data(values, "inputType", init.InputType);
76
76
var evt = engine.Invoke(bootstrap.Get("event"), bootstrap, [(JsValue)type, values]);
77
77
var result = engine.Invoke(bootstrap.Get("dispatch"), bootstrap, [target is null ? engine.Global : Wrap(target), evt]);
78
engine.Evaluate("void 0"); return result.AsBoolean();
78
engine.Evaluate(BrowserDomBootstrap.FlushJobs); return result.AsBoolean();
79
79
}
80
80
81
81
public void CompleteLoading()
@@ -0,0 +1,37 @@
1
namespace XFESystem.NativeRuntime.Application.Web;
2
3
/// <summary>One idle, same-origin wire connection. No response bytes or cookies are cached.</summary>
4
internal sealed class NativeHttpConnectionPool
5
{
6
internal sealed class Connection(Uri origin, Stream wire, Action<long> setDeadline, Action close,
7
bool certificateValidated, string protocol)
8
{
9
private int closed;
10
public Uri Origin { get; } = origin;
11
public Stream Wire { get; } = wire;
12
public bool CertificateValidated { get; } = certificateValidated;
13
public string Protocol { get; } = protocol;
14
public void SetDeadline(long deadline) => setDeadline(deadline);
15
public void Close() { if (Interlocked.Exchange(ref closed, 1) == 0) close(); }
16
}
17
private Connection? idle;
18
private long returnedAt;
19
// Called only under NativeWebTransport's single ownership gate. The
20
// network has one active TCP stream, so close before opening another.
21
internal Connection Take(Uri target, long now, long deadline, Func<Connection> open, out bool reused)
22
{
23
var candidate = idle; idle = null;
24
reused = candidate is not null && now >= returnedAt && now - returnedAt <= 10_000 &&
25
target.Scheme == candidate.Origin.Scheme && target.IdnHost.Equals(candidate.Origin.IdnHost, StringComparison.OrdinalIgnoreCase) &&
26
target.Port == candidate.Origin.Port && (target.Scheme != "https" || candidate.CertificateValidated);
27
if (!reused) { candidate?.Close(); candidate = open(); }
28
try { candidate!.SetDeadline(deadline); return candidate; }
29
catch { candidate!.Close(); throw; }
30
}
31
internal void Return(Connection connection, bool canReuse, long now)
32
{
33
idle?.Close(); idle = null;
34
if (canReuse) { idle = connection; returnedAt = now; }
35
else connection.Close();
36
}
37
}
@@ -6,7 +6,10 @@ namespace XFESystem.NativeRuntime.Application.Web;
6
6
// Bounded HTTP framing shared in semantics with the legacy tested reader.
7
7
// This implementation depends on a supplied Stream read, never host sockets.
8
8
internal sealed record NativeHttpResponse(int StatusCode, string ContentType, byte[] Body,
9
string? Location, string? ContentSecurityPolicy, IReadOnlyDictionary<string,string> Headers, string StatusLine);
9
string? Location, string? ContentSecurityPolicy, IReadOnlyDictionary<string,string> Headers, string StatusLine)
10
{
11
public bool CanReuseConnection { get; init; }
12
}
10
13
11
14
/// <summary>Bounded HTTP framing over actual stream bytes, retaining parsed response headers.</summary>
12
15
internal static class NativeHttpProtocol
@@ -85,7 +88,15 @@ internal static class NativeHttpProtocol
85
88
int count;
86
89
while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) body.Append(buffer, count);
87
90
}
88
return new(status, contentType ?? "text/plain; charset=utf-8", body.ToArray(), location, csp, headers, statusLine);
91
// Only fully consumed, explicitly framed HTTP/1.1 responses qualify.
92
// Redirect bodies are deliberately not consumed above and never pool.
93
bool close = headers.TryGetValue("Connection", out var connection) &&
94
connection.Split(',').Any(token => token.Trim().Equals("close", StringComparison.OrdinalIgnoreCase));
95
return new(status, contentType ?? "text/plain; charset=utf-8", body.ToArray(), location, csp, headers, statusLine)
96
{
97
CanReuseConnection = statusLine.StartsWith("HTTP/1.1 ", StringComparison.Ordinal) &&
98
(hasLength || hasTransfer) && !close && reader.BufferedBytes == 0
99
};
89
100
}
90
101
91
102
public static string DecodeBody(NativeHttpResponse response)
@@ -157,6 +168,7 @@ internal static class NativeHttpProtocol
157
168
private readonly byte[] buffer = new byte[4_096];
158
169
private int position;
159
170
private int length;
171
public int BufferedBytes => length - position;
160
172
161
173
public int Byte()
162
174
{
@@ -16,6 +16,7 @@ internal sealed class NativeWebTransport : IWebTransport, IWebTransportCapabilit
16
16
private static readonly object gate = new();
17
17
private static TlsCertificateValidator? certificates;
18
18
private static int requestId;
19
private static readonly NativeHttpConnectionPool connections = new();
19
20
public bool IsNative => true;
20
21
public bool SupportsHttp => true;
21
22
public bool SupportsHttps => true;
@@ -68,25 +69,15 @@ internal sealed class NativeWebTransport : IWebTransport, IWebTransportCapabilit
68
69
string headers = "GET " + target.PathAndQuery + " HTTP/1.1\r\nHost: " + authority +
69
70
"\r\nUser-Agent: Mozilla/5.0 (XFESystem; x86_64) XFEWeb/0.3\r\n" +
70
71
"Accept: text/html,application/xhtml+xml,text/css,application/javascript,text/plain,*/*;q=0.5\r\n" +
71
"Accept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n";
72
"Accept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\nAccept-Encoding: identity\r\nConnection: keep-alive\r\n\r\n";
72
73
NativePlatform.Write("XFE_NATIVE_WEB_REQUEST|" + id + "|" + target.AbsoluteUri + "\n");
73
using Stream tcp = NativeNetwork.OpenTcp(host, target.Port, Remaining(deadline));
74
using var bounded = new DeadlineStream(tcp, deadline);
75
long handshakeStarted = NativePlatform.Milliseconds();
76
using TlsClientConnection? tls = target.Scheme == "https"
77
? new TlsClientConnection(bounded, host, Roots(), NativeTlsSecurity.Context) : null;
78
if (tls is not null) NativePlatform.Write("XFE_NATIVE_TLS_CONNECTED|Host|" + host + "|Verified|" +
79
(tls.CertificateValidated ? 1 : 0) + "|Protocol|" + tls.Protocol + "|InitializationAndHandshakeMilliseconds|" +
80
(NativePlatform.Milliseconds() - handshakeStarted) + "\n");
81
Stream wire = tls?.Stream ?? bounded;
82
byte[] request = Encoding.ASCII.GetBytes(headers);
83
wire.Write(request, 0, request.Length); wire.Flush();
84
var response = NativeHttpProtocol.ReadResponse((buffer, offset, count) =>
85
wire.Read(buffer, offset, count), checked(limits.MaximumHtmlCharacters * 4));
74
long started = NativePlatform.Milliseconds();
75
var (response, verified, protocol, reused) = Request(target, headers, limits, deadline);
86
76
string body = NativeHttpProtocol.DecodeBody(response);
87
77
if (body.Length > limits.MaximumHtmlCharacters) throw new BrowserLimitException("The decoded response exceeds its character limit.");
88
bool verified = tls?.CertificateValidated == true;
89
EmitResponse(id, target, headers, response, body, verified, tls?.Protocol ?? "HTTP");
78
NativePlatform.Write("XFE_NATIVE_WEB_TIMING|RequestId|" + id + "|TotalMilliseconds|" +
79
(NativePlatform.Milliseconds() - started) + "|ConnectionReused|" + (reused ? 1 : 0) + "\n");
80
EmitResponse(id, target, headers, response, body, verified, protocol);
90
81
if (response.StatusCode is 301 or 302 or 303 or 307 or 308)
91
82
{
92
83
if (redirects >= limits.MaximumRedirects) throw new IOException("The HTTP redirect limit was reached.");
@@ -102,6 +93,59 @@ internal sealed class NativeWebTransport : IWebTransport, IWebTransportCapabilit
102
93
finally { Monitor.Exit(gate); }
103
94
}
104
95
96
private static NativeHttpConnectionPool.Connection OpenConnection(Uri target, long deadline)
97
{
98
Stream tcp = NativeNetwork.OpenTcp(target.IdnHost, target.Port, Remaining(deadline));
99
var bounded = new DeadlineStream(tcp, deadline);
100
TlsClientConnection? tls = null;
101
try
102
{
103
long started = NativePlatform.Milliseconds();
104
if (target.Scheme == "https")
105
{
106
tls = new(bounded, target.IdnHost, Roots(), NativeTlsSecurity.Context);
107
NativePlatform.Write("XFE_NATIVE_TLS_CONNECTED|Host|" + target.IdnHost + "|Verified|" +
108
(tls.CertificateValidated ? 1 : 0) + "|Protocol|" + tls.Protocol +
109
"|InitializationAndHandshakeMilliseconds|" + (NativePlatform.Milliseconds() - started) + "\n");
110
}
111
return new(target, tls?.Stream ?? bounded, bounded.SetDeadline, () =>
112
{
113
// Closing has the TCP stream's own finite close budget. A stale
114
// HTTP deadline must not stop owner/resource cleanup.
115
try { tls?.Dispose(); } finally { tcp.Dispose(); }
116
}, tls?.CertificateValidated == true, tls?.Protocol ?? "HTTP");
117
}
118
catch { try { tls?.Dispose(); } finally { tcp.Dispose(); } throw; }
119
}
120
121
private static (NativeHttpResponse Response, bool Verified, string Protocol, bool Reused) Request(
122
Uri target, string headers, BrowserLimits limits, long deadline)
123
{
124
byte[] request = Encoding.ASCII.GetBytes(headers);
125
for (int attempt = 0; ; attempt++)
126
{
127
var connection = connections.Take(target, NativePlatform.Milliseconds(), deadline, () => OpenConnection(target, deadline), out bool reused);
128
long received = 0;
129
try
130
{
131
connection.Wire.Write(request, 0, request.Length); connection.Wire.Flush();
132
var response = NativeHttpProtocol.ReadResponse((buffer, offset, count) =>
133
{
134
int read = connection.Wire.Read(buffer, offset, count); received += read; return read;
135
}, checked(limits.MaximumHtmlCharacters * 4));
136
connections.Return(connection, response.CanReuseConnection, NativePlatform.Milliseconds());
137
return (response, connection.CertificateValidated, connection.Protocol, reused);
138
}
139
catch (IOException) when (reused && attempt == 0 && received == 0 && NativePlatform.Milliseconds() < deadline)
140
{
141
// One idempotent GET retry for a silently closed idle socket.
142
// Partial/malformed responses and fresh failures are not retried.
143
connection.Close();
144
}
145
catch { connection.Close(); throw; }
146
}
147
}
148
105
149
private static int Remaining(long deadline)
106
150
{
107
151
long remaining = deadline - NativePlatform.Milliseconds();
@@ -152,17 +196,21 @@ internal sealed class NativeWebTransport : IWebTransport, IWebTransportCapabilit
152
196
153
197
private sealed class DeadlineStream(Stream inner, long deadline) : Stream
154
198
{
199
private long deadlineMilliseconds = deadline;
200
public void SetDeadline(long value) => deadlineMilliseconds = value;
155
201
public override bool CanRead => true; public override bool CanWrite => true; public override bool CanSeek => false;
156
202
public override long Length => throw new NotSupportedException();
157
203
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
158
204
private void Check()
159
205
{
160
int left = Remaining(deadline);
206
int left = Remaining(deadlineMilliseconds);
161
207
if (!inner.CanTimeout) throw new IOException("The native TCP stream cannot enforce bounded web I/O.");
162
208
inner.ReadTimeout = left; inner.WriteTimeout = left;
163
209
}
164
210
public override int Read(byte[] buffer, int offset, int count) { Check(); int read = inner.Read(buffer, offset, count); Check(); return read; }
211
public override int Read(Span<byte> buffer) { Check(); int read = inner.Read(buffer); Check(); return read; }
165
212
public override void Write(byte[] buffer, int offset, int count) { Check(); inner.Write(buffer, offset, count); Check(); }
213
public override void Write(ReadOnlySpan<byte> buffer) { Check(); inner.Write(buffer); Check(); }
166
214
public override void Flush() { Check(); inner.Flush(); }
167
215
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
168
216
public override void SetLength(long value) => throw new NotSupportedException();