193 lines
11 KiB
C#
193 lines
11 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
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;
|
|
namespace HealthApp.AcceptanceTests;
|
|
|
|
public sealed class OperationalTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
|
{
|
|
[Fact]
|
|
public async Task Readiness_uses_configured_schemas_and_guidance_remains_public_during_database_outage()
|
|
{
|
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient);
|
|
async Task<HttpResponseMessage> Ready() { using var q = new HttpRequestMessage(HttpMethod.Get, "/health/ready"); q.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return await fixture.RawClient.SendAsync(q); }
|
|
using (var ready = await Ready()) Assert.Equal(HttpStatusCode.OK, ready.StatusCode);
|
|
await fixture.StopObservationServiceAsync();
|
|
try
|
|
{
|
|
using var notReady = await Ready(); Assert.Equal(HttpStatusCode.ServiceUnavailable, notReady.StatusCode);
|
|
using var guidance = await fixture.RawClient.GetAsync("/api/measurement-guidance"); Assert.Equal(HttpStatusCode.OK, guidance.StatusCode);
|
|
Assert.NotEmpty(await AuthenticatedTestClient.LoginAsync(fixture.RawClient));
|
|
}
|
|
finally { await fixture.RestartHostsAsync(); }
|
|
}
|
|
[Fact]
|
|
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 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 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 { 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 Full_provider_pool_waits_and_client_cancellation_does_not_leak_a_connection()
|
|
{
|
|
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 =>
|
|
{
|
|
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
|
|
{
|
|
// 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();
|
|
}
|
|
}
|
|
|
|
private sealed class PausedProfile(ProfileQueries inner, Func<CancellationToken, Task> pause) : ProfileQueries
|
|
{
|
|
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()
|
|
{
|
|
fixture.AdditionalGatewayConfiguration["Database:Remote"] = "true";
|
|
try
|
|
{
|
|
var e = await Assert.ThrowsAsync<InvalidOperationException>(() => fixture.RestartHostsAsync()); Assert.Contains("verified TLS", e.Message);
|
|
}
|
|
finally { fixture.AdditionalGatewayConfiguration.Remove("Database:Remote"); await fixture.RestartHostsAsync(); }
|
|
}
|
|
}
|