Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for timing out SQL integration tests #3917

Merged
merged 26 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
c731ece
Add version
SergeyGaluzo Jun 12, 2024
3f0431a
reduced timeout on delete and reduced retries on create
SergeyGaluzo Jun 12, 2024
593e7f1
new name
SergeyGaluzo Jun 12, 2024
39d5a86
Merge branch 'main' into users/sergal/integration
SergeyGaluzo Jun 12, 2024
bc1df86
force unique database name
SergeyGaluzo Jun 12, 2024
67c43f6
one more unique name
SergeyGaluzo Jun 12, 2024
22a096e
disable drop
SergeyGaluzo Jun 12, 2024
fb339a9
Semaphore removed
SergeyGaluzo Jun 13, 2024
0d0a042
skip drop if azure
SergeyGaluzo Jun 13, 2024
2e0bd62
100 on custom query
SergeyGaluzo Jun 13, 2024
a65b40b
SQL Azure in correct order
SergeyGaluzo Jun 13, 2024
a9d1308
oops
SergeyGaluzo Jun 13, 2024
8c53897
simpler is azure
SergeyGaluzo Jun 13, 2024
e3b9615
revert semaphore
SergeyGaluzo Jun 13, 2024
bd92853
semaphore 32
SergeyGaluzo Jun 13, 2024
ca4a654
14
SergeyGaluzo Jun 13, 2024
05f61ca
Removed unneccessary interpolation
SergeyGaluzo Jun 13, 2024
09c3664
Update test/Microsoft.Health.Fhir.Shared.Tests.Integration/Features/C…
SergeyGaluzo Jun 13, 2024
9757d12
Merge branch 'users/sergal/integration' of https://github.com/microso…
SergeyGaluzo Jun 13, 2024
f3568e6
Drop dbs yml
SergeyGaluzo Jun 14, 2024
3d490ca
simple loop
SergeyGaluzo Jun 15, 2024
582dc35
adjusted min version
SergeyGaluzo Jun 15, 2024
b5943cf
drop in separate job
SergeyGaluzo Jun 15, 2024
04ce895
120->240
SergeyGaluzo Jun 15, 2024
5a233fa
True fix
SergeyGaluzo Jun 16, 2024
3fc42d6
Removed delete job
SergeyGaluzo Jun 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task GivenADatabaseSupportsResourceChangeCapture_WhenResourceChange
FhirStorageTestsFixture fhirStorageTestsFixture = null;
try
{
string databaseName = $"FHIRRESOURCECHANGEDISABLEDTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}";
string databaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName($"ChangeCaptureDisabled");
SergeyGaluzo marked this conversation as resolved.
Show resolved Hide resolved

// this will either create the database or upgrade the schema.
var coreFeatureConfigOptions = Options.Create(new CoreFeatureConfiguration() { SupportsResourceChangeCapture = false });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class SqlServerFhirResourceChangeCaptureFixture : IAsyncLifetime

public SqlServerFhirResourceChangeCaptureFixture()
{
_databaseName = $"FHIRRESOURCECHANGEINTTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}";
_databaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName($"ChangeCapture");
_coreFeatureConfigOptions = Options.Create(new CoreFeatureConfiguration() { SupportsResourceChangeCapture = true });
_sqlFixture = new SqlServerFhirStorageTestsFixture(SchemaVersionConstants.Max, _databaseName, _coreFeatureConfigOptions);
_storageFixture = new FhirStorageTestsFixture(_sqlFixture);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task GivenASqlQuery_IfAStoredProcExistsWithMatchingHash_ThenStoredP
// Query after adding an sproc to the database
var sw = Stopwatch.StartNew();
var sprocWasUsed = false;
while (sw.Elapsed.TotalSeconds < 10) // previous single try after 1.1 sec delay was not reliable.
while (sw.Elapsed.TotalSeconds < 100) // previous single try after 1.1 sec delay was not reliable.
{
await Task.Delay(300);
await _fixture.SearchService.SearchAsync(KnownResourceTypes.Patient, query, CancellationToken.None);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
private readonly ISqlConnectionBuilder _sqlConnectionBuilder;
private readonly AsyncRetryPolicy _dbSetupRetryPolicy;
private readonly TestQueueClient _queueClient;
private static readonly SemaphoreSlim DbSetupSemaphore = new(4);
private static readonly object _locker = new object();
private static bool? _isAzure = null;

public SqlServerFhirStorageTestHelper(
string initialConnectionString,
Expand All @@ -61,12 +62,10 @@
_dbSetupRetryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(
retryCount: 20,
retryCount: 5,
sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(3));
}

internal bool DropDatabase => true;

public async Task CreateAndInitializeDatabase(string databaseName, int maximumSupportedSchemaVersion, bool forceIncrementalSchemaUpgrade, SchemaInitializer schemaInitializer = null, CancellationToken cancellationToken = default)
{
string testConnectionString = new SqlConnectionStringBuilder(_initialConnectionString) { InitialCatalog = databaseName }.ToString();
Expand All @@ -79,23 +78,13 @@
await connection.OpenAsync(cancellationToken);

await using SqlCommand command = connection.CreateCommand();
command.CommandTimeout = 600;
command.CommandTimeout = 300;
command.CommandText = @$"
IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = '{databaseName}')
BEGIN
CREATE DATABASE {databaseName};
END";

await DbSetupSemaphore.WaitAsync(cancellationToken);
try
{
await command.ExecuteNonQueryAsync(cancellationToken);
}
finally
{
DbSetupSemaphore.Release();
}

await command.ExecuteNonQueryAsync(cancellationToken);
await connection.CloseAsync();
});

Expand Down Expand Up @@ -211,31 +200,34 @@

public async Task DeleteDatabase(string databaseName, CancellationToken cancellationToken = default)
{
if (!DropDatabase)
if (!_isAzure.HasValue)
{
lock (_locker)
{
if (!_isAzure.HasValue)
{
_isAzure = IsAzure(); // cannot await in the lock
Fixed Show fixed Hide fixed
}
}
}

if (_isAzure.Value)
{
return;
}

try
{
await DbSetupSemaphore.WaitAsync(cancellationToken);
try
{
SqlConnection.ClearAllPools();
SqlConnection.ClearAllPools();

await using SqlConnection connection = await _sqlConnectionBuilder.GetSqlConnectionAsync(_masterDatabaseName, null, cancellationToken);
await connection.OpenAsync(cancellationToken);
await using SqlCommand command = connection.CreateCommand();
command.CommandTimeout = 600;
command.CommandText = $"DROP DATABASE IF EXISTS {databaseName}";
await using SqlConnection connection = await _sqlConnectionBuilder.GetSqlConnectionAsync(_masterDatabaseName, null, cancellationToken);
await connection.OpenAsync(cancellationToken);
await using SqlCommand command = connection.CreateCommand();
command.CommandTimeout = 15;
command.CommandText = $"DROP DATABASE IF EXISTS {databaseName}";

await command.ExecuteNonQueryAsync(cancellationToken);
await connection.CloseAsync();
}
finally
{
DbSetupSemaphore.Release();
}
await command.ExecuteNonQueryAsync(cancellationToken);
await connection.CloseAsync();
}
catch (Exception ex)
{
Expand Down Expand Up @@ -384,5 +376,14 @@
var result = new SqlConnection(connectionBuilder.ToString());
return result;
}

private bool IsAzure()
{
using var conn = _sqlConnectionBuilder.GetSqlConnection(_masterDatabaseName);
using var cmd = new SqlCommand("SELECT patindex('%Azure SQL%',@@version)", conn);
conn.Open();
var value = cmd.ExecuteScalar();
return (int)value > 0;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public class SqlServerFhirStorageTestsFixture : IServiceProvider, IAsyncLifetime
private SqlQueueClient _sqlQueueClient;

public SqlServerFhirStorageTestsFixture()
: this(SchemaVersionConstants.Max, $"FHIRINTEGRATIONTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}")
: this(SchemaVersionConstants.Max, GetDatabaseName())
{
}

Expand Down Expand Up @@ -125,6 +125,11 @@ internal SqlServerFhirStorageTestsFixture(int maximumSupportedSchemaVersion, str

internal ISqlQueryHashCalculator SqlQueryHashCalculator { get; private set; }

internal static string GetDatabaseName(string test = null)
{
return $"{ModelInfoProvider.Version}{(test == null ? string.Empty : $"_{test}")}_{DateTimeOffset.UtcNow.ToString("s").Replace("-", string.Empty).Replace(":", string.Empty)}_{Guid.NewGuid().ToString().Replace("-", string.Empty)}";
}

public async Task InitializeAsync()
{
var scriptProvider = new ScriptProvider<SchemaVersion>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public SqlServerSchemaUpgradeTests()
[Fact]
public async Task GivenTwoSchemaInitializationMethods_WhenCreatingTwoDatabases_BothSchemasShouldBeEquivalent()
{
var snapshotDatabaseName = $"SNAPSHOT_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}";
var diffDatabaseName = $"DIFF_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}";
var snapshotDatabaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName($"Upgrade_Snapshot");
var diffDatabaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName($"Upgrade_Diff");

SqlServerFhirStorageTestHelper testHelper1 = null;
SqlServerFhirStorageTestHelper testHelper2 = null;
Expand Down Expand Up @@ -92,7 +92,7 @@ public void GivenASchemaVersion_WhenApplyingDiffTwice_ShouldSucceed()
// The schema upgrade scripts starting from v7 were made idempotent.
if (version >= 7 && version >= SchemaVersionConstants.MinForUpgrade) // no sense in checking not supported versions
{
var snapshotDatabaseName = $"SNAPSHOT_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}";
var snapshotDatabaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName($"Upgrade_Snapshot_Diff");

SqlServerFhirStorageTestHelper testHelper = null;
SchemaUpgradeRunner upgradeRunner;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class SqlServerSqlCompatibilityTests
[Fact]
public async Task GivenADatabaseWithAnEarlierSupportedSchemaAndUpgraded_WhenUpsertingAfter_OperationSucceeds()
{
string databaseName = $"FHIRCOMPATIBILITYTEST_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
string databaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName("Compatibility");
var insertedElements = new List<string>();

FhirStorageTestsFixture fhirStorageTestsFixture = null;
Expand Down Expand Up @@ -93,7 +93,7 @@ public async Task GivenADatabaseWithAnEarlierSupportedSchema_WhenUpserting_Opera
{
if (version >= Math.Max(SchemaVersionConstants.Min, SchemaVersionConstants.Max - 5) && version <= SchemaVersionConstants.Max)
{
string databaseName = $"FHIRCOMPATIBILITYTEST_V{version}_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
string databaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName($"Compatibility_V{version}");
FhirStorageTestsFixture fhirStorageTestsFixture = null;
try
{
Expand Down Expand Up @@ -135,7 +135,7 @@ public async Task GivenADatabaseWithAnEarlierSupportedSchema_WhenSearchingWithSo
{
Skip.If(SchemaVersionConstants.AddMinMaxForDateAndStringSearchParamVersion < SchemaVersionConstants.Min, "Schema version required for this test is not supported");

string databaseName = $"FHIRCOMPATIBILITYTEST_SORT_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
string databaseName = SqlServerFhirStorageTestsFixture.GetDatabaseName($"Compatibility_Sort");
int schemaVersion = SchemaVersionConstants.AddMinMaxForDateAndStringSearchParamVersion - 1;
var fhirStorageTestsFixture = new FhirStorageTestsFixture(new SqlServerFhirStorageTestsFixture(
schemaVersion,
Expand Down
Loading