priority_queue.go 2.2 KB

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