Class: Riak::Stamp
Overview
Implements a client-side form of monotonically-increasing k-sorted unique identifiers. These are useful for key generation if your data is time-sequential and needs to be sorted by key, perhaps in Riak Search. Inspired by Twitter’s Snowflake project.
Constant Summary collapse
- CLIENT_ID_MASK =
(1 << 10) - 1
- SEQUENCE_MASK =
(1 << 12) - 1
- TIMESTAMP_MASK =
(1 << 41) - 1
- SEQUENCE_SHIFT =
10
- TIMESTAMP_SHIFT =
22
Instance Attribute Summary collapse
-
#client ⇒ Object
readonly
Returns the value of attribute client.
Instance Method Summary collapse
-
#initialize(client) ⇒ Stamp
constructor
A new instance of Stamp.
-
#next ⇒ Object
Generates a k-sorted unique ID for use as a key or other disambiguation purposes.
Constructor Details
#initialize(client) ⇒ Stamp
Returns a new instance of Stamp.
22 23 24 25 26 27 |
# File 'lib/riak/stamp.rb', line 22 def initialize(client) @client = client @mutex = Mutex.new @timestamp = time_gen @sequence = 0 end |
Instance Attribute Details
#client ⇒ Object (readonly)
Returns the value of attribute client.
11 12 13 |
# File 'lib/riak/stamp.rb', line 11 def client @client end |
Instance Method Details
#next ⇒ Object
Generates a k-sorted unique ID for use as a key or other disambiguation purposes.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/riak/stamp.rb', line 31 def next @mutex.synchronize do now = time_gen if @timestamp == now @sequence = (@sequence + 1) & SEQUENCE_MASK now = wait_for_next_ms(@timestamp) if @sequence == 0 else @sequence = 0 end raise BackwardsClockError.new(@timestamp - now) if now < @timestamp @timestamp = now @timestamp << TIMESTAMP_SHIFT | @sequence << SEQUENCE_SHIFT | client_id end end |