| 75 | |
| 76 | |
| 77 | class Queue: |
| 78 | # Public functions |
| 79 | def __init__(self, subspace, highContention=True): |
| 80 | self.subspace = subspace |
| 81 | self.highContention = highContention |
| 82 | |
| 83 | self._conflictedPop = self.subspace['pop'] |
| 84 | self._conflictedItem = self.subspace['conflict'] |
| 85 | self._queueItem = self.subspace['item'] |
| 86 | |
| 87 | @fdb.transactional |
| 88 | def clear(self, tr): |
| 89 | """Remove all items from the queue.""" |
| 90 | del tr[self.subspace.range()] |
| 91 | |
| 92 | @fdb.transactional |
| 93 | def push(self, tr, value): |
| 94 | """Push a single item onto the queue.""" |
| 95 | index = self._getNextIndex(tr.snapshot, self._queueItem) |
| 96 | self._pushAt(tr, self._encodeValue(value), index) |
| 97 | |
| 98 | def pop(self, db): |
| 99 | """Pop the next item from the queue. Cannot be composed with other functions in a single transaction.""" |
| 100 | |
| 101 | if self.highContention: |
| 102 | result = self._popHighContention(db) |
| 103 | else: |
| 104 | result = self._popSimple(db) |
| 105 | |
| 106 | if result is None: |
| 107 | return result |
| 108 | |
| 109 | return self._decodeValue(result) |
| 110 | |
| 111 | @fdb.transactional |
| 112 | def empty(self, tr): |
| 113 | """Test whether the queue is empty.""" |
| 114 | return self._getFirstItem(tr) is None |
| 115 | |
| 116 | @fdb.transactional |
| 117 | def peek(self, tr): |
| 118 | """Get the value of the next item in the queue without popping it.""" |
| 119 | firstItem = self._getFirstItem(tr) |
| 120 | if firstItem is None: |
| 121 | return None |
| 122 | else: |
| 123 | return self._decodeValue(firstItem.value) |
| 124 | |
| 125 | # Private functions |
| 126 | |
| 127 | def _conflictedItemKey(self, subKey): |
| 128 | return self._conflictedItem.pack((subKey,)) |
| 129 | |
| 130 | def _randID(self): |
| 131 | return os.urandom(20) # this relies on good random data from the OS to avoid collisions |
| 132 | |
| 133 | def _encodeValue(self, value): |
| 134 | return fdb.tuple.pack((value,)) |
no outgoing calls
no test coverage detected