Class: Harnex::Stopper

Inherits:
Object
  • Object
show all
Defined in:
lib/harnex/commands/stop.rb

Defined Under Namespace

Classes: TimeoutError

Constant Summary collapse

DEFAULT_TIMEOUT =
5.0
MIN_HTTP_TIMEOUT =
0.1

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Stopper

Returns a new instance of Stopper.



29
30
31
32
33
34
35
36
37
38
# File 'lib/harnex/commands/stop.rb', line 29

def initialize(argv)
  @argv = argv.dup
  @options = {
    id: nil,
    repo_path: Dir.pwd,
    cli: nil,
    timeout: DEFAULT_TIMEOUT,
    help: false
  }
end

Class Method Details

.usage(program_name = "harnex stop") ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/harnex/commands/stop.rb', line 13

def self.usage(program_name = "harnex stop")
  <<~TEXT
    Usage: #{program_name} [options]

    Options:
      --id ID      Session ID to stop (required)
      --repo PATH  Resolve the session using PATH's repo root (default: current repo)
      --cli CLI    Filter by CLI type
      --timeout S  How long to retry transient API failures (default: #{DEFAULT_TIMEOUT})
      -h, --help   Show this help

    Sends the adapter stop sequence to the session.
    Use `harnex wait --id ID` afterward to block until the session finishes.
  TEXT
end

Instance Method Details

#runObject



40
41
42
43
44
45
46
47
48
49
50
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
# File 'lib/harnex/commands/stop.rb', line 40

def run
  parser.parse!(@argv)
  if @options[:help]
    puts self.class.usage
    return 0
  end

  raise "--id is required for harnex stop" unless @options[:id]

  repo_root = Harnex.resolve_repo_root(@options[:repo_path])
  registry = Harnex.read_registry(repo_root, @options[:id], cli: @options[:cli])
  unless registry
    warn("harnex stop: no session found with id #{@options[:id].inspect}")
    return 1
  end

  uri = URI("http://#{registry.fetch('host')}:#{registry.fetch('port')}/stop")
  request = Net::HTTP::Post.new(uri)
  request["Authorization"] = "Bearer #{registry['token']}" if registry["token"]

  deadline = monotonic_now + @options[:timeout]
  response = with_http_retry(deadline: deadline) do
    Net::HTTP.start(
      uri.host,
      uri.port,
      open_timeout: http_timeout(deadline, cap: 1.0),
      read_timeout: http_timeout(deadline, cap: 2.0)
    ) { |http| http.request(request) }
  end

  parsed = parse_json_body(response.body)
  puts JSON.generate(parsed)
  response.is_a?(Net::HTTPSuccess) && parsed["error"].nil? ? 0 : 1
rescue TimeoutError => e
  puts JSON.generate(ok: false, id: @options[:id], status: "timeout", error: e.message)
  124
end