chore: full stack stability and migration fixes, plus react UI progress
Some checks failed
CI / podman-build (push) Has been cancelled
CI / rust (push) Has been cancelled

This commit is contained in:
2026-03-18 09:01:38 +02:00
parent 38cab8c246
commit a66d908eff
142 changed files with 12210 additions and 3402 deletions

View File

@@ -1,20 +1,24 @@
const { createApp } = Vue;
const API_BASE = '/platform/v1';
const API = '/platform/v1';
createApp({
data() {
return {
currentTab: 'dashboard',
gatewayStatus: 'Checking...',
serviceKey: '',
// Auth State
// Auth
isAuthenticated: false,
isVerifyingAuth: true,
isLoggingIn: false,
adminPassword: '',
loginError: null,
csrfToken: '',
// UI
currentTab: 'dashboard',
gatewayStatus: 'Checking...',
errorMessage: '',
grafanaUrl: window.MADBASE_GRAFANA_URL || '/grafana',
appVersion: '',
// Dashboard
projects: [],
newProjectName: '',
@@ -23,6 +27,12 @@ createApp({
metricsInterval: null,
pillars: [],
pillarInterval: null,
chart: null,
// Auth Management
authUsers: [],
authUserSearch: '',
selectedAuthUser: null,
// Functions
functions: [],
@@ -47,6 +57,7 @@ createApp({
wsChannel: 'room:lobby',
wsMessages: [],
wsInput: '{"event":"broadcast","payload":{"message":"Hello"}}',
rtStats: { connections: 0, channels: 0, events: 0 },
// Logs
logQuery: '{app="gateway"}',
@@ -54,21 +65,59 @@ createApp({
logs: []
}
},
computed: {
filteredAuthUsers() {
if (!this.authUserSearch) return this.authUsers;
const q = this.authUserSearch.toLowerCase();
return this.authUsers.filter(u =>
(u.email || '').toLowerCase().includes(q) ||
(u.id || '').toLowerCase().includes(q)
);
}
},
async mounted() {
console.log('MadBase Studio: Mounting...');
await this.checkAuth();
this.isVerifyingAuth = false;
},
methods: {
async checkAuth() {
// Quick check if we can access the platform API
// ─── Error Handling ───
showError(msg) {
this.errorMessage = msg;
setTimeout(() => this.errorMessage = '', 5000);
},
async apiCall(url, options = {}) {
try {
const res = await fetch(`${API_BASE}/projects`);
// Add CSRF token to mutations
if (options.method && options.method !== 'GET') {
options.headers = options.headers || {};
options.headers['X-CSRF-Token'] = this.csrfToken;
}
const resp = await fetch(url, options);
if (!resp.ok) {
let errMsg = 'Request failed';
try {
const err = await resp.json();
errMsg = err.error || err.message || errMsg;
} catch { /* ignore */ }
this.showError(errMsg);
return null;
}
return resp;
} catch (e) {
this.showError(e.message || 'Network error');
return null;
}
},
// ─── Auth ───
async checkAuth() {
try {
const res = await fetch(`${API}/projects`);
if (res.status === 401) {
this.isAuthenticated = false;
} else {
this.isAuthenticated = true;
this.onAuthenticated();
await this.onAuthenticated();
}
} catch {
this.isAuthenticated = false;
@@ -78,15 +127,15 @@ createApp({
this.isLoggingIn = true;
this.loginError = null;
try {
const res = await fetch(`${API_BASE}/login`, {
const res = await fetch(`${API}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: this.adminPassword })
});
if (res.ok) {
this.isAuthenticated = true;
this.onAuthenticated();
this.adminPassword = '';
await this.onAuthenticated();
} else {
this.loginError = 'Invalid admin password';
}
@@ -96,11 +145,43 @@ createApp({
this.isLoggingIn = false;
}
},
async logout() {
await fetch(`${API}/logout`, { method: 'POST' });
this.isAuthenticated = false;
this.projects = [];
this.users = [];
this.authUsers = [];
this.functions = [];
this.buckets = [];
this.objects = [];
this.pillars = [];
this.csrfToken = '';
if (this.metricsInterval) clearInterval(this.metricsInterval);
if (this.pillarInterval) clearInterval(this.pillarInterval);
if (this.ws) { this.ws.close(); this.wsConnected = false; }
this.currentTab = 'dashboard';
},
async onAuthenticated() {
// First fetch config (service key)
await this.fetchAdminConfig();
// Then init regular data
// Fetch CSRF token
try {
const res = await fetch(`${API}/csrf-token`);
if (res.ok) {
const data = await res.json();
this.csrfToken = data.token;
}
} catch { /* ignore */ }
// Fetch admin config
try {
const res = await fetch(`${API}/admin/config`);
if (res.ok) {
const data = await res.json();
this.grafanaUrl = data.grafana_url || this.grafanaUrl;
this.appVersion = data.version || '';
}
} catch { /* ignore */ }
// Init data
this.checkHealth();
this.fetchProjects();
this.fetchUsers();
@@ -112,19 +193,9 @@ createApp({
this.metricsInterval = setInterval(this.fetchMetrics, 5000);
if (this.pillarInterval) clearInterval(this.pillarInterval);
this.pillarInterval = setInterval(this.fetchPillars, 5000);
console.log('MadBase Studio: Ready.');
},
async fetchAdminConfig() {
try {
const res = await fetch(`${API_BASE}/admin/config`);
const data = await res.json();
this.serviceKey = data.service_role_key;
console.log('MadBase Studio: Service Key Provisioned.');
} catch (e) {
console.error('Failed to fetch admin config:', e);
}
},
// Dashboard
// ─── Dashboard ───
async checkHealth() {
try {
const res = await fetch('/');
@@ -132,108 +203,95 @@ createApp({
} catch { this.gatewayStatus = 'Offline'; }
},
async fetchProjects() {
try {
const res = await fetch(`${API_BASE}/projects`);
this.projects = await res.json();
} catch (e) { console.error(e); }
const res = await this.apiCall(`${API}/projects`);
if (res) this.projects = await res.json();
},
async createProject() {
if (!this.newProjectName) return;
await fetch(`${API_BASE}/projects`, {
const res = await this.apiCall(`${API}/projects`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: this.newProjectName, owner_id: null })
});
this.newProjectName = '';
this.fetchProjects();
if (res) {
this.newProjectName = '';
this.fetchProjects();
}
},
async deleteProject(id) {
if (!confirm('Are you sure you want to delete this project?')) return;
await fetch(`${API_BASE}/projects/${id}`, { method: 'DELETE' });
this.fetchProjects();
async deleteProject(id, name) {
if (!confirm(`Delete project "${name || id}"? This cannot be undone.`)) return;
const res = await this.apiCall(`${API}/projects/${id}`, { method: 'DELETE' });
if (res) this.fetchProjects();
},
async fetchUsers() {
try {
const res = await fetch(`${API_BASE}/users`);
this.users = await res.json();
} catch (e) { console.error(e); }
const res = await this.apiCall(`${API}/users`);
if (res) this.users = await res.json();
},
async deleteUser(id) {
if (!confirm('Are you sure you want to delete this user?')) return;
await fetch(`${API_BASE}/users/${id}`, { method: 'DELETE' });
this.fetchUsers();
if (!confirm(`Delete user ${id}? This cannot be undone.`)) return;
const res = await this.apiCall(`${API}/users/${id}`, { method: 'DELETE' });
if (res) this.fetchUsers();
},
async fetchMetrics() {
try {
const res = await fetch('/metrics');
const text = await res.text();
this.metrics = text.split('\n').filter(l => !l.startsWith('#') && l.trim()).slice(0, 20).join('\n');
// Parse for chart
const match = text.match(/axum_http_requests_total\{.*?\} (\d+)/);
if (match && this.chart) {
const val = parseInt(match[1]);
const now = new Date().toLocaleTimeString();
this.chart.data.labels.push(now);
this.chart.data.datasets[0].data.push(val);
if (this.chart.data.labels.length > 20) {
this.chart.data.labels.shift();
this.chart.data.datasets[0].data.shift();
}
this.chart.update('none');
}
} catch {}
} catch { /* ignore */ }
},
async fetchPillars() {
try {
const res = await fetch(`${API_BASE}/cluster/pillars`);
if (res.ok) {
this.pillars = await res.json();
}
} catch (e) { console.error('Pillar fetch failed:', e); }
const res = await this.apiCall(`${API}/cluster/pillars`);
if (res) {
try { this.pillars = await res.json(); } catch { /* ignore */ }
}
},
async scalePillar(pillar, direction) {
const p = this.pillars.find(x => x.pillar === pillar);
if (!p) return;
const targetCount = direction === 'up' ? p.node_count + 1 : p.node_count - 1;
if (targetCount < 1) return;
const req = {
provider: 'hetzner', // Default for now
provider: 'hetzner',
target_worker_count: pillar === 'worker' ? targetCount : undefined,
target_db_count: pillar === 'database' ? targetCount : undefined,
target_control_count: pillar === 'proxyapi' ? targetCount : undefined,
};
try {
const res = await fetch(`${API_BASE}/cluster/scale-plan`, {
const res = await this.apiCall(`${API}/cluster/scale-plan`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(req)
});
if (!res) return;
const plan = await res.json();
if (confirm(`Scaling ${pillar} to ${targetCount} nodes. Monthly cost: €${plan.total_cost_monthly}. Proceed?`)) {
await this.apiCall(`${API}/cluster/scale-execute`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(req)
body: JSON.stringify(plan.scaling_plan)
});
const plan = await res.json();
if (confirm(`Scaling ${pillar} to ${targetCount} nodes. Monthly cost impact: €${plan.total_cost_monthly}. Proceed?`)) {
await fetch(`${API_BASE}/cluster/scale-execute`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(plan.scaling_plan)
});
this.fetchPillars();
}
} catch (e) { alert('Scaling failed: ' + e.message); }
this.fetchPillars();
}
},
initChart() {
if (typeof Chart === 'undefined') {
console.warn('MadBase Studio: Chart.js is not loaded yet.');
return;
}
if (typeof Chart === 'undefined') return;
const ctx = document.getElementById('metricsChart');
if (!ctx) return;
this.chart = new Chart(ctx, {
type: 'line',
data: {
@@ -242,39 +300,47 @@ createApp({
label: 'HTTP Requests',
data: [],
borderColor: '#0ea5e9',
backgroundColor: 'rgba(14, 165, 233, 0.1)',
fill: true,
tension: 0.4,
borderWidth: 2,
pointRadius: 0,
pointHoverRadius: 4
backgroundColor: 'rgba(14,165,233,0.1)',
fill: true, tension: 0.4, borderWidth: 2,
pointRadius: 0, pointHoverRadius: 4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
responsive: true, maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
x: { display: false },
y: {
beginAtZero: false,
grid: { color: 'rgba(0,0,0,0.05)' },
ticks: { font: { size: 10 } }
}
y: { beginAtZero: false, grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { font: { size: 10 } } }
},
animation: { duration: 0 }
}
});
},
// Functions
// ─── Auth Management ───
async fetchAuthUsers() {
const res = await this.apiCall(`${API}/users`);
if (res) this.authUsers = await res.json();
},
selectAuthUser(user) {
this.selectedAuthUser = user;
},
async deleteAuthUser(id) {
if (!confirm(`Delete user ${id}? This cannot be undone.`)) return;
const res = await this.apiCall(`${API}/users/${id}`, { method: 'DELETE' });
if (res) {
this.selectedAuthUser = null;
this.fetchAuthUsers();
this.fetchUsers();
}
},
// ─── Functions ───
async fetchFunctions() {
try {
const res = await fetch('/functions/v1', {
headers: { 'x-project-ref': 'default', 'Authorization': `Bearer ${this.serviceKey}` }
});
this.functions = await res.json();
} catch (e) { console.error(e); }
const res = await this.apiCall(`${API}/functions`);
if (res) {
try { this.functions = await res.json(); } catch { this.functions = []; }
}
},
initNewFunction() {
this.selectedFunction = { name: 'new-func' };
@@ -284,129 +350,102 @@ createApp({
async deployFunction() {
this.isDeploying = true;
try {
const payload = {
name: this.newFunctionName,
runtime: 'deno',
code_base64: btoa(this.newFunctionCode)
};
const res = await fetch('/functions/v1', {
const payload = { name: this.newFunctionName, runtime: 'deno', code_base64: btoa(this.newFunctionCode) };
const res = await this.apiCall(`${API}/functions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-project-ref': 'default',
'Authorization': `Bearer ${this.serviceKey}`
},
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (res.ok) {
alert('Function deployed successfully!');
if (res) {
this.showError(''); // Clear any error
this.fetchFunctions();
this.selectedFunction = null; // Clear view
} else {
alert('Deployment failed: ' + await res.text());
this.selectedFunction = null;
}
} catch (e) { alert('Deployment error: ' + e); }
finally { this.isDeploying = false; }
} finally { this.isDeploying = false; }
},
async selectFunction(name) {
try {
const res = await fetch(`/functions/v1/${name}`, {
headers: { 'x-project-ref': 'default', 'Authorization': `Bearer ${this.serviceKey}` }
});
const res = await this.apiCall(`${API}/functions/${name}`);
if (res) {
const func = await res.json();
this.selectedFunction = func;
this.newFunctionName = func.name;
this.newFunctionCode = atob(func.code);
} catch (e) { console.error(e); }
}
},
// Database
// ─── Database ───
async fetchTables() {
try {
const res = await fetch(`${API_BASE}/db/tables`);
this.tables = await res.json();
} catch (e) { console.error(e); }
const res = await this.apiCall(`${API}/db/tables`);
if (res) this.tables = await res.json();
},
async selectTable(t) {
this.selectedTable = t;
this.tableData = [];
try {
const res = await fetch(`${API_BASE}/db/tables/${t.schema}/${t.name}`);
this.tableData = await res.json();
} catch (e) { console.error(e); }
const res = await this.apiCall(`${API}/db/tables/${t.schema}/${t.name}`);
if (res) this.tableData = await res.json();
},
// Storage
// ─── Storage (admin-proxied, no service key) ───
async fetchBuckets() {
try {
const res = await fetch('/storage/v1/bucket', {
headers: { 'Authorization': `Bearer ${this.serviceKey}`, 'x-project-ref': 'default' }
});
this.buckets = await res.json();
} catch (e) { alert('Failed to fetch buckets. Check Service Key.'); }
const res = await this.apiCall(`${API}/storage/buckets`);
if (res) this.buckets = await res.json();
},
async selectBucket(id) {
this.selectedBucket = id;
this.objects = [];
try {
const res = await fetch(`/storage/v1/object/list/${id}`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${this.serviceKey}`, 'x-project-ref': 'default' }
});
this.objects = await res.json();
} catch (e) { console.error(e); }
const res = await this.apiCall(`${API}/storage/buckets/${id}/objects`, { method: 'POST' });
if (res) this.objects = await res.json();
},
async uploadFile(event) {
const file = event.target.files[0];
if (!file || !this.selectedBucket) return;
try {
await fetch(`/storage/v1/object/${this.selectedBucket}/${file.name}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.serviceKey}`,
'x-project-ref': 'default',
'Content-Type': file.type || 'application/octet-stream'
},
body: file
});
this.selectBucket(this.selectedBucket); // Refresh
alert('Upload successful');
} catch (e) { alert('Upload failed'); }
const res = await this.apiCall(`${API}/storage/upload/${this.selectedBucket}/${file.name}`, {
method: 'POST',
headers: { 'Content-Type': file.type || 'application/octet-stream' },
body: file
});
if (res) {
this.selectBucket(this.selectedBucket);
}
event.target.value = '';
},
async deleteObject(bucketId, objectName) {
if (!confirm(`Delete "${objectName}"?`)) return;
const res = await this.apiCall(`${API}/storage/${bucketId}/${objectName}`, { method: 'DELETE' });
if (res) this.selectBucket(bucketId);
},
getObjectUrl(name) {
return `/storage/v1/object/${this.selectedBucket}/${name}?token=SERVICE_ROLE_BYPASS_NOT_IMPLEMENTED`;
return `${API}/storage/${this.selectedBucket}/${name}`;
},
formatBytes(bytes, decimals = 2) {
if (!+bytes) return '0 Bytes';
if (!+bytes) return '0 B';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KiB', 'MiB', 'GiB'];
const sizes = ['B', 'KiB', 'MiB', 'GiB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
},
// Realtime
// ─── Realtime ───
toggleWs() {
if (this.wsConnected) {
this.ws.close();
this.wsConnected = false;
this.wsMessages.push({ type: 'sys', time: new Date().toLocaleTimeString(), data: 'Disconnected' });
} else {
const url = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/realtime/v1/websocket?apikey=${this.serviceKey}&vsn=1.0.0`;
const url = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/realtime/v1/websocket?vsn=1.0.0`;
this.ws = new WebSocket(url);
this.ws.onopen = () => {
this.wsConnected = true;
this.rtStats.connections++;
this.wsMessages.push({ type: 'sys', time: new Date().toLocaleTimeString(), data: 'Connected' });
this.sendJson({ event: 'phx_join', topic: this.wsChannel, payload: {}, ref: '1' });
};
this.ws.onmessage = (e) => {
this.rtStats.events++;
this.wsMessages.push({ type: 'in', time: new Date().toLocaleTimeString(), data: e.data });
if (this.wsMessages.length > 100) this.wsMessages.shift();
if (this.wsMessages.length > 200) this.wsMessages.shift();
};
this.ws.onclose = () => {
this.wsConnected = false;
this.wsMessages.push({ type: 'sys', time: new Date().toLocaleTimeString(), data: 'Connection Closed' });
@@ -419,31 +458,29 @@ createApp({
const payload = JSON.parse(this.wsInput);
const msg = { event: payload.event || 'broadcast', topic: this.wsChannel, payload: payload.payload || payload, ref: '2' };
this.sendJson(msg);
} catch (e) { alert('Invalid JSON'); }
} catch { this.showError('Invalid JSON'); }
},
sendJson(data) {
const str = JSON.stringify(data);
this.ws.send(str);
this.wsMessages.push({ type: 'out', time: new Date().toLocaleTimeString(), data: str });
},
clearWsMessages() {
this.wsMessages = [];
this.rtStats.events = 0;
},
// Logs
// ─── Logs ───
async fetchLogs() {
try {
const params = new URLSearchParams({
query: this.logQuery,
limit: this.logLimit
});
const res = await fetch(`${API_BASE}/logs?${params}`);
if (!res.ok) throw new Error(await res.text());
const params = new URLSearchParams({ query: this.logQuery, limit: this.logLimit });
const res = await this.apiCall(`${API}/logs?${params}`);
if (res) {
const data = await res.json();
if (data.data && data.data.result) {
this.logs = data.data.result.flatMap(r => r.values).sort((a, b) => b[0] - a[0]);
} else {
this.logs = [];
}
} catch (e) {
alert('Log fetch failed: ' + e.message);
}
}
},
@@ -452,6 +489,7 @@ createApp({
if (val === 'storage' && !this.buckets.length) this.fetchBuckets();
if (val === 'functions' && !this.functions.length) this.fetchFunctions();
if (val === 'database' && !this.tables.length) this.fetchTables();
if (val === 'auth' && !this.authUsers.length) this.fetchAuthUsers();
}
}
}).mount('#app');