1/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package queue
18
19import (
20	"sync"
21	"time"
22
23	"k8s.io/apimachinery/pkg/types"
24	"k8s.io/apimachinery/pkg/util/clock"
25)
26
27// WorkQueue allows queuing items with a timestamp. An item is
28// considered ready to process if the timestamp has expired.
29type WorkQueue interface {
30	// GetWork dequeues and returns all ready items.
31	GetWork() []types.UID
32	// Enqueue inserts a new item or overwrites an existing item.
33	Enqueue(item types.UID, delay time.Duration)
34}
35
36type basicWorkQueue struct {
37	clock clock.Clock
38	lock  sync.Mutex
39	queue map[types.UID]time.Time
40}
41
42var _ WorkQueue = &basicWorkQueue{}
43
44// NewBasicWorkQueue returns a new basic WorkQueue with the provided clock
45func NewBasicWorkQueue(clock clock.Clock) WorkQueue {
46	queue := make(map[types.UID]time.Time)
47	return &basicWorkQueue{queue: queue, clock: clock}
48}
49
50func (q *basicWorkQueue) GetWork() []types.UID {
51	q.lock.Lock()
52	defer q.lock.Unlock()
53	now := q.clock.Now()
54	var items []types.UID
55	for k, v := range q.queue {
56		if v.Before(now) {
57			items = append(items, k)
58			delete(q.queue, k)
59		}
60	}
61	return items
62}
63
64func (q *basicWorkQueue) Enqueue(item types.UID, delay time.Duration) {
65	q.lock.Lock()
66	defer q.lock.Unlock()
67	q.queue[item] = q.clock.Now().Add(delay)
68}
69