ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(realtime): one room grammar + mirrored event constants (plan 77 E3)
Juan Denis00eac38d5de2
diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.pyindex 710fb494..de276e30 100644--- a/backend/app/agent_gateway.py+++ b/backend/app/agent_gateway.py@@ -13,6 +13,8 @@ import timefrom flask import requestfrom flask_socketio import Namespace, emit, disconnect+from app import sockets_rooms as rooms+from app.services.agent_registry import agent_registryfrom app.models.server import Server@@ -253,21 +255,21 @@ class AgentNamespace(Namespace):if not isinstance(channel, str) or not channel:return- # Broadcast to subscribers- # The channel format determines where to broadcast:- # - "metrics" -> room: f"server_{server_id}_metrics"- # - "container:xxx:logs" -> room: f"server_{server_id}_container_logs"+ # Broadcast to subscribers. The channel format determines the room+ # (grammar owned by app/sockets_rooms.py):+ # - "metrics" -> server_metrics_room+ # - "container:xxx:logs" -> server_container_logs_roomif channel == 'metrics':- room = f"server_{agent.server_id}_metrics"+ room = rooms.server_metrics_room(agent.server_id)elif channel.startswith('container:') and channel.endswith(':logs'):parts = channel.split(':')if len(parts) < 3:returncontainer_id = parts[1]- room = f"server_{agent.server_id}_container_{container_id}_logs"+ room = rooms.server_container_logs_room(agent.server_id, container_id)else:- room = f"server_{agent.server_id}_{channel}"+ room = rooms.server_channel_room(agent.server_id, channel)# Emit to the main namespace for UI clientsfrom app import get_socketiodiff --git a/backend/app/constants.py b/backend/app/constants.pynew file mode 100644index 00000000..6bb22559--- /dev/null+++ b/backend/app/constants.py@@ -0,0 +1,42 @@+"""Shared wire-protocol constants (plan 77 E3).++``SOCKET_EVENTS`` is mirrored verbatim by ``frontend/src/constants/events.js``+so a renamed event cannot fail silently — ``tests/test_socket_contract.py``+parses the JS file and asserts the two tables are identical. Add or rename an+event in BOTH files (the test tells you when you forgot).+"""++SOCKET_EVENTS = {+ # lifecycle / control plane+ 'CONNECTED': 'connected',+ 'ERROR': 'error',+ 'SUBSCRIBED': 'subscribed',+ 'UNSUBSCRIBED': 'unsubscribed',+ 'JOINED': 'joined',+ 'LEFT': 'left',++ # broadcast channels+ 'METRICS': 'metrics',+ 'CONTAINER_STATUS': 'container_status',+ 'NOTIFICATION': 'notification',++ # file log streaming+ 'LOG_LINE': 'log_line',+ 'LOG_ERROR': 'log_error',++ # deploy console (legacy names, dual-emitted with the run envelope)+ 'DEPLOY_LOG': 'deploy_log',+ 'DEPLOY_STATUS': 'deploy_status',++ # generalized run envelope (plan 77 E1) — one event pair for every run kind+ 'RUN_LOG': 'run_log',+ 'RUN_STATUS': 'run_status',++ # container log streaming+ 'CONTAINER_LOG': 'container_log',+ 'CONTAINER_LOG_ERROR': 'container_log_error',+ 'CONTAINER_LOG_ENDED': 'container_log_ended',++ # agent stream rebroadcast (metrics / PTY / arbitrary channels)+ 'SERVER_STREAM': 'server_stream',+}diff --git a/backend/app/notifications/service.py b/backend/app/notifications/service.pyindex e76a2177..e3d629c0 100644--- a/backend/app/notifications/service.py+++ b/backend/app/notifications/service.py@@ -171,7 +171,8 @@ class NotificationBusService:payload = notification.to_dict()payload['delivery_id'] = delivery_idpayload['read'] = False- socketio.emit('notification', payload, room=f'user_{user_id}')+ from app.sockets_rooms import user_room+ socketio.emit('notification', payload, room=user_room(user_id))except Exception as exc: # pragma: no cover - socket is best-effortlogger.debug('Socket emit for notification skipped: %s', exc)diff --git a/backend/app/sockets.py b/backend/app/sockets.pyindex 5e12763e..936003b5 100644--- a/backend/app/sockets.py+++ b/backend/app/sockets.py@@ -8,6 +8,7 @@ import queuefrom app.services.system_service import SystemServicefrom app.services.log_service import LogService, LogStreamerfrom app.services.docker_service import DockerService+from app import sockets_rooms as roomssocketio = SocketIO()log_streamer = LogStreamer()@@ -108,7 +109,7 @@ def handle_connect(auth):# Join a per-user room so the Notification Bus can push in-app notifications# to every tab/device this user has open.- join_room(f'user_{user.id}')+ join_room(rooms.user_room(user.id))emit('connected', {'status': 'connected'})@@ -276,7 +277,7 @@ def handle_subscribe_terminal(data):emit('error', {'message': 'Unknown terminal session'})return- join_room(f"server_{session['server_id']}_terminal:{session_id}")+ join_room(rooms.server_terminal_room(session['server_id'], session_id))emit('subscribed', {'channel': f'terminal:{session_id}'})@@ -290,7 +291,7 @@ def handle_unsubscribe_terminal(data):returnsession = TerminalService.get_session(session_id)if session:- leave_room(f"server_{session['server_id']}_terminal:{session_id}")+ leave_room(rooms.server_terminal_room(session['server_id'], session_id))@socketio.on('subscribe_logs')@@ -349,7 +350,7 @@ def handle_join_room(data):emit('error', {'message': 'room required'})return- if '_terminal:' in room and not _client_is_privileged(request.sid):+ if rooms.is_terminal_room(room) and not _client_is_privileged(request.sid):emit('error', {'message': 'Developer role required for terminal access'})return@@ -394,7 +395,7 @@ def handle_subscribe_deploy(data):emit('error', {'message': 'job_id required'})return- join_room(f'deploy_{job_id}')+ join_room(rooms.deploy_room(job_id))emit('subscribed', {'channel': 'deploy', 'job_id': job_id})@@ -403,7 +404,7 @@ def handle_unsubscribe_deploy(data=None):"""Leave a deployment job's live room."""job_id = (data or {}).get('job_id')if job_id:- leave_room(f'deploy_{job_id}')+ leave_room(rooms.deploy_room(job_id))emit('unsubscribed', {'channel': 'deploy', 'job_id': job_id})@@ -417,7 +418,7 @@ def emit_deploy_log(job_id: str, lines: list):socketio.emit('deploy_log', {'job_id': job_id,'lines': lines,- }, room=f'deploy_{job_id}')+ }, room=rooms.deploy_room(job_id))def emit_deploy_status(job_id: str, status: dict):@@ -426,7 +427,7 @@ def emit_deploy_status(job_id: str, status: dict):socketio.emit('deploy_status', {'job_id': job_id,'status': status,- }, room=f'deploy_{job_id}')+ }, room=rooms.deploy_room(job_id))# ==================== CONTAINER LOG STREAMING ====================@@ -509,7 +510,7 @@ def handle_subscribe_container_logs(data):return# Join room for this app's logs- join_room(f'logs_{app_id}')+ join_room(rooms.app_logs_room(app_id))# Start streaming processprocess = DockerService.stream_container_logs(@@ -540,7 +541,7 @@ def handle_subscribe_container_logs(data):socketio.emit('container_log_ended', {'app_id': app_id,'message': 'Container log stream ended'- }, room=f'logs_{app_id}')+ }, room=rooms.app_logs_room(app_id))break# Parse the log line@@ -551,13 +552,13 @@ def handle_subscribe_container_logs(data):'line': line.rstrip('\n'),'parsed': parsed,'timestamp': time.time()- }, room=f'logs_{app_id}')+ }, room=rooms.app_logs_room(app_id))except Exception as e:if not stop_event.is_set():socketio.emit('container_log_error', {'app_id': app_id,'message': f'Stream error: {str(e)}'- }, room=f'logs_{app_id}')+ }, room=rooms.app_logs_room(app_id))finally:# Clean uptry:@@ -599,7 +600,7 @@ def handle_unsubscribe_container_logs():if stream_info:app_id = stream_info.get('app_id')- leave_room(f'logs_{app_id}')+ leave_room(rooms.app_logs_room(app_id))stop_container_log_stream(sid)emit('unsubscribed', {'channel': 'container_logs'})@@ -645,7 +646,7 @@ def emit_container_log(app_id: int, line: str, level: str = 'info'):'level': level},'timestamp': time.time()- }, room=f'logs_{app_id}')+ }, room=rooms.app_logs_room(app_id))# ==================== PIPELINE EVENT STREAMING ====================diff --git a/backend/app/sockets_rooms.py b/backend/app/sockets_rooms.pynew file mode 100644index 00000000..f686cce3--- /dev/null+++ b/backend/app/sockets_rooms.py@@ -0,0 +1,59 @@+"""Every Socket.IO room name is built HERE (plan 77 E3).++The room grammar used to live in ~25 scattered f-strings across sockets.py,+agent_gateway.py and the notification bus — and was re-derived by hand in+frontend template literals. One typo'd segment means a silently dead stream,+so the builders below are the single source of truth; the frontend mirrors+the same grammar in ``src/constants/events.js`` (kept in lockstep by+``tests/test_socket_contract.py``).++Grammar:++ user_<user_id> per-user notification fan-out+ deploy_<job_id> Deploy Console (legacy run envelope)+ run_<kind>_<run_id> generalized run envelope (plan 77 E1)+ logs_<app_id> container log streaming for an app+ server_<id>_<channel> generic agent-stream rebroadcast+ server_<id>_metrics agent metrics fan-out+ server_<id>_container_<cid>_logs agent container logs+ server_<id>_terminal:<session_id> remote PTY (role-gated!)+"""+++def user_room(user_id) -> str:+ return f'user_{user_id}'+++def deploy_room(job_id) -> str:+ return f'deploy_{job_id}'+++def run_room(run_kind, run_id) -> str:+ """The plan 77 E1 run envelope room — one grammar for every run kind."""+ return f'run_{run_kind}_{run_id}'+++def app_logs_room(app_id) -> str:+ return f'logs_{app_id}'+++def server_channel_room(server_id, channel) -> str:+ return f'server_{server_id}_{channel}'+++def server_metrics_room(server_id) -> str:+ return server_channel_room(server_id, 'metrics')+++def server_container_logs_room(server_id, container_id) -> str:+ return server_channel_room(server_id, f'container_{container_id}_logs')+++def server_terminal_room(server_id, session_id) -> str:+ return server_channel_room(server_id, f'terminal:{session_id}')+++def is_terminal_room(room: str) -> bool:+ """True for the privileged PTY stream rooms — the role gate keys off this+ (both subscribe_terminal and the generic join_room must agree)."""+ return isinstance(room, str) and '_terminal:' in roomdiff --git a/backend/tests/test_socket_contract.py b/backend/tests/test_socket_contract.pynew file mode 100644index 00000000..8676bdf2--- /dev/null+++ b/backend/tests/test_socket_contract.py@@ -0,0 +1,67 @@+"""Plan 77 E3 — the socket wire protocol has one definition per side, mirrored.++Room names come only from app/sockets_rooms.py; event names only from+app/constants.py, mirrored verbatim by frontend/src/constants/events.js.+The mirror test parses the JS file so a renamed event fails HERE instead of+silently killing a stream in production.+"""+import re+from pathlib import Path++from app import sockets_rooms as rooms+from app.constants import SOCKET_EVENTS++REPO = Path(__file__).resolve().parents[2]+EVENTS_JS = REPO / 'frontend' / 'src' / 'constants' / 'events.js'+++def _parse_js_events():+ text = EVENTS_JS.read_text(encoding='utf-8')+ block = re.search(r'export const SOCKET_EVENTS = \{(.*?)\n\};', text, re.S)+ assert block, 'SOCKET_EVENTS block missing from events.js'+ return dict(re.findall(r"^\s*([A-Z_]+):\s*'([a-z_]+)',", block.group(1), re.M))+++def test_event_tables_are_identical():+ js = _parse_js_events()+ assert js == SOCKET_EVENTS, (+ 'backend/app/constants.py and frontend/src/constants/events.js drifted. '+ f'Only in backend: {sorted(set(SOCKET_EVENTS) - set(js))}; '+ f'only in frontend: {sorted(set(js) - set(SOCKET_EVENTS))}; '+ f'value mismatches: '+ f'{ {k: (SOCKET_EVENTS[k], js[k]) for k in set(js) & set(SOCKET_EVENTS) if js[k] != SOCKET_EVENTS[k]} }'+ )+++def test_room_grammar():+ assert rooms.user_room(7) == 'user_7'+ assert rooms.deploy_room('j1') == 'deploy_j1'+ assert rooms.run_room('sandbox', 42) == 'run_sandbox_42'+ assert rooms.app_logs_room(3) == 'logs_3'+ assert rooms.server_channel_room('s1', 'jobs') == 'server_s1_jobs'+ assert rooms.server_metrics_room('s1') == 'server_s1_metrics'+ assert rooms.server_container_logs_room('s1', 'abc') == 'server_s1_container_abc_logs'+ assert rooms.server_terminal_room('s1', 'sess') == 'server_s1_terminal:sess'+++def test_terminal_room_gate_agrees_with_builder():+ assert rooms.is_terminal_room(rooms.server_terminal_room('s1', 'x'))+ assert not rooms.is_terminal_room(rooms.server_metrics_room('s1'))+ assert not rooms.is_terminal_room(None)+++def test_no_room_fstrings_outside_the_rooms_module():+ """Ratchet: no hand-assembled room name f-strings in the realtime layer."""+ offenders = []+ pattern = re.compile(+ r"f['\"](?:user_\{|deploy_\{|run_\{|logs_\{|server_\{)")+ for rel in ('app/sockets.py', 'app/agent_gateway.py',+ 'app/notifications/service.py', 'app/services/run_log_service.py'):+ text = (REPO / 'backend' / rel).read_text(encoding='utf-8')+ for i, line in enumerate(text.split('\n'), 1):+ if pattern.search(line) and 'sockets_rooms' not in line:+ offenders.append(f'{rel}:{i}')+ assert not offenders, (+ f'Hand-assembled room names at {offenders} — use app/sockets_rooms.py '+ '(plan 77 E3).'+ )diff --git a/frontend/src/components/JobProgressModal.jsx b/frontend/src/components/JobProgressModal.jsxindex 8954b21b..69dffeef 100644--- a/frontend/src/components/JobProgressModal.jsx+++ b/frontend/src/components/JobProgressModal.jsx@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react';import Modal from './Modal';import { Button } from '@/components/ui/button';import socketService from '../services/socket';+import { rooms } from '@/constants/events';// Subscribes to a remote agent's job:<id> stream channel and renders// the live log output. Used by PackagesTab and ServicesTab for@@ -26,7 +27,7 @@ export default function JobProgressModal({useEffect(() => {if (!open || !channel || !serverId) return;- const room = `server_${serverId}_${channel}`;+ const room = rooms.serverChannel(serverId, channel);const socket = socketService.socket;if (!socket) {// Connect lazily — happens once per panel session normally.diff --git a/frontend/src/components/serverdetail/CloudflaredTab.jsx b/frontend/src/components/serverdetail/CloudflaredTab.jsxindex 8a013aea..c95f4560 100644--- a/frontend/src/components/serverdetail/CloudflaredTab.jsx+++ b/frontend/src/components/serverdetail/CloudflaredTab.jsx@@ -16,6 +16,7 @@ import { Cloud } from 'lucide-react';import Modal from '@/components/Modal';import { Label } from '@/components/ui/label';import { copyToClipboard } from '@/utils/clipboard';+import { rooms } from '@/constants/events';import {OfflineIcon,TrashIcon,@@ -225,7 +226,7 @@ const CloudflaredTab = ({ serverId, serverStatus }) => {toast.error('Socket not available');return;}- const room = `server_${serverId}_${channel}`;+ const room = rooms.serverChannel(serverId, channel);const onStream = (msg) => {if (msg?.channel !== channel) return;const ev = msg.data || {};diff --git a/frontend/src/constants/events.js b/frontend/src/constants/events.jsnew file mode 100644index 00000000..eaa9d7d2--- /dev/null+++ b/frontend/src/constants/events.js@@ -0,0 +1,53 @@+// Shared wire-protocol constants (plan 77 E3).+//+// This table mirrors backend/app/constants.py::SOCKET_EVENTS verbatim — a+// backend test (tests/test_socket_contract.py) parses this file and fails+// when the two drift, so a renamed event can never fail silently. Add or+// rename events in BOTH files.++export const SOCKET_EVENTS = {+ // lifecycle / control plane+ CONNECTED: 'connected',+ ERROR: 'error',+ SUBSCRIBED: 'subscribed',+ UNSUBSCRIBED: 'unsubscribed',+ JOINED: 'joined',+ LEFT: 'left',++ // broadcast channels+ METRICS: 'metrics',+ CONTAINER_STATUS: 'container_status',+ NOTIFICATION: 'notification',++ // file log streaming+ LOG_LINE: 'log_line',+ LOG_ERROR: 'log_error',++ // deploy console (legacy names, dual-emitted with the run envelope)+ DEPLOY_LOG: 'deploy_log',+ DEPLOY_STATUS: 'deploy_status',++ // generalized run envelope (plan 77 E1) — one event pair for every run kind+ RUN_LOG: 'run_log',+ RUN_STATUS: 'run_status',++ // container log streaming+ CONTAINER_LOG: 'container_log',+ CONTAINER_LOG_ERROR: 'container_log_error',+ CONTAINER_LOG_ENDED: 'container_log_ended',++ // agent stream rebroadcast (metrics / PTY / arbitrary channels)+ SERVER_STREAM: 'server_stream',+};++// Room-name builders — the same grammar as backend/app/sockets_rooms.py.+// Never assemble a room string inline in a component; a typo'd segment is a+// silently dead stream.++export const rooms = {+ serverChannel: (serverId, channel) => `server_${serverId}_${channel}`,+ deploy: (jobId) => `deploy_${jobId}`,+ run: (kind, runId) => `run_${kind}_${runId}`,+ appLogs: (appId) => `logs_${appId}`,+ serverTerminal: (serverId, sessionId) => `server_${serverId}_terminal:${sessionId}`,+};