|
8 | 8 | "testing" |
9 | 9 | "time" |
10 | 10 |
|
| 11 | + "sync/atomic" |
| 12 | + |
11 | 13 | "github.com/stretchr/testify/assert" |
12 | 14 | "github.com/stretchr/testify/require" |
13 | 15 | "go.opentelemetry.io/otel/attribute" |
@@ -453,6 +455,63 @@ func TestResourcePoolLimiter_BasicUsage(t *testing.T) { |
453 | 455 | assert.Equal(t, 5, avail) |
454 | 456 | } |
455 | 457 |
|
| 458 | +// TestResourcePoolLimiter_LimitFlapToZeroDoesNotDeadlock verifies that a waiter |
| 459 | +// is woken up when the limit is reduced to zero and then increased again. |
| 460 | +func TestResourcePoolLimiter_LimitFlapToZeroDoesNotDeadlock(t *testing.T) { |
| 461 | + t.Parallel() |
| 462 | + |
| 463 | + origPoll := pollPeriod |
| 464 | + pollPeriod = 10 * time.Millisecond |
| 465 | + t.Cleanup(func() { pollPeriod = origPoll }) |
| 466 | + |
| 467 | + var limit atomic.Int64 |
| 468 | + limit.Store(1) |
| 469 | + |
| 470 | + limiter := newUnscopedResourcePoolLimiter(1) |
| 471 | + limiter.getLimitFn = func(context.Context) (int, error) { |
| 472 | + return int(limit.Load()), nil |
| 473 | + } |
| 474 | + go limiter.updateLoop(contexts.CRE{}) |
| 475 | + t.Cleanup(func() { assert.NoError(t, limiter.Close()) }) |
| 476 | + |
| 477 | + ctx := t.Context() |
| 478 | + |
| 479 | + // Consume the single available resource to force the next waiter to enqueue. |
| 480 | + freeFirst, err := limiter.Wait(ctx, 1) |
| 481 | + require.NoError(t, err) |
| 482 | + |
| 483 | + enqueued := make(chan struct{}, 1) |
| 484 | + limiter.resourcePoolUsage.setOnEnqueue(func() { enqueued <- struct{}{} }) |
| 485 | + |
| 486 | + waitErr := make(chan error, 1) |
| 487 | + go func() { |
| 488 | + waitCtx, cancel := context.WithTimeout(ctx, 200*time.Millisecond) |
| 489 | + defer cancel() |
| 490 | + _, err := limiter.Wait(waitCtx, 1) |
| 491 | + waitErr <- err |
| 492 | + }() |
| 493 | + |
| 494 | + // Ensure the waiter is queued before mutating the limit. |
| 495 | + <-enqueued |
| 496 | + |
| 497 | + // Drop the limit to zero, then free the first resource. The queued waiter |
| 498 | + // remains blocked because tryWakeWaiters sees a zero limit. |
| 499 | + limit.Store(0) |
| 500 | + freeFirst() |
| 501 | + |
| 502 | + // Raise the limit again; the queued waiter should be woken by the update. |
| 503 | + limit.Store(1) |
| 504 | + |
| 505 | + select { |
| 506 | + case err := <-waitErr: |
| 507 | + require.NoError(t, err) |
| 508 | + // release to avoid affecting subsequent waits |
| 509 | + _ = limiter.Free(ctx, 1) |
| 510 | + case <-time.After(time.Second): |
| 511 | + t.Fatal("waiter did not return after limit flap") |
| 512 | + } |
| 513 | +} |
| 514 | + |
456 | 515 | // setOnEnqueue sets a callback that is invoked each time a waiter is added to the queue. |
457 | 516 | // The callback is called with the mutex held. Used for testing to synchronize without sleeps. |
458 | 517 | func (u *resourcePoolUsage[N]) setOnEnqueue(fn func()) { |
|
0 commit comments