otelite-api 0.1.139

Lightweight web dashboard for visualizing OpenTelemetry logs, traces, and metrics
1
2
3
4
5
6
7
8
9
10
11
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
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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Main application entry point

import { api } from './api.js';
import { CommandPalette } from './palette.js';
import { fillEndpointPlaceholders } from './setup.js';

/**
 * Main application class
 */
const VALID_VIEWS = ['overview', 'logs', 'traces', 'sessions', 'metrics', 'analytics', 'setup'];

// Old hash routes that should redirect to a renamed view.
const VIEW_ALIASES = { usage: 'analytics' };

class App {
    constructor() {
        this.currentView = this._readHash() || 'overview';
        this.connectionCheckInterval = null;
        this.renderedViews = new Set();
        this.views = {};
        this.popoverOpen = false;
        this.lastHealthData = null;
        this.init();
    }

    _readHash() {
        const raw = (window.location.hash || '').replace(/^#/, '').split('?')[0];
        const h = VIEW_ALIASES[raw] || raw;
        return VALID_VIEWS.includes(h) ? h : null;
    }

    /**
     * Initialize the application
     */
    init() {
        this.views = {
            overview: new window.OverviewView(api),
            logs: new window.LogsView(api),
            traces: new window.TracesView(api),
            sessions: new window.SessionsView(api),
            metrics: new window.MetricsView(api),
            analytics: new window.AnalyticsView(api),
            // setup is static HTML — no view class needed
        };
        this.setupNavigation();
        this.setupConnectionMonitoring();
        this.setupEndpointPlaceholders();
        this.palette = new CommandPalette(this);
        this.loadInitialView();

        window.addEventListener('hashchange', () => {
            const v = this._readHash();
            if (v && v !== this.currentView) {
                this.switchView(v);
            }
        });
    }

    /**
     * Setup navigation between views
     */
    setupNavigation() {
        const navButtons = document.querySelectorAll('.nav-btn');

        navButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const view = btn.dataset.view;
                this.switchView(view);
            });
        });
    }

    /**
     * Switch to a different view
     */
    switchView(viewName) {
        // Update navigation buttons
        document.querySelectorAll('.nav-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.view === viewName);
        });

        // Update views
        document.querySelectorAll('.view').forEach(view => {
            view.classList.toggle('active', view.id === `${viewName}-view`);
        });

        this.currentView = viewName;

        // Persist tab in URL hash so reload/back/forward keep the current view.
        // Use replaceState to avoid spawning extra history entries on every click.
        if (this._readHash() !== viewName) {
            window.history.replaceState(null, '', `#${viewName}`);
        }

        // Render the view on first visit; subsequent visits use the view's own auto-refresh
        if (this.views[viewName] && !this.renderedViews.has(viewName)) {
            this.renderedViews.add(viewName);
            this.views[viewName].render();
        }

        // Trigger view-specific initialization
        this.dispatchViewChange(viewName);
    }

    /**
     * Navigate to the Traces view, pre-filtered to a specific trace ID.
     */
    navigateToTrace(traceId) {
        this.switchView('traces');
        const tracesView = this.views.traces;
        tracesView.filters.traceId = traceId;
        const el = document.getElementById('trace-id-filter');
        if (el) el.value = traceId;
        tracesView.loadTraces();
    }

    /**
     * Navigate to the Logs view, pre-filtered to a specific trace ID.
     */
    navigateToLogs(traceId) {
        this.switchView('logs');
        const logsView = this.views.logs;
        logsView.filters.trace_id = traceId;
        logsView.currentPage = 0;
        logsView.loadLogs();
    }

    navigateToLogsBySession(sessionId) {
        this.switchView('logs');
        const v = this.views.logs;
        v.filters.session_id = sessionId;
        v.currentPage = 0;
        v.loadLogs();
    }

    navigateToTracesBySession(sessionId) {
        this.switchView('traces');
        const v = this.views.traces;
        v.filters.sessionId = sessionId;
        v.currentPage = 0;
        v.loadTraces();
    }

    navigateToLogsByPrompt(promptId) {
        this.switchView('logs');
        const v = this.views.logs;
        v.filters.prompt_id = promptId;
        v.currentPage = 0;
        v.loadLogs();
    }

    navigateToLogsByConversation(conversationId) {
        this.switchView('logs');
        const v = this.views.logs;
        v.filters.conversation_id = conversationId;
        v.currentPage = 0;
        v.loadLogs();
    }

    navigateToTracesByConversation(conversationId) {
        this.switchView('traces');
        const v = this.views.traces;
        v.filters.conversation_id = conversationId;
        v.currentPage = 0;
        v.loadTraces();
    }

    /**
     * Open the Session Report modal for a session ID without switching tabs.
     * Falls back to navigating to Traces filtered by session if the modal helper
     * isn't available yet (e.g. traces view hasn't rendered).
     */
    navigateToSessionReport(sessionId) {
        if (this.views.traces &&
            typeof this.views.traces.openSessionDiagnoseModal === 'function') {
            if (!this.renderedViews.has('traces')) {
                this.views.traces.render();
                this.renderedViews.add('traces');
            }
            this.views.traces.openSessionDiagnoseModal(sessionId);
        } else {
            this.navigateToTracesBySession(sessionId);
        }
    }

    /**
     * Dispatch custom event for view change
     */
    dispatchViewChange(viewName) {
        const event = new CustomEvent('viewchange', { detail: { view: viewName } });
        window.dispatchEvent(event);
    }

    /**
     * Setup connection monitoring
     */
    setupConnectionMonitoring() {
        this.checkConnection();

        // Check connection every 5 seconds
        this.connectionCheckInterval = setInterval(() => {
            this.checkConnection();
        }, 5000);

        // Make the connection status clickable
        const statusWrapper = document.getElementById('status-wrapper');
        if (statusWrapper) {
            statusWrapper.addEventListener('click', (e) => {
                e.stopPropagation();
                this.togglePopover();
            });
        }

        // Close popover when clicking outside
        document.addEventListener('click', () => {
            if (this.popoverOpen) {
                this.closePopover();
            }
        });
    }

    /**
     * Fill the setup view's endpoint placeholders with the actual host
     * and OTLP ports (#73). The host is where the browser reached the
     * dashboard (correct for remote browsing); the ports come from
     * /api/health, which reports the server's real receiver ports
     * (re-pointable via OTELITE_OTLP_GRPC_PORT / OTELITE_OTLP_HTTP_PORT).
     */
    async setupEndpointPlaceholders() {
        const setupView = document.getElementById('setup-view');
        if (!setupView) return;
        let grpcPort = 4317;
        let httpPort = 4318;
        try {
            const health = this.lastHealthData || (await api.getHealth());
            if (Number.isFinite(health.otlp_grpc_port)) grpcPort = health.otlp_grpc_port;
            if (Number.isFinite(health.otlp_http_port)) httpPort = health.otlp_http_port;
        } catch (err) {
            // Keep the standard defaults — the placeholders are still
            // filled with the browser's host.
        }
        const host =
            (typeof window !== 'undefined' && window.location && window.location.hostname) || 'localhost';
        setupView.innerHTML = fillEndpointPlaceholders(setupView.innerHTML, host, grpcPort, httpPort);
    }

    /**
     * Check connection to backend
     */
    async checkConnection() {
        const indicator = document.getElementById('status-indicator');
        const text = document.getElementById('status-text');

        try {
            const health = await api.getHealth();
            this.lastHealthData = health;
            indicator.classList.remove('disconnected');
            text.textContent = 'Connected';
            if (this.popoverOpen) {
                this.refreshPopover();
            }
        } catch (error) {
            this.lastHealthData = null;
            indicator.classList.add('disconnected');
            text.textContent = 'Disconnected';
            console.error('Connection check failed:', error);
            if (this.popoverOpen) {
                this.closePopover();
            }
        }
    }

    /**
     * Format uptime seconds into human-readable string (e.g. "2h 14m")
     */
    formatUptime(seconds) {
        if (seconds < 60) return `${seconds}s`;
        const mins = Math.floor(seconds / 60) % 60;
        const hours = Math.floor(seconds / 3600) % 24;
        const days = Math.floor(seconds / 86400);
        const parts = [];
        if (days > 0) parts.push(`${days}d`);
        if (hours > 0) parts.push(`${hours}h`);
        if (mins > 0) parts.push(`${mins}m`);
        return parts.join(' ') || '0m';
    }

    /**
     * Toggle the status popover
     */
    async togglePopover() {
        if (this.popoverOpen) {
            this.closePopover();
        } else {
            await this.openPopover();
        }
    }

    /**
     * Open the status popover and populate it
     */
    async openPopover() {
        this.popoverOpen = true;
        const popover = document.getElementById('status-popover');
        if (!popover) return;
        popover.classList.add('visible');
        await this.refreshPopover();
    }

    /**
     * Refresh popover content with latest health + stats data
     */
    async refreshPopover() {
        const popover = document.getElementById('status-popover');
        if (!popover) return;

        const health = this.lastHealthData;
        if (!health) {
            popover.innerHTML = '<div class="popover-row popover-error">Server unreachable</div>';
            return;
        }

        let statsHtml = '<div class="popover-row">Loading counts…</div>';
        try {
            const stats = await api.getStats();
            statsHtml = `
                <div class="popover-row"><span class="popover-label">Logs</span><span class="popover-value">${stats.log_count.toLocaleString()}</span></div>
                <div class="popover-row"><span class="popover-label">Traces</span><span class="popover-value">${stats.span_count.toLocaleString()}</span></div>
                <div class="popover-row"><span class="popover-label">Metric points</span><span class="popover-value">${stats.metric_count.toLocaleString()}</span></div>`;
        } catch (_) {
            statsHtml = '<div class="popover-row popover-error">Could not load counts</div>';
        }

        popover.innerHTML = `
            <div class="popover-row"><span class="popover-label">Version</span><span class="popover-value">${health.version}</span></div>
            <div class="popover-row"><span class="popover-label">Uptime</span><span class="popover-value">${this.formatUptime(health.uptime_seconds)}</span></div>
            <div class="popover-divider"></div>
            ${statsHtml}
            <div class="popover-divider"></div>
            <div class="popover-row"><span class="popover-label">gRPC</span><span class="popover-value">:${health.otlp_grpc_port || 4317}</span></div>
            <div class="popover-row"><span class="popover-label">HTTP</span><span class="popover-value">:${health.otlp_http_port || 4318}</span></div>
            <div class="popover-divider"></div>
            <div class="popover-row popover-action-row"><button class="popover-danger-btn" onclick="app.clearAllData()">Clear all data</button></div>`;
    }

    /**
     * Close the status popover
     */
    closePopover() {
        this.popoverOpen = false;
        const popover = document.getElementById('status-popover');
        if (popover) {
            popover.classList.remove('visible');
        }
    }

    /**
     * Delete all telemetry data after user confirmation
     */
    async clearAllData() {
        if (!confirm('Delete all telemetry data? This cannot be undone.')) {
            return;
        }
        try {
            const response = await fetch('/api/admin/purge', { method: 'POST' });
            if (!response.ok) {
                const popover = document.getElementById('status-popover');
                if (popover) {
                    const errRow = document.createElement('div');
                    errRow.className = 'popover-row popover-error';
                    errRow.textContent = `Clear failed: HTTP ${response.status}`;
                    popover.prepend(errRow);
                }
                return;
            }
            const popover = document.getElementById('status-popover');
            if (popover) {
                const okRow = document.createElement('div');
                okRow.className = 'popover-row';
                okRow.style.color = '#4ade80';
                okRow.textContent = 'All data cleared.';
                popover.prepend(okRow);
                setTimeout(() => okRow.remove(), 3000);
            }
            await this.refreshPopover();
        } catch (err) {
            const popover = document.getElementById('status-popover');
            if (popover) {
                const errRow = document.createElement('div');
                errRow.className = 'popover-row popover-error';
                errRow.textContent = `Clear failed: ${err.message}`;
                popover.prepend(errRow);
            }
        }
    }

    /**
     * Load initial view
     */
    loadInitialView() {
        this.switchView(this.currentView);
    }

    /**
     * Show loading overlay
     */
    showLoading() {
        document.getElementById('loading-overlay').classList.remove('hidden');
    }

    /**
     * Hide loading overlay
     */
    hideLoading() {
        document.getElementById('loading-overlay').classList.add('hidden');
    }
}

// Initialize app when DOM is ready
if (typeof document !== 'undefined') {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            window.app = new App();
        });
    } else {
        window.app = new App();
    }
}

// Export for use in other modules
export { App };