github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/doltcore/sqle/read_replica_database_test.go (about) 1 // Copyright 2022 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package sqle 16 17 import ( 18 "context" 19 "runtime" 20 "sync" 21 "sync/atomic" 22 "testing" 23 "time" 24 25 "github.com/stretchr/testify/assert" 26 "golang.org/x/sync/semaphore" 27 ) 28 29 func TestLimiter(t *testing.T) { 30 t.Run("NoConcurrency", func(t *testing.T) { 31 l := newLimiter() 32 for i := 0; i < 16; i++ { 33 l.Run(context.Background(), "key_one", func() (any, error) { 34 return 1, nil 35 }) 36 l.Run(context.Background(), "key_two", func() (any, error) { 37 return 1, nil 38 }) 39 l.Run(context.Background(), "key_three", func() (any, error) { 40 return 1, nil 41 }) 42 } 43 }) 44 t.Run("ConcurrentRuns", func(t *testing.T) { 45 l := newLimiter() 46 var wg sync.WaitGroup 47 sema := semaphore.NewWeighted(16) 48 sema.Acquire(context.Background(), 16) 49 var numRuns int32 50 v, err := l.Run(context.Background(), "one", func() (any, error) { 51 for i := 0; i < 16; i++ { 52 wg.Add(1) 53 go func() { 54 defer wg.Done() 55 sema.Release(1) 56 v, err := l.Run(context.Background(), "one", func() (any, error) { 57 atomic.AddInt32(&numRuns, 1) 58 return 2, nil 59 }) 60 assert.NoError(t, err) 61 assert.Equal(t, 2, v) 62 }() 63 } 64 65 // TODO: This is some jank to reduce flakiness. 66 sema.Acquire(context.Background(), 16) 67 time.Sleep(10 * time.Millisecond) 68 for i := 0; i < 128; i++ { 69 runtime.Gosched() 70 } 71 time.Sleep(10 * time.Millisecond) 72 73 return 1, nil 74 }) 75 assert.NoError(t, err) 76 assert.Equal(t, 1, v) 77 wg.Wait() 78 assert.Equal(t, int32(1), numRuns) 79 }) 80 }