File size: 8,287 Bytes
fea99b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | package lockr_test
import (
"context"
"database/sql"
"fmt"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/openmeterio/openmeter/openmeter/ent/db"
"github.com/openmeterio/openmeter/openmeter/testutils"
"github.com/openmeterio/openmeter/pkg/framework/entutils"
"github.com/openmeterio/openmeter/pkg/framework/entutils/entdriver"
"github.com/openmeterio/openmeter/pkg/framework/lockr"
"github.com/openmeterio/openmeter/pkg/framework/pgdriver"
"github.com/openmeterio/openmeter/pkg/framework/transaction"
)
// Lets set up a dummy tx creator
type creator struct {
db *db.Client
}
var _ transaction.Creator = &creator{}
func (c *creator) Tx(ctx context.Context) (context.Context, transaction.Driver, error) {
txCtx, rawConfig, eDriver, err := c.db.HijackTx(ctx, &sql.TxOptions{
ReadOnly: false,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to hijack transaction: %w", err)
}
return txCtx, entutils.NewTxDriver(eDriver, rawConfig), nil
}
func TestLockerLockForTx(t *testing.T) {
withDBClient := func(fn func(t *testing.T, client *db.Client)) func(t *testing.T) {
return func(t *testing.T) {
testdb := testutils.InitPostgresDB(t, testutils.PostgresDBStateEmpty)
dbClient := testdb.EntDriver.Client()
t.Cleanup(func() { testdb.Close(t) })
fn(t, dbClient)
}
}
t.Run("Should error if not in a transaction", withDBClient(func(t *testing.T, client *db.Client) {
locker, err := lockr.NewLocker(&lockr.LockerConfig{
Logger: testutils.NewLogger(t),
})
require.NoError(t, err)
key, err := lockr.NewKey("test")
require.NoError(t, err)
err = locker.LockForTX(context.Background(), key)
require.Error(t, err)
require.ErrorContains(t, err, "lockr only works in a transaction, but driver not found")
}))
t.Run("Should acquire a lock", withDBClient(func(t *testing.T, client *db.Client) {
txCreator := &creator{db: client}
locker, err := lockr.NewLocker(&lockr.LockerConfig{
Logger: testutils.NewLogger(t),
})
require.NoError(t, err)
require.NoError(t, transaction.RunWithNoValue(context.Background(), txCreator, func(ctx context.Context) error {
key, err := lockr.NewKey("test")
if err != nil {
t.Fatalf("failed to create key: %v", err)
}
require.NoError(t, locker.LockForTX(ctx, key))
return nil
}))
}))
t.Run("Should be able to acquire same lock twice if in same transaction", withDBClient(func(t *testing.T, client *db.Client) {
txCreator := &creator{db: client}
locker, err := lockr.NewLocker(&lockr.LockerConfig{
Logger: testutils.NewLogger(t),
})
require.NoError(t, err)
require.NoError(t, transaction.RunWithNoValue(context.Background(), txCreator, func(ctx context.Context) error {
key, err := lockr.NewKey("test")
if err != nil {
t.Fatalf("failed to create key: %v", err)
}
require.NoError(t, locker.LockForTX(ctx, key))
require.NoError(t, locker.LockForTX(ctx, key))
return nil
}))
}))
t.Run("Should be able to acquire same lock in sub-transaction", withDBClient(func(t *testing.T, client *db.Client) {
txCreator := &creator{db: client}
locker, err := lockr.NewLocker(&lockr.LockerConfig{
Logger: testutils.NewLogger(t),
})
require.NoError(t, err)
require.NoError(t, transaction.RunWithNoValue(context.Background(), txCreator, func(ctx context.Context) error {
key, err := lockr.NewKey("test")
if err != nil {
t.Fatalf("failed to create key: %v", err)
}
require.NoError(t, locker.LockForTX(ctx, key))
require.NoError(t, transaction.RunWithNoValue(ctx, txCreator, func(ctx context.Context) error {
require.NoError(t, locker.LockForTX(ctx, key))
require.NoError(t, transaction.RunWithNoValue(ctx, txCreator, func(ctx context.Context) error {
require.NoError(t, locker.LockForTX(ctx, key))
return nil
}))
return nil
}))
return nil
}))
}))
t.Run("Should wait while acquiring lock from parallel transactions", withDBClient(func(t *testing.T, client *db.Client) {
txCreator := &creator{db: client}
locker, err := lockr.NewLocker(&lockr.LockerConfig{
Logger: testutils.NewLogger(t),
})
require.NoError(t, err)
key, err := lockr.NewKey("test")
require.NoError(t, err)
// We run two parallel go routines, each with a transaction, with different delays
// We'll synchronize the two with a trigger channel
trigTwo := make(chan struct{}, 1)
wg := sync.WaitGroup{}
wg.Add(2)
finCh := make(chan string, 4)
go func() {
defer wg.Done()
require.NoError(t, transaction.RunWithNoValue(context.Background(), txCreator, func(ctx context.Context) error {
finCh <- "1 start"
require.NoError(t, locker.LockForTX(ctx, key))
trigTwo <- struct{}{}
// non-blocking sleep for 1 second (we keep the lock for 1 second)
time.Sleep(1 * time.Second)
finCh <- "1 done"
return nil
}))
}()
go func() {
defer wg.Done()
timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second) // First goroutine should start and acquire the lock within a second
defer cancel()
require.NoError(t, transaction.RunWithNoValue(context.Background(), txCreator, func(ctx context.Context) error {
for {
select {
case <-timeoutCtx.Done():
require.Fail(t, "first routine failed to acquire the lock in time")
return nil
case <-trigTwo:
finCh <- "2 start"
require.NoError(t, locker.LockForTX(ctx, key))
finCh <- "2 done"
return nil
}
}
}))
}()
wg.Wait()
close(finCh)
// Let's read the contents of the chan to make sure things finished in the correct order
results := []string{}
for fin := range finCh {
results = append(results, fin)
}
// We assert that they end in the correct order
require.Equal(t, []string{"1 start", "2 start", "1 done", "2 done"}, results)
}))
t.Run("Should error if acquiring lock takes longer than timeout", func(t *testing.T) {
lockTimeout := time.Second * 3
testDB := testutils.InitPostgresDB(t, testutils.PostgresDBStateEmpty)
t.Cleanup(func() { testDB.Close(t) })
pgdrv, err := pgdriver.NewPostgresDriver(
t.Context(),
testDB.URL,
pgdriver.WithLockTimeout(lockTimeout),
)
if err != nil {
t.Fatalf("failed to get pg driver: %s", err)
}
client := entdriver.NewEntPostgresDriver(pgdrv.DB()).Client()
defer func() {
_ = client.Close()
_ = pgdrv.Close()
time.Sleep(1 * time.Second)
}()
txCreator := &creator{db: client}
locker, err := lockr.NewLocker(&lockr.LockerConfig{
Logger: testutils.NewLogger(t),
})
require.NoError(t, err)
key, err := lockr.NewKey("test")
require.NoError(t, err)
// We run two parallel go routines, each with a transaction, with different delays
// We need to ensure that they start in the correct order (that the locks are acquired in the correct order)
// We'll synchronize the two with a trigger channel
trigTwo := make(chan struct{}, 1)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
require.NoError(t, transaction.RunWithNoValue(context.Background(), txCreator, func(ctx context.Context) error {
require.NoError(t, locker.LockForTX(ctx, key))
trigTwo <- struct{}{}
// non-blocking sleep for 4 seconds (more than 3)
time.Sleep(lockTimeout + time.Second)
return nil
}))
}()
go func() {
defer wg.Done()
timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second) // First goroutine should start and acquire the lock within a second
defer cancel()
// This will fail as the timeout cancels the context and the client connection
require.Error(t, transaction.RunWithNoValue(context.Background(), txCreator, func(ctx context.Context) error {
for {
select {
case <-timeoutCtx.Done():
require.Fail(t, "first routine failed to acquire the lock in time")
return nil
// We only try to acquire the lock if the first has already acquired it
case <-trigTwo:
// We should get a timeout error as we've been trying to get the lock for over 3 second
err := locker.LockForTX(ctx, key)
require.Error(t, err)
require.ErrorIs(t, err, lockr.ErrLockTimeout)
return err
}
}
}))
}()
wg.Wait()
})
}
|