Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
44 changes: 44 additions & 0 deletions src/Weasel.Core/Migrations/DatabaseBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

public abstract DatabaseDescriptor Describe();

public DatabaseBase(

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / EF Core net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net9.0 Case Sensitive true

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Oracle net9.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / SQLite ubuntu-latest net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / SQLite ubuntu-latest net9.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Core net9.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2022-latest net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2022-latest net9.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Core net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / EF Core net9.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MySql mysql:8.0 net9.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2019-latest net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2019-latest net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net10.0 Case Sensitive true

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net10.0 Case Sensitive false

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Oracle net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MySql mysql:8.0 net10.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2019-latest net9.0

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 46 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net9.0 Case Sensitive false

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
IMigrationLogger logger,
AutoCreate autoCreate,
Migrator migrator,
Expand Down Expand Up @@ -438,6 +438,12 @@
: null;

TConnection? conn = null;

// weasel#659: the global lock is session-scoped, so nothing but an explicit release -- or the
// connection actually going back to the pool and being reset -- gives it up. Track whether this
// call is the holder so a failed migration releases it on the way out.
var holdsGlobalLock = false;

try
{
conn = CreateConnection();
Expand Down Expand Up @@ -478,6 +484,8 @@

if (attainLockResult == AttainLockResult.Success)
{
holdsGlobalLock = true;

// Re-check the fingerprint now that we hold the lock: a concurrent applier (another
// replica racing this one) may have applied + stamped while we waited.
if (fingerprint != null)
Expand All @@ -488,6 +496,7 @@
{
MarkAllFeaturesAsChecked();
await globalLock.ReleaseLock(conn, ct).ConfigureAwait(false);
holdsGlobalLock = false;
return SchemaPatchDifference.None;
}
}
Expand All @@ -510,6 +519,7 @@
MarkAllFeaturesAsChecked();

await globalLock.ReleaseLock(conn, ct).ConfigureAwait(false);
holdsGlobalLock = false;

return patch.Difference;
}
Expand All @@ -531,13 +541,47 @@
+ "applying them; set ResourceMigrationFailureMode.ContinueOnFailures to let a replica that loses "
+ "this race start against the schema the winner is applying.");
}
catch
{
if (holdsGlobalLock && conn != null)
{
await releaseGlobalLockAfterFailure(globalLock, conn).ConfigureAwait(false);
}

throw;
}
finally
{
if (conn != null)
await conn.DisposeAsync().ConfigureAwait(false);
}
}

/// <summary>
/// Give up the global migration lock when the apply fails (weasel#659). Without this, a
/// migration that threw anywhere between attaining the lock and finishing left it held for the
/// life of that connection, and every other store or replica sharing the database was locked
/// out of migrating -- reporting "Unable to attain the global lock in time to apply database
/// changes", whose own advice (ContinueOnFailures) would then start them against an unmigrated
/// schema. Disposing the connection is not enough on its own: the reset that releases a
/// session-scoped lock only happens when the connection is really returned to the pool, and a
/// connection observed sitting idle kept the lock for the rest of the run.
/// </summary>
private static async Task releaseGlobalLockAfterFailure(IGlobalLock<TConnection> globalLock, TConnection conn)
{
try
{
// CancellationToken.None deliberately: a cancelled apply is one of the ways to get here,
// and passing the caller's token would mean never releasing in exactly that case.
await globalLock.ReleaseLock(conn, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception)
{
// The migration failure is the one the caller needs to see, and a release that cannot run
// has nothing to fall back on -- the connection is disposed either way.
}
}

public async Task WriteMigrationFileAsync(string filename, CancellationToken ct = default)
{
var patch = await CreateMigrationAsync(ct).ConfigureAwait(false);
Expand Down Expand Up @@ -575,7 +619,7 @@

public virtual IFeatureSchema FindFeature(Type featureType)
{
return null; // TODO - could get smarter and try to create by type

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / EF Core net10.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net9.0 Case Sensitive true

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Oracle net9.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / SQLite ubuntu-latest net10.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / SQLite ubuntu-latest net9.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Core net9.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2022-latest net10.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2022-latest net9.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Core net10.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / EF Core net9.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MySql mysql:8.0 net9.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2019-latest net10.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net10.0 Case Sensitive true

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net10.0 Case Sensitive false

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Oracle net10.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MySql mysql:8.0 net10.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / MSSQL mcr.microsoft.com/mssql/server:2019-latest net9.0

Possible null reference return.

Check warning on line 622 in src/Weasel.Core/Migrations/DatabaseBase.cs

View workflow job for this annotation

GitHub Actions / Postgres postgres:15.3-alpine net9.0 Case Sensitive false

Possible null reference return.
}

public void MarkAllFeaturesAsChecked()
Expand Down
138 changes: 138 additions & 0 deletions src/Weasel.Postgresql.Tests/Migrations/releasing_the_global_lock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using JasperFx;
using Npgsql;
using Shouldly;
using Weasel.Core;
using Weasel.Core.Migrations;
using Xunit;

namespace Weasel.Postgresql.Tests.Migrations;

/// <summary>
/// weasel#659: <c>ApplyAllConfiguredChangesToDatabaseAsync</c> released the global migration lock
/// only on its success paths. A migration that threw left the lock held, and every other store or
/// replica sharing the database was then locked out of migrating -- told "Unable to attain the
/// global lock in time to apply database changes", whose own advice (<c>ContinueOnFailures</c>)
/// would start them against an unmigrated schema.
/// </summary>
/// <remarks>
/// Found while investigating JasperFx/marten#5529: one test's host migration failed with a DDL
/// error and every later test that migrated against that database failed, which reads as flakiness
/// in a suite and as one node bricking the rest in a deployment.
/// </remarks>
[Collection("migrations")]
public class releasing_the_global_lock: IntegrationContext, IAsyncLifetime
{
private readonly TestDatabaseWithTables theDatabase;
private readonly CountingGlobalLock theLock = new(AdvisoryLockTesting.NextLockId());

public releasing_the_global_lock(): base("migrations")
{
theDatabase = new TestDatabaseWithTables(AutoCreate.All, "Migrations", theDataSource);
}

public override ValueTask InitializeAsync()
{
return new(ResetSchema());
}

/// <summary>
/// A table whose DDL the server will refuse, so the apply throws from inside
/// <c>Migrator.ApplyAllAsync</c> -- after the lock has been attained.
/// </summary>
private void configureAMigrationThatWillFail()
{
var table = theDatabase.Features["One"].AddTable(SchemaName, "one");
table.AddColumn("bad", "this_type_does_not_exist");
}

[Fact]
public async Task the_lock_is_released_after_a_successful_apply()
{
theDatabase.Features["One"].AddTable(SchemaName, "one");

await theDatabase.ApplyAllConfiguredChangesToDatabaseAsync(theLock);

theLock.Attained.ShouldBe(1);
theLock.Released.ShouldBe(1);
}

[Fact]
public async Task the_lock_is_released_after_a_failed_apply()
{
configureAMigrationThatWillFail();

await Should.ThrowAsync<PostgresException>(() =>
theDatabase.ApplyAllConfiguredChangesToDatabaseAsync(theLock));

theLock.Attained.ShouldBe(1);
theLock.Released.ShouldBe(1);
}

[Fact]
public async Task another_node_can_attain_the_lock_after_a_failed_apply()
{
// The postcondition the other replicas actually care about, asserted from a separate session.
// Disposing the connection is not enough on its own: Npgsql resets a pooled connection when it
// is next used rather than when it is returned, so the session-scoped lock outlives the apply
// for as long as that connection sits idle in the pool.
configureAMigrationThatWillFail();

await Should.ThrowAsync<PostgresException>(() =>
theDatabase.ApplyAllConfiguredChangesToDatabaseAsync(theLock));

(await AdvisoryLockTesting.IsFreeAsync(theLock.LockId)).ShouldBeTrue();
}

[Fact]
public async Task a_release_that_fails_does_not_replace_the_migration_failure()
{
// The migration failure is the one an operator needs to see. A release that cannot run has
// nothing to fall back on anyway.
theLock.ReleaseThrows = true;
configureAMigrationThatWillFail();

await Should.ThrowAsync<PostgresException>(() =>
theDatabase.ApplyAllConfiguredChangesToDatabaseAsync(theLock));
}
}

/// <summary>
/// A real session-scoped advisory lock on a lock id of its own, counting what the caller does with it.
/// </summary>
internal class CountingGlobalLock: IGlobalLock<NpgsqlConnection>
{
public CountingGlobalLock(int lockId)
{
LockId = lockId;
}

public int LockId { get; }
public int Attained { get; private set; }
public int Released { get; private set; }
public bool ReleaseThrows { get; set; }

public async Task<AttainLockResult> TryAttainLock(NpgsqlConnection conn, CancellationToken ct = default)
{
var result = await conn.TryGetGlobalLock(LockId, cancellation: ct).ConfigureAwait(false);
if (result.Succeeded)
{
Attained++;
}

return result;
}

public Task ReleaseLock(NpgsqlConnection conn, CancellationToken ct = default)
{
Released++;
if (ReleaseThrows)
{
throw new InvalidOperationException("the lock could not be released");
}

return conn.ReleaseGlobalLock(LockId, cancellation: ct);
}
}
Loading