Class: IdGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/id_generator.rb

Constant Summary collapse

EPOCH =

Project Epoch: Midnight, Mountain Time, January 1st, 2013

1357023600
TIMESTAMP_BIT_LENGTH =

Field Bit Lengths

40
HOST_ID_BIT_LENGTH =
5
WORKER_ID_BIT_LENGTH =
5
SEQUENCE_BIT_LENGTH =
14
TIMESTAMP_SHIFT =

Field Shifts

HOST_ID_BIT_LENGTH + WORKER_ID_BIT_LENGTH + SEQUENCE_BIT_LENGTH
HOST_ID_SHIFT =
WORKER_ID_BIT_LENGTH + SEQUENCE_BIT_LENGTH
WORKER_ID_SHIFT =
SEQUENCE_BIT_LENGTH
TIMESTAMP_MASK =

Field Masks

0xFFFFFFFFFF000000
HOST_ID_MASK =
0x0000000000F80000
WORKER_ID_MASK =
0x000000000007C000
SEQUENCE_MASK =
0x0000000000003FFF

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ IdGenerator

Returns a new instance of IdGenerator.

Raises:

  • (ArgumentError)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/id_generator.rb', line 30

def initialize(options = {})
  options.symbolize_keys!

  raise ArgumentError, 'missing host id' if options[:host].nil?
  raise ArgumentError, 'missing worker id' if options[:worker].nil?

  @debug      = options[:debug]
  @host       = options[:host].to_i
  @worker     = options[:worker].to_i
  @sequence   = 0
  @last_stamp = -1

  puts 'Initialized IdGenerator' if @debug
end

Instance Method Details

#get_idObject

Raises:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/id_generator.rb', line 45

def get_id
  now = get_timestamp

  raise InvalidSystemClock if now < @last_stamp

  if @last_stamp == now
    @sequence = (@sequence + 1) & SEQUENCE_MASK

    if @sequence == 0
      sleep_until_next_millisecond
      now = get_timestamp
    end
  else
    @sequence = 0
  end

  @last_stamp = now

  id = (now << TIMESTAMP_SHIFT) | (@host << HOST_ID_SHIFT) | (@worker << WORKER_ID_SHIFT) | @sequence
  puts "Generated ID: #{id}" if @debug
  id
end

#get_timestampObject



68
69
70
# File 'lib/id_generator.rb', line 68

def get_timestamp
  Time.now.to_i - EPOCH
end