Class: Snowflake::IdGenerator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(datacenter_id, worker_id) ⇒ IdGenerator

Returns a new instance of IdGenerator.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/snowflake_id_generator.rb', line 19

def initialize(datacenter_id, worker_id)
  if datacenter_id > Snowflake::MAX_DATACENTER_ID || datacenter_id < 0
    raise ArgumentError, "datacenter_id must be between 0 and #{Snowflake::MAX_DATACENTER_ID}"
  end

  if worker_id > Snowflake::MAX_WORKER_ID || worker_id < 0
    raise ArgumentError, "worker_id must be between 0 and #{Snowflake::MAX_WORKER_ID}"
  end

  @datacenter_id = datacenter_id
  @worker_id = worker_id
  @sequence = 0
  @last_timestamp = -1
end

Instance Attribute Details

#datacenter_idObject (readonly)

Returns the value of attribute datacenter_id.



17
18
19
# File 'lib/snowflake_id_generator.rb', line 17

def datacenter_id
  @datacenter_id
end

#last_timestampObject (readonly)

Returns the value of attribute last_timestamp.



17
18
19
# File 'lib/snowflake_id_generator.rb', line 17

def last_timestamp
  @last_timestamp
end

#sequenceObject (readonly)

Returns the value of attribute sequence.



17
18
19
# File 'lib/snowflake_id_generator.rb', line 17

def sequence
  @sequence
end

#worker_idObject (readonly)

Returns the value of attribute worker_id.



17
18
19
# File 'lib/snowflake_id_generator.rb', line 17

def worker_id
  @worker_id
end

Instance Method Details

#next_idObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/snowflake_id_generator.rb', line 34

def next_id
  timestamp = current_time_millis

  if timestamp < @last_timestamp
    raise "Clock moved backwards. Refusing to generate id for #{@last_timestamp - timestamp} milliseconds"
  end

  if @last_timestamp == timestamp
    @sequence = (@sequence + 1) & Snowflake::MAX_SEQUENCE
    if @sequence == 0
      timestamp = wait_for_next_millis(@last_timestamp)
    end
  else
    @sequence = 0
  end

  @last_timestamp = timestamp

  p "timestamp - EPOCH: #{timestamp - Snowflake::EPOCH}"

  ((timestamp - Snowflake::EPOCH) << Snowflake::TIMESTAMP_SHIFT) |
    (@datacenter_id << Snowflake::DATACENTER_ID_SHIFT) |
    (@worker_id << Snowflake::WORKER_ID_SHIFT) |
    @sequence
end