From 31a0e128fc1e08c96eaaacfc5e8407f5b0a07646 Mon Sep 17 00:00:00 2001 From: Yash Mehrotra Date: Tue, 17 Dec 2024 13:59:33 +0530 Subject: [PATCH] fix: priority queue delay logic was inverse (#256) --- collections/priorityqueue.go | 6 ++---- collections/priorityqueue_test.go | 24 +++++++++++++++++++----- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/collections/priorityqueue.go b/collections/priorityqueue.go index f1135a4..f554b04 100644 --- a/collections/priorityqueue.go +++ b/collections/priorityqueue.go @@ -271,10 +271,8 @@ func (queue *Queue[T]) Dequeue() (T, bool) { // Peek for notBefore v, _ := queue.heap.Peek() - if !v.notBefore.IsZero() { - if time.Until(v.notBefore) < 0 { - return zero, false - } + if !v.notBefore.IsZero() && time.Until(v.notBefore) > 0 { + return zero, false } wrapper, ok := queue.heap.Pop() diff --git a/collections/priorityqueue_test.go b/collections/priorityqueue_test.go index fe50a5a..fdb9edb 100644 --- a/collections/priorityqueue_test.go +++ b/collections/priorityqueue_test.go @@ -223,21 +223,35 @@ func TestPriorityQueueWithDelay(t *testing.T) { g.Expect(err).To(BeNil()) g.Expect(pq.Size()).To(BeNumerically("==", 0)) - pq.EnqueueWithDelay("item1-delay-10s", 10*time.Second) - pq.EnqueueWithDelay("item1-delay-05s", 5*time.Second) + pq.EnqueueWithDelay("item1-delay-06s", 6*time.Second) + pq.EnqueueWithDelay("item1-delay-03s", 3*time.Second) pq.Enqueue("item1") + start := time.Now() + var items []string for { if pq.Size() == 0 { break } - item, _ := pq.Dequeue() - items = append(items, item) + item, valid := pq.Dequeue() + if valid { + items = append(items, item) + } + + if time.Since(start) > (1*time.Second) && time.Since(start) < (2*time.Second) { + g.Expect(items).To(Equal([]string{"item1"})) + } + if time.Since(start) > (3*time.Second) && time.Since(start) < (5*time.Second) { + g.Expect(items).To(Equal([]string{"item1", "item1-delay-03s"})) + } + if time.Since(start) > (6 * time.Second) { + g.Expect(items).To(Equal([]string{"item1", "item1-delay-03s", "item1-delay-06s"})) + } } - g.Expect(items).To(Equal([]string{"item1", "item1-delay-05s", "item1-delay-10s"})) + g.Expect(items).To(Equal([]string{"item1", "item1-delay-03s", "item1-delay-06s"})) } func first[T1 any, T2 any](a T1, _ T2) T1 {