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
- 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)
-
- (Object) client
readonly
Returns the value of attribute client.
Instance Method Summary (collapse)
-
- (Stamp) initialize(client)
constructor
A new instance of Stamp.
-
- (Object) next
Generates a k-sorted unique ID for use as a key or other disambiguation purposes.
Constructor Details
- (Stamp) initialize(client)
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
- (Object) client (readonly)
Returns the value of attribute client
11 12 13 |
# File 'lib/riak/stamp.rb', line 11 def client @client end |
Instance Method Details
- (Object) next
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 |