Class: TrakFlow::IdGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/trak_flow/id_generator.rb

Overview

Generates hash-based IDs to prevent merge conflicts when multiple agents or branches work simultaneously. The ID format is “tf-XXXX” where XXXX is a truncated hash derived from a UUID.

Constant Summary collapse

DEFAULT_PREFIX =
"tf"
MIN_HASH_LENGTH =
4
MAX_HASH_LENGTH =
8

Class Method Summary collapse

Class Method Details

.content_hash(data) ⇒ Object



39
40
41
# File 'lib/trak_flow/id_generator.rb', line 39

def content_hash(data)
  Digest::SHA256.hexdigest(Oj.dump(data, mode: :compat))[0, 16]
end

.generate(prefix: DEFAULT_PREFIX, existing_ids: [], min_length: MIN_HASH_LENGTH) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/trak_flow/id_generator.rb', line 13

def generate(prefix: DEFAULT_PREFIX, existing_ids: [], min_length: MIN_HASH_LENGTH)
  loop do
    uuid = SecureRandom.uuid
    hash = Digest::SHA256.hexdigest(uuid)[0, max_length_needed(existing_ids, min_length)]
    id = "#{prefix}-#{hash}"

    return id unless existing_ids.include?(id)
  end
end

.generate_child_id(parent_id, child_index) ⇒ Object



23
24
25
# File 'lib/trak_flow/id_generator.rb', line 23

def generate_child_id(parent_id, child_index)
  "#{parent_id}.#{child_index}"
end

.parent_id(child_id) ⇒ Object



27
28
29
30
31
# File 'lib/trak_flow/id_generator.rb', line 27

def parent_id(child_id)
  return nil unless child_id.include?(".")

  child_id.split(".")[0..-2].join(".")
end

.valid?(id) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/trak_flow/id_generator.rb', line 33

def valid?(id)
  return false if id.nil? || id.empty?

  id.match?(/^[a-z]+-[a-f0-9]{#{MIN_HASH_LENGTH},#{MAX_HASH_LENGTH}}(\.\d+)*$/i)
end