Class: Phronomy::Persistence::InMemory::Journals

Inherits:
Object
  • Object
show all
Defined in:
lib/phronomy/persistence/in_memory.rb

Instance Method Summary collapse

Constructor Details

#initialize(owner) ⇒ Journals

Returns a new instance of Journals.



93
# File 'lib/phronomy/persistence/in_memory.rb', line 93

def initialize(owner) = @owner = owner

Instance Method Details

#append(agent_id, expected_position:, records:) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/phronomy/persistence/in_memory.rb', line 95

def append(agent_id, expected_position:, records:)
  @owner.synchronize do
    target = (@owner.state[:journals][agent_id.to_s] ||= [])
    unless target.length == expected_position
      raise ConflictError,
        "journal position conflict: expected #{expected_position}, actual #{target.length}"
    end
    existing_ids = target.to_h { |record| [record.record_id, true] }
    incoming_ids = {}
    appended = Array(records).each_with_index.map do |record, index|
      unless record.agent_id.to_s == agent_id.to_s
        raise ConflictError,
          "Journal record Agent mismatch: #{record.agent_id} != #{agent_id}"
      end
      if existing_ids[record.record_id] || incoming_ids[record.record_id]
        raise ConflictError, "duplicate Journal record_id: #{record.record_id}"
      end
      incoming_ids[record.record_id] = true
      record.with_sequence(expected_position + index + 1)
    end
    target.concat(appended)
    appended.freeze
  end
end

#delete(agent_id) ⇒ Object



133
134
135
# File 'lib/phronomy/persistence/in_memory.rb', line 133

def delete(agent_id)
  @owner.synchronize { @owner.state[:journals].delete(agent_id.to_s) }
end

#head(agent_id) ⇒ Object



129
130
131
# File 'lib/phronomy/persistence/in_memory.rb', line 129

def head(agent_id)
  @owner.synchronize { Array(@owner.state[:journals][agent_id.to_s]).length }
end

#read(agent_id, after: nil, limit: nil) ⇒ Object



120
121
122
123
124
125
126
127
# File 'lib/phronomy/persistence/in_memory.rb', line 120

def read(agent_id, after: nil, limit: nil)
  @owner.synchronize do
    result = Array(@owner.state[:journals][agent_id.to_s])
    result = result.drop(Integer(after)) if after
    result = result.first(limit) if limit
    result.dup.freeze
  end
end