Spaces:
Paused
Paused
Update static/js/app.js
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172183 unmodified lines222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446// static/js/app.jsdocument.addEventListener('DOMContentLoaded', () => {// --- STATE ---let migrationState = {};let updateInterval = null;let lastLogId = -1;let confirmAction = null;// --- SELECTORS ---const selectors = {// NavigationnavLinks: document.querySelectorAll('.nav-link'),pages: document.querySelectorAll('.page'),headerTitle: document.getElementById('header-title'),// StatusstatusBadge: document.getElementById('status-badge'),statusDot: document.querySelector('#status-badge .status-dot'),statusText: document.querySelector('#status-badge .status-text'),// DashboarddashboardStatusText: document.getElementById('dashboard-status-text'),dashboardGotoDump: document.getElementById('dashboard-goto-dump'),dashboardGotoRestore: document.getElementById('dashboard-goto-restore'),lastOpSummary: document.getElementById('last-operation-summary'),miniLogFeed: document.getElementById('mini-log-feed'),// ConnectionssourceConnInput: document.getElementById('source-conn'),targetConnInput: document.getElementById('target-conn'),toggleSourceVisibility: document.getElementById('toggle-source-visibility'),toggleTargetVisibility: document.getElementById('toggle-target-visibility'),testSourceBtn: document.getElementById('test-source-btn'),testTargetBtn: document.getElementById('test-target-btn'),sourceStatusDetails: document.getElementById('source-status-details'),targetStatusDetails: document.getElementById('target-status-details'),// DumpdumpConfigView: document.getElementById('dump-config-view'),dumpProgressView: document.getElementById('dump-progress-view'),startDumpBtn: document.getElementById('start-dump-btn'),stopDumpBtn: document.getElementById('stop-dump-btn'),dumpFormat: document.getElementById('dump-format'),dumpCompression: document.getElementById('dump-compression'),schemaFilter: document.getElementById('schema-filter'),dumpFilename: document.getElementById('dump-filename'),dumpElapsedTime: document.getElementById('dump-elapsed-time'),dumpFileSize: document.getElementById('dump-file-size'),dumpCurrentTable: document.getElementById('dump-current-table'),dumpSizeProgressBar: document.getElementById('dump-size-progress-bar'),dumpSizeProgressText: document.getElementById('dump-size-progress-text'),dumpSizeSubtext: document.getElementById('dump-size-subtext'),dumpCountProgressBar: document.getElementById('dump-count-progress-bar'),dumpCountProgressText: document.getElementById('dump-count-progress-text'),dumpCountSubtext: document.getElementById('dump-count-subtext'),// RestorerestoreConfigView: document.getElementById('restore-config-view'),restoreProgressView: document.getElementById('restore-progress-view'),startRestoreBtn: document.getElementById('start-restore-btn'),stopRestoreBtn: document.getElementById('stop-restore-btn'),serverBackupFile: document.getElementById('server-backup-file'),restoreElapsedTime: document.getElementById('restore-elapsed-time'),restoreTablesCompleted: document.getElementById('restore-tables-completed'),restoreCurrentTable: document.getElementById('restore-current-table'),// LogslogOutput: document.getElementById('log-output'),logAutoscrollToggle: document.getElementById('log-autoscroll-toggle'),// ModalconfirmModal: document.getElementById('confirm-modal'),confirmModalTitle: document.getElementById('confirm-modal-title'),confirmModalBody: document.getElementById('confirm-modal-body'),closeConfirmModal: document.getElementById('close-confirm-modal'),cancelConfirmBtn: document.getElementById('cancel-confirm-btn'),confirmActionBtn: document.getElementById('confirm-action-btn'),};// --- UTILITY FUNCTIONS ---const formatBytes = (bytes, decimals = 2) => {if (bytes === 0) return '0 B';const k = 1024;const dm = decimals < 0 ? 0 : decimals;const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];const i = Math.floor(Math.log(bytes) / Math.log(k));return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];};const formatDuration = (seconds) => {if (seconds < 0) seconds = 0;const h = Math.floor(seconds / 3600).toString().padStart(2, '0');const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');const s = Math.floor(seconds % 60).toString().padStart(2, '0');return `${h}:${m}:${s}`;};const showToast = (type, title, message) => {const container = document.getElementById('toast-container');const toast = document.createElement('div');toast.className = `toast ${type}`;const icons = { success: 'fa-check-circle', error: 'fa-times-circle' };toast.innerHTML = `<i class="fas ${icons[type]} toast-icon"></i><div class="toast-body"><h4>${title}</h4><p>${message}</p></div>`;container.appendChild(toast);setTimeout(() => toast.remove(), 5000);};const navigateTo = (targetId) => {selectors.pages.forEach(p => p.classList.remove('active'));document.getElementById(`${targetId}-page`).classList.add('active');selectors.navLinks.forEach(l => l.classList.remove('active'));const activeLink = document.querySelector(`.nav-link[data-target="${targetId}"]`);activeLink.classList.add('active');selectors.headerTitle.textContent = activeLink.querySelector('span').textContent;};// --- UI RENDERING ---const renderUI = (state) => {migrationState = state;// Global Status Badgeif (state.running) {const operationText = state.operation === 'dump' ? 'Dumping' : 'Restoring';selectors.statusBadge.className = 'status-badge running';selectors.statusText.textContent = operationText;} else if (state.dump_completed || state.restore_completed) {selectors.statusBadge.className = 'status-badge success';selectors.statusText.textContent = 'Completed';} else if (state.end_time && !state.dump_completed && !state.restore_completed) {selectors.statusBadge.className = 'status-badge error';selectors.statusText.textContent = 'Failed/Stopped';} else {selectors.statusBadge.className = 'status-badge idle';selectors.statusText.textContent = 'Idle';}// DashboardrenderDashboard(state);// Dump Pageif (state.operation === 'dump') {selectors.dumpConfigView.classList.toggle('hidden', state.running);selectors.dumpProgressView.classList.toggle('hidden', !state.running);if (state.running) {renderDumpProgress(state);}} else { // If not dumping, show configselectors.dumpConfigView.classList.remove('hidden');selectors.dumpProgressView.classList.add('hidden');}// Restore Pageif (state.operation === 'restore') {selectors.restoreConfigView.classList.toggle('hidden', state.running);selectors.restoreProgressView.classList.toggle('hidden', !state.running);if(state.running) {renderRestoreProgress(state);}} else {selectors.restoreConfigView.classList.remove('hidden');selectors.restoreProgressView.classList.add('hidden');}// LogsrenderLogs(state.log);};const renderDashboard = (state) => {if (state.running) {const opText = state.operation === 'dump' ? 'A database dump' : 'A database restore';selectors.dashboardStatusText.textContent = `${opText} is currently in progress.`;} else {selectors.dashboardStatusText.textContent = 'The system is currently idle and ready for a new operation.';}if (state.end_time) {const success = state.dump_completed || state.restore_completed;const duration = formatDuration(state.end_time - state.start_time);const op = state.operation === 'dump' ? 'Dump' : 'Restore';selectors.lastOpSummary.innerHTML = `<p class="op-status ${success ? 'success' : 'error'}"><i class="fas ${success ? 'fa-check-circle' : 'fa-times-circle'}"></i>${op} ${success ? 'Completed' : 'Failed/Stopped'}</p><div class="op-details"><span>Duration:</span><strong>${duration}</strong>${state.operation === 'dump' ? `<span>File Size:</span><strong>${formatBytes(state.dump_file_size * 1024 * 1024)}</strong>` : ''}</div>`;} else {selectors.lastOpSummary.innerHTML = `<p class="text-muted">No operations have been run yet.</p>`;}};const renderDumpProgress = (state) => {const elapsed = state.start_time ? (Date.now() / 1000) - state.start_time : 0;selectors.dumpElapsedTime.textContent = formatDuration(elapsed);selectors.dumpFileSize.textContent = formatBytes(state.dump_file_size * 1024 * 1024);selectors.dumpCurrentTable.textContent = state.progress.current_table || '-';const { progress } = state;selectors.dumpSizeProgressBar.style.width = `${progress.percent_complete_by_size}%`;selectors.dumpSizeProgressText.textContent = `${progress.percent_complete_by_size.toFixed(2)}%`;selectors.dumpSizeSubtext.textContent = `${formatBytes(progress.size_processed_bytes)} / ${formatBytes(progress.total_size_bytes)}`;selectors.dumpCountProgressBar.style.width = `${progress.percent_complete_by_count}%`;selectors.dumpCountProgressText.textContent = `${progress.percent_complete_by_count.toFixed(2)}%`;selectors.dumpCountSubtext.textContent = `${progress.chunks_processed} / ${progress.total_chunks} Chunks`;};const renderRestoreProgress = (state) => {const elapsed = state.start_time ? (Date.now() / 1000) - state.start_time : 0;selectors.restoreElapsedTime.textContent = formatDuration(elapsed);selectors.restoreTablesCompleted.textContent = state.progress.tables_completed;selectors.restoreCurrentTable.textContent = state.progress.current_table || '-';};const renderLogs = (logs) => {3 unmodified linesnewLogs.forEach(log => {const entry = document.createElement('div');entry.className = 'log-entry';entry.innerHTML = `<span class="timestamp">${log.timestamp}</span><span class="level level-${log.level}">${log.level.toUpperCase()}</span><span class="message">${log.message}</span>`;fragment.appendChild(entry);});selectors.logOutput.appendChild(fragment);lastLogId = newLogs[newLogs.length - 1].id;if (selectors.logAutoscrollToggle.checked) {selectors.logOutput.scrollTop = selectors.logOutput.scrollHeight;}}// Update mini log feed on dashboardconst recentLogs = logs.slice(-5).reverse();selectors.miniLogFeed.innerHTML = recentLogs.map(log => `<div class="mini-log-entry"><span class="timestamp">${log.timestamp.split(' ')[1]}</span><span class="level level-${log.level}">${log.level.toUpperCase()}</span><span class="message">${log.message}</span></div>`).join('');};// --- API CALLS ---const updateStatus = async () => {try {const response = await fetch('/status');if (!response.ok) throw new Error('Network response was not ok');const state = await response.json();renderUI(state);// If process is finished, stop pollingif (!state.running && updateInterval) {clearInterval(updateInterval);updateInterval = null;}} catch (error) {console.error('Failed to fetch status:', error);if (updateInterval) {clearInterval(updateInterval);updateInterval = null;}// You might want to show a "disconnected" message here}};const startPolling = () => {if (!updateInterval) {updateStatus(); // Initial callupdateInterval = setInterval(updateStatus, 1500);}};const testConnection = async (connString, detailsElement) => {detailsElement.innerHTML = `<p><i class="fas fa-spinner fa-spin"></i> Testing connection...</p>`;try {const response = await fetch('/test-connection', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ connection_string: connString }),});const data = await response.json();if (data.success) {detailsElement.innerHTML = `<p class="success"><i class="fas fa-check-circle"></i> Connection successful!</p><p><strong>DB:</strong> ${data.database}</p><p><strong>Version:</strong> ${data.is_timescaledb ? `TimescaleDB ${data.timescaledb_version}` : 'PostgreSQL'}</p>`;} else {detailsElement.innerHTML = `<p class="error"><i class="fas fa-times-circle"></i> ${data.message}</p>`;}} catch (error) {detailsElement.innerHTML = `<p class="error"><i class="fas fa-exclamation-triangle"></i> Request failed. Is the server running?</p>`;}};const loadServerBackups = async () => {try {const response = await fetch('/list-dumps');const data = await response.json();selectors.serverBackupFile.innerHTML = '';if (data.dumps && data.dumps.length > 0) {data.dumps.forEach(d => {const option = document.createElement('option');option.value = d.path;option.textContent = `${d.name} (${d.size_mb.toFixed(2)} MB)`;selectors.serverBackupFile.appendChild(option);});} else {selectors.serverBackupFile.innerHTML = '<option value="" disabled>No backups found</option>';}} catch (error) {console.error('Failed to load backups:', error);selectors.serverBackupFile.innerHTML = '<option value="" disabled>Error loading backups</option>';}};// --- EVENT LISTENERS ---selectors.navLinks.forEach(link => {link.addEventListener('click', (e) => {e.preventDefault();navigateTo(link.dataset.target);});});selectors.dashboardGotoDump.addEventListener('click', () => navigateTo('dump'));selectors.dashboardGotoRestore.addEventListener('click', () => navigateTo('restore'));selectors.toggleSourceVisibility.addEventListener('click', () => {const input = selectors.sourceConnInput;input.type = input.type === 'password' ? 'text' : 'password';});selectors.toggleTargetVisibility.addEventListener('click', () => {const input = selectors.targetConnInput;input.type = input.type === 'password' ? 'text' : 'password';});selectors.testSourceBtn.addEventListener('click', () => testConnection(selectors.sourceConnInput.value, selectors.sourceStatusDetails));selectors.testTargetBtn.addEventListener('click', () => testConnection(selectors.targetConnInput.value, selectors.targetStatusDetails));selectors.startDumpBtn.addEventListener('click', async () => {if (!selectors.sourceConnInput.value) {return showToast('error', 'Missing Input', 'Source connection string is required.');}try {const response = await fetch('/start-dump', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({source_conn: selectors.sourceConnInput.value,options: {format: selectors.dumpFormat.value,compression: selectors.dumpCompression.value,schema: selectors.schemaFilter.value,filename: selectors.dumpFilename.value,}})});const data = await response.json();if (data.success) {showToast('success', 'Dump Started', 'The database dump is now in progress.');startPolling();} else {showToast('error', 'Failed to Start', data.detail || 'An unknown error occurred.');}} catch (error) {showToast('error', 'Request Failed', 'Could not start the dump process.');}});selectors.startRestoreBtn.addEventListener('click', async () => {if (!selectors.targetConnInput.value || !selectors.serverBackupFile.value) {return showToast('error', 'Missing Input', 'Target connection and a backup file are required.');}try {const response = await fetch('/start-restore', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({target_conn: selectors.targetConnInput.value,dump_file: selectors.serverBackupFile.value,options: {timescaledb_pre_restore: document.getElementById('timescaledb-pre-restore').checked,timescaledb_post_restore: document.getElementById('timescaledb-post-restore').checked,no_owner: document.getElementById('no-owner').checked,clean: document.getElementById('clean').checked,}})});const data = await response.json();if (data.success) {showToast('success', 'Restore Started', 'The database restore is now in progress.');startPolling();} else {showToast('error', 'Failed to Start', data.detail || 'An unknown error occurred.');}} catch (error) {showToast('error', 'Request Failed', 'Could not start the restore process.');}});const openConfirmModal = (action, title, body) => {confirmAction = action;selectors.confirmModalTitle.textContent = title;selectors.confirmModalBody.textContent = body;selectors.confirmModal.classList.remove('hidden');};const stopProcess = async () => {try {await fetch('/stop-process', { method: 'POST' });showToast('success', 'Stop Initiated', 'Attempting to stop the current operation.');// Polling will handle the UI update once the process is confirmed stopped.} catch (error) {showToast('error', 'Request Failed', 'Could not send stop command.');}};selectors.stopDumpBtn.addEventListener('click', () => {openConfirmModal('stop', 'Stop Dump?', 'Are you sure you want to stop the dump? The backup file will be incomplete.');});selectors.stopRestoreBtn.addEventListener('click', () => {openConfirmModal('stop', 'Stop Restore?', 'Are you sure? Stopping a restore may leave the target database in an inconsistent state.');});selectors.closeConfirmModal.addEventListener('click', () => selectors.confirmModal.classList.add('hidden'));selectors.cancelConfirmBtn.addEventListener('click', () => selectors.confirmModal.classList.add('hidden'));selectors.confirmActionBtn.addEventListener('click', () => {if (confirmAction === 'stop') {stopProcess();}selectors.confirmModal.classList.add('hidden');});// --- INITIALIZATION ---const initialize = () => {startPolling();loadServerBackups();};initialize();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511523 unmodified lines156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355// static/js/app.jsdocument.addEventListener('DOMContentLoaded', () => {// --- STATE & CONFIG ---let state = {};let updateInterval = null;let lastLogId = -1;let confirmAction = null;// --- DOM SELECTORS ---const $ = (selector) => document.querySelector(selector);const $$ = (selector) => document.querySelectorAll(selector);const elements = {sidebar: $('#sidebar'), menuToggle: $('#menu-toggle'), navLinks: $$('.nav-link'),pages: $$('.page'), headerTitle: $('#header-title'), statusBadge: $('#status-badge'),sourceConn: $('#source-conn'), targetConn: $('#target-conn'), testSourceBtn: $('#test-source-btn'),testTargetBtn: $('#test-target-btn'), sourceStatusCard: $('#source-status-card'),targetStatusCard: $('#target-status-card'), dumpConfigView: $('#dump-config-view'),dumpMonitoringView: $('#dump-monitoring-view'), startDumpBtn: $('#start-dump-btn'),dumpFormat: $('#dump-format'), dumpCompression: $('#dump-compression'),schemaFilter: $('#schema-filter'), dumpFilename: $('#dump-filename'),dumpCommandPreview: $('#dump-command-preview'), restoreConfigView: $('#restore-config-view'),restoreMonitoringView: $('#restore-monitoring-view'), startRestoreBtn: $('#start-restore-btn'),serverBackupFile: $('#server-backup-file'), restoreCommandPreview: $('#restore-command-preview'),logExplorer: $('.log-explorer'), logOutput: $('#log-output'), logLevelFilters: $('#log-level-filters'),logSearch: $('#log-search'), logAutoscroll: $('#log-autoscroll-toggle'),exportLogsBtn: $('#export-logs-btn'), clearLogsBtn: $('#clear-logs-btn'),confirmModal: $('#confirm-modal'), confirmModalTitle: $('#confirm-modal-title'),confirmModalBody: $('#confirm-modal-body'), cancelConfirmBtn: $('#cancel-confirm-btn'),confirmActionBtn: $('#confirm-action-btn'),};// --- UTILITY FUNCTIONS ---const formatBytes = (bytes, d=2) => (bytes===0)?'0 B':(k=1024,dm=d<0?0:d,sizes=['B','KB','MB','GB','TB'],i=Math.floor(Math.log(bytes)/Math.log(k)),parseFloat((bytes/Math.pow(k,i)).toFixed(dm))+' '+sizes[i]);const formatDuration = (s) => (s<0)&&(s=0), [Math.floor(s/3600),Math.floor(s%3600/60),Math.floor(s%60)].map(v=>v.toString().padStart(2,'0')).join(':');const showToast = (type, msg) => {const icon = type === 'success' ? 'fa-check-circle' : 'fa-times-circle';const toast = document.createElement('div');toast.className = `toast ${type}`;toast.innerHTML = `<i class="fas ${icon}"></i> <p>${msg}</p>`;$('#toast-container').appendChild(toast);setTimeout(() => toast.remove(), 4000);};const navigateTo = (targetId) => {elements.pages.forEach(p => p.classList.remove('active'));$(`#${targetId}-page`).classList.add('active');elements.navLinks.forEach(l => l.classList.remove('active'));const link = $(`[data-target="${targetId}"]`);link.classList.add('active');elements.headerTitle.textContent = link.querySelector('span').textContent;if (window.innerWidth <= 1024) elements.sidebar.classList.remove('open');};const apiFetch = async (endpoint, options) => {const response = await fetch(endpoint, options);if (!response.ok) {const err = await response.json();throw new Error(err.detail || 'API request failed');}return response.json();};// --- UI RENDERING ---const renderConnectionStatus = (card, data) => {if (data.loading) {card.innerHTML = `<div class="status-header"><i class="fas fa-spinner fa-spin"></i> Testing...</div>`;return;}if (!data.success) {card.innerHTML = `<div class="status-header error"><i class="fas fa-times-circle"></i> Connection Failed</div><p>${data.message}</p>`;return;}card.innerHTML = `<div class="status-header success"><i class="fas fa-check-circle"></i> Connected</div><div class="details-grid"><strong>Database:</strong><span>${data.database}</span><strong>PG Version:</strong><span>${data.version.split(' ')[1]}</span><strong>TSDB Version:</strong><span>${data.is_timescaledb ? data.timescaledb_version : 'N/A'}</span><strong>Tables:</strong><span id="${card.id}-tables">${data.table_count || '...'}</span><strong>Size:</strong><span id="${card.id}-size">${data.database_size || '...'}</span></div>`;};const createMonitoringView = (operation) => {const view = document.createElement('div');view.className = 'monitoring-card';view.innerHTML = `<div class="monitoring-header"><h3><i class="fas fa-sync fa-spin"></i> ${operation.charAt(0).toUpperCase() + operation.slice(1)} in Progress</h3><button id="stop-${operation}-btn" class="btn btn-danger"><i class="fas fa-stop"></i> Stop</button></div><div class="monitoring-stats"><div><span class="stat-label">Elapsed Time</span><span class="stat-value" id="${operation}-elapsed-time">00:00:00</span></div><div><span class="stat-label">Data Processed</span><span class="stat-value" id="${operation}-size-processed">-</span></div><div><span class="stat-label">Current Chunk</span><span class="stat-value" id="${operation}-current-table">-</span></div></div><div class="progress-tracker" id="${operation}-size-tracker"><label>Data Size Progress (<span id="${operation}-size-percent">0%</span>)</label><div class="progress-bar-container"><div id="${operation}-size-bar" class="progress-bar"></div></div><span class="progress-subtext" id="${operation}-size-subtext">0 B / 0 B</span></div><div class="progress-tracker" id="${operation}-count-tracker"><label>Chunk Count Progress (<span id="${operation}-count-percent">0%</span>)</label><div class="progress-bar-container"><div class="progress-bar secondary" id="${operation}-count-bar"></div></div><span class="progress-subtext" id="${operation}-count-subtext">0 / 0 Chunks</span></div><div class="monitoring-footer" id="${operation}-footer"></div>`;return view;};const updateMonitoringView = (operation, state) => {const elapsed = state.start_time ? (Date.now() / 1000) - state.start_time : 0;$(`#${operation}-elapsed-time`).textContent = formatDuration(elapsed);$(`#${operation}-current-table`).textContent = state.progress.current_table || '-';$(`#${operation}-size-processed`).textContent = formatBytes(state.progress.size_processed_bytes);if (state.progress.manifest_loaded) {$(`#${operation}-size-tracker`).classList.remove('hidden');$(`#${operation}-count-tracker`).classList.remove('hidden');$(`#${operation}-size-bar`).style.width = `${state.progress.percent_complete_by_size}%`;$(`#${operation}-size-percent`).textContent = `${state.progress.percent_complete_by_size.toFixed(2)}%`;$(`#${operation}-size-subtext`).textContent = `${formatBytes(state.progress.size_processed_bytes)} / ${formatBytes(state.progress.total_size_bytes)}`;$(`#${operation}-count-bar`).style.width = `${state.progress.percent_complete_by_count}%`;$(`#${operation}-count-percent`).textContent = `${state.progress.percent_complete_by_count.toFixed(2)}%`;$(`#${operation}-count-subtext`).textContent = `${state.progress.chunks_processed} / ${state.progress.total_chunks} Chunks`;} else {$(`#${operation}-size-tracker`).classList.add('hidden');$(`#${operation}-count-tracker`).classList.add('hidden');}};const renderGlobalStatus = (state) => {let statusClass = 'idle', statusText = 'Idle';if (state.running) {statusClass = 'running';statusText = state.operation === 'dump' ? 'Dumping' : 'Restoring';}elements.statusBadge.className = `status-badge ${statusClass}`;elements.statusBadge.querySelector('.status-text').textContent = statusText;};const filterLogs = () => {const level = elements.logLevelFilters.querySelector('.active').dataset.level;const search = elements.logSearch.value.toLowerCase();$$('#log-output .log-entry').forEach(entry => {const showLevel = level === 'all' || entry.dataset.level === level;const showSearch = !search || entry.textContent.toLowerCase().includes(search);entry.style.display = (showLevel && showSearch) ? 'flex' : 'none';});};const renderLogs = (logs) => {3 unmodified linesnewLogs.forEach(log => {const entry = document.createElement('div');entry.className = 'log-entry';entry.dataset.level = log.level;entry.innerHTML = `<span class="timestamp">${log.timestamp}</span><span class="level level-${log.level}">${log.level.toUpperCase()}</span><span class="message">${log.message}</span>`;fragment.appendChild(entry);});elements.logOutput.appendChild(fragment);lastLogId = newLogs[newLogs.length - 1].id;if (elements.logAutoscroll.checked) elements.logOutput.scrollTop = elements.logOutput.scrollHeight;filterLogs();}};const updateCommandPreviews = () => {// Dump Previewconst sourcePrev = elements.sourceConn.value ? elements.sourceConn.value.replace(/:(?!\/\/)([^@]+)@/, ':********@') : '...';elements.dumpCommandPreview.innerHTML = `<span class="keyword">pg_dump</span> <span class="value">"${sourcePrev}"</span> <span class="flag">-F${elements.dumpFormat.value}</span> <span class="flag">-v</span> ...`;// Restore Previewconst targetPrev = elements.targetConn.value ? elements.targetConn.value.replace(/:(?!\/\/)([^@]+)@/, ':********@') : '...';const filePrev = elements.serverBackupFile.selectedOptions[0]?.text.split(' ')[0] || '...';elements.restoreCommandPreview.innerHTML = `<span class="keyword">pg_restore</span> <span class="flag">-d</span> <span class="value">"${targetPrev}"</span> <span class="flag">-v</span> <span class="value">"${filePrev}"</span> ...`;};const restoreUiState = (state) => {if (state.running) {navigateTo(state.operation);const viewContainer = $(`#${state.operation}-monitoring-view`);viewContainer.innerHTML = '';viewContainer.appendChild(createMonitoringView(state.operation));$(`#${state.operation}-config-view`).classList.add('hidden');viewContainer.classList.remove('hidden');updateMonitoringView(state.operation, state);startPolling();} else if (state.end_time) { // Operation finishedif (state.operation === 'dump' && state.dump_completed) {const footer = $('#dump-footer');if(footer) {footer.innerHTML = `<a href="/downloads/${state.dump_file.split(/[\\/]/).pop()}" class="btn btn-secondary" target="_blank"><i class="fas fa-download"></i> Download</a><button id="goto-restore-btn" class="btn btn-primary"><i class="fas fa-upload"></i> Go to Restore</button>`;}}}};// --- API & WORKFLOWS ---const testConnection = async (connStr, card, type) => {if (!connStr) return;renderConnectionStatus(card, { loading: true });try {const data = await apiFetch('/test-connection', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ connection_string: connStr })});renderConnectionStatus(card, data);localStorage.setItem(`${type}_conn`, connStr);// Fetch extended infoconst info = await apiFetch('/database-info', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ connection_string: connStr })});if (info.success) {$(`#${card.id}-tables`).textContent = info.table_count;$(`#${card.id}-size`).textContent = info.database_size;}} catch (error) {renderConnectionStatus(card, { success: false, message: error.message });}};const loadServerBackups = async () => {try {const data = await apiFetch('/list-dumps');elements.serverBackupFile.innerHTML = data.dumps.length > 0? data.dumps.map(d => `<option value="${d.path}">${d.name} (${d.size_mb.toFixed(2)} MB)</option>`).join(''): '<option value="" disabled>No backups found</option>';} catch (error) {elements.serverBackupFile.innerHTML = '<option value="" disabled>Error loading backups</option>';}updateCommandPreviews();};const startOperation = async (operation) => {const isDump = operation === 'dump';const config = isDump ? {source_conn: elements.sourceConn.value,options: { format: elements.dumpFormat.value, compression: elements.dumpCompression.value, schema: elements.schemaFilter.value, filename: elements.dumpFilename.value }} : {target_conn: elements.targetConn.value, dump_file: elements.serverBackupFile.value,options: {timescaledb_pre_restore: $('#timescaledb-pre-restore').checked,timescaledb_post_restore: $('#timescaledb-post-restore').checked,no_owner: $('#no-owner').checked, clean: $('#clean').checked}};if ((isDump && !config.source_conn) || (!isDump && (!config.target_conn || !config.dump_file))) {return showToast('error', 'Please complete all required fields.');}try {await apiFetch(`/start-${operation}`, {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify(config)});showToast('success', `${operation.charAt(0).toUpperCase() + operation.slice(1)} process started.`);navigateTo(operation);restoreUiState({ running: true, operation: operation }); // Immediately switch view} catch (error) {showToast('error', `Failed to start ${operation}: ${error.message}`);}};// --- EVENT LISTENERS ---elements.menuToggle.addEventListener('click', () => elements.sidebar.classList.toggle('open'));elements.navLinks.forEach(link => link.addEventListener('click', e => { e.preventDefault(); navigateTo(link.dataset.target); }));elements.testSourceBtn.addEventListener('click', () => testConnection(elements.sourceConn.value, elements.sourceStatusCard, 'source'));elements.testTargetBtn.addEventListener('click', () => testConnection(elements.targetConn.value, elements.targetStatusCard, 'target'));[elements.sourceConn, elements.targetConn, elements.dumpFormat, elements.serverBackupFile].forEach(el => el.addEventListener('change', updateCommandPreviews));elements.startDumpBtn.addEventListener('click', () => {elements.confirmModalTitle.textContent = 'Confirm Dump';elements.confirmModalBody.textContent = 'Are you sure you want to start the dump process?';confirmAction = () => startOperation('dump');elements.confirmModal.classList.remove('hidden');});elements.startRestoreBtn.addEventListener('click', () => {elements.confirmModalTitle.textContent = 'Confirm Restore';elements.confirmModalBody.textContent = 'WARNING: This may overwrite data on the target database. Are you sure you want to proceed?';confirmAction = () => startOperation('restore');elements.confirmModal.classList.remove('hidden');});document.body.addEventListener('click', e => {if (e.target.matches('#stop-dump-btn') || e.target.matches('#stop-restore-btn')) {elements.confirmModalTitle.textContent = 'Confirm Stop';elements.confirmModalBody.textContent = 'Are you sure you want to stop the current operation?';confirmAction = async () => {try { await apiFetch('/stop-process', { method: 'POST' }); showToast('success', 'Stop command sent.'); }catch (error) { showToast('error', `Failed to stop: ${error.message}`); }};elements.confirmModal.classList.remove('hidden');}if (e.target.matches('#goto-restore-btn')) {const lastFile = state.dump_file;if (lastFile) {const option = Array.from(elements.serverBackupFile.options).find(opt => opt.value === lastFile);if (option) option.selected = true;}navigateTo('restore');updateCommandPreviews();}});elements.cancelConfirmBtn.addEventListener('click', () => elements.confirmModal.classList.add('hidden'));elements.confirmActionBtn.addEventListener('click', () => {if (confirmAction) confirmAction();elements.confirmModal.classList.add('hidden');});elements.logLevelFilters.addEventListener('click', e => {if (e.target.tagName === 'BUTTON') {elements.logLevelFilters.querySelector('.active').classList.remove('active');e.target.classList.add('active');filterLogs();}});elements.logSearch.addEventListener('input', filterLogs);elements.exportLogsBtn.addEventListener('click', () => {const content = Array.from($$('#log-output .log-entry')).map(e => e.textContent.trim()).join('\n');const blob = new Blob([content], { type: 'text/plain' });const a = document.createElement('a');a.href = URL.createObjectURL(blob);a.download = `migrator-logs-${new Date().toISOString()}.txt`;a.click();});elements.clearLogsBtn.addEventListener('click', () => {elements.logOutput.innerHTML = '';lastLogId = -1;});// --- INITIALIZATION ---const initialize = async () => {elements.sourceConn.value = localStorage.getItem('source_conn') || '';elements.targetConn.value = localStorage.getItem('target_conn') || '';updateCommandPreviews();await loadServerBackups();try {state = await apiFetch('/status');renderGlobalStatus(state);renderLogs(state.log);restoreUiState(state);} catch (e) {showToast('error', 'Could not connect to backend.');}};initialize();
static/js/app.js+273-364