askrobots / dbbasic Public

Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.

0 downloads

dbbasic/realtime_monitor_presentation.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add DBBasic crate engine logo and update README 0d628db 1 year, 2 months ago History
realtime_monitor_presentation.py · 11.0 KB · 241 lines
1#!/usr/bin/env python3
2"""
3Real-time Monitor UI using Presentation Layer
4Converts the monitor dashboard to data structures
5"""
6
7from presentation_layer import PresentationLayer
8from bootstrap_components import ExtendedBootstrapRenderer
9
10# Initialize presentation layer
11PresentationLayer.add_renderer('bootstrap', ExtendedBootstrapRenderer())
12
13def get_realtime_monitor_ui():
14 """Generate Real-time Monitor dashboard as data structure"""
15 return {
16 'type': 'page',
17 'title': 'DBBasic Real-time Monitor',
18 'components': [
19 # Navigation
20 {
21 'type': 'navbar',
22 'brand': 'DBBasic Monitor',
23 'variant': 'dark',
24 'links': [
25 {'text': 'Dashboard', 'url': 'http://localhost:8005'},
26 {'text': 'Data', 'url': 'http://localhost:8005'},
27 {'text': 'AI Services', 'url': 'http://localhost:8003'},
28 {'text': 'Templates', 'url': 'http://localhost:8005/templates'}
29 ]
30 },
31
32 # Main container
33 {
34 'type': 'container',
35 'fluid': True,
36 'children': [
37 # Header with performance badge
38 '<div class="text-center mb-4">',
39 '<h1 class="display-4">',
40 '<i class="bi bi-activity text-success"></i> Real-time Monitor',
41 '</h1>',
42 {'type': 'badge', 'text': '⚡ 402M rows/sec', 'variant': 'success', 'pill': True},
43 '</div>',
44
45 # Metrics cards
46 {
47 'type': 'grid',
48 'columns': 4,
49 'items': [
50 {
51 'type': 'card',
52 'title': 'Operations/sec',
53 'description': '<h2 id="opsPerSec" class="text-primary">0</h2>'
54 },
55 {
56 'type': 'card',
57 'title': 'Active Services',
58 'description': '<h2 id="activeServices" class="text-success">0</h2>'
59 },
60 {
61 'type': 'card',
62 'title': 'Total Operations',
63 'description': '<h2 id="totalOps" class="text-info">0</h2>'
64 },
65 {
66 'type': 'card',
67 'title': 'Connected Clients',
68 'description': '<h2 id="connectedClients" class="text-warning">0</h2>'
69 }
70 ]
71 },
72
73 # Activity sections
74 '<div class="row mt-4">',
75
76 # Service calls column
77 '<div class="col-md-6">',
78 {
79 'type': 'card',
80 'title': '📡 Live Service Calls',
81 'body': '<div id="serviceCalls" class="activity-feed" style="height: 400px; overflow-y: auto;"></div>'
82 },
83 '</div>',
84
85 # Database operations column
86 '<div class="col-md-6">',
87 {
88 'type': 'card',
89 'title': '💾 Database Operations',
90 'body': '<div id="dbOperations" class="activity-feed" style="height: 400px; overflow-y: auto;"></div>'
91 },
92 '</div>',
93
94 '</div>',
95
96 # Table activity
97 '<div class="mt-4">',
98 {
99 'type': 'card',
100 'title': '📊 Table Activity',
101 'body': {
102 'type': 'table',
103 'headers': ['Table', 'Operations', 'Rows/sec', 'Status'],
104 'rows': [
105 ['customers', '<span id="customers-ops">0</span>', '<span id="customers-rate">0</span>', {'type': 'badge', 'text': 'Active', 'variant': 'success'}],
106 ['orders', '<span id="orders-ops">0</span>', '<span id="orders-rate">0</span>', {'type': 'badge', 'text': 'Active', 'variant': 'success'}],
107 ['products', '<span id="products-ops">0</span>', '<span id="products-rate">0</span>', {'type': 'badge', 'text': 'Active', 'variant': 'success'}],
108 ['inventory', '<span id="inventory-ops">0</span>', '<span id="inventory-rate">0</span>', {'type': 'badge', 'text': 'Idle', 'variant': 'secondary'}],
109 ['analytics', '<span id="analytics-ops">0</span>', '<span id="analytics-rate">0</span>', {'type': 'badge', 'text': 'Idle', 'variant': 'secondary'}]
110 ]
111 }
112 },
113 '</div>',
114
115 # WebSocket connection status
116 '<div class="mt-4 text-center">',
117 '<div id="connectionStatus" class="badge bg-secondary">Connecting...</div>',
118 '</div>',
119
120 # Add WebSocket JavaScript
121 '''
122 <script>
123 let ws = null;
124 let reconnectInterval = null;
125
126 function connectWebSocket() {
127 ws = new WebSocket('ws://localhost:8004/ws');
128
129 ws.onopen = function() {
130 document.getElementById('connectionStatus').className = 'badge bg-success';
131 document.getElementById('connectionStatus').textContent = '🟢 Connected';
132 clearInterval(reconnectInterval);
133 };
134
135 ws.onmessage = function(event) {
136 const data = JSON.parse(event.data);
137
138 if (data.type === 'metrics') {
139 updateMetrics(data.data);
140 } else if (data.type === 'service_call') {
141 addServiceCall(data.data);
142 } else if (data.type === 'db_operation') {
143 addDbOperation(data.data);
144 }
145 };
146
147 ws.onclose = function() {
148 document.getElementById('connectionStatus').className = 'badge bg-danger';
149 document.getElementById('connectionStatus').textContent = '🔴 Disconnected';
150
151 // Attempt to reconnect every 3 seconds
152 if (!reconnectInterval) {
153 reconnectInterval = setInterval(connectWebSocket, 3000);
154 }
155 };
156
157 ws.onerror = function(error) {
158 console.error('WebSocket error:', error);
159 };
160 }
161
162 function updateMetrics(metrics) {
163 document.getElementById('opsPerSec').textContent =
164 metrics.operations_per_second ? metrics.operations_per_second.toLocaleString() : '0';
165 document.getElementById('activeServices').textContent =
166 metrics.active_services || '0';
167 document.getElementById('totalOps').textContent =
168 metrics.total_operations ? metrics.total_operations.toLocaleString() : '0';
169 document.getElementById('connectedClients').textContent =
170 metrics.active_connections || '0';
171 }
172
173 function addServiceCall(data) {
174 const feed = document.getElementById('serviceCalls');
175 const entry = document.createElement('div');
176 entry.className = 'alert alert-info py-2 mb-2';
177 entry.innerHTML = `
178 <small class="text-muted">${new Date(data.timestamp).toLocaleTimeString()}</small><br>
179 <strong>${data.service}</strong>: ${data.result}
180 `;
181 feed.insertBefore(entry, feed.firstChild);
182
183 // Keep only last 20 entries
184 while (feed.children.length > 20) {
185 feed.removeChild(feed.lastChild);
186 }
187 }
188
189 function addDbOperation(data) {
190 const feed = document.getElementById('dbOperations');
191 const entry = document.createElement('div');
192 entry.className = 'alert alert-success py-2 mb-2';
193 entry.innerHTML = `
194 <small class="text-muted">${new Date(data.timestamp).toLocaleTimeString()}</small><br>
195 <strong>${data.operation}</strong> on ${data.table}: ${data.count} rows
196 `;
197 feed.insertBefore(entry, feed.firstChild);
198
199 // Update table stats
200 if (data.table) {
201 const opsElement = document.getElementById(data.table + '-ops');
202 if (opsElement) {
203 const current = parseInt(opsElement.textContent) || 0;
204 opsElement.textContent = (current + 1).toLocaleString();
205 }
206
207 const rateElement = document.getElementById(data.table + '-rate');
208 if (rateElement) {
209 rateElement.textContent = data.rate ? data.rate.toLocaleString() : '0';
210 }
211 }
212
213 // Keep only last 20 entries
214 while (feed.children.length > 20) {
215 feed.removeChild(feed.lastChild);
216 }
217 }
218
219 // Connect on page load
220 document.addEventListener('DOMContentLoaded', function() {
221 connectWebSocket();
222 });
223 </script>
224 '''
225 ]
226 }
227 ]
228 }
229
230# Generate the HTML
231if __name__ == "__main__":
232 monitor_html = PresentationLayer.render(get_realtime_monitor_ui(), 'bootstrap')
233
234 # Save to file
235 with open('realtime_monitor_new.html', 'w') as f:
236 f.write(monitor_html)
237
238 print("✅ Generated Real-time Monitor using presentation layer")
239 print("\nBefore: ~400 lines of HTML in Python")
240 print("After: ~150 lines of data structures")
241 print("Token reduction: ~65%")