Class: RailsMcpCodeSearch::BackgroundWorker

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_mcp_code_search/background_worker.rb

Constant Summary collapse

REINDEX_COOLDOWN =
60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(indexer:, logger: nil) ⇒ BackgroundWorker

Returns a new instance of BackgroundWorker.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/rails_mcp_code_search/background_worker.rb', line 7

def initialize(indexer:, logger: nil)
  @indexer = indexer
  @logger = logger
  @queue = Queue.new
  @mutex = Mutex.new
  @state = :idle
  @progress = 0.0
  @errors = []
  @stop_requested = false
  @last_full_reindex_at = nil
  @hit_count_buffer = []
  @search_count = 0
  @reindex_count = 0
end

Instance Attribute Details

#errors ⇒ Object (readonly)

Returns the value of attribute errors.



5
6
7
# File 'lib/rails_mcp_code_search/background_worker.rb', line 5

def errors
  @errors
end

#progress ⇒ Object (readonly)

Returns the value of attribute progress.



5
6
7
# File 'lib/rails_mcp_code_search/background_worker.rb', line 5

def progress
  @progress
end

#state ⇒ Object (readonly)

Returns the value of attribute state.



5
6
7
# File 'lib/rails_mcp_code_search/background_worker.rb', line 5

def state
  @state
end

Instance Method Details

#enqueue(work_type, payload: nil) ⇒ Object



34
35
36
# File 'lib/rails_mcp_code_search/background_worker.rb', line 34

def enqueue(work_type, payload: nil)
  @queue.push({ type: work_type, payload: })
end

#enqueue_hit_counts(chunk_ids) ⇒ Object



38
39
40
# File 'lib/rails_mcp_code_search/background_worker.rb', line 38

def enqueue_hit_counts(chunk_ids)
  @mutex.synchronize { @hit_count_buffer.concat(chunk_ids) }
end

#increment_reindex_count ⇒ Object



46
47
48
# File 'lib/rails_mcp_code_search/background_worker.rb', line 46

def increment_reindex_count
  @mutex.synchronize { @reindex_count += 1 }
end

#increment_search_count ⇒ Object



42
43
44
# File 'lib/rails_mcp_code_search/background_worker.rb', line 42

def increment_search_count
  @mutex.synchronize { @search_count += 1 }
end

#start ⇒ Object



22
23
24
25
26
# File 'lib/rails_mcp_code_search/background_worker.rb', line 22

def start
  @thread = Thread.new { run }
  enqueue(:full_index)
  self
end

#stop ⇒ Object



28
29
30
31
32
# File 'lib/rails_mcp_code_search/background_worker.rb', line 28

def stop
  @stop_requested = true
  @queue.push(:shutdown)
  @thread&.join(5)
end

#wait_for_reindex(timeout: 0.2) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/rails_mcp_code_search/background_worker.rb', line 50

def wait_for_reindex(timeout: 0.2)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
  loop do
    return true if @mutex.synchronize { @state } == :idle
    remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
    return false if remaining <= 0
    sleep([ remaining, 0.05 ].min)
  end
end