Class: Teakflake::IdWorker

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

Defined Under Namespace

Classes: BackwardsTimeError

Instance Method Summary collapse

Constructor Details

#initialize(worker_id_assigner) ⇒ IdWorker

Returns a new instance of IdWorker.



25
26
27
28
29
30
31
# File 'lib/teakflake/id_worker.rb', line 25

def initialize(worker_id_assigner)
  @clock = worker_id_assigner.clock
  @sequence = 0
  @worker_id_assigner = worker_id_assigner
  @datacenter_id = worker_id_assigner.datacenter_id
  @last_time = 0
end

Instance Method Details

#id(requested_count = 1) ⇒ Object



33
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/teakflake/id_worker.rb', line 33

def id(requested_count = 1)
  if requested_count < 1
    raise 'Must request at least one id'
  end

  time = @clock.millis
  if time < @last_time
    raise BackwardsTimeError, "Clocked moved backwards. Refusing to generate id for #{@last_time - time} milliseconds"
  end

  worker_id = @worker_id_assigner.assert(time)

  @sequence = 0 if time > @last_time

  if Id::MAX_SEQUENCE == @sequence
    time = til_next_millis
    @sequence = 0
  end

  available_count = Id::MAX_SEQUENCE - @sequence
  requested_count =
    if available_count < requested_count
      available_count
    else
      requested_count
    end

  next_sequence = @sequence + requested_count

  @last_time = time
  timestamp_part = time - Id::EPOCH

  response = Array.new(requested_count) do |i|
    timestamp_part << Id::TIMESTAMP_SHIFT |
      @datacenter_id << Id::DATACENTER_ID_SHIFT |
      worker_id << Id::WORKER_ID_SHIFT |
      @sequence + i
  end

  @sequence = next_sequence
  response
end

#til_next_millisObject



76
77
78
79
80
81
82
83
84
85
# File 'lib/teakflake/id_worker.rb', line 76

def til_next_millis
  loop do
    time = @clock.millis
    if time < @last_time
      raise BackwardsTimeError, "Clocked moved backwards. Refusing to generate id for #{@last_time - time} milliseconds"
    elsif time > @last_time
      break time
    end
  end
end