Class: DecisionAgent::Monitoring::DashboardServer
- Inherits:
-
Object
- Object
- DecisionAgent::Monitoring::DashboardServer
- Defined in:
- lib/decision_agent/monitoring/dashboard_server.rb
Overview
Real-time monitoring dashboard server Framework-agnostic: Pure Rack application compatible with any Rack server
Constant Summary collapse
- PUBLIC_FOLDER =
File.("dashboard/public", __dir__)
- VIEWS_FOLDER =
File.("dashboard/views", __dir__)
Class Attribute Summary collapse
-
.alert_manager ⇒ Object
Returns the value of attribute alert_manager.
-
.bind ⇒ Object
Returns the value of attribute bind.
-
.metrics_collector ⇒ Object
Returns the value of attribute metrics_collector.
-
.port ⇒ Object
Returns the value of attribute port.
-
.prometheus_exporter ⇒ Object
Returns the value of attribute prometheus_exporter.
-
.public_folder ⇒ Object
Returns the value of attribute public_folder.
-
.views_folder ⇒ Object
Returns the value of attribute views_folder.
-
.websocket_clients ⇒ Object
readonly
Returns the value of attribute websocket_clients.
Class Method Summary collapse
- .add_websocket_client(ws) ⇒ Object
- .broadcast_to_clients(message) ⇒ Object
-
.call(env) ⇒ Object
Rack call method - entry point for Rack requests.
- .configure_monitoring(metrics_collector:, prometheus_exporter:, alert_manager:) ⇒ Object
- .define_routes(router) ⇒ Object
- .handle_websocket_message(ws, data) ⇒ Object
- .parse_alert_condition(condition_data, condition_type) ⇒ Object
- .remove_websocket_client(ws) ⇒ Object
- .router ⇒ Object
- .setup_real_time_updates ⇒ Object
-
.start!(metrics_collector:, prometheus_exporter:, alert_manager:, port: 4568, host: "0.0.0.0") ⇒ Object
Class method to start the server Framework-agnostic: uses Rack::Server which supports any Rack-compatible server.
Instance Method Summary collapse
Class Attribute Details
.alert_manager ⇒ Object
Returns the value of attribute alert_manager.
27 28 29 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 27 def alert_manager @alert_manager end |
.bind ⇒ Object
Returns the value of attribute bind.
27 28 29 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 27 def bind @bind end |
.metrics_collector ⇒ Object
Returns the value of attribute metrics_collector.
27 28 29 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 27 def metrics_collector @metrics_collector end |
.port ⇒ Object
Returns the value of attribute port.
27 28 29 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 27 def port @port end |
.prometheus_exporter ⇒ Object
Returns the value of attribute prometheus_exporter.
27 28 29 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 27 def prometheus_exporter @prometheus_exporter end |
.public_folder ⇒ Object
Returns the value of attribute public_folder.
27 28 29 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 27 def public_folder @public_folder end |
.views_folder ⇒ Object
Returns the value of attribute views_folder.
27 28 29 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 27 def views_folder @views_folder end |
.websocket_clients ⇒ Object (readonly)
Returns the value of attribute websocket_clients.
28 29 30 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 28 def websocket_clients @websocket_clients end |
Class Method Details
.add_websocket_client(ws) ⇒ Object
377 378 379 380 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 377 def add_websocket_client(ws) @websocket_clients ||= [] @websocket_clients << ws end |
.broadcast_to_clients(message) ⇒ Object
365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 365 def broadcast_to_clients() return unless WEBSOCKET_AVAILABLE return if @websocket_clients.empty? # Skip if no clients connected = .to_json @websocket_clients.each do |client| client.send() if client.ready_state == Faye::WebSocket::API::OPEN rescue StandardError => e warn "WebSocket send failed: #{e.}" end end |
.call(env) ⇒ Object
Rack call method - entry point for Rack requests
39 40 41 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 39 def call(env) new.call(env) end |
.configure_monitoring(metrics_collector:, prometheus_exporter:, alert_manager:) ⇒ Object
335 336 337 338 339 340 341 342 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 335 def configure_monitoring(metrics_collector:, prometheus_exporter:, alert_manager:) @metrics_collector = metrics_collector @prometheus_exporter = prometheus_exporter @alert_manager = alert_manager @websocket_clients = [] setup_real_time_updates end |
.define_routes(router) ⇒ Object
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 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 105 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 163 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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 43 def define_routes(router) # Enable CORS router.before do |ctx| ctx.headers["Access-Control-Allow-Origin"] = "*" ctx.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS" ctx.headers["Access-Control-Allow-Headers"] = "Content-Type" end # OPTIONS handler for CORS preflight router. "*" do |ctx| ctx.status(200) ctx.body("") end # Class-level configuration class << self attr_accessor :metrics_collector, :prometheus_exporter, :alert_manager attr_reader :websocket_clients def configure_monitoring(metrics_collector:, prometheus_exporter:, alert_manager:) @metrics_collector = metrics_collector @prometheus_exporter = prometheus_exporter @alert_manager = alert_manager @websocket_clients = [] setup_real_time_updates end def setup_real_time_updates # Register observer for real-time metric updates @metrics_collector.add_observer do |event_type, metric| broadcast_to_clients({ type: "metric_update", event: event_type, data: metric, timestamp: Time.now.utc.iso8601 }) end # Register alert handler @alert_manager.add_handler do |alert| broadcast_to_clients({ type: "alert", data: alert, timestamp: Time.now.utc.iso8601 }) end end def broadcast_to_clients() return unless WEBSOCKET_AVAILABLE return if @websocket_clients.empty? # Skip if no clients connected = .to_json @websocket_clients.each do |client| client.send() if client.ready_state == Faye::WebSocket::API::OPEN rescue StandardError => e warn "WebSocket send failed: #{e.}" end end def add_websocket_client(ws) @websocket_clients << ws end def remove_websocket_client(ws) @websocket_clients.delete(ws) end end # Main dashboard page router.get "/" do |ctx| index_file = File.join(DashboardServer.public_folder || PUBLIC_FOLDER, "index.html") if File.exist?(index_file) ctx.send_file(index_file) else ctx.status(404) ctx.body("Dashboard page not found") end end # WebSocket endpoint for real-time updates router.get "/ws" do |ctx| unless WEBSOCKET_AVAILABLE ctx.status(503) ctx.content_type "application/json" ctx.json({ error: "WebSocket support not available. Install faye-websocket gem." }) next end if Faye::WebSocket.websocket?(ctx.env) ws = Faye::WebSocket.new(ctx.env) ws.on :open do |_event| DashboardServer.add_websocket_client(ws) # Send initial state ws.send({ type: "connected", message: "Connected to DecisionAgent monitoring", timestamp: Time.now.utc.iso8601 }.to_json) end ws.on :message do |event| # Handle client messages DashboardServer.(ws, event.data) end ws.on :close do |_event| DashboardServer.remove_websocket_client(ws) end ws.rack_response else ctx.status(426) ctx.content_type "application/json" ctx.json({ error: "WebSocket connection required" }) end end # API: Get current statistics router.get "/api/stats" do |ctx| ctx.content_type "application/json" time_range = (ctx.params[:time_range] || ctx.params["time_range"])&.to_i stats = DashboardServer.metrics_collector.statistics(time_range: time_range) ctx.json(stats) end # API: Get time series data router.get "/api/timeseries/:metric_type" do |ctx| ctx.content_type "application/json" metric_type = (ctx.params[:metric_type] || ctx.params["metric_type"]).to_sym bucket_size = ((ctx.params[:bucket_size] || ctx.params["bucket_size"]) || 60).to_i time_range = ((ctx.params[:time_range] || ctx.params["time_range"]) || 3600).to_i data = DashboardServer.metrics_collector.time_series( metric_type: metric_type, bucket_size: bucket_size, time_range: time_range ) ctx.json(data) end # API: Prometheus metrics endpoint router.get "/metrics" do |ctx| ctx.content_type DashboardServer.prometheus_exporter.class::CONTENT_TYPE ctx.body(DashboardServer.prometheus_exporter.export) end # API: Get Prometheus metrics in JSON format router.get "/api/metrics" do |ctx| ctx.content_type "application/json" ctx.json(DashboardServer.prometheus_exporter.metrics_hash) end # API: Register custom KPI router.post "/api/kpi" do |ctx| ctx.content_type "application/json" begin request_body = Web::RackRequestHelpers.read_body(ctx.env) data = JSON.parse(request_body, symbolize_names: true) DashboardServer.prometheus_exporter.register_kpi( name: data[:name], value: data[:value], labels: data[:labels] || {}, help: data[:help] ) ctx.json({ success: true, message: "KPI registered" }) rescue StandardError => e ctx.status(400) ctx.json({ error: e. }) end end # API: Get active alerts router.get "/api/alerts" do |ctx| ctx.content_type "application/json" ctx.json(DashboardServer.alert_manager.active_alerts) end # API: Get all alerts router.get "/api/alerts/all" do |ctx| ctx.content_type "application/json" limit = ((ctx.params[:limit] || ctx.params["limit"]) || 100).to_i ctx.json(DashboardServer.alert_manager.all_alerts(limit: limit)) end # API: Create alert rule router.post "/api/alerts/rules" do |ctx| ctx.content_type "application/json" begin request_body = Web::RackRequestHelpers.read_body(ctx.env) data = JSON.parse(request_body, symbolize_names: true) # Parse condition condition = DashboardServer.parse_alert_condition(data[:condition], data[:condition_type]) rule = DashboardServer.alert_manager.add_rule( name: data[:name], condition: condition, severity: (data[:severity] || :warning).to_sym, threshold: data[:threshold], message: data[:message], cooldown: data[:cooldown] || 300 ) ctx.status(201) ctx.json(rule) rescue StandardError => e ctx.status(400) ctx.json({ error: e. }) end end # API: Toggle alert rule router.put "/api/alerts/rules/:rule_id/toggle" do |ctx| ctx.content_type "application/json" begin request_body = Web::RackRequestHelpers.read_body(ctx.env) data = JSON.parse(request_body, symbolize_names: true) enabled = data[:enabled] || false rule_id = ctx.params[:rule_id] || ctx.params["rule_id"] DashboardServer.alert_manager.toggle_rule(rule_id, enabled) ctx.json({ success: true, message: "Rule #{enabled ? 'enabled' : 'disabled'}" }) rescue StandardError => e ctx.status(400) ctx.json({ error: e. }) end end # API: Acknowledge alert router.post "/api/alerts/:alert_id/acknowledge" do |ctx| ctx.content_type "application/json" begin request_body = Web::RackRequestHelpers.read_body(ctx.env) data = JSON.parse(request_body, symbolize_names: true) acknowledged_by = data[:acknowledged_by] || "user" alert_id = ctx.params[:alert_id] || ctx.params["alert_id"] DashboardServer.alert_manager.acknowledge_alert(alert_id, acknowledged_by: acknowledged_by) ctx.json({ success: true, message: "Alert acknowledged" }) rescue StandardError => e ctx.status(400) ctx.json({ error: e. }) end end # API: Resolve alert router.post "/api/alerts/:alert_id/resolve" do |ctx| ctx.content_type "application/json" begin request_body = Web::RackRequestHelpers.read_body(ctx.env) data = JSON.parse(request_body, symbolize_names: true) resolved_by = data[:resolved_by] || "user" alert_id = ctx.params[:alert_id] || ctx.params["alert_id"] DashboardServer.alert_manager.resolve_alert(alert_id, resolved_by: resolved_by) ctx.json({ success: true, message: "Alert resolved" }) rescue StandardError => e ctx.status(400) ctx.json({ error: e. }) end end # Health check router.get "/health" do |ctx| ctx.content_type "application/json" ctx.json({ status: "ok", version: DecisionAgent::VERSION, websocket_clients: DashboardServer.websocket_clients.size, metrics_count: DashboardServer.metrics_collector.metrics_count }) end end |
.handle_websocket_message(ws, data) ⇒ Object
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 387 def (ws, data) = JSON.parse(data, symbolize_names: true) case [:action] when "subscribe" # Send current stats stats = metrics_collector.statistics ws.send({ type: "stats", data: stats }.to_json) when "get_alerts" alerts = alert_manager.active_alerts ws.send({ type: "alerts", data: alerts }.to_json) end rescue StandardError => e ws.send({ type: "error", message: e. }.to_json) end |
.parse_alert_condition(condition_data, condition_type) ⇒ Object
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 403 def parse_alert_condition(condition_data, condition_type) case condition_type when "high_error_rate" AlertManager.high_error_rate(threshold: condition_data[:threshold] || 0.1) when "low_confidence" AlertManager.low_confidence(threshold: condition_data[:threshold] || 0.5) when "high_latency" AlertManager.high_latency(threshold_ms: condition_data[:threshold_ms] || 1000) when "error_spike" AlertManager.error_spike(threshold: condition_data[:threshold] || 10) when "custom" condition_data else raise "Unknown condition type: #{condition_type}" end end |
.remove_websocket_client(ws) ⇒ Object
382 383 384 385 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 382 def remove_websocket_client(ws) @websocket_clients ||= [] @websocket_clients.delete(ws) end |
.router ⇒ Object
30 31 32 33 34 35 36 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 30 def router @router ||= begin router = Web::RackHelpers::Router.new define_routes(router) router end end |
.setup_real_time_updates ⇒ Object
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 344 def setup_real_time_updates # Register observer for real-time metric updates @metrics_collector.add_observer do |event_type, metric| broadcast_to_clients({ type: "metric_update", event: event_type, data: metric, timestamp: Time.now.utc.iso8601 }) end # Register alert handler @alert_manager.add_handler do |alert| broadcast_to_clients({ type: "alert", data: alert, timestamp: Time.now.utc.iso8601 }) end end |
.start!(metrics_collector:, prometheus_exporter:, alert_manager:, port: 4568, host: "0.0.0.0") ⇒ Object
Class method to start the server Framework-agnostic: uses Rack::Server which supports any Rack-compatible server
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 422 def start!(metrics_collector:, prometheus_exporter:, alert_manager:, port: 4568, host: "0.0.0.0") configure_monitoring( metrics_collector: metrics_collector, prometheus_exporter: prometheus_exporter, alert_manager: alert_manager ) @port = port @bind = host @public_folder = PUBLIC_FOLDER @views_folder = VIEWS_FOLDER puts "🎯 DecisionAgent Monitoring Dashboard starting..." puts "📍 Server: http://#{host == '0.0.0.0' ? 'localhost' : host}:#{port}" puts "⚡️ Press Ctrl+C to stop" puts "" # Use Rack::Server which automatically selects the best available handler # Supports: Puma, WEBrick, Thin, Unicorn, etc. (any Rack-compatible server) Rack::Server.start( app: self, Port: port, Host: host, server: ENV.fetch("RACK_HANDLER", nil), # Allows override via ENV environment: ENV.fetch("RACK_ENV", "development") ) end |
Instance Method Details
#call(env) ⇒ Object
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 |
# File 'lib/decision_agent/monitoring/dashboard_server.rb', line 451 def call(env) route_match = DashboardServer.router.match(env) return [404, { "Content-Type" => "text/plain" }, ["Not Found"]] unless route_match # Create request context with route params ctx = Web::RackRequestHelpers::RequestContext.new(env, route_match[:params] || {}) # Run before filters route_match[:before_filters].each do |filter| filter.call(ctx) return ctx.to_rack_response if ctx.halted? end # Execute route handler begin route_match[:handler].call(ctx) ctx.to_rack_response rescue StandardError => e [500, { "Content-Type" => "application/json" }, [{ error: e. }.to_json]] end end |