Record architecture B corrections and measurement tooling
This commit is contained in:
1 parent
097d156c18
commit
6ea20b2365
78 files changed
+45820
-67
No files matched your search
@@ -3,6 +3,7 @@ using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using HealthApp.Infrastructure;
|
||||
using Npgsql;
|
||||
using Observation.AcceptanceTests;
|
||||
using Xunit;
|
||||
@@ -26,45 +27,158 @@ public sealed class OperationalTests(ObservationApiFixture fixture) : IClassFixt
|
||||
finally { await fixture.RestartHostsAsync(); }
|
||||
}
|
||||
[Fact]
|
||||
public async Task Deadline_cancels_locked_write_without_changing_profile()
|
||||
public async Task Client_cancellation_rolls_back_a_locked_write_and_releases_the_connection()
|
||||
{
|
||||
using var create = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Keep", dateOfBirth = "1980-01-01" }); var p = (await create.Content.ReadFromJsonAsync<PatientDto>())!;
|
||||
fixture.AdditionalGatewayConfiguration["Resources:RequestDeadlineSeconds"] = "0.2"; await fixture.RestartHostsAsync();
|
||||
await using var c = new NpgsqlConnection(fixture.ConnectionString); await c.OpenAsync(); await using var t = await c.BeginTransactionAsync();
|
||||
await new NpgsqlCommand("SELECT patient_id FROM profile.patient WHERE patient_id=@id FOR UPDATE", c, t) { Parameters = { new NpgsqlParameter("id", p.PatientId) } }.ExecuteScalarAsync();
|
||||
using var create = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Keep", dateOfBirth = "1980-01-01" });
|
||||
var patient = (await create.Content.ReadFromJsonAsync<PatientDto>())!;
|
||||
await using var connection = new NpgsqlConnection(fixture.ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var transaction = await connection.BeginTransactionAsync();
|
||||
await new NpgsqlCommand("SELECT patient_id FROM profile.patient WHERE patient_id=@id FOR UPDATE", connection, transaction)
|
||||
{ Parameters = { new NpgsqlParameter("id", patient.PatientId) } }.ExecuteScalarAsync();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var write = fixture.Client.PutAsJsonAsync($"/api/patients/{patient.PatientId}", new { name = "Must not persist" }, cancellation.Token);
|
||||
try
|
||||
{
|
||||
using var timed = await fixture.Client.PutAsJsonAsync($"/api/patients/{p.PatientId}", new { name = "Must not persist" });
|
||||
Assert.Equal(HttpStatusCode.GatewayTimeout, timed.StatusCode);
|
||||
await t.RollbackAsync(); var saved = (await fixture.Client.GetFromJsonAsync<PatientDto>($"/api/patients/{p.PatientId}"))!; Assert.Equal("Keep", saved.Name);
|
||||
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
while (true)
|
||||
{
|
||||
await using var monitor = new NpgsqlConnection(fixture.ConnectionString);
|
||||
await monitor.OpenAsync(limit.Token);
|
||||
using var query = new NpgsqlCommand("SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%FOR UPDATE%')", monitor);
|
||||
if (await query.ExecuteScalarAsync(limit.Token) is true) break;
|
||||
await Task.Delay(10, limit.Token);
|
||||
}
|
||||
Assert.False(write.IsCompleted);
|
||||
cancellation.Cancel();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await write);
|
||||
}
|
||||
finally { fixture.AdditionalGatewayConfiguration.Remove("Resources:RequestDeadlineSeconds"); await fixture.RestartHostsAsync(); }
|
||||
finally { cancellation.Cancel(); await transaction.RollbackAsync(); }
|
||||
var saved = (await fixture.Client.GetFromJsonAsync<PatientDto>($"/api/patients/{patient.PatientId}"))!;
|
||||
Assert.Equal("Keep", saved.Name);
|
||||
using var retry = await fixture.Client.PutAsJsonAsync($"/api/patients/{patient.PatientId}", new { name = "Recovered" });
|
||||
Assert.Equal(HttpStatusCode.OK, retry.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Assessment_admission_does_not_block_guidance_and_overload_is_explicit()
|
||||
public async Task Full_provider_pool_waits_and_client_cancellation_does_not_leak_a_connection()
|
||||
{
|
||||
using var create = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Budget", dateOfBirth = "1980-01-01" }); var p = (await create.Content.ReadFromJsonAsync<PatientDto>())!;
|
||||
fixture.AdditionalGatewayConfiguration["Resources:MaxConcurrentAssessments"] = "1"; await fixture.RestartHostsAsync();
|
||||
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var options = new NpgsqlConnectionStringBuilder(fixture.RuntimeConnectionString) { MaxPoolSize = 1 };
|
||||
await using var source = NpgsqlDataSource.Create(options.ConnectionString);
|
||||
await using var first = new RequestTransaction(source);
|
||||
await first.BeginAsync(false, CancellationToken.None);
|
||||
await using var second = new RequestTransaction(source);
|
||||
var waiting = second.BeginAsync(false, CancellationToken.None);
|
||||
Assert.False(waiting.IsCompleted);
|
||||
await first.DisposeAsync();
|
||||
await waiting.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
Assert.True(second.Active);
|
||||
await using var canceled = new RequestTransaction(source);
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var pending = canceled.BeginAsync(false, cancellation.Token);
|
||||
Assert.False(pending.IsCompleted);
|
||||
cancellation.Cancel();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await pending);
|
||||
await second.DisposeAsync();
|
||||
await using var recovered = new RequestTransaction(source);
|
||||
await recovered.BeginAsync(false, CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10));
|
||||
Assert.True(recovered.Active);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("overview", 5)]
|
||||
[InlineData("overview", 26)]
|
||||
[InlineData("overview", 40)]
|
||||
[InlineData("profile", 40)]
|
||||
[InlineData("insights", 26)]
|
||||
[InlineData("trends", 26)]
|
||||
public async Task Overlapping_requests_preserve_A_success_without_admission_rejection(string endpoint, int concurrency)
|
||||
{
|
||||
using var create = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Overlap", dateOfBirth = "1980-01-01" });
|
||||
var patient = (await create.Content.ReadFromJsonAsync<PatientDto>())!;
|
||||
using var observation = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient.PatientId}/observations", new
|
||||
{ measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 });
|
||||
Assert.Equal(HttpStatusCode.Created, observation.StatusCode);
|
||||
var arrived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var entered = 0;
|
||||
async Task Pause(CancellationToken ct)
|
||||
{
|
||||
if (Interlocked.Increment(ref entered) == concurrency) arrived.TrySetResult();
|
||||
await release.Task.WaitAsync(ct);
|
||||
}
|
||||
// Retained configuration on an existing installation must not reactivate
|
||||
// the removed four/32 gates or its blanket deadline.
|
||||
fixture.AdditionalGatewayConfiguration["Resources:MaxConcurrentAssessments"] = "4";
|
||||
fixture.AdditionalGatewayConfiguration["Resources:MaxConcurrentRequests"] = "32";
|
||||
fixture.AdditionalGatewayConfiguration["Resources:RequestDeadlineSeconds"] = "0.001";
|
||||
fixture.ConfigureServices = services =>
|
||||
{
|
||||
var descriptor = services.Last(d => d.ServiceType == typeof(ProfileQueries)); services.Remove(descriptor);
|
||||
services.AddScoped<ProfileQueries>(sp => new PausedProfile((ProfileQueries)descriptor.ImplementationFactory!(sp), async () => { held.TrySetResult(); await release.Task; }));
|
||||
}; await fixture.RestartHostsAsync();
|
||||
if (endpoint is "insights" or "trends")
|
||||
{
|
||||
var descriptor = services.Last(d => d.ServiceType == typeof(AnalyticsQueries));
|
||||
services.Remove(descriptor);
|
||||
services.AddScoped<AnalyticsQueries>(sp => new PausedAnalytics(
|
||||
(AnalyticsQueries)ActivatorUtilities.CreateInstance(sp, descriptor.ImplementationType!), Pause));
|
||||
}
|
||||
else
|
||||
{
|
||||
var descriptor = services.Last(d => d.ServiceType == typeof(ProfileQueries));
|
||||
services.Remove(descriptor);
|
||||
services.AddScoped<ProfileQueries>(sp => new PausedProfile((ProfileQueries)descriptor.ImplementationFactory!(sp), Pause));
|
||||
}
|
||||
};
|
||||
await fixture.RestartHostsAsync();
|
||||
var path = $"/api/patients/{patient.PatientId}" + (endpoint == "profile" ? "" : $"/{endpoint}?from=2026-09-01&to=2026-09-30");
|
||||
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
var requests = Enumerable.Range(0, concurrency).Select(_ => fixture.Client.GetAsync(path, stop.Token)).ToArray();
|
||||
try
|
||||
{
|
||||
var path = $"/api/patients/{p.PatientId}/overview?from=2026-09-01&to=2026-09-30"; var first = fixture.Client.GetAsync(path); await held.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
using var second = await fixture.Client.GetAsync(path); Assert.Equal(HttpStatusCode.ServiceUnavailable, second.StatusCode); Assert.NotNull(second.Headers.RetryAfter);
|
||||
using var guidance = await fixture.RawClient.GetAsync("/api/measurement-guidance"); Assert.Equal(HttpStatusCode.OK, guidance.StatusCode);
|
||||
release.SetResult(); using var completed = await first; Assert.Equal(HttpStatusCode.OK, completed.StatusCode);
|
||||
// Every request must enter before any is released. This fails on the
|
||||
// old implementation, even if requests would otherwise finish quickly.
|
||||
await arrived.Task.WaitAsync(TimeSpan.FromSeconds(15));
|
||||
Assert.All(requests, request => Assert.False(request.IsCompleted));
|
||||
using var guidance = await fixture.RawClient.GetAsync("/api/measurement-guidance");
|
||||
Assert.Equal(HttpStatusCode.OK, guidance.StatusCode);
|
||||
Assert.NotEmpty(await AuthenticatedTestClient.LoginAsync(fixture.RawClient));
|
||||
release.TrySetResult();
|
||||
var responses = await Task.WhenAll(requests);
|
||||
try
|
||||
{
|
||||
Assert.All(responses, response =>
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Null(response.Headers.RetryAfter);
|
||||
});
|
||||
}
|
||||
finally { foreach (var response in responses) response.Dispose(); }
|
||||
}
|
||||
finally
|
||||
{
|
||||
release.TrySetResult();
|
||||
stop.Cancel();
|
||||
try { await Task.WhenAll(requests); } catch (OperationCanceledException) { }
|
||||
fixture.ConfigureServices = null;
|
||||
fixture.AdditionalGatewayConfiguration.Clear();
|
||||
await fixture.RestartHostsAsync();
|
||||
}
|
||||
finally { release.TrySetResult(); fixture.ConfigureServices = null; fixture.AdditionalGatewayConfiguration.Remove("Resources:MaxConcurrentAssessments"); await fixture.RestartHostsAsync(); }
|
||||
}
|
||||
private sealed class PausedProfile(ProfileQueries inner, Func<Task> pause) : ProfileQueries
|
||||
|
||||
private sealed class PausedProfile(ProfileQueries inner, Func<CancellationToken, Task> pause) : ProfileQueries
|
||||
{
|
||||
public Task<Guid?> ResolveAccountAsync(string a, CancellationToken ct) => inner.ResolveAccountAsync(a, ct);
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope, CancellationToken ct) { var p = await inner.GetAsync(scope, ct); await pause(); return p; }
|
||||
public Task<Guid?> ResolveAccountAsync(string account, CancellationToken ct) => inner.ResolveAccountAsync(account, ct);
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope, CancellationToken ct)
|
||||
{ var patient = await inner.GetAsync(scope, ct); await pause(ct); return patient; }
|
||||
}
|
||||
|
||||
private sealed class PausedAnalytics(AnalyticsQueries inner, Func<CancellationToken, Task> pause) : AnalyticsQueries
|
||||
{
|
||||
public async Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{ var result = await inner.InsightAsync(scope, from, to, selection, ct); await pause(ct); return result; }
|
||||
public async Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{ var result = await inner.TrendAsync(scope, from, to, selection, ct); await pause(ct); return result; }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Remote_connection_without_hostname_verified_tls_is_rejected_before_start()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user