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
4 changes: 1 addition & 3 deletions .github/workflows/database-contracts.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ jobs:

- name: Run Database Contract Suite
run: >
dotnet test Tests/GameFrameX.Tests/GameFrameX.Tests.csproj --no-build

--logger GitHubActions
dotnet test Tests/GameFrameX.Tests/GameFrameX.Tests.csproj --no-build --logger GitHubActions

- name: Run Hotfix and Wrapper Assembly Tests
run: dotnet test Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj --no-build --logger GitHubActions
Expand Down
87 changes: 85 additions & 2 deletions GameFrameX.Network.HTTP/HttpActionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@
namespace GameFrameX.Network.HTTP;

/// <summary>
/// HTTP 处理管线统一请求上下文,承载客户端 IP、请求 URL、参数字典、消息对象与请求消息对象。
/// HTTP 处理管线统一请求上下文,承载客户端 IP、请求 URL、参数字典、消息对象与请求消息对象,
/// 以及请求头快照、HTTP 方法、Content-Type、追踪标识、原始查询串、Cookie、Scheme、本机判定与请求中断令牌。
/// </summary>
/// <remarks>
/// Unified request context for the HTTP handling pipeline, carrying the client IP, request URL, parameter dictionary, message object, and request message object.
/// Unified request context for the HTTP handling pipeline, carrying the client IP, request URL, parameter dictionary, message object, and request message object,
/// plus the request header snapshot, HTTP method, Content-Type, trace identifier, raw query string, cookies, scheme, loopback flag, and request-abort token.
/// </remarks>
public sealed class HttpActionContext
{
Expand Down Expand Up @@ -66,6 +68,87 @@ public sealed class HttpActionContext
/// <value>请求参数字典 / Request parameter dictionary</value>
public Dictionary<string, object> Parameters { get; init; }

/// <summary>
/// 获取请求头快照(键不区分大小写;同名多值以逗号合并),供业务处理器读取鉴权头、User-Agent 等原样信息。
/// </summary>
/// <remarks>
/// Gets the request header snapshot (case-insensitive keys; multiple values of the same name joined by comma), allowing business handlers to read authorization headers, User-Agent, etc. verbatim.
/// </remarks>
/// <value>请求头快照 / Request header snapshot</value>
public Dictionary<string, string> Headers { get; init; }

/// <summary>
/// 获取 HTTP 请求方法(GET/POST 等)。
/// </summary>
/// <remarks>
/// Gets the HTTP request method (GET/POST, etc.).
/// </remarks>
/// <value>HTTP 请求方法 / HTTP request method</value>
public string Method { get; init; }

/// <summary>
/// 获取请求体的 Content-Type;无请求体时为 null。
/// </summary>
/// <remarks>
/// Gets the Content-Type of the request body; null when the request has no body.
/// </remarks>
/// <value>请求体 Content-Type / Request body Content-Type</value>
public string ContentType { get; init; }

/// <summary>
/// 获取请求的追踪标识(关联标识),用于日志与链路追踪对齐。
/// </summary>
/// <remarks>
/// Gets the trace identifier (correlation identifier) of the request, used for log and tracing alignment.
/// </remarks>
/// <value>追踪标识 / Trace identifier</value>
public string TraceIdentifier { get; init; }

/// <summary>
/// 获取原始查询串(含前导 '?';无查询参数时为空串),供签名校验与原样日志使用。
/// </summary>
/// <remarks>
/// Gets the raw query string (with leading '?'; empty when absent), for signature validation and verbatim logging.
/// </remarks>
/// <value>原始查询串 / Raw query string</value>
public string QueryString { get; init; }

/// <summary>
/// 获取解析后的请求 Cookie(键不区分大小写)。
/// </summary>
/// <remarks>
/// Gets the parsed request cookies (case-insensitive keys).
/// </remarks>
/// <value>请求 Cookie 字典 / Request cookie dictionary</value>
public IReadOnlyDictionary<string, string> Cookies { get; init; }

/// <summary>
/// 获取请求协议方案(http/https),供构造回调绝对地址。
/// </summary>
/// <remarks>
/// Gets the request scheme (http/https), for building absolute callback URLs.
/// </remarks>
/// <value>请求方案 / Request scheme</value>
public string Scheme { get; init; }

/// <summary>
/// 获取请求是否来自本机回环地址(GM / 运维端点信任本机的判定依据)。
/// </summary>
/// <remarks>
/// Gets whether the request originates from a loopback address (basis for trusting local GM / operation endpoints).
/// </remarks>
/// <value>是否本机请求 / Whether the request is local</value>
public bool IsLocal { get; init; }

/// <summary>
/// 获取请求中断令牌:客户端断开连接时触发,长轮询 / 慢处理器应观测该令牌提前释放资源。
/// </summary>
/// <remarks>
/// Gets the request-abort token: fired when client disconnects; long-poll or slow handlers should observe it to release early.
/// </remarks>
/// <value>请求中断令牌 / Request abort token</value>
public CancellationToken RequestAborted { get; init; }

/// <summary>
/// 获取 ProtoBuf 形态的消息对象。
/// </summary>
Expand Down
24 changes: 22 additions & 2 deletions GameFrameX.Network.HTTP/HttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
/// <param name="baseHandler">基础 HTTP 处理器工厂方法,根据命令名称返回对应的处理器 / Base HTTP handler factory method that returns the corresponding handler based on command name</param>
/// <param name="aopHandlerTypes">AOP 处理器列表,可选 / AOP handler list, optional</param>
/// <returns>表示异步操作的任务 / A task representing the asynchronous operation</returns>
public static async Task HandleRequestAsync(HttpContext context, Func<string, BaseHttpHandler> baseHandler, List<IHttpAopHandler> aopHandlerTypes = null)

Check failure on line 81 in GameFrameX.Network.HTTP/HttpHandler.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=GameFrameX.Server.Source&issues=AaII-8PN1-9moRit9FjH&open=AaII-8PN1-9moRit9FjH&pullRequest=998
{
var ip = context.Connection.RemoteIpAddress?.ToString();
string url = context.Request.PathBase + context.Request.Path;
Expand Down Expand Up @@ -123,7 +123,27 @@
LogHelper.Debug(LocalizationService.GetString(Localization.Keys.NetworkHttp.RequestParameters, JsonHelper.Serialize(paramMap)));
}

var actionContext = new HttpActionContext { Ip = ip, Url = url, Parameters = paramMap, MessageObject = message };
// 请求原样信息快照(头/方法/Content-Type/追踪标识/查询串/Cookie/Scheme/本机判定/中断令牌),供业务处理器按需读取
var requestHeaders = new Dictionary<string, string>(context.Request.Headers.Count, StringComparer.OrdinalIgnoreCase);
foreach (var header in context.Request.Headers)
{
requestHeaders[header.Key] = string.Join(", ", header.Value);

Check warning on line 130 in GameFrameX.Network.HTTP/HttpHandler.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Review this call, which partially matches an overload without 'params'. The partial match is 'string string.Join(string? separator, IEnumerable<string?> values)'.

See more on https://sonarcloud.io/project/issues?id=GameFrameX.Server.Source&issues=AaII-8PN1-9moRit9FjI&open=AaII-8PN1-9moRit9FjI&pullRequest=998
}

var requestCookies = new Dictionary<string, string>(context.Request.Cookies.Count, StringComparer.OrdinalIgnoreCase);
foreach (var cookie in context.Request.Cookies)
{
requestCookies[cookie.Key] = cookie.Value;
}

var requestMethod = context.Request.Method;
var requestContentType = context.Request.ContentType;
var traceIdentifier = context.TraceIdentifier;
var requestQueryString = context.Request.QueryString.Value ?? string.Empty;
var requestScheme = context.Request.Scheme;
var isLocalRequest = context.Connection.RemoteIpAddress is not null && System.Net.IPAddress.IsLoopback(context.Connection.RemoteIpAddress);
var requestAborted = context.RequestAborted;
var actionContext = new HttpActionContext { Ip = ip, Url = url, Parameters = paramMap, Headers = requestHeaders, Method = requestMethod, ContentType = requestContentType, TraceIdentifier = traceIdentifier, QueryString = requestQueryString, Cookies = requestCookies, Scheme = requestScheme, IsLocal = isLocalRequest, RequestAborted = requestAborted, MessageObject = message };
var validation = await TryValidateAndResolveHandlerAsync(context, baseHandler, command, actionContext, aopHandlerTypes);
if (!validation.IsValid)
{
Expand All @@ -147,7 +167,7 @@
else
{
var messageRequest = BuildHttpMessageRequest(mappingAttribute.RequestType, paramMap, jsonBody, queryStringParamCount);
var typedContext = new HttpActionContext { Ip = ip, Url = url, Parameters = paramMap, Request = messageRequest };
var typedContext = new HttpActionContext { Ip = ip, Url = url, Parameters = paramMap, Headers = requestHeaders, Method = requestMethod, ContentType = requestContentType, TraceIdentifier = traceIdentifier, QueryString = requestQueryString, Cookies = requestCookies, Scheme = requestScheme, IsLocal = isLocalRequest, RequestAborted = requestAborted, Request = messageRequest };
await ExecuteJsonMessageRequestAsync(context, handler, typedContext, logHeader);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
// ==========================================================================================

using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Http.Features;
Expand All @@ -41,6 +42,7 @@
using GameFrameX.Utility.Runtime;
using GameFrameX.Utility.Setting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace GameFrameX.Tests.Network.Http;

Expand Down Expand Up @@ -221,6 +223,34 @@ public async Task HandleRequest_ShouldNotAppendResponse_WhenAopWritesOwnResponse
}
}

[Fact]
public async Task HandleRequest_ShouldExposeRequestSnapshot_ForPlainJsonHandler()
{
EnsureSettings();
HttpActionContext captured = null;
var context = CreateContext("application/json", new MemoryStream(Encoding.UTF8.GetBytes("{\"userId\":2}")));
PrepareSnapshotRequest(context);

await HttpHandler.HandleRequestAsync(context, _ => new SnapshotCaptureHttpHandler(c => captured = c));

AssertSnapshot(captured, context);
Assert.Null(captured.Request);
}

[Fact]
public async Task HandleRequest_ShouldExposeRequestSnapshot_ForTypedRequestHandler()
{
EnsureSettings();
HttpActionContext captured = null;
var context = CreateContext("application/json", new MemoryStream(Encoding.UTF8.GetBytes("{\"userId\":2}")));
PrepareSnapshotRequest(context);

await HttpHandler.HandleRequestAsync(context, _ => new TypedSnapshotCaptureHttpHandler(c => captured = c));

AssertSnapshot(captured, context);
Assert.IsType<SnapshotProbeRequest>(captured.Request);
}

[Fact]
public void CheckSign_ShouldReturnLocalizedMessage_WhenSignParametersMissing()
{
Expand Down Expand Up @@ -258,6 +288,35 @@ private static DefaultHttpContext CreateContext(string contentType, Stream body)
return context;
}

// 构造携带自定义鉴权头、多值头、Cookie、查询串与回环地址的请求,用于断言 HttpActionContext 的原样信息快照
// Build a request with custom auth header, multi-value header, cookies, query string and loopback address to assert the verbatim snapshot on HttpActionContext
private static void PrepareSnapshotRequest(DefaultHttpContext context)
{
context.Request.Scheme = "http";
context.Request.QueryString = new QueryString("?trace=abc");
context.Request.Headers["X-HandshakeAuthorization"] = "session-token";
context.Request.Headers["Accept-Language"] = new StringValues(new[] { "zh-CN", "en-US", });
context.Request.Headers["Cookie"] = "session=cookie-value";
context.Connection.RemoteIpAddress = IPAddress.Loopback;
}

private static void AssertSnapshot(HttpActionContext captured, DefaultHttpContext context)
{
Assert.NotNull(captured);
Assert.Equal("POST", captured.Method);
Assert.Equal("application/json", captured.ContentType);
Assert.Equal("?trace=abc", captured.QueryString);
Assert.Equal("http", captured.Scheme);
Assert.True(captured.IsLocal);
Assert.Equal(context.TraceIdentifier, captured.TraceIdentifier);
Assert.False(string.IsNullOrEmpty(captured.TraceIdentifier));
Assert.Equal(context.RequestAborted, captured.RequestAborted);
// 键大小写不敏感:以与原头不同的大小写读取
Assert.Equal("session-token", captured.Headers["X-HANDSHAKEAUTHORIZATION"]);
Assert.Equal("zh-CN, en-US", captured.Headers["Accept-Language"]);
Assert.Equal("cookie-value", captured.Cookies["SESSION"]);
}

private static async Task<JsonElement> ReadEnvelopeAsync(DefaultHttpContext context)
{
context.Response.Body.Seek(0, SeekOrigin.Begin);
Expand Down Expand Up @@ -373,6 +432,50 @@ private sealed class ValidationProbeRequest : IHttpMessageRequest
public string OptionalName { get; set; }
}

/// <summary>
/// 快照捕获处理器(普通 JSON 路径):捕获 <see cref="HttpActionContext"/> 以断言请求原样信息快照。
/// </summary>
private sealed class SnapshotCaptureHttpHandler : BaseHttpHandler
{
private readonly Action<HttpActionContext> _capture;

public SnapshotCaptureHttpHandler(Action<HttpActionContext> capture)
{
_capture = capture;
}

public override Task<string> ActionAsync(HttpActionContext context)
{
_capture(context);
return Task.FromResult(HttpJsonResultData<string>.SuccessString());
}
}

/// <summary>
/// 快照捕获处理器(强类型 Request 路径):验证第二个 HttpActionContext 构造点同样填充快照。
/// </summary>
[HttpMessageMapping(typeof(SnapshotProbeRequest))]
private sealed class TypedSnapshotCaptureHttpHandler : BaseHttpHandler
{
private readonly Action<HttpActionContext> _capture;

public TypedSnapshotCaptureHttpHandler(Action<HttpActionContext> capture)
{
_capture = capture;
}

public override Task<string> ActionAsync(HttpActionContext context)
{
_capture(context);
return Task.FromResult(HttpJsonResultData<string>.SuccessString());
}
}

private sealed class SnapshotProbeRequest : IHttpMessageRequest
{
public string Token { get; set; }
}

private sealed class RejectingAopHandler : IHttpAopHandler
{
public int Priority
Expand Down
15 changes: 13 additions & 2 deletions Tests/GameFrameX.Tests/Utility/IllegalWordDetectionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@
[Fact]
public void Init_WithBackgroundThread_ShouldNotBlock()
{
// Arrange
var badWords = new[] { "background1", "background2" };
// Arrange:探测词须不超过 10 字符——算法 FastLength/StartCache 按 8 位截断,
// 更长的词扫描会在到达末字符前被 StartCache 上限截断而不可检出,无法充当完成探针
var badWords = new[] { "bgword1", "bgword2" };
var startTime = DateTime.Now;

// Act
Expand All @@ -121,6 +122,16 @@
// Assert
// 后台初始化应该很快返回
Assert.True((endTime - startTime).TotalMilliseconds < 100);

// 等待后台注册真正完成再收尾:慢机上 Task.Run 可能延迟到同序列后续用例执行期间才重置静态词库,
// 会把先同步注册好的词表冲掉造成 HasBlockWords 假失败(CI database-contracts 门禁偶发红)
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!IllegalWordDetection.HasBlockWords("bgword1") && DateTime.UtcNow < deadline)
{
System.Threading.Thread.Sleep(10);

Check warning on line 131 in Tests/GameFrameX.Tests/Utility/IllegalWordDetectionTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Do not use 'Thread.Sleep()' in a test.

See more on https://sonarcloud.io/project/issues?id=GameFrameX.Server.Source&issues=AaIJCJVF7IMKGlXprVMN&open=AaIJCJVF7IMKGlXprVMN&pullRequest=998
}

Assert.True(IllegalWordDetection.HasBlockWords("bgword1"));
}

#endregion
Expand Down
Loading