Class: CRDT::VectorClock
- Inherits:
-
Object
- Object
- CRDT::VectorClock
- 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
-
#clocks ⇒ Object
Returns the value of attribute clocks.
Class Method Summary collapse
-
.from_h(hash) ⇒ Object
Create a new VectorClock from the provided hash.
Instance Method Summary collapse
-
#increment_clock(node = nil) ⇒ Object
Increment the clock for the given node by 1.
-
#initialize(default_node = Thread.current.object_id) ⇒ VectorClock
constructor
Create a new vector clock.
-
#merge(other) ⇒ Object
Perform a one-way merge, bringing in clock values from the other clock.
-
#to_h ⇒ Object
Get a hash representation of this vector clock, suitable for serialization to JSON.
-
#value(node = nil) ⇒ Object
Get the current clock value for the given node.
Constructor Details
#initialize(default_node = Thread.current.object_id) ⇒ VectorClock
Create a new vector clock
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
#clocks ⇒ Object
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
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_h ⇒ Object
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
30 31 32 33 |
# File 'lib/crdt/vector_clock.rb', line 30 def value(node = nil) node ||= @default_node @clocks[node] end |