Class: DecisionAgent::Versioning::FileStorageAdapter

Inherits:
Adapter
  • Object
show all
Includes:
StatusValidator
Defined in:
lib/decision_agent/versioning/file_storage_adapter.rb

Overview

File-based version storage adapter for non-Rails applications Stores versions as JSON files in a directory structure

Constant Summary

Constants included from StatusValidator

StatusValidator::VALID_STATUSES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from StatusValidator

#validate_status!

Methods inherited from Adapter

#compare_versions

Constructor Details

#initialize(storage_path: "./versions") ⇒ FileStorageAdapter

Initialize with a storage directory

Parameters:

  • storage_path (String) (defaults to: "./versions")

    Path to store version files (default: ./versions)



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 30

def initialize(storage_path: "./versions")
  @storage_path = storage_path
  # Per-rule mutex for better concurrency - allows different rules to be processed in parallel
  @rule_mutexes = Hash.new { |h, k| h[k] = Mutex.new }
  @rule_mutexes_lock = Mutex.new # Protects the hash itself
  # Index cache: version_id => rule_id mapping for O(1) lookups
  @version_index = {}
  @version_index_lock = Mutex.new
  FileUtils.mkdir_p(@storage_path)
  load_version_index
end

Instance Attribute Details

#storage_pathObject (readonly)

Returns the value of attribute storage_path.



26
27
28
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 26

def storage_path
  @storage_path
end

Instance Method Details

#activate_version(version_id:) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 137

def activate_version(version_id:)
  # Use index to find rule_id quickly - O(1) instead of O(n)
  rule_id = get_rule_id_from_index(version_id)
  raise DecisionAgent::NotFoundError, "Version not found: #{version_id}" unless rule_id

  # Now lock on the specific rule
  with_rule_lock(rule_id) do
    # Read only this rule's versions
    versions = list_versions_unsafe(rule_id: rule_id)
    version = versions.find { |v| v[:id] == version_id }
    raise DecisionAgent::NotFoundError, "Version not found: #{version_id}" unless version

    # Deactivate all other versions for this rule
    versions.each do |v|
      update_version_status_unsafe(v[:id], "archived", rule_id) if v[:id] != version_id && v[:status] == "active"
    end

    # Activate this version
    version[:status] = "active"
    write_version_file(version)

    version
  end
end

#create_tag(model_id:, version_id:, name:) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 162

def create_tag(model_id:, version_id:, name:)
  raise DecisionAgent::ValidationError, "Tag name cannot be blank" if name.nil? || name.to_s.strip.empty?

  # Validate the version exists
  version = get_version(version_id: version_id)
  raise DecisionAgent::NotFoundError, "Version not found: #{version_id}" unless version

  with_rule_lock(model_id) do
    tags = read_tags_unsafe(model_id)
    tag = { name: name, version_id: version_id, created_at: Time.now.utc.iso8601 }
    tags[name] = tag
    write_tags_unsafe(model_id, tags)
    tag
  end
end

#create_version(rule_id:, content:, metadata: {}) ⇒ Object



42
43
44
45
46
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 42

def create_version(rule_id:, content:, metadata: {})
  with_rule_lock(rule_id) do
    create_version_unsafe(rule_id: rule_id, content: content, metadata: )
  end
end

#delete_tag(model_id:, name:) ⇒ Object



190
191
192
193
194
195
196
197
198
199
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 190

def delete_tag(model_id:, name:)
  with_rule_lock(model_id) do
    tags = read_tags_unsafe(model_id)
    return false unless tags.key?(name)

    tags.delete(name)
    write_tags_unsafe(model_id, tags)
    true
  end
end

#delete_version(version_id:) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 201

def delete_version(version_id:)
  # Use index to find rule_id quickly - O(1) instead of O(n)
  begin
    rule_id = get_rule_id_from_index(version_id)
  rescue StandardError => e
    # If index lookup fails, version doesn't exist
    warn "[DecisionAgent] Version index lookup failed for '#{version_id}': #{e.message}"
    raise DecisionAgent::NotFoundError, "Version not found: #{version_id}"
  end

  # Validate rule_id - must be present and non-empty
  raise DecisionAgent::NotFoundError, "Version not found: #{version_id}" unless rule_id && !rule_id.to_s.strip.empty?

  # Now lock on the specific rule
  begin
    with_rule_lock(rule_id) do
      # Read only this rule's versions
      versions = list_versions_unsafe(rule_id: rule_id)
      version = versions.find { |v| v[:id] == version_id || v[:id].to_s == version_id.to_s }

      # If version not in list, check if file exists - might have been manually deleted
      unless version
        rule_dir = File.join(@storage_path, sanitize_filename(rule_id))
        # Try to find the file by checking all version files
        file_found = false
        begin
          Dir.glob(File.join(rule_dir, "*.json")).each do |filepath|
            file_data = JSON.parse(File.read(filepath))
            if file_data["id"] == version_id || file_data[:id] == version_id ||
               file_data["id"].to_s == version_id.to_s || file_data[:id].to_s == version_id.to_s
              # File exists but not in versions list - remove from index and return false
              file_found = true
              remove_from_index(version_id)
              return false
            end
          rescue Errno::ENOENT, JSON::ParserError
            # File was deleted or corrupted, continue searching
            next
          end
        rescue Errno::ENOENT
          # Directory doesn't exist, version not found
        end
        # Version not found in list and file doesn't exist - clean up index and return false
        remove_from_index(version_id)
        return false
      end

      # Prevent deletion of active versions
      if version[:status] == "active"
        raise DecisionAgent::ValidationError, "Cannot delete active version. Please activate another version first."
      end

      # Delete the file
      rule_dir = File.join(@storage_path, sanitize_filename(rule_id))
      filename = "#{version[:version_number]}.json"
      filepath = File.join(rule_dir, filename)

      if File.exist?(filepath)
        File.delete(filepath)
        # Remove from index
        remove_from_index(version_id)
        true
      else
        # File already deleted - clean up index and return false
        remove_from_index(version_id)
        false
      end
    end
  rescue DecisionAgent::ValidationError, DecisionAgent::NotFoundError
    # Re-raise expected errors
    raise
  rescue StandardError => e
    # If any unexpected error occurs during the lock operation, treat as version not found
    # This prevents 500 errors from propagating when version doesn't exist or is in an invalid state
    # This handles ThreadError (deadlocks, recursive locks), SystemCallError (file system issues), etc.
    # This is safe because if the version existed and was valid, we would have found it above
    warn "[DecisionAgent] Version delete lock operation failed for '#{version_id}': #{e.message}"
    begin
      remove_from_index(version_id)
    rescue StandardError => cleanup_error
      warn "[DecisionAgent] Failed to clean up index for '#{version_id}': #{cleanup_error.message}"
    end
    raise DecisionAgent::NotFoundError, "Version not found: #{version_id}"
  end
end

#get_active_version(rule_id:) ⇒ Object



130
131
132
133
134
135
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 130

def get_active_version(rule_id:)
  with_rule_lock(rule_id) do
    versions = list_versions_unsafe(rule_id: rule_id)
    versions.find { |v| v[:status] == "active" }
  end
end

#get_tag(model_id:, name:) ⇒ Object



178
179
180
181
182
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 178

def get_tag(model_id:, name:)
  with_rule_lock(model_id) do
    read_tags_unsafe(model_id)[name]
  end
end

#get_version(version_id:) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 98

def get_version(version_id:)
  # Use index to find rule_id quickly - O(1) instead of O(n)
  begin
    rule_id = get_rule_id_from_index(version_id)
  rescue StandardError => e
    # If index lookup fails, version doesn't exist
    warn "[DecisionAgent] Version index lookup failed for '#{version_id}': #{e.message}"
    return nil
  end
  return nil unless rule_id

  # Now lock on the specific rule
  begin
    with_rule_lock(rule_id) do
      # Read only this rule's versions
      versions = list_versions_unsafe(rule_id: rule_id)
      versions.find { |v| v[:id] == version_id }
    end
  rescue StandardError => e
    # If any error occurs during lookup, treat as version not found
    warn "[DecisionAgent] Version lookup failed for '#{version_id}': #{e.message}"
    nil
  end
end

#get_version_by_number(rule_id:, version_number:) ⇒ Object



123
124
125
126
127
128
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 123

def get_version_by_number(rule_id:, version_number:)
  with_rule_lock(rule_id) do
    versions = list_versions_unsafe(rule_id: rule_id)
    versions.find { |v| v[:version_number] == version_number }
  end
end

#list_all_versions(limit: nil) ⇒ Object



91
92
93
94
95
96
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 91

def list_all_versions(limit: nil)
  @version_index_lock.synchronize do
    versions = all_versions_unsafe
    limit ? versions.take(limit) : versions
  end
end

#list_tags(model_id:) ⇒ Object



184
185
186
187
188
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 184

def list_tags(model_id:)
  with_rule_lock(model_id) do
    read_tags_unsafe(model_id).values.sort_by { |t| t[:name] }
  end
end

#list_versions(rule_id:, limit: nil) ⇒ Object



85
86
87
88
89
# File 'lib/decision_agent/versioning/file_storage_adapter.rb', line 85

def list_versions(rule_id:, limit: nil)
  with_rule_lock(rule_id) do
    list_versions_unsafe(rule_id: rule_id, limit: limit)
  end
end