perf: close Theme 6 — 11 allocation / N+1 / lock-contention findings
Well-localised perf fixes across 8 modules.
Lock decoupling / SQL streaming:
- AuditLog-005: SqliteAuditWriter gains dedicated read-only _readConnection
(+ _readLock) backed by WAL journal mode. GetBacklogStatsAsync,
ReadPendingAsync, ReadPendingSinceAsync, ReadForwardedAsync no longer
contend with the hot-path INSERT lock — backlog probes on a 30s timer
can't stall the writer under multi-hundred-K Pending backlog.
- SEL-022: dropped Cache=Shared from SiteEventLogger's default connection
string (single-connection logger; mode was dormant config).
Memory / streaming:
- CLI-019: bundle export streams base64 in 1 MB-aligned chunks via
Convert.TryFromBase64Chars straight into the FileStream — no more
full-bundle byte[] allocation.
- CentralUI-031: TransportImport now stages the upload to a per-session
temp file under Path.GetTempPath() (replaces in-memory byte[] field);
page implements IDisposable to delete the temp file on reset / new
upload / dispose. Per-circuit working set drops from ~100 MB to ~80 KB.
N+1 hoisting:
- Transport-008: added ITemplateEngineRepository.GetTemplatesWithChildrenAsync
bulk method; BundleImporter.PreviewAsync calls it once instead of per-
template-name. Single query with .Include(...).AsSplitQuery().
- DM-023: BuildDeployArtifactsCommandAsync's per-site loop now references
a pre-fetched GlobalArtifactSnapshot (shared scripts, external systems,
DB connections, notification lists, SMTP) instead of re-querying per site.
- MgmtSvc-023: HandleQueryDeployments unfiltered branch uses one
GetAllInstancesAsync bulk load + Dictionary<int,int?> lookup (was a
GetInstanceByIdAsync per record).
Small allocations / per-tick rebuilds:
- InboundAPI-019: AuditWriteMiddleware gates EnableBuffering() on
RequestHasBody() so GET/HEAD/DELETE/TRACE/OPTIONS and Content-Length:0
requests skip the FileBufferingReadStream allocation.
- NotifOutbox-006: ResolveAdapters dictionary now cached on
_adaptersCache (built lazily on first sweep) + actor-lifetime
_adaptersScope; ResolveAdapters no longer rebuilds per dispatch tick.
Verify-only:
- Comm-017: Confirmed _inProgressDeployments was deleted by Comm-016 in
commit ac96b83 — marked Resolved with that attribution. No code change.
Doc-correction:
- NS-022: Updated MailKitSmtpClientWrapper XML doc to spell out single-
connection / per-delivery-factory contract (option (b) — transient
client per Send — rejected because it re-handshakes TLS per email).
10+ new regression tests across 8 test projects. Build clean; affected
suites all green. README regenerated: 54 open (was 65).
This commit is contained in:
@@ -800,4 +800,109 @@ public class AuditWriteMiddlewareTests
|
||||
"Expected a Warning log entry observing the async audit-write fault — none found. " +
|
||||
$"Entries: [{string.Join(", ", snapshot)}]");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// InboundAPI-019 — bodyless requests skip EnableBuffering so the
|
||||
// FileBufferingReadStream allocation is avoided on GET/HEAD/DELETE
|
||||
// and any request whose Content-Length is 0. The audit row still emits
|
||||
// with a null RequestSummary, mirroring the bodyless-POST contract.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET")]
|
||||
[InlineData("HEAD")]
|
||||
[InlineData("DELETE")]
|
||||
public async Task BodylessMethod_SkipsEnableBuffering_RequestStreamIsNotReplaced(string method)
|
||||
{
|
||||
// The middleware previously called EnableBuffering on every request,
|
||||
// installing a FileBufferingReadStream wrapper even when the request
|
||||
// had no body. The bodyless-method short-circuit must leave
|
||||
// Request.Body untouched (still the original empty stream the test
|
||||
// assigns below), proving the buffering wrapper allocation is avoided.
|
||||
var writer = new RecordingAuditWriter();
|
||||
var ctx = new DefaultHttpContext();
|
||||
ctx.Request.Method = method;
|
||||
ctx.Request.Path = "/api/echo";
|
||||
ctx.Request.RouteValues["methodName"] = "echo";
|
||||
ctx.Connection.RemoteIpAddress = IPAddress.Parse("10.0.0.5");
|
||||
|
||||
// Distinct sentinel stream — the production code path that called
|
||||
// EnableBuffering would replace this with FileBufferingReadStream.
|
||||
// After the fix the original stream survives untouched.
|
||||
var sentinel = new MemoryStream();
|
||||
ctx.Request.Body = sentinel;
|
||||
|
||||
Stream? observedDuringHandler = null;
|
||||
var mw = CreateMiddleware(hc =>
|
||||
{
|
||||
observedDuringHandler = hc.Request.Body;
|
||||
hc.Response.StatusCode = 200;
|
||||
return Task.CompletedTask;
|
||||
}, writer);
|
||||
|
||||
await mw.InvokeAsync(ctx);
|
||||
|
||||
Assert.Same(sentinel, observedDuringHandler);
|
||||
var evt = Assert.Single(writer.Events);
|
||||
// No body → RequestSummary stays null, matching the bodyless-POST contract.
|
||||
Assert.Null(evt.RequestSummary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BodylessPost_ContentLengthZero_SkipsEnableBuffering()
|
||||
{
|
||||
// A POST with an explicit Content-Length of 0 is also bodyless — even
|
||||
// though POST is conventionally a body-carrying method, the explicit
|
||||
// zero short-circuits buffering. This pins the ContentLength branch of
|
||||
// the RequestHasBody guard.
|
||||
var writer = new RecordingAuditWriter();
|
||||
var ctx = new DefaultHttpContext();
|
||||
ctx.Request.Method = "POST";
|
||||
ctx.Request.Path = "/api/echo";
|
||||
ctx.Request.RouteValues["methodName"] = "echo";
|
||||
ctx.Request.ContentLength = 0;
|
||||
ctx.Connection.RemoteIpAddress = IPAddress.Parse("10.0.0.5");
|
||||
|
||||
var sentinel = new MemoryStream();
|
||||
ctx.Request.Body = sentinel;
|
||||
|
||||
Stream? observedDuringHandler = null;
|
||||
var mw = CreateMiddleware(hc =>
|
||||
{
|
||||
observedDuringHandler = hc.Request.Body;
|
||||
hc.Response.StatusCode = 200;
|
||||
return Task.CompletedTask;
|
||||
}, writer);
|
||||
|
||||
await mw.InvokeAsync(ctx);
|
||||
|
||||
Assert.Same(sentinel, observedDuringHandler);
|
||||
var evt = Assert.Single(writer.Events);
|
||||
Assert.Null(evt.RequestSummary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostWithBody_StillEnablesBuffering_AndCapturesRequestSummary()
|
||||
{
|
||||
// Regression: the bodyless short-circuit must NOT regress the existing
|
||||
// body-capture contract for normal POSTs — we still need to buffer +
|
||||
// capture the request body for the audit row.
|
||||
var writer = new RecordingAuditWriter();
|
||||
var requestJson = "{\"a\":42}";
|
||||
var ctx = BuildContext(body: requestJson);
|
||||
|
||||
string? observedAfterMiddleware = null;
|
||||
var mw = CreateMiddleware(async hc =>
|
||||
{
|
||||
using var reader = new StreamReader(hc.Request.Body);
|
||||
observedAfterMiddleware = await reader.ReadToEndAsync();
|
||||
hc.Response.StatusCode = 200;
|
||||
}, writer);
|
||||
|
||||
await mw.InvokeAsync(ctx);
|
||||
|
||||
Assert.Equal(requestJson, observedAfterMiddleware);
|
||||
var evt = Assert.Single(writer.Events);
|
||||
Assert.Equal(requestJson, evt.RequestSummary);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user