Class: Phronomy::StateStore::ActiveRecord

Inherits:
Base
  • Object
show all
Defined in:
lib/phronomy/state_store/active_record.rb

Overview

ActiveRecord-backed state store. Persists graph state to a relational database using an AR model.

The model_class must respond to: .find_by(thread_id:) .find_or_initialize_by(thread_id:) #state_json=, #save! .where(thread_id:).delete_all

Minimal migration: create_table :phronomy_states do |t| t.string :thread_id, null: false, index: { unique: true } t.text :state_json, null: false t.timestamps end

Examples:

Phronomy.configure do |c|
  c.default_state_store = Phronomy::StateStore::ActiveRecord.new(
    model_class: PhronomyState
  )
end

Instance Method Summary collapse

Constructor Details

#initialize(model_class:, encryptor: nil) ⇒ ActiveRecord

Returns a new instance of ActiveRecord.

Parameters:

  • model_class (Class)

    ActiveRecord model with the schema above.

  • encryptor (Phronomy::StateStore::Encryptor::Base, nil) (defaults to: nil)

    Optional encryption adapter. When supplied, the JSON payload is encrypted before writing and decrypted after reading. When nil (default), data is stored as plain JSON.



35
36
37
38
# File 'lib/phronomy/state_store/active_record.rb', line 35

def initialize(model_class:, encryptor: nil)
  @model_class = model_class
  @encryptor = encryptor
end

Instance Method Details

#clear(thread_id) ⇒ self

Deletes the state for the given thread_id.

Returns:

  • (self)


66
67
68
69
# File 'lib/phronomy/state_store/active_record.rb', line 66

def clear(thread_id)
  @model_class.where(thread_id: thread_id).delete_all
  self
end

#load(thread_id) ⇒ Object?

Loads and deserializes the state for the given thread_id.

Parameters:

  • thread_id (String)

Returns:

  • (Object, nil)

    state instance or nil



55
56
57
58
59
60
61
62
# File 'lib/phronomy/state_store/active_record.rb', line 55

def load(thread_id)
  record = @model_class.find_by(thread_id: thread_id)
  return nil unless record

  payload = record.state_json
  json = @encryptor ? @encryptor.decrypt(payload) : payload
  deserialize_state(json)
end

#save(state) ⇒ self

Serializes and upserts the state for the given thread_id.

Parameters:

  • state (Object)

    includes Phronomy::Graph::State

Returns:

  • (self)


43
44
45
46
47
48
49
50
# File 'lib/phronomy/state_store/active_record.rb', line 43

def save(state)
  json = serialize_state(state)
  payload = @encryptor ? @encryptor.encrypt(json) : json
  record = @model_class.find_or_initialize_by(thread_id: state.thread_id)
  record.state_json = payload
  record.save!
  self
end