pg_reports 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 72b693934d81353991eadfbfaf0a17a9f6c73e33048270435cb6ad917d3bee1c
4
- data.tar.gz: 56159c5cd3315d96cff002af0ab3328c3ce4345f463bbf22c3ddfca3f3180ae0
3
+ metadata.gz: 10a498c16d57884f8f551449454e670e1f62e8cfb73a7259198ed6634672c9c3
4
+ data.tar.gz: 4c80eeebe20506f1210a1a8c543d1f903853f7a21d4e2714f8da614326d417ac
5
5
  SHA512:
6
- metadata.gz: 9d71b455e90c577a21a0793899d4d6cfddd6afc73c2bad4d5f681e4c45fcf23380a0b2e76159d4b5d42ee198b75c64ebdb3b8048761f3af141c004a48676f159
7
- data.tar.gz: a96c4dd926bb28c041283d3a3c025111545fa46995290791785ab43d6c976f4b39d3f009929b829376ef4b2dbcb8704d9966e349183210a5f6619d01fd681fd8
6
+ metadata.gz: d91cc17427845a2287bd5cda856536c27f16c1d32155417688aa0c7883d3e0b0c7867ca5d2e4f884457034f3c868d21795d64f6695ab895247b2e3eb83920ab8
7
+ data.tar.gz: fd07c5ed63a60a4b477bdbb91cdb07a7288c04ac4029c24a4dceaf5fd182168bfdf878f7b6a313b9aa43a23cb4b66340d996b0b21179e96b3bbca368a6060d34
data/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.3.0] - 2026-01-28
9
+
10
+ ### Added
11
+
12
+ - **Live Monitoring Panel** on the main dashboard with real-time metrics:
13
+ - Connections (active/idle/total, % of max_connections)
14
+ - TPS (transactions per second, calculated from pg_stat_database)
15
+ - Cache Hit Ratio (heap blocks from cache)
16
+ - Long Running Queries (count of queries > 60s)
17
+ - Blocked Processes (waiting for locks)
18
+ - SVG sparkline charts showing 2.5 minutes of history (30 data points)
19
+ - Color-coded status indicators (green/yellow/red) based on thresholds
20
+ - Pause/resume button for live monitoring (state saved to localStorage)
21
+ - Auto-refresh every 5 seconds
22
+ - Responsive grid layout for metric cards
23
+ - New `/live_metrics` API endpoint
24
+
25
+ ### Changed
26
+
27
+ - Dashboard now shows live monitoring panel above the categories grid
28
+
8
29
  ## [0.2.3] - 2026-01-28
9
30
 
10
31
  ### Added
@@ -23,6 +23,19 @@ module PgReports
23
23
  render json: {success: false, error: e.message}, status: :unprocessable_entity
24
24
  end
25
25
 
26
+ def live_metrics
27
+ threshold = params[:long_query_threshold]&.to_i || 60
28
+ data = Modules::System.live_metrics(long_query_threshold: threshold)
29
+
30
+ render json: {
31
+ success: true,
32
+ metrics: data,
33
+ timestamp: Time.current.to_i
34
+ }
35
+ rescue => e
36
+ render json: {success: false, error: e.message}, status: :unprocessable_entity
37
+ end
38
+
26
39
  def show
27
40
  @category = params[:category].to_sym
28
41
  @report_key = params[:report].to_sym
@@ -85,6 +85,123 @@ pg_stat_statements.track = all</pre>
85
85
  </div>
86
86
  </div>
87
87
 
88
+ <!-- Live Monitoring Panel -->
89
+ <div id="live-monitoring" class="live-monitoring-panel" style="display: none;">
90
+ <div class="live-monitoring-header">
91
+ <div class="live-monitoring-title">
92
+ <span class="live-indicator"></span>
93
+ <span>Live Monitoring</span>
94
+ </div>
95
+ <div class="live-monitoring-controls">
96
+ <span class="live-monitoring-interval">Updates every 5s</span>
97
+ <button class="btn-toggle-live" onclick="toggleLiveMonitoring()" title="Toggle live monitoring">
98
+ <span id="toggle-icon">⏸</span>
99
+ </button>
100
+ </div>
101
+ </div>
102
+
103
+ <div class="live-metrics-grid">
104
+ <!-- Connections -->
105
+ <div class="live-metric-card" data-metric="connections">
106
+ <div class="metric-header">
107
+ <span class="metric-icon" style="background: rgba(107, 159, 232, 0.12); color: var(--accent-blue);">🔗</span>
108
+ <span class="metric-name">Connections</span>
109
+ </div>
110
+ <div class="metric-body">
111
+ <div class="metric-value">
112
+ <span id="metric-connections-value">-</span>
113
+ <span class="metric-unit">/ <span id="metric-connections-max">-</span></span>
114
+ </div>
115
+ <div class="metric-detail">
116
+ <span id="metric-connections-pct">-</span>% used
117
+ </div>
118
+ <div class="metric-sparkline">
119
+ <svg id="sparkline-connections" viewBox="0 0 100 30" preserveAspectRatio="none"></svg>
120
+ </div>
121
+ </div>
122
+ <div class="metric-status" id="status-connections"></div>
123
+ </div>
124
+
125
+ <!-- TPS -->
126
+ <div class="live-metric-card" data-metric="tps">
127
+ <div class="metric-header">
128
+ <span class="metric-icon" style="background: rgba(95, 184, 154, 0.12); color: var(--accent-green);">⚡</span>
129
+ <span class="metric-name">TPS</span>
130
+ </div>
131
+ <div class="metric-body">
132
+ <div class="metric-value">
133
+ <span id="metric-tps-value">-</span>
134
+ <span class="metric-unit">tx/s</span>
135
+ </div>
136
+ <div class="metric-detail">
137
+ commit: <span id="metric-tps-commit">-</span> / rollback: <span id="metric-tps-rollback">-</span>
138
+ </div>
139
+ <div class="metric-sparkline">
140
+ <svg id="sparkline-tps" viewBox="0 0 100 30" preserveAspectRatio="none"></svg>
141
+ </div>
142
+ </div>
143
+ <div class="metric-status" id="status-tps"></div>
144
+ </div>
145
+
146
+ <!-- Cache Hit Ratio -->
147
+ <div class="live-metric-card" data-metric="cache">
148
+ <div class="metric-header">
149
+ <span class="metric-icon" style="background: rgba(157, 140, 214, 0.12); color: var(--accent-purple);">💾</span>
150
+ <span class="metric-name">Cache Hit</span>
151
+ </div>
152
+ <div class="metric-body">
153
+ <div class="metric-value">
154
+ <span id="metric-cache-value">-</span>
155
+ <span class="metric-unit">%</span>
156
+ </div>
157
+ <div class="metric-detail">heap blocks from cache</div>
158
+ <div class="metric-sparkline">
159
+ <svg id="sparkline-cache" viewBox="0 0 100 30" preserveAspectRatio="none"></svg>
160
+ </div>
161
+ </div>
162
+ <div class="metric-status" id="status-cache"></div>
163
+ </div>
164
+
165
+ <!-- Long Running Queries -->
166
+ <div class="live-metric-card" data-metric="longrunning">
167
+ <div class="metric-header">
168
+ <span class="metric-icon" style="background: rgba(212, 160, 86, 0.12); color: var(--accent-amber);">🐢</span>
169
+ <span class="metric-name">Long Queries</span>
170
+ </div>
171
+ <div class="metric-body">
172
+ <div class="metric-value">
173
+ <span id="metric-longrunning-value">-</span>
174
+ <span class="metric-unit">queries</span>
175
+ </div>
176
+ <div class="metric-detail">&gt; 60s runtime</div>
177
+ <div class="metric-sparkline">
178
+ <svg id="sparkline-longrunning" viewBox="0 0 100 30" preserveAspectRatio="none"></svg>
179
+ </div>
180
+ </div>
181
+ <div class="metric-status" id="status-longrunning"></div>
182
+ </div>
183
+
184
+ <!-- Blocked Queries -->
185
+ <div class="live-metric-card" data-metric="blocked">
186
+ <div class="metric-header">
187
+ <span class="metric-icon" style="background: rgba(217, 112, 132, 0.12); color: var(--accent-rose);">🔒</span>
188
+ <span class="metric-name">Blocked</span>
189
+ </div>
190
+ <div class="metric-body">
191
+ <div class="metric-value">
192
+ <span id="metric-blocked-value">-</span>
193
+ <span class="metric-unit">processes</span>
194
+ </div>
195
+ <div class="metric-detail">waiting for locks</div>
196
+ <div class="metric-sparkline">
197
+ <svg id="sparkline-blocked" viewBox="0 0 100 30" preserveAspectRatio="none"></svg>
198
+ </div>
199
+ </div>
200
+ <div class="metric-status" id="status-blocked"></div>
201
+ </div>
202
+ </div>
203
+ </div>
204
+
88
205
  <div class="categories-grid">
89
206
  <% @categories.each do |category_key, category| %>
90
207
  <div class="category-card<%= ' disabled' if category_key == :queries && !@pg_stat_status[:ready] %>">
@@ -370,6 +487,202 @@ pg_stat_statements.track = all</pre>
370
487
  padding: 0.625rem 1.25rem;
371
488
  font-size: 0.875rem;
372
489
  }
490
+
491
+ /* Live Monitoring Panel */
492
+ .live-monitoring-panel {
493
+ margin-bottom: 2rem;
494
+ background: var(--bg-card);
495
+ border: 1px solid var(--border-color);
496
+ border-radius: 16px;
497
+ padding: 1.25rem 1.5rem;
498
+ }
499
+
500
+ .live-monitoring-header {
501
+ display: flex;
502
+ align-items: center;
503
+ justify-content: space-between;
504
+ margin-bottom: 1.25rem;
505
+ padding-bottom: 1rem;
506
+ border-bottom: 1px solid var(--border-color);
507
+ }
508
+
509
+ .live-monitoring-title {
510
+ display: flex;
511
+ align-items: center;
512
+ gap: 0.75rem;
513
+ font-weight: 600;
514
+ font-size: 1rem;
515
+ }
516
+
517
+ .live-indicator {
518
+ width: 8px;
519
+ height: 8px;
520
+ border-radius: 50%;
521
+ background: var(--accent-green);
522
+ animation: pulse 2s infinite;
523
+ }
524
+
525
+ .live-indicator.paused {
526
+ background: var(--text-muted);
527
+ animation: none;
528
+ }
529
+
530
+ .live-monitoring-controls {
531
+ display: flex;
532
+ align-items: center;
533
+ gap: 1rem;
534
+ }
535
+
536
+ .live-monitoring-interval {
537
+ font-size: 0.75rem;
538
+ color: var(--text-muted);
539
+ }
540
+
541
+ .btn-toggle-live {
542
+ width: 32px;
543
+ height: 32px;
544
+ padding: 0;
545
+ background: var(--bg-tertiary);
546
+ border: 1px solid var(--border-color);
547
+ border-radius: 8px;
548
+ color: var(--text-muted);
549
+ font-size: 0.875rem;
550
+ cursor: pointer;
551
+ transition: all 0.15s;
552
+ }
553
+
554
+ .btn-toggle-live:hover {
555
+ background: var(--bg-secondary);
556
+ color: var(--text-primary);
557
+ }
558
+
559
+ /* Metrics Grid */
560
+ .live-metrics-grid {
561
+ display: grid;
562
+ grid-template-columns: repeat(5, 1fr);
563
+ gap: 1rem;
564
+ }
565
+
566
+ @media (max-width: 1200px) {
567
+ .live-metrics-grid {
568
+ grid-template-columns: repeat(3, 1fr);
569
+ }
570
+ }
571
+
572
+ @media (max-width: 768px) {
573
+ .live-metrics-grid {
574
+ grid-template-columns: repeat(2, 1fr);
575
+ }
576
+ }
577
+
578
+ @media (max-width: 500px) {
579
+ .live-metrics-grid {
580
+ grid-template-columns: 1fr;
581
+ }
582
+ }
583
+
584
+ /* Metric Card */
585
+ .live-metric-card {
586
+ background: var(--bg-tertiary);
587
+ border: 1px solid var(--border-color);
588
+ border-radius: 12px;
589
+ padding: 1rem;
590
+ position: relative;
591
+ transition: all 0.2s;
592
+ }
593
+
594
+ .live-metric-card:hover {
595
+ border-color: var(--accent-purple);
596
+ }
597
+
598
+ .live-metric-card.status-ok {
599
+ border-left: 3px solid var(--accent-green);
600
+ }
601
+
602
+ .live-metric-card.status-warning {
603
+ border-left: 3px solid var(--accent-amber);
604
+ }
605
+
606
+ .live-metric-card.status-critical {
607
+ border-left: 3px solid var(--accent-rose);
608
+ }
609
+
610
+ .metric-header {
611
+ display: flex;
612
+ align-items: center;
613
+ gap: 0.5rem;
614
+ margin-bottom: 0.75rem;
615
+ }
616
+
617
+ .metric-icon {
618
+ width: 28px;
619
+ height: 28px;
620
+ border-radius: 6px;
621
+ display: flex;
622
+ align-items: center;
623
+ justify-content: center;
624
+ font-size: 0.875rem;
625
+ }
626
+
627
+ .metric-name {
628
+ font-size: 0.8rem;
629
+ font-weight: 500;
630
+ color: var(--text-secondary);
631
+ }
632
+
633
+ .metric-body {
634
+ display: flex;
635
+ flex-direction: column;
636
+ gap: 0.25rem;
637
+ }
638
+
639
+ .metric-value {
640
+ display: flex;
641
+ align-items: baseline;
642
+ gap: 0.25rem;
643
+ }
644
+
645
+ .metric-value span:first-child {
646
+ font-size: 1.5rem;
647
+ font-weight: 700;
648
+ color: var(--text-primary);
649
+ line-height: 1;
650
+ }
651
+
652
+ .metric-unit {
653
+ font-size: 0.75rem;
654
+ color: var(--text-muted);
655
+ }
656
+
657
+ .metric-detail {
658
+ font-size: 0.7rem;
659
+ color: var(--text-muted);
660
+ }
661
+
662
+ /* Sparkline */
663
+ .metric-sparkline {
664
+ height: 30px;
665
+ margin-top: 0.5rem;
666
+ }
667
+
668
+ .metric-sparkline svg {
669
+ width: 100%;
670
+ height: 100%;
671
+ }
672
+
673
+ /* Status indicator */
674
+ .metric-status {
675
+ position: absolute;
676
+ top: 0.5rem;
677
+ right: 0.5rem;
678
+ width: 6px;
679
+ height: 6px;
680
+ border-radius: 50%;
681
+ }
682
+
683
+ .metric-status.ok { background: var(--accent-green); }
684
+ .metric-status.warning { background: var(--accent-amber); }
685
+ .metric-status.critical { background: var(--accent-rose); }
373
686
  </style>
374
687
 
375
688
  <script>
@@ -463,4 +776,229 @@ pg_stat_statements.track = all</pre>
463
776
  button.innerHTML = '⚡ Create Extension';
464
777
  }
465
778
  }
779
+
780
+ // ============================================
781
+ // Live Monitoring
782
+ // ============================================
783
+
784
+ const LIVE_CONFIG = {
785
+ pollInterval: 5000,
786
+ historyLength: 30,
787
+ thresholds: {
788
+ connections: { warning: 70, critical: 90 },
789
+ tps: { warning: null, critical: null },
790
+ cache: { warning: 95, critical: 90 },
791
+ longrunning: { warning: 1, critical: 5 },
792
+ blocked: { warning: 1, critical: 3 }
793
+ }
794
+ };
795
+
796
+ let liveMonitoringEnabled = true;
797
+ let pollTimer = null;
798
+ let previousMetrics = null;
799
+ const metricsHistory = {
800
+ connections: [],
801
+ tps: [],
802
+ cache: [],
803
+ longrunning: [],
804
+ blocked: []
805
+ };
806
+
807
+ function initLiveMonitoring() {
808
+ const panel = document.getElementById('live-monitoring');
809
+ if (!panel) return;
810
+
811
+ panel.style.display = 'block';
812
+
813
+ const savedState = localStorage.getItem('pgReportsLiveMonitoring');
814
+ if (savedState === 'disabled') {
815
+ liveMonitoringEnabled = false;
816
+ updateToggleUI();
817
+ }
818
+
819
+ if (liveMonitoringEnabled) {
820
+ fetchLiveMetrics();
821
+ startPolling();
822
+ }
823
+ }
824
+
825
+ function startPolling() {
826
+ if (pollTimer) clearInterval(pollTimer);
827
+ pollTimer = setInterval(fetchLiveMetrics, LIVE_CONFIG.pollInterval);
828
+ }
829
+
830
+ function stopPolling() {
831
+ if (pollTimer) {
832
+ clearInterval(pollTimer);
833
+ pollTimer = null;
834
+ }
835
+ }
836
+
837
+ function toggleLiveMonitoring() {
838
+ liveMonitoringEnabled = !liveMonitoringEnabled;
839
+ localStorage.setItem('pgReportsLiveMonitoring', liveMonitoringEnabled ? 'enabled' : 'disabled');
840
+ updateToggleUI();
841
+
842
+ if (liveMonitoringEnabled) {
843
+ fetchLiveMetrics();
844
+ startPolling();
845
+ } else {
846
+ stopPolling();
847
+ }
848
+ }
849
+
850
+ function updateToggleUI() {
851
+ const icon = document.getElementById('toggle-icon');
852
+ const indicator = document.querySelector('.live-indicator');
853
+
854
+ if (liveMonitoringEnabled) {
855
+ icon.textContent = '⏸';
856
+ indicator.classList.remove('paused');
857
+ } else {
858
+ icon.textContent = '▶';
859
+ indicator.classList.add('paused');
860
+ }
861
+ }
862
+
863
+ async function fetchLiveMetrics() {
864
+ try {
865
+ const response = await fetch(`${pgReportsRoot}/live_metrics`);
866
+ const data = await response.json();
867
+
868
+ if (data.success) {
869
+ updateMetricsDisplay(data.metrics);
870
+ }
871
+ } catch (error) {
872
+ console.error('Failed to fetch live metrics:', error);
873
+ }
874
+ }
875
+
876
+ function updateMetricsDisplay(metrics) {
877
+ let tps = 0;
878
+ if (previousMetrics) {
879
+ const timeDelta = metrics.timestamp - previousMetrics.timestamp;
880
+ if (timeDelta > 0) {
881
+ const txDelta = metrics.transactions.total - previousMetrics.transactions.total;
882
+ tps = Math.max(0, Math.round(txDelta / timeDelta));
883
+ }
884
+ }
885
+
886
+ document.getElementById('metric-connections-value').textContent = metrics.connections.total;
887
+ document.getElementById('metric-connections-max').textContent = metrics.connections.max;
888
+ document.getElementById('metric-connections-pct').textContent = metrics.connections.percent.toFixed(1);
889
+
890
+ document.getElementById('metric-tps-value').textContent = tps;
891
+ document.getElementById('metric-tps-commit').textContent = formatNumber(metrics.transactions.commit);
892
+ document.getElementById('metric-tps-rollback').textContent = formatNumber(metrics.transactions.rollback);
893
+
894
+ document.getElementById('metric-cache-value').textContent = metrics.cache_hit_ratio.toFixed(2);
895
+
896
+ document.getElementById('metric-longrunning-value').textContent = metrics.long_running_count;
897
+
898
+ document.getElementById('metric-blocked-value').textContent = metrics.blocked_count;
899
+
900
+ addToHistory('connections', metrics.connections.percent);
901
+ addToHistory('tps', tps);
902
+ addToHistory('cache', metrics.cache_hit_ratio);
903
+ addToHistory('longrunning', metrics.long_running_count);
904
+ addToHistory('blocked', metrics.blocked_count);
905
+
906
+ renderSparkline('connections', metricsHistory.connections, 'var(--accent-blue)');
907
+ renderSparkline('tps', metricsHistory.tps, 'var(--accent-green)');
908
+ renderSparkline('cache', metricsHistory.cache, 'var(--accent-purple)');
909
+ renderSparkline('longrunning', metricsHistory.longrunning, 'var(--accent-amber)');
910
+ renderSparkline('blocked', metricsHistory.blocked, 'var(--accent-rose)');
911
+
912
+ updateStatus('connections', metrics.connections.percent, 'higher');
913
+ updateStatus('tps', tps, null);
914
+ updateStatus('cache', metrics.cache_hit_ratio, 'lower');
915
+ updateStatus('longrunning', metrics.long_running_count, 'higher');
916
+ updateStatus('blocked', metrics.blocked_count, 'higher');
917
+
918
+ previousMetrics = metrics;
919
+ }
920
+
921
+ function addToHistory(metric, value) {
922
+ metricsHistory[metric].push(value);
923
+ if (metricsHistory[metric].length > LIVE_CONFIG.historyLength) {
924
+ metricsHistory[metric].shift();
925
+ }
926
+ }
927
+
928
+ function formatNumber(num) {
929
+ if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
930
+ if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
931
+ return num.toString();
932
+ }
933
+
934
+ function renderSparkline(metric, data, color) {
935
+ const svg = document.getElementById(`sparkline-${metric}`);
936
+ if (!svg || data.length < 2) return;
937
+
938
+ svg.innerHTML = '';
939
+
940
+ const width = 100;
941
+ const height = 30;
942
+ const padding = 2;
943
+
944
+ const min = Math.min(...data);
945
+ const max = Math.max(...data);
946
+ const range = max - min || 1;
947
+
948
+ const points = data.map((value, index) => {
949
+ const x = padding + (index / (data.length - 1)) * (width - 2 * padding);
950
+ const y = height - padding - ((value - min) / range) * (height - 2 * padding);
951
+ return { x, y };
952
+ });
953
+
954
+ const pathD = points.map((p, i) => (i === 0 ? `M ${p.x} ${p.y}` : `L ${p.x} ${p.y}`)).join(' ');
955
+
956
+ const areaD = pathD +
957
+ ` L ${points[points.length - 1].x} ${height - padding}` +
958
+ ` L ${points[0].x} ${height - padding} Z`;
959
+
960
+ const area = document.createElementNS('http://www.w3.org/2000/svg', 'path');
961
+ area.setAttribute('d', areaD);
962
+ area.setAttribute('fill', color);
963
+ area.setAttribute('opacity', '0.15');
964
+ svg.appendChild(area);
965
+
966
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
967
+ path.setAttribute('d', pathD);
968
+ path.setAttribute('fill', 'none');
969
+ path.setAttribute('stroke', color);
970
+ path.setAttribute('stroke-width', '1.5');
971
+ path.setAttribute('stroke-linecap', 'round');
972
+ path.setAttribute('stroke-linejoin', 'round');
973
+ svg.appendChild(path);
974
+ }
975
+
976
+ function updateStatus(metric, value, badDirection) {
977
+ const card = document.querySelector(`[data-metric="${metric}"]`);
978
+ const statusDot = document.getElementById(`status-${metric}`);
979
+ if (!card || !statusDot) return;
980
+
981
+ const thresholds = LIVE_CONFIG.thresholds[metric];
982
+ if (!thresholds.warning && !thresholds.critical) {
983
+ card.className = 'live-metric-card status-ok';
984
+ statusDot.className = 'metric-status ok';
985
+ return;
986
+ }
987
+
988
+ let status = 'ok';
989
+
990
+ if (badDirection === 'higher') {
991
+ if (value >= thresholds.critical) status = 'critical';
992
+ else if (value >= thresholds.warning) status = 'warning';
993
+ } else if (badDirection === 'lower') {
994
+ if (value <= thresholds.critical) status = 'critical';
995
+ else if (value <= thresholds.warning) status = 'warning';
996
+ }
997
+
998
+ card.className = `live-metric-card status-${status}`;
999
+ statusDot.className = `metric-status ${status}`;
1000
+ }
1001
+
1002
+ document.addEventListener('DOMContentLoaded', initLiveMonitoring);
1003
+ window.addEventListener('beforeunload', stopPolling);
466
1004
  </script>
data/config/routes.rb CHANGED
@@ -3,6 +3,8 @@
3
3
  PgReports::Engine.routes.draw do
4
4
  root to: "dashboard#index"
5
5
 
6
+ get "live_metrics", to: "dashboard#live_metrics", as: :live_metrics
7
+
6
8
  post "enable_pg_stat_statements", to: "dashboard#enable_pg_stat_statements", as: :enable_pg_stat_statements
7
9
  post "reset_statistics", to: "dashboard#reset_statistics", as: :reset_statistics
8
10
  post "explain_analyze", to: "dashboard#explain_analyze", as: :explain_analyze
@@ -97,6 +97,36 @@ module PgReports
97
97
  }
98
98
  end
99
99
 
100
+ # Live metrics for dashboard monitoring
101
+ # @param long_query_threshold [Integer] Threshold in seconds for long queries
102
+ # @return [Hash] Metrics data
103
+ def live_metrics(long_query_threshold: 60)
104
+ data = executor.execute_from_file(:system, :live_metrics,
105
+ long_query_threshold: long_query_threshold
106
+ )
107
+
108
+ row = data.first || {}
109
+
110
+ {
111
+ connections: {
112
+ active: row["active_connections"].to_i,
113
+ idle: row["idle_connections"].to_i,
114
+ total: row["total_connections"].to_i,
115
+ max: row["max_connections"].to_i,
116
+ percent: row["connections_pct"].to_f
117
+ },
118
+ transactions: {
119
+ total: row["total_transactions"].to_i,
120
+ commit: row["xact_commit"].to_i,
121
+ rollback: row["xact_rollback"].to_i
122
+ },
123
+ cache_hit_ratio: row["heap_hit_ratio"].to_f,
124
+ long_running_count: row["long_running_count"].to_i,
125
+ blocked_count: row["blocked_count"].to_i,
126
+ timestamp: row["timestamp_epoch"].to_f
127
+ }
128
+ end
129
+
100
130
  # Enable pg_stat_statements extension
101
131
  # Tries to create extension, returns helpful error if it fails
102
132
  # @return [Hash] Result with success status and message
@@ -0,0 +1,62 @@
1
+ -- Live monitoring metrics
2
+ -- Single optimized query for dashboard live metrics
3
+
4
+ WITH connection_stats AS (
5
+ SELECT
6
+ COUNT(*) FILTER (WHERE state = 'active' AND pid != pg_backend_pid()) AS active_connections,
7
+ COUNT(*) FILTER (WHERE state = 'idle') AS idle_connections,
8
+ COUNT(*) FILTER (WHERE pid != pg_backend_pid()) AS total_connections,
9
+ (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS max_connections
10
+ FROM pg_stat_activity
11
+ WHERE datname = current_database()
12
+ ),
13
+ tps_stats AS (
14
+ SELECT
15
+ xact_commit + xact_rollback AS total_transactions,
16
+ xact_commit,
17
+ xact_rollback
18
+ FROM pg_stat_database
19
+ WHERE datname = current_database()
20
+ ),
21
+ cache_stats AS (
22
+ SELECT
23
+ CASE
24
+ WHEN blks_hit + blks_read > 0 THEN
25
+ ROUND((blks_hit * 100.0 / (blks_hit + blks_read))::numeric, 2)
26
+ ELSE 100.0
27
+ END AS heap_hit_ratio
28
+ FROM pg_stat_database
29
+ WHERE datname = current_database()
30
+ ),
31
+ long_running AS (
32
+ SELECT COUNT(*) AS count
33
+ FROM pg_stat_activity
34
+ WHERE datname = current_database()
35
+ AND pid != pg_backend_pid()
36
+ AND state = 'active'
37
+ AND query_start IS NOT NULL
38
+ AND EXTRACT(EPOCH FROM (NOW() - query_start)) > :long_query_threshold
39
+ ),
40
+ blocked AS (
41
+ SELECT COUNT(*) AS count
42
+ FROM pg_locks
43
+ WHERE NOT granted
44
+ )
45
+ SELECT
46
+ cs.active_connections,
47
+ cs.idle_connections,
48
+ cs.total_connections,
49
+ cs.max_connections,
50
+ ROUND((cs.total_connections * 100.0 / NULLIF(cs.max_connections, 0))::numeric, 1) AS connections_pct,
51
+ ts.total_transactions,
52
+ ts.xact_commit,
53
+ ts.xact_rollback,
54
+ ca.heap_hit_ratio,
55
+ lr.count AS long_running_count,
56
+ bl.count AS blocked_count,
57
+ EXTRACT(EPOCH FROM NOW()) AS timestamp_epoch
58
+ FROM connection_stats cs
59
+ CROSS JOIN tps_stats ts
60
+ CROSS JOIN cache_stats ca
61
+ CROSS JOIN long_running lr
62
+ CROSS JOIN blocked bl;
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PgReports
4
- VERSION = "0.2.3"
4
+ VERSION = "0.3.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pg_reports
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.3
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Eldar Avatov
@@ -153,6 +153,7 @@ files:
153
153
  - lib/pg_reports/sql/system/cache_stats.sql
154
154
  - lib/pg_reports/sql/system/database_sizes.sql
155
155
  - lib/pg_reports/sql/system/extensions.sql
156
+ - lib/pg_reports/sql/system/live_metrics.sql
156
157
  - lib/pg_reports/sql/system/settings.sql
157
158
  - lib/pg_reports/sql/tables/bloated_tables.sql
158
159
  - lib/pg_reports/sql/tables/cache_hit_ratios.sql