using SQLInsight.Collectors;
using SQLInsight.Connectivity;
using SQLInsight.Core.Instances;
namespace SQLInsight.IntegrationTests;
///
/// A monitoring connection as the least-privilege agent login, opened exactly like the agent does.
///
internal sealed class AgentSession : IAsyncDisposable
{
private readonly OpenedConnection _opened;
private AgentSession(OpenedConnection opened, InstanceInfo instance)
{
_opened = opened;
Instance = instance;
Capabilities = InstanceCapabilities.From(instance);
}
public InstanceInfo Instance { get; }
public InstanceCapabilities Capabilities { get; }
public System.Data.Common.DbConnection Connection => _opened.Connection;
public static async Task OpenAsync(SqlServerFixture sql)
{
var opened = await new SqlConnectionFactory().OpenAsync(new ConnectionTarget
{
Server = sql.Server,
Authentication = AuthenticationMode.SqlLogin,
UserName = SqlServerFixture.AgentLogin,
Password = SqlServerFixture.AgentPassword,
Provider = ConnectionProvider.SqlClient,
TrustServerCertificate = true,
});
var instance = await InstanceProbe.DetectAsync(opened.Connection);
return new AgentSession(opened, instance);
}
public async Task CollectAsync(ICollector collector, T? previous = null, Core.Configuration.DatabaseSelection? selection = null)
where T : class
{
var context = new CollectorContext(_opened.Connection, Instance, Capabilities, DateTimeOffset.UtcNow, previous, CancellationToken.None, selection);
return (T)await collector.CollectAsync(context);
}
public ValueTask DisposeAsync() => _opened.DisposeAsync();
}