Class: Torid::Generator

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

Overview

Public: A class that will generate unique identifiers.

Torid::Generator is the class that is used to generate Torid::UUID instances.

Example:

Torid::Generator.next # => Torid::UUID

generator = Torid::Generator.new
generator.next                    # => Torid::UUID

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(clock = Torid::Clock, node_id = Generator.create_node_id) ⇒ Generator

Internal: Create a new Torid UUID Generator

clock - an object that responds to ‘#tick` and returns a 64bit integer.

(default: Torid::Clock)

node_id - the 64bit node id of this node. (default: Generator.create_node_id)



30
31
32
33
34
# File 'lib/torid/generator.rb', line 30

def initialize( clock = Torid::Clock, node_id = Generator.create_node_id )
  @clock   = clock
  @node_id = node_id
  @pid     = Process.pid
end

Instance Attribute Details

#clockObject (readonly)

Internal: The Clock instance used to get 64bit timestamps



22
23
24
# File 'lib/torid/generator.rb', line 22

def clock
  @clock
end

Class Method Details

.create_node_id(pid = Process.pid) ⇒ Object

Internal: Generate a unique node identifier.

Uses the first hostname of the system, the process id, some random bytes and hashes them all together using the non-cryptographic FNV hash.

en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function

This method is copeid from github.com/jamesgolick/lexical_uuid/blob/master/lib/lexical_uuid.rb#L14 with the random bytes added by me.

Returns a 64 bit Integer



71
72
73
74
75
# File 'lib/torid/generator.rb', line 71

def self.create_node_id( pid = Process.pid )
  hostname = Socket.gethostbyname( Socket.gethostname ).first
  random   = SecureRandom.hex( 16 )
  FNV.new.fnv1a_64("#{hostname}-#{pid}-#{random}")
end

.nextObject

Public: Return the next UUID from the default Generator

Returns a Torid::UUID



90
91
92
# File 'lib/torid/generator.rb', line 90

def self.next
  @instance.next
end

.node_idObject

Public: Return the node id of the default Generator instance

Returns a 64 bit Integer



83
84
85
# File 'lib/torid/generator.rb', line 83

def self.node_id
  @instance.node_id
end

Instance Method Details

#nextObject

Public: Return the next UUID from this generator

Returns Torid::UUID



39
40
41
# File 'lib/torid/generator.rb', line 39

def next
 Torid::UUID.new( clock.tick, node_id )
end

#node_idObject

Public: Return the node id

This also checks if the node id is still a valid node id, by checking the pid of the process and the pid of the last time the node id was generated.

Returns the node_id



50
51
52
53
54
55
56
57
# File 'lib/torid/generator.rb', line 50

def node_id
  current_pid = Process.pid
  if current_pid != @pid then
    @pid     = current_pid
    @node_id = Generator.create_node_id( @pid )
  end
  return @node_id
end