Class: CRDT::VectorClock

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

Overview

Vector clocks are a loose synchronization primitive

Vector clocks can be used as a building block to create other replicated data types, and tracking operations

Formally, a vector clock is equivalent to a GCounter that is only incremented by 1, and the aggregate value is ignored

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_node = Thread.current.object_id) ⇒ VectorClock

Create a new vector clock

Parameters:

  • default_node (defaults to: Thread.current.object_id)

    Identity of the current node. Defaults to the current Thread object id



11
12
13
14
# File 'lib/crdt/vector_clock.rb', line 11

def initialize(default_node = Thread.current.object_id)
  @default_node = default_node
  @clocks = {}
end

Instance Attribute Details

#clocksObject

Returns the value of attribute clocks.



16
17
18
# File 'lib/crdt/vector_clock.rb', line 16

def clocks
  @clocks
end

Class Method Details

.from_h(hash) ⇒ Object

Create a new VectorClock from the provided hash. The hash should follow this syntax:

{

"clocks" => {
  "1" => 3,
  "3" => 2
}

}



43
44
45
46
47
48
49
50
51
# File 'lib/crdt/vector_clock.rb', line 43

def self.from_h(hash)
  clock = VectorClock.new

  hash["clocks"].each do |node, value|
    clock.clocks[node] = value
  end

  return clock
end

Instance Method Details

#increment_clock(node = nil) ⇒ Object

Increment the clock for the given node by 1

Parameters:

  • node (defaults to: nil)

    The node to update the clock for. Defaults to the default node



21
22
23
24
25
# File 'lib/crdt/vector_clock.rb', line 21

def increment_clock(node = nil)
  node ||= @default_node
  @clocks[node] ||= 0
  @clocks[node] += 1
end

#merge(other) ⇒ Object

Perform a one-way merge, bringing in clock values from the other clock



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/crdt/vector_clock.rb', line 61

def merge(other)
  other.clocks.each do |node, value|
    current_value = @clocks[node]
    if current_value
      if current_value < value
        @clocks[node] = value
      end
    else
      @clocks[node] = value
    end
  end
end

#to_hObject

Get a hash representation of this vector clock, suitable for serialization to JSON



54
55
56
57
58
# File 'lib/crdt/vector_clock.rb', line 54

def to_h
  return {
    clocks: @clocks,
  }
end

#value(node = nil) ⇒ Object

Get the current clock value for the given node

Parameters:

  • node (defaults to: nil)

    the node to check for. Defaults to the default node



30
31
32
33
# File 'lib/crdt/vector_clock.rb', line 30

def value(node = nil)
  node ||= @default_node
  @clocks[node]
end