补上边端取流的请求级日志,并让 A 侧连接失败自动重试一次

现场表现:查询提示「设备管理服务无响应,改由本机校验」,但边端和 A 侧
都没留下任何痕迹 —— /check 这条路径原来只在异常时记一行,成功完全静默,
A 侧拿到非 2xx 也只返回 null。

- 边端 /check 每次记一行(通道、时间窗、hasRecord、帧数、来源、耗时)
- 主体不符被拒时记录路径、原因和本体主体
- A 侧 EdgeClient:非 2xx 记录状态码+响应体;传输层异常(worker 重启后
  连接池里的死连接)自动重试一次,取成片同理

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-10-22 03:24:41 +08:00
parent f38bf082f1
commit 63b70c6ad5
3 changed files with 84 additions and 21 deletions

View File

@ -173,6 +173,9 @@ public sealed class EdgeHttpService
// 除 health 外都要校验主体 // 除 health 外都要校验主体
if (!CheckSubject(request, out var subjectError)) if (!CheckSubject(request, out var subjectError))
{ {
var config = AgentFiles.LoadConfig();
AppLog.Write($"[edge] 拒绝 {request.Method} {path}:{subjectError}"
+ $"(本体主体 {(config is null ? "无" : config.SubjectId.ToString())})");
await WriteJsonAsync(stream, 403, "Forbidden", new { ok = false, error = subjectError }, ct) await WriteJsonAsync(stream, 403, "Forbidden", new { ok = false, error = subjectError }, ct)
.ConfigureAwait(false); .ConfigureAwait(false);
return; return;
@ -368,6 +371,10 @@ public sealed class EdgeHttpService
var check = await playback.CheckAsync(host, port, username, password, channelNo, start, end, ct) var check = await playback.CheckAsync(host, port, username, password, channelNo, start, end, ct)
.ConfigureAwait(false); .ConfigureAwait(false);
AppLog.Write($"[edge] 校验 {host}:{port} 通道 {channelNo} "
+ $"{start:HH:mm:ss}~{end:HH:mm:ss} → hasRecord={check.HasRecord}"
+ $"({check.Source},{check.Frames} 帧{(string.IsNullOrEmpty(check.Error) ? "" : "," + check.Error)})");
await WriteJsonAsync(stream, 200, "OK", new await WriteJsonAsync(stream, 200, "OK", new
{ {
ok = true, ok = true,
@ -383,6 +390,7 @@ public sealed class EdgeHttpService
} }
catch (Exception ex) catch (Exception ex)
{ {
AppLog.Write($"[edge] 校验失败 {host}:{port} 通道 {channelNo}:{ex.Message}");
await WriteJsonAsync(stream, 200, "OK", new await WriteJsonAsync(stream, 200, "OK", new
{ {
ok = true, ok = true,

View File

@ -83,17 +83,36 @@ public sealed class EdgeClient : IDisposable
endTime = end.ToString("O"), endTime = end.ToString("O"),
}; };
using var response = await SendAsync(HttpMethod.Post, "/check", payload, ct).ConfigureAwait(false); HttpResponseMessage response;
if (!response.IsSuccessStatusCode) return null; try
{
response = await SendAsync(HttpMethod.Post, "/check", payload, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
AppLog.Write($"[edge] 校验请求失败({_baseUrl}):{ex.Message}");
return null;
}
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false)); using (response)
var root = doc.RootElement; {
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var hasRecord = root.TryGetProperty("hasRecord", out var value) if (!response.IsSuccessStatusCode)
&& value.ValueKind == JsonValueKind.True; {
var frames = root.TryGetProperty("frames", out var f) && f.TryGetInt32(out var parsed) ? parsed : 0; AppLog.Write($"[edge] 校验请求被拒({(int)response.StatusCode} {response.StatusCode}):{Trim(text)}");
return null;
}
return new EdgeCheckResult(hasRecord, frames, GetString(root, "error"), GetString(root, "source")); using var doc = JsonDocument.Parse(text);
var root = doc.RootElement;
var hasRecord = root.TryGetProperty("hasRecord", out var value)
&& value.ValueKind == JsonValueKind.True;
var frames = root.TryGetProperty("frames", out var f) && f.TryGetInt32(out var parsed) ? parsed : 0;
return new EdgeCheckResult(hasRecord, frames, GetString(root, "error"), GetString(root, "source"));
}
} }
/// <summary>下发下载计划,返回任务 id(服务端后台执行)</summary> /// <summary>下发下载计划,返回任务 id(服务端后台执行)</summary>
@ -140,11 +159,25 @@ public sealed class EdgeClient : IDisposable
/// </summary> /// </summary>
public async Task<long> DownloadFileAsync(string taskId, string savePath, CancellationToken ct = default) public async Task<long> DownloadFileAsync(string taskId, string savePath, CancellationToken ct = default)
{ {
using var request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}/download/{taskId}/file"); HttpResponseMessage response = null!;
request.Headers.TryAddWithoutValidation("X-Edge-Subject", _subjectId.ToString()); for (var attempt = 1; attempt <= 2; attempt++)
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}/download/{taskId}/file");
request.Headers.TryAddWithoutValidation("X-Edge-Subject", _subjectId.ToString());
using var response = await Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct) try
.ConfigureAwait(false); {
response = await Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct)
.ConfigureAwait(false);
break;
}
catch (Exception ex) when (attempt == 1 && ex is not OperationCanceledException)
{
AppLog.Write($"[edge] 取成片连接失败(重试一次):{ex.Message}");
}
}
using var _ = response;
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var dir = Path.GetDirectoryName(savePath); var dir = Path.GetDirectoryName(savePath);
@ -167,18 +200,33 @@ public sealed class EdgeClient : IDisposable
return total; return total;
} }
private Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, object? payload, /// <summary>
/// 发一个请求。**传输层失败重试一次**:worker 是子进程,重启/崩溃后连接池里会留着
/// 已经死掉的 keep-alive 连接,第一个请求必然抛 IOException —— 现场表现就是
/// 「设备管理服务无响应,改由本机校验」(2026-10-22 03:22 更新完就复现过)。
/// </summary>
private async Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, object? payload,
CancellationToken ct) CancellationToken ct)
{ {
var request = new HttpRequestMessage(method, _baseUrl + path); for (var attempt = 1; ; attempt++)
request.Headers.TryAddWithoutValidation("X-Edge-Subject", _subjectId.ToString());
if (payload is not null)
{ {
request.Content = JsonContent.Create(payload, options: HikWorkerJson.Options); using var request = new HttpRequestMessage(method, _baseUrl + path);
} request.Headers.TryAddWithoutValidation("X-Edge-Subject", _subjectId.ToString());
return Http.SendAsync(request, ct); if (payload is not null)
{
request.Content = JsonContent.Create(payload, options: HikWorkerJson.Options);
}
try
{
return await Http.SendAsync(request, ct).ConfigureAwait(false);
}
catch (Exception ex) when (attempt == 1 && ex is not OperationCanceledException)
{
AppLog.Write($"[edge] {path} 连接失败(重试一次):{ex.Message}");
}
}
} }
private static object[] BuildCredentialPayload(IReadOnlyList<NvrCredential> credentials) private static object[] BuildCredentialPayload(IReadOnlyList<NvrCredential> credentials)
@ -204,6 +252,13 @@ public sealed class EdgeClient : IDisposable
? value.GetString() ? value.GetString()
: null; : null;
private static string Trim(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return "(空)";
var trimmed = text.Trim();
return trimmed.Length <= 200 ? trimmed : trimmed[..200] + "…";
}
public void Dispose() public void Dispose()
{ {
// HttpClient 是静态共享的,这里没有需要释放的实例资源 // HttpClient 是静态共享的,这里没有需要释放的实例资源

View File

@ -42,7 +42,7 @@
<ServerBaseUrl Condition="'$(Configuration)' == 'Debug' and '$(ServerBaseUrl)' == ''">http://127.0.0.1:7300</ServerBaseUrl> <ServerBaseUrl Condition="'$(Configuration)' == 'Debug' and '$(ServerBaseUrl)' == ''">http://127.0.0.1:7300</ServerBaseUrl>
<ServerBaseUrl Condition="'$(Configuration)' == 'Release' and '$(ServerBaseUrl)' == ''">https://packs.example.com</ServerBaseUrl> <ServerBaseUrl Condition="'$(Configuration)' == 'Release' and '$(ServerBaseUrl)' == ''">https://packs.example.com</ServerBaseUrl>
<Version>1.0.108</Version> <Version>1.0.109</Version>
<Product>浜戜粨瑙嗛婧簮杞欢</Product> <Product>浜戜粨瑙嗛婧簮杞欢</Product>
<Company>浜戜粨</Company> <Company>浜戜粨</Company>
<AssemblyTitle>浜戜粨瑙嗛婧簮杞欢锛堟湰鏈烘湇鍔★級</AssemblyTitle> <AssemblyTitle>浜戜粨瑙嗛婧簮杞欢锛堟湰鏈烘湇鍔★級</AssemblyTitle>