Module: VSM::Lens

Defined in:
lib/vsm/lens.rb,
lib/vsm/lens/tui.rb,
lib/vsm/lens/stats.rb,
lib/vsm/lens/server.rb,
lib/vsm/lens/event_hub.rb

Defined Under Namespace

Modules: TUI Classes: EventHub, SSEBody, Server, Stats

Class Method Summary collapse

Class Method Details

.attach!(capsule, host: "127.0.0.1", port: 9292, token: nil) ⇒ Object

Starts a tiny Rack server (Puma or WEBrick) and streams events via SSE. Returns the EventHub so other lenses (e.g., TUI) can also subscribe.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/vsm/lens.rb', line 12

def self.attach!(capsule, host: "127.0.0.1", port: 9292, token: nil)
  hub = EventHub.new
  capsule.bus.subscribe { |msg| hub.publish(msg) }

  require_relative "lens/stats"
  stats  = Stats.new(hub: hub, capsule: capsule)
  server = Server.new(hub: hub, token: token, stats: stats)


  Thread.new do
    app = server.rack_app

    # Prefer Puma if present:
    if try_run_puma(app, host, port)
      # ok
    elsif try_run_webrick(app, host, port)
      # ok
    else
      warn "        vsm-lens: no Rack handler found. Install one of:\n          - `bundle add puma`\n          - or `bundle add webrick`\n        Then re-run with VSM_LENS=1.\n      MSG\n    end\n  end\n\n  hub\nend\n"

.try_run_puma(app, host, port) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/vsm/lens.rb', line 42

def self.try_run_puma(app, host, port)
  begin
    require "rack/handler/puma"
  rescue LoadError
    return false
  end
  Thread.new do
    Rack::Handler::Puma.run(app, Host: host, Port: port, Silent: true)
  end
  true
rescue => e
  warn "vsm-lens: Puma failed to start: #{e.class}: #{e.message}"
  false
end

.try_run_webrick(app, host, port) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/vsm/lens.rb', line 57

def self.try_run_webrick(app, host, port)
  begin
    require "webrick"                 # provide the server
    require "rack/handler/webrick"    # rack adapter (Rack 3 loads this if webrick gem is present)
  rescue LoadError
    return false
  end
  Thread.new do
    Rack::Handler::WEBrick.run(
      app,
      Host: host, Port: port,
      AccessLog: [],
      Logger: WEBrick::Log.new($stderr, WEBrick::Log::WARN)
    )
  end
  true
rescue => e
  warn "vsm-lens: WEBrick failed to start: #{e.class}: #{e.message}"
  false
end