From 01dc3695bebedf8d4a648a0c32fa5185c428d178 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 20:05:40 +0000 Subject: [PATCH 1/6] Fix drivers not satisfying drivers.Lockable, which silently disabled locking The Lockable rewrite in #33 declared NewMutex(key string, logger Logger) (Locker, error) but the postgres and mysql drivers implement NewMutex returning (*Mutex, error). Go requires an exact method signature match, so neither driver satisfies drivers.Lockable and morph.New's type assertion fails. WithLock(...) is then skipped without any error and no migration lock is ever taken. Return drivers.Locker from both drivers, add compile-time assertions so the signatures cannot drift again, and add an engine-level postgres test that checks morph.New really holds the db_lock row and Close releases it. The test fails on master ("relation db_lock does not exist") and passes with this fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FpCfx4vHgXXz8FocntG7Y2 --- drivers/mysql/lock.go | 9 +++- drivers/postgres/engine_lock_test.go | 62 ++++++++++++++++++++++++++++ drivers/postgres/lock.go | 9 +++- 3 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 drivers/postgres/engine_lock_test.go diff --git a/drivers/mysql/lock.go b/drivers/mysql/lock.go index e37b0cc..764290e 100644 --- a/drivers/mysql/lock.go +++ b/drivers/mysql/lock.go @@ -12,6 +12,13 @@ import ( "github.com/mattermost/morph/drivers" ) +// Compile-time checks: morph.New only acquires the migration lock when the driver +// satisfies drivers.Lockable, so a signature drift here would silently disable locking. +var ( + _ drivers.Lockable = (*MySQL)(nil) + _ drivers.Locker = (*Mutex)(nil) +) + // Mutex is similar to sync.Mutex, except usable by morph to lock the db. // // Pick a unique name for each mutex your plugin requires. @@ -34,7 +41,7 @@ type Mutex struct { // NewMutex creates a mutex with the given key name. // // returns error if key is empty. -func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (*Mutex, error) { +func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (drivers.Locker, error) { key, err := drivers.MakeLockKey(key) if err != nil { return nil, err diff --git a/drivers/postgres/engine_lock_test.go b/drivers/postgres/engine_lock_test.go new file mode 100644 index 0000000..38ba6c9 --- /dev/null +++ b/drivers/postgres/engine_lock_test.go @@ -0,0 +1,62 @@ +//go:build !sources && drivers +// +build !sources,drivers + +package postgres_test + +import ( + "context" + "database/sql" + "fmt" + "io" + "log" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/mattermost/morph" + "github.com/mattermost/morph/drivers" + "github.com/mattermost/morph/drivers/postgres" + "github.com/mattermost/morph/sources/embedded" +) + +const engineLockTestConnURL = "postgres://morph:morph@localhost:6432/morph_test?sslmode=disable" + +// TestEngineAcquiresLock makes sure morph.New actually takes the migration lock +// through the postgres driver, i.e. that *postgres.Postgres is recognised as a +// drivers.Lockable at runtime and not silently skipped. +func TestEngineAcquiresLock(t *testing.T) { + const lockKey = "engine-lock-test" + + db, err := sql.Open("postgres", engineLockTestConnURL) + require.NoError(t, err) + defer db.Close() + _, err = db.Exec(fmt.Sprintf("DROP TABLE IF EXISTS %s", drivers.MutexTableName)) + require.NoError(t, err) + + driver, err := postgres.Open(engineLockTestConnURL) + require.NoError(t, err) + + src, err := embedded.WithInstance(&embedded.AssetSource{ + Names: []string{}, + AssetFunc: func(string) ([]byte, error) { return nil, nil }, + }) + require.NoError(t, err) + + engine, err := morph.New(context.Background(), driver, src, + morph.WithLock(lockKey), + morph.WithLogger(log.New(io.Discard, "", 0)), + ) + require.NoError(t, err) + + countLocks := func() int { + var n int + err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE id = $1", drivers.MutexTableName), lockKey).Scan(&n) + require.NoError(t, err) + return n + } + + require.Equal(t, 1, countLocks(), "morph.New should hold the lock while the engine is open") + + require.NoError(t, engine.Close()) + require.Equal(t, 0, countLocks(), "engine.Close should release the lock") +} diff --git a/drivers/postgres/lock.go b/drivers/postgres/lock.go index 58f59b6..fe629cf 100644 --- a/drivers/postgres/lock.go +++ b/drivers/postgres/lock.go @@ -12,6 +12,13 @@ import ( "github.com/mattermost/morph/drivers" ) +// Compile-time checks: morph.New only acquires the migration lock when the driver +// satisfies drivers.Lockable, so a signature drift here would silently disable locking. +var ( + _ drivers.Lockable = (*Postgres)(nil) + _ drivers.Locker = (*Mutex)(nil) +) + // Mutex is similar to sync.Mutex, except usable by morph to lock the db. // // Pick a unique name for each mutex your plugin requires. @@ -34,7 +41,7 @@ type Mutex struct { // NewMutex creates a mutex with the given key name. // // returns error if key is empty. -func (pg *Postgres) NewMutex(key string, logger drivers.Logger) (*Mutex, error) { +func (pg *Postgres) NewMutex(key string, logger drivers.Logger) (drivers.Locker, error) { key, err := drivers.MakeLockKey(key) if err != nil { return nil, err From d7bf1c16e41a2156e4f7a2d14a43cc0d09622280 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 20:17:58 +0000 Subject: [PATCH 2/6] Simplify engine lock test morph.New doesn't touch the migration source before migrations are applied, so the test can pass a nil source and drop the custom logger and table setup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FpCfx4vHgXXz8FocntG7Y2 --- drivers/postgres/engine_lock_test.go | 47 +++++++--------------------- 1 file changed, 11 insertions(+), 36 deletions(-) diff --git a/drivers/postgres/engine_lock_test.go b/drivers/postgres/engine_lock_test.go index 38ba6c9..dbdf123 100644 --- a/drivers/postgres/engine_lock_test.go +++ b/drivers/postgres/engine_lock_test.go @@ -6,57 +6,32 @@ package postgres_test import ( "context" "database/sql" - "fmt" - "io" - "log" "testing" "github.com/stretchr/testify/require" "github.com/mattermost/morph" - "github.com/mattermost/morph/drivers" "github.com/mattermost/morph/drivers/postgres" - "github.com/mattermost/morph/sources/embedded" ) -const engineLockTestConnURL = "postgres://morph:morph@localhost:6432/morph_test?sslmode=disable" - -// TestEngineAcquiresLock makes sure morph.New actually takes the migration lock -// through the postgres driver, i.e. that *postgres.Postgres is recognised as a -// drivers.Lockable at runtime and not silently skipped. +// TestEngineAcquiresLock checks that morph.New takes the db lock through the +// postgres driver instead of silently skipping it. func TestEngineAcquiresLock(t *testing.T) { - const lockKey = "engine-lock-test" + const connURL = "postgres://morph:morph@localhost:6432/morph_test?sslmode=disable" - db, err := sql.Open("postgres", engineLockTestConnURL) - require.NoError(t, err) - defer db.Close() - _, err = db.Exec(fmt.Sprintf("DROP TABLE IF EXISTS %s", drivers.MutexTableName)) + driver, err := postgres.Open(connURL) require.NoError(t, err) - driver, err := postgres.Open(engineLockTestConnURL) + engine, err := morph.New(context.Background(), driver, nil, morph.WithLock("engine-lock-test")) require.NoError(t, err) + defer engine.Close() - src, err := embedded.WithInstance(&embedded.AssetSource{ - Names: []string{}, - AssetFunc: func(string) ([]byte, error) { return nil, nil }, - }) + db, err := sql.Open("postgres", connURL) require.NoError(t, err) + defer db.Close() - engine, err := morph.New(context.Background(), driver, src, - morph.WithLock(lockKey), - morph.WithLogger(log.New(io.Discard, "", 0)), - ) + var held bool + err = db.QueryRow("SELECT EXISTS (SELECT 1 FROM db_lock WHERE id = 'engine-lock-test')").Scan(&held) require.NoError(t, err) - - countLocks := func() int { - var n int - err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE id = $1", drivers.MutexTableName), lockKey).Scan(&n) - require.NoError(t, err) - return n - } - - require.Equal(t, 1, countLocks(), "morph.New should hold the lock while the engine is open") - - require.NoError(t, engine.Close()) - require.Equal(t, 0, countLocks(), "engine.Close should release the lock") + require.True(t, held, "morph.New should hold the lock") } From 223a3c4c83466a55d4db992bd9a0e0993c67c3ca Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Fri, 4 Dec 2026 05:05:26 +0100 Subject: [PATCH 3/6] fix: return an error when WithLock is set but the driver can't lock morph.New skipped the lock silently when the driver did not implement drivers.Lockable, which is how the NewMutex signature drift went unnoticed. It now returns an error instead. The CLI always passes WithLock via the --lock-key default, so it now skips the lock for the sqlite driver, which has no lock support. TestEngineAcquiresLock also checks that Close releases the lock. --- commands/apply.go | 11 +++++++++-- drivers/postgres/engine_lock_test.go | 16 +++++++++++----- morph.go | 13 +++++++++---- morph_test.go | 6 ++++++ 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/commands/apply.go b/commands/apply.go index 1791708..7e936ad 100644 --- a/commands/apply.go +++ b/commands/apply.go @@ -186,11 +186,18 @@ func parseEngineFlags(cmd *cobra.Command) []morph.EngineOption { tableName, _ := cmd.Flags().GetString("migrations-table") mutexKey, _ := cmd.Flags().GetString("lock-key") dryRun, _ := cmd.Flags().GetBool("dry-run") + driverName, _ := cmd.Flags().GetString("driver") - return []morph.EngineOption{ + options := []morph.EngineOption{ morph.SetMigrationTableName(tableName), morph.SetStatementTimeoutInSeconds(timeout), - morph.WithLock(mutexKey), morph.SetDryRun(dryRun), } + + // The sqlite driver doesn't support locking. + if driverName != "sqlite" { + options = append(options, morph.WithLock(mutexKey)) + } + + return options } diff --git a/drivers/postgres/engine_lock_test.go b/drivers/postgres/engine_lock_test.go index dbdf123..1f90dfd 100644 --- a/drivers/postgres/engine_lock_test.go +++ b/drivers/postgres/engine_lock_test.go @@ -24,14 +24,20 @@ func TestEngineAcquiresLock(t *testing.T) { engine, err := morph.New(context.Background(), driver, nil, morph.WithLock("engine-lock-test")) require.NoError(t, err) - defer engine.Close() db, err := sql.Open("postgres", connURL) require.NoError(t, err) defer db.Close() - var held bool - err = db.QueryRow("SELECT EXISTS (SELECT 1 FROM db_lock WHERE id = 'engine-lock-test')").Scan(&held) - require.NoError(t, err) - require.True(t, held, "morph.New should hold the lock") + lockHeld := func() bool { + var held bool + err := db.QueryRow("SELECT EXISTS (SELECT 1 FROM db_lock WHERE id = 'engine-lock-test')").Scan(&held) + require.NoError(t, err) + return held + } + + require.True(t, lockHeld(), "morph.New should hold the lock") + + require.NoError(t, engine.Close()) + require.False(t, lockHeld(), "Close should release the lock") } diff --git a/morph.go b/morph.go index be47061..0c2bb17 100644 --- a/morph.go +++ b/morph.go @@ -90,9 +90,9 @@ func SetDryRun(enable bool) EngineOption { } // New creates a new instance of the migrations engine from an existing db instance and a migrations source. -// If the driver implements the Lockable interface, it will also wait until it has acquired a lock. -// The context is propagated to the drivers lock method (if the driver implements divers.Locker interface) and -// it can be used to cancel the lock acquisition. +// If WithLock is set, it waits until it has acquired the lock, and returns an error if the driver +// does not implement the drivers.Lockable interface. +// The context is propagated to the lock method and it can be used to cancel the lock acquisition. func New(ctx context.Context, driver drivers.Driver, source sources.Source, options ...EngineOption) (*Morph, error) { engine := &Morph{ config: &Config{ @@ -114,7 +114,12 @@ func New(ctx context.Context, driver drivers.Driver, source sources.Source, opti return nil, err } - if impl, ok := driver.(drivers.Lockable); ok && engine.config.LockKey != "" { + if engine.config.LockKey != "" { + impl, ok := driver.(drivers.Lockable) + if !ok { + return nil, fmt.Errorf("driver %T does not support locking", driver) + } + mx, err := impl.NewMutex(engine.config.LockKey, engine.config.Logger) if err != nil { return nil, err diff --git a/morph_test.go b/morph_test.go index 3519796..6afe859 100644 --- a/morph_test.go +++ b/morph_test.go @@ -303,6 +303,12 @@ func TestOppositeMigrations(t *testing.T) { }) } +func TestNewWithLockRequiresLockableDriver(t *testing.T) { + _, err := New(context.Background(), &testDriver{}, &basicSource{}, WithLock("test-lock")) + require.Error(t, err) + require.Contains(t, err.Error(), "does not support locking") +} + func TestGeneratePlan(t *testing.T) { h := newTestHelper(t).CreateBasicMigrations(t) defer h.Teardown(t) From 79a6f7d7ea662b97452e717de7f801b6663d91b1 Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Fri, 4 Dec 2026 06:02:55 +0100 Subject: [PATCH 4/6] fix: harden the db lock now that drivers use it - Bound the lock connection checkout by the setup timeout. - Close the lock connection when table creation fails or Lock is canceled. - Renew the lock expiry from the current time instead of the stored expiry, which let the lease grow with the engine's lifetime. - Lock the row in getExpireAt so two instances can't both take over an expired lock. --- drivers/mysql/lock.go | 12 ++++++------ drivers/postgres/lock.go | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/drivers/mysql/lock.go b/drivers/mysql/lock.go index 764290e..20574b4 100644 --- a/drivers/mysql/lock.go +++ b/drivers/mysql/lock.go @@ -50,13 +50,14 @@ func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (drivers.Locker ctx, cancel := context.WithTimeout(context.Background(), drivers.TTL) defer cancel() - conn, err := driver.db.Conn(context.Background()) + conn, err := driver.db.Conn(ctx) if err != nil { return nil, err } createTableIfNotExistsQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (Id varchar(64) NOT NULL, ExpireAt bigint(20) NOT NULL, PRIMARY KEY (Id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", drivers.MutexTableName) if _, err = conn.ExecContext(ctx, createTableIfNotExistsQuery); err != nil { + _ = conn.Close() return nil, err } @@ -132,7 +133,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { var expireAt int64 - query := fmt.Sprintf("SELECT ExpireAt FROM %s WHERE Id = ?", drivers.MutexTableName) + query := fmt.Sprintf("SELECT ExpireAt FROM %s WHERE Id = ? FOR UPDATE", drivers.MutexTableName) err := tx.QueryRow(query, m.key).Scan(&expireAt) if err != nil { return -1, fmt.Errorf("failed to fetch mutex from db: %w", err) @@ -149,14 +150,12 @@ func (m *Mutex) refreshLock(ctx context.Context) error { } defer m.finalizeTx(tx) - e, err := m.getExpireAt(tx) - if err != nil { + if _, err = m.getExpireAt(tx); err != nil { return err } - tmp := time.Unix(e, 0) query := fmt.Sprintf("UPDATE %s SET ExpireAt = ? WHERE Id = ?", drivers.MutexTableName) - if err = executeTx(tx, query, tmp.Add(drivers.TTL).Unix(), m.key); err != nil { + if err = executeTx(tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil { return err } @@ -179,6 +178,7 @@ func (m *Mutex) Lock(ctx context.Context) error { for { select { case <-ctx.Done(): + _ = m.conn.Close() return ctx.Err() case <-time.After(waitInterval): } diff --git a/drivers/postgres/lock.go b/drivers/postgres/lock.go index fe629cf..4ee9482 100644 --- a/drivers/postgres/lock.go +++ b/drivers/postgres/lock.go @@ -50,13 +50,14 @@ func (pg *Postgres) NewMutex(key string, logger drivers.Logger) (drivers.Locker, ctx, cancel := context.WithTimeout(context.Background(), drivers.TTL) defer cancel() - conn, err := pg.db.Conn(context.Background()) + conn, err := pg.db.Conn(ctx) if err != nil { return nil, err } createTableIfNotExistsQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id varchar(64) PRIMARY KEY, expireat bigint);", drivers.MutexTableName) if _, err = conn.ExecContext(ctx, createTableIfNotExistsQuery); err != nil { + _ = conn.Close() return nil, err } @@ -132,7 +133,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { var expireAt int64 - query := fmt.Sprintf("SELECT expireat FROM %s WHERE id = $1", drivers.MutexTableName) + query := fmt.Sprintf("SELECT expireat FROM %s WHERE id = $1 FOR UPDATE", drivers.MutexTableName) err := tx.QueryRow(query, m.key).Scan(&expireAt) if err != nil { return -1, fmt.Errorf("failed to fetch mutex from db: %w", err) @@ -149,14 +150,12 @@ func (m *Mutex) refreshLock(ctx context.Context) error { } defer m.finalizeTx(tx) - e, err := m.getExpireAt(tx) - if err != nil { + if _, err = m.getExpireAt(tx); err != nil { return err } - tmp := time.Unix(e, 0) query := fmt.Sprintf("UPDATE %s SET expireat = $1 WHERE id = $2", drivers.MutexTableName) - if err = executeTx(tx, query, tmp.Add(drivers.TTL).Unix(), m.key); err != nil { + if err = executeTx(tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil { return err } @@ -179,6 +178,7 @@ func (m *Mutex) Lock(ctx context.Context) error { for { select { case <-ctx.Done(): + _ = m.conn.Close() return ctx.Err() case <-time.After(waitInterval): } From 5b06bb8b985ba44125dfc4f6bf81abb9f486bfa3 Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Fri, 4 Dec 2026 06:07:11 +0100 Subject: [PATCH 5/6] fix: keep the db lock alive until Unlock and always close the driver - Refresh the lock on a context detached from the one passed to New, which only bounds lock acquisition. - Log a failed refresh and retry on the next tick instead of giving up. - Stop the refresh ticker when the goroutine exits. - Close the driver in Morph.Close even when Unlock fails. - Close the driver in TestEngineAcquiresLock when New fails. --- drivers/mysql/lock.go | 10 +++++++--- drivers/postgres/engine_lock_test.go | 3 +++ drivers/postgres/lock.go | 10 +++++++--- morph.go | 12 +++++++----- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/drivers/mysql/lock.go b/drivers/mysql/lock.go index 20574b4..cd17dab 100644 --- a/drivers/mysql/lock.go +++ b/drivers/mysql/lock.go @@ -195,15 +195,19 @@ func (m *Mutex) Lock(ctx context.Context) error { stop := make(chan bool) done := make(chan bool) + // The refresh must outlive the caller's context: it is only meant to bound lock + // acquisition, and the lock has to stay alive until Unlock. + refreshCtx := context.WithoutCancel(ctx) go func() { defer close(done) t := time.NewTicker(drivers.RefreshInterval) + defer t.Stop() for { select { case <-t.C: - err := m.refreshLock(ctx) - if err != nil { - return + // Keep trying on errors: giving up would let the lock expire while it's held. + if err := m.refreshLock(refreshCtx); err != nil { + m.logger.Printf("Failed to refresh lock: %v\n", err) } case <-stop: return diff --git a/drivers/postgres/engine_lock_test.go b/drivers/postgres/engine_lock_test.go index 1f90dfd..444d807 100644 --- a/drivers/postgres/engine_lock_test.go +++ b/drivers/postgres/engine_lock_test.go @@ -23,6 +23,9 @@ func TestEngineAcquiresLock(t *testing.T) { require.NoError(t, err) engine, err := morph.New(context.Background(), driver, nil, morph.WithLock("engine-lock-test")) + if err != nil { + _ = driver.Close() + } require.NoError(t, err) db, err := sql.Open("postgres", connURL) diff --git a/drivers/postgres/lock.go b/drivers/postgres/lock.go index 4ee9482..1e9d83a 100644 --- a/drivers/postgres/lock.go +++ b/drivers/postgres/lock.go @@ -195,15 +195,19 @@ func (m *Mutex) Lock(ctx context.Context) error { stop := make(chan bool) done := make(chan bool) + // The refresh must outlive the caller's context: it is only meant to bound lock + // acquisition, and the lock has to stay alive until Unlock. + refreshCtx := context.WithoutCancel(ctx) go func() { defer close(done) t := time.NewTicker(drivers.RefreshInterval) + defer t.Stop() for { select { case <-t.C: - err := m.refreshLock(ctx) - if err != nil { - return + // Keep trying on errors: giving up would let the lock expire while it's held. + if err := m.refreshLock(refreshCtx); err != nil { + m.logger.Printf("Failed to refresh lock: %v\n", err) } case <-stop: return diff --git a/morph.go b/morph.go index 0c2bb17..abad80c 100644 --- a/morph.go +++ b/morph.go @@ -137,14 +137,16 @@ func New(ctx context.Context, driver drivers.Driver, source sources.Source, opti // Close closes the underlying database connection of the engine. func (m *Morph) Close() error { + var unlockErr error if m.mutex != nil { - err := m.mutex.Unlock() - if err != nil { - return err - } + unlockErr = m.mutex.Unlock() + } + + if err := m.driver.Close(); err != nil { + return err } - return m.driver.Close() + return unlockErr } func (m *Morph) apply(migration *models.Migration, saveVersion, dryRun bool) error { From 8cfe9d5988b4e3f6024b8a3f51f128f02d8e59d8 Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Fri, 4 Dec 2026 08:05:35 +0100 Subject: [PATCH 6/6] fix: bound each lock renewal so Unlock can't block forever Run each renewal under a RefreshInterval timeout and pass the context to the queries inside the lock transaction, which previously ignored cancellation. --- drivers/mysql/lock.go | 19 +++++++++++-------- drivers/postgres/lock.go | 19 +++++++++++-------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/drivers/mysql/lock.go b/drivers/mysql/lock.go index cd17dab..0caddc9 100644 --- a/drivers/mysql/lock.go +++ b/drivers/mysql/lock.go @@ -109,7 +109,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { } defer m.finalizeTx(tx) - e, err := m.getExpireAt(tx) + e, err := m.getExpireAt(ctx, tx) if err != nil { return err } @@ -119,7 +119,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { } query := fmt.Sprintf("UPDATE %s SET ExpireAt = ? WHERE Id = ?", drivers.MutexTableName) - if err = executeTx(tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil { + if err = executeTx(ctx, tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil { return err } @@ -131,10 +131,10 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { return nil } -func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { +func (m *Mutex) getExpireAt(ctx context.Context, tx *sql.Tx) (int64, error) { var expireAt int64 query := fmt.Sprintf("SELECT ExpireAt FROM %s WHERE Id = ? FOR UPDATE", drivers.MutexTableName) - err := tx.QueryRow(query, m.key).Scan(&expireAt) + err := tx.QueryRowContext(ctx, query, m.key).Scan(&expireAt) if err != nil { return -1, fmt.Errorf("failed to fetch mutex from db: %w", err) } @@ -144,18 +144,21 @@ func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { // refreshLock rewrites the lock key value with a new expiry, returning nil only if successful. func (m *Mutex) refreshLock(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, drivers.RefreshInterval) + defer cancel() + tx, err := m.conn.BeginTx(ctx, nil) if err != nil { return err } defer m.finalizeTx(tx) - if _, err = m.getExpireAt(tx); err != nil { + if _, err = m.getExpireAt(ctx, tx); err != nil { return err } query := fmt.Sprintf("UPDATE %s SET ExpireAt = ? WHERE Id = ?", drivers.MutexTableName) - if err = executeTx(tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil { + if err = executeTx(ctx, tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil { return err } @@ -246,8 +249,8 @@ func (m *Mutex) Unlock() error { return err } -func executeTx(tx *sql.Tx, query string, args ...interface{}) error { - if _, err := tx.Exec(query, args...); err != nil { +func executeTx(ctx context.Context, tx *sql.Tx, query string, args ...interface{}) error { + if _, err := tx.ExecContext(ctx, query, args...); err != nil { return err } diff --git a/drivers/postgres/lock.go b/drivers/postgres/lock.go index 1e9d83a..30731d1 100644 --- a/drivers/postgres/lock.go +++ b/drivers/postgres/lock.go @@ -109,7 +109,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { } defer m.finalizeTx(tx) - e, err := m.getExpireAt(tx) + e, err := m.getExpireAt(ctx, tx) if err != nil { return err } @@ -119,7 +119,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { } query := fmt.Sprintf("UPDATE %s SET expireat = $1 WHERE id = $2", drivers.MutexTableName) - if err = executeTx(tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil { + if err = executeTx(ctx, tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil { return err } @@ -131,10 +131,10 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { return nil } -func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { +func (m *Mutex) getExpireAt(ctx context.Context, tx *sql.Tx) (int64, error) { var expireAt int64 query := fmt.Sprintf("SELECT expireat FROM %s WHERE id = $1 FOR UPDATE", drivers.MutexTableName) - err := tx.QueryRow(query, m.key).Scan(&expireAt) + err := tx.QueryRowContext(ctx, query, m.key).Scan(&expireAt) if err != nil { return -1, fmt.Errorf("failed to fetch mutex from db: %w", err) } @@ -144,18 +144,21 @@ func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { // refreshLock rewrites the lock key value with a new expiry, returning nil only if successful. func (m *Mutex) refreshLock(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, drivers.RefreshInterval) + defer cancel() + tx, err := m.conn.BeginTx(ctx, nil) if err != nil { return err } defer m.finalizeTx(tx) - if _, err = m.getExpireAt(tx); err != nil { + if _, err = m.getExpireAt(ctx, tx); err != nil { return err } query := fmt.Sprintf("UPDATE %s SET expireat = $1 WHERE id = $2", drivers.MutexTableName) - if err = executeTx(tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil { + if err = executeTx(ctx, tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil { return err } @@ -246,8 +249,8 @@ func (m *Mutex) Unlock() error { return err } -func executeTx(tx *sql.Tx, query string, args ...interface{}) error { - if _, err := tx.Exec(query, args...); err != nil { +func executeTx(ctx context.Context, tx *sql.Tx, query string, args ...interface{}) error { + if _, err := tx.ExecContext(ctx, query, args...); err != nil { return err }