priority_queue.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2016 CoreOS, 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. package recipe
  15. import (
  16. "fmt"
  17. "github.com/coreos/etcd/clientv3"
  18. "github.com/coreos/etcd/storage/storagepb"
  19. )
  20. // PriorityQueue implements a multi-reader, multi-writer distributed queue.
  21. type PriorityQueue struct {
  22. client *clientv3.Client
  23. key string
  24. }
  25. // NewPriorityQueue creates an etcd priority queue.
  26. func NewPriorityQueue(client *clientv3.Client, key string) *PriorityQueue {
  27. return &PriorityQueue{client, key + "/"}
  28. }
  29. // Enqueue puts a value into a queue with a given priority.
  30. func (q *PriorityQueue) Enqueue(val string, pr uint16) error {
  31. prefix := fmt.Sprintf("%s%05d", q.key, pr)
  32. _, err := NewSequentialKV(q.client, prefix, val)
  33. return err
  34. }
  35. // Dequeue returns Enqueue()'d items in FIFO order. If the
  36. // queue is empty, Dequeue blocks until items are available.
  37. func (q *PriorityQueue) Dequeue() (string, error) {
  38. // TODO: fewer round trips by fetching more than one key
  39. resp, err := NewRange(q.client, q.key).FirstKey()
  40. if err != nil {
  41. return "", err
  42. }
  43. kv, err := claimFirstKey(q.client.KV, resp.Kvs)
  44. if err != nil {
  45. return "", err
  46. } else if kv != nil {
  47. return string(kv.Value), nil
  48. } else if resp.More {
  49. // missed some items, retry to read in more
  50. return q.Dequeue()
  51. }
  52. // nothing to dequeue; wait on items
  53. ev, err := WaitPrefixEvents(
  54. q.client,
  55. q.key,
  56. resp.Header.Revision,
  57. []storagepb.Event_EventType{storagepb.PUT})
  58. if err != nil {
  59. return "", err
  60. }
  61. ok, err := deleteRevKey(q.client.KV, string(ev.Kv.Key), ev.Kv.ModRevision)
  62. if err != nil {
  63. return "", err
  64. } else if !ok {
  65. return q.Dequeue()
  66. }
  67. return string(ev.Kv.Value), err
  68. }