Class: Octo::BackgroundTaskRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/octo/background_task_registry.rb

Constant Summary collapse

HANDLE_ALPHABET =
(('a'..'z').to_a + ('0'..'9').to_a).freeze
HANDLE_LENGTH =
9
TTL_UNWATCHED =
600
SWEEP_INTERVAL =
30

Class Method Summary collapse

Class Method Details

.cancel(handle_id, reason: nil) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/octo/background_task_registry.rb', line 106

def cancel(handle_id, reason: nil)
  task = nil
  handler = nil

  @mutex.synchronize do
    task = @tasks[handle_id]
    return false unless task
    return false if task[:status] == "completed" || task[:status] == "cancelled"

    task[:status] = "cancelled"
    task[:completed_at] = Time.now
    task[:cancel_reason] = reason || "Task was cancelled by user."
    handler = @callbacks.delete(handle_id)
  end

  begin
    task[:on_cancel]&.call(task)
  rescue => e
    Octo::Logger.error("background_task_cancel_hook_error",
      handle_id: handle_id,
      error: e
    )
  end

  if handler
    enriched = enrich_with_timing({
      cancelled: true,
      output: task[:cancel_reason],
      exit_code: nil,
      state: "cancelled"
    }, task)
    Thread.new do
      Thread.current.name = "bg-task-cancel-#{handle_id[0, 8]}"
      begin
        handler[:callback].call(enriched)
      rescue => e
        Octo::Logger.warn("background_task_callback_retry",
          handle_id: handle_id,
          agent_session: handler[:agent]&.session_id,
          error: e
        )
        begin
          sleep 0.5
          handler[:callback].call(enriched)
        rescue => e2
          Octo::Logger.error("background_task_callback_error",
            handle_id: handle_id,
            agent_session: handler[:agent]&.session_id,
            error: e2
          )
        end
      end
    end
  end

  true
end

.complete(handle_id, result) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/octo/background_task_registry.rb', line 164

def complete(handle_id, result)
  task = nil
  handler = nil

  @mutex.synchronize do
    task = @tasks[handle_id]
    return unless task
    return if task[:status] == "cancelled"

    task[:status] = "completed"
    task[:result] = result
    task[:completed_at] = Time.now

    handler = @callbacks.delete(handle_id)
  end

  return unless handler

  enriched = enrich_with_timing(result, task)

  Thread.new do
    Thread.current.name = "bg-task-notify-#{handle_id[0, 8]}"
    begin
      handler[:callback].call(enriched)
    rescue => e
      Octo::Logger.warn("background_task_callback_retry",
        handle_id: handle_id,
        agent_session: handler[:agent]&.session_id,
        error: e
      )
      begin
        sleep 0.5
        handler[:callback].call(enriched)
      rescue => e2
        Octo::Logger.error("background_task_callback_error",
          handle_id: handle_id,
          agent_session: handler[:agent]&.session_id,
          error: e2
        )
      end
    end
  end
end

.create_task(type:, metadata: {}, on_cancel: nil, dedup_key: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/octo/background_task_registry.rb', line 19

def create_task(type:, metadata: {}, on_cancel: nil, dedup_key: nil)
  @mutex.synchronize do
    if dedup_key
      existing = @tasks.values.find do |t|
        t[:status] == "running" &&
          t[:type] == type &&
          t[:metadata]&.[](:dedup_key) == dedup_key
      end
      if existing
        return { duplicate: true, handle_id: existing[:id], created_at: existing[:created_at] }
      end
    end

    handle_id = generate_unique_handle_id
    @tasks[handle_id] = {
      id: handle_id,
      type: type,
      status: "running",
      metadata: dedup_key ? .merge(dedup_key: dedup_key) : ,
      result: nil,
      created_at: Time.now,
      completed_at: nil,
      on_cancel: on_cancel,
      last_activity_at: [:watched] ? nil : Time.now
    }

    ensure_sweep_thread unless [:watched]

    handle_id
  end
end

.forget(handle_id) ⇒ Object



234
235
236
237
238
239
# File 'lib/octo/background_task_registry.rb', line 234

def forget(handle_id)
  @mutex.synchronize do
    @tasks.delete(handle_id)
    @callbacks.delete(handle_id)
  end
end

.get(handle_id) ⇒ Object



223
224
225
# File 'lib/octo/background_task_registry.rb', line 223

def get(handle_id)
  @mutex.synchronize { @tasks[handle_id]&.dup }
end

.list_running(agent_session_id: nil) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/octo/background_task_registry.rb', line 208

def list_running(agent_session_id: nil)
  @mutex.synchronize do
    tasks = @tasks.values.select { |t| t[:status] == "running" }
    tasks = tasks.select { |t| t[:metadata][:agent_session_id] == agent_session_id } if agent_session_id
    tasks.map do |t|
      {
        handle_id: t[:id],
        type: t[:type],
        command: t[:metadata][:command],
        started_at: t[:created_at]
      }
    end
  end
end

.prune_completed(max_age: 3600, agent_session_id: nil) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
# File 'lib/octo/background_task_registry.rb', line 241

def prune_completed(max_age: 3600, agent_session_id: nil)
  cutoff = Time.now - max_age
  @mutex.synchronize do
    @tasks.delete_if do |_id, task|
      next false unless task[:status] == "completed"
      next false unless task[:completed_at] && task[:completed_at] < cutoff
      next false if agent_session_id && task[:metadata][:agent_session_id] != agent_session_id
      true
    end
  end
end

.record_activity(handle_id) ⇒ Object



227
228
229
230
231
232
# File 'lib/octo/background_task_registry.rb', line 227

def record_activity(handle_id)
  @mutex.synchronize do
    task = @tasks[handle_id]
    task[:last_activity_at] = Time.now if task
  end
end

.register_callback(handle_id:, agent:, &block) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/octo/background_task_registry.rb', line 51

def register_callback(handle_id:, agent:, &block)
  fire_immediately = nil
  captured_task    = nil

  @mutex.synchronize do
    task = @tasks[handle_id]
    return false unless task

    if task[:status] == "completed" || task[:status] == "cancelled"
      fire_immediately = task[:result] || {
        cancelled: task[:status] == "cancelled",
        output: task[:cancel_reason] || (task[:status] == "cancelled" ? "Task was cancelled by user." : ""),
        exit_code: nil,
        state: task[:status]
      }
      captured_task = task
    else
      @callbacks[handle_id] = {
        agent: agent,
        callback: block,
        registered_at: Time.now
      }
    end
  end

  fire_immediately = enrich_with_timing(fire_immediately, captured_task) if fire_immediately

  if fire_immediately
    Thread.new do
      Thread.current.name = "bg-task-notify-late-#{handle_id[0, 8]}"
      begin
        block.call(fire_immediately)
      rescue => e
        Octo::Logger.warn("background_task_callback_retry",
          handle_id: handle_id,
          agent_session: agent&.session_id,
          error: e
        )
        begin
          sleep 0.5
          block.call(fire_immediately)
        rescue => e2
          Octo::Logger.error("background_task_callback_error",
            handle_id: handle_id,
            agent_session: agent&.session_id,
            error: e2
          )
        end
      end
    end
  end

  true
end

.reset!Object



253
254
255
256
257
258
259
# File 'lib/octo/background_task_registry.rb', line 253

def reset!
  @mutex.synchronize do
    @tasks.clear
    @callbacks.clear
    @sweep_running = false
  end
end