调整部分前端布局和后端增删改逻辑

This commit is contained in:
焦龙言
2026-09-20 10:38:10 +08:00
parent acddc8a237
commit 3edba99d2d
227 changed files with 122871 additions and 839 deletions
@@ -0,0 +1,3 @@
from .command import app
__all__ = ['app']
@@ -0,0 +1,89 @@
import typer
from cli.context import EnvOption, OutputOption
from .controller import OpsCommandController
app = typer.Typer(
help='运维相关命令',
no_args_is_help=True,
context_settings={'help_option_names': ['-h', '--help']},
)
_OPS_COMMAND_CONTROLLER = OpsCommandController()
@app.command('ping-db', help='检查数据库连接')
def ping_db(
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
检查数据库连接。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_OPS_COMMAND_CONTROLLER.ping_db(env, output)
@app.command('ping-redis', help='检查 Redis 连接')
def ping_redis_command(
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
检查 Redis 连接。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_OPS_COMMAND_CONTROLLER.ping_redis(env, output)
@app.command('health', help='查看基础健康检查结果')
def health(
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
输出基础健康检查结果。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_OPS_COMMAND_CONTROLLER.health(env, output)
@app.command('deps', help='查看当前 CLI 和后端运行依赖版本')
def deps(
env: EnvOption = 'dev',
output: OutputOption = 'text',
include_dev: bool = typer.Option(False, '--include-dev', help='附带输出开发依赖'),
) -> None:
"""
检查当前 CLI 和后端运行依赖版本。
:param env: 当前命令运行环境
:param output: 输出格式
:param include_dev: 是否附带输出开发依赖
:return: None
"""
_OPS_COMMAND_CONTROLLER.deps(env, output, include_dev=include_dev)
@app.command('server-info', help='查看服务器运行时信息')
def server_info(
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
输出服务器运行时信息。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_OPS_COMMAND_CONTROLLER.server_info(env, output)
@@ -0,0 +1,137 @@
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
CliExecutionService,
)
from cli.exit_codes import DEPENDENCY_ERROR, SUCCESS
from cli.runtime.db import DATABASE_RUNTIME, DatabaseRuntimeService
from cli.runtime.ops import OPERATIONS_RUNTIME, OperationsRuntimeService
from .presenter import OpsCommandPresenter
class OpsCommandController:
"""
运维命令控制器。
该控制器负责组织 `ops` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
:param context_factory: CLI 上下文工厂
:param execution_service: CLI 执行服务
:param presenter: 运维命令文本渲染器
"""
def __init__(
self,
*,
context_factory: CliContextFactory | None = None,
execution_service: CliExecutionService | None = None,
presenter: OpsCommandPresenter | None = None,
database_runtime: DatabaseRuntimeService | None = None,
operations_runtime: OperationsRuntimeService | None = None,
) -> None:
"""
初始化运维命令控制器。
:param context_factory: CLI 上下文工厂
:param execution_service: CLI 执行服务
:param presenter: 运维命令文本渲染器
:param database_runtime: 数据库运行时服务
:param operations_runtime: 运维运行时服务
:return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
self.presenter = presenter or OpsCommandPresenter()
self.database_runtime = database_runtime or DATABASE_RUNTIME
self.operations_runtime = operations_runtime or OPERATIONS_RUNTIME
def ping_db(self, env: str, output: str) -> None:
"""
检查数据库连接。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload(
ctx, self.execution_service.run_async(self.database_runtime.ping_database())
)
def ping_redis(self, env: str, output: str) -> None:
"""
检查 Redis 连接。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload(
ctx,
self.execution_service.run_async(self.operations_runtime.ping_redis()),
)
def health(self, env: str, output: str) -> None:
"""
输出基础健康检查结果。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
db_status = self.execution_service.run_async(self.database_runtime.ping_database())
redis_status = self.execution_service.run_async(self.operations_runtime.ping_redis())
payload = {
'env': ctx.env,
'database': db_status,
'redis': redis_status,
'ok': db_status.get('ok', False) and redis_status.get('ok', False),
}
exit_code = SUCCESS if payload['ok'] else DEPENDENCY_ERROR
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_health_text,
default_exit_code=exit_code,
)
def deps(self, env: str, output: str, *, include_dev: bool) -> None:
"""
检查当前 CLI 和后端运行依赖版本。
:param env: 当前命令运行环境
:param output: 输出格式
:param include_dev: 是否附带输出开发依赖
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.operations_runtime.get_dependency_versions(include_dev=include_dev)
exit_code = SUCCESS if payload.get('ok', False) else DEPENDENCY_ERROR
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_dependencies_text,
default_exit_code=exit_code,
)
def server_info(self, env: str, output: str) -> None:
"""
输出服务器运行时信息。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.operations_runtime.get_server_info())
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_server_info_text,
default_exit_code=SUCCESS,
text_condition=lambda data: data.get('ok', False),
)
@@ -0,0 +1,177 @@
from cli.utils import SHELL_TEXT_FORMATTER
class OpsCommandPresenter:
"""
运维命令文本渲染器。
该渲染器负责将 `ops` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
def build_health_text(self, payload: dict[str, object]) -> str:
"""
将基础健康检查结果渲染为文本摘要。
:param payload: 健康检查结果字典
:return: 文本摘要
"""
return '\n'.join(
[
f'ok: {str(payload.get("ok", False)).lower()}',
f'env: {payload.get("env", "")}',
'checks:',
self._build_check_status_line('database', payload.get('database')),
self._build_check_status_line('redis', payload.get('redis')),
]
)
def build_server_info_text(self, payload: dict[str, object]) -> str:
"""
将服务器运行时信息渲染为文本摘要。
:param payload: 服务器运行时信息结果字典
:return: 文本摘要
"""
server = payload.get('server')
if not isinstance(server, dict):
return '\n'.join(
[
f'ok: {str(payload.get("ok", False)).lower()}',
'server: none',
]
)
sys_info = server.get('sys')
cpu_info = server.get('cpu')
mem_info = server.get('mem')
py_info = server.get('py')
sys_files = server.get('sysFiles')
lines = [f'ok: {str(payload.get("ok", False)).lower()}']
if isinstance(sys_info, dict):
lines.extend(
[
'host:',
f' name: {sys_info.get("computerName", "-")}',
f' ip: {sys_info.get("computerIp", "-")}',
f' os: {SHELL_TEXT_FORMATTER.truncate_text(sys_info.get("osName", "-"), 90)}',
f' arch: {sys_info.get("osArch", "-")}',
f' user_dir: {SHELL_TEXT_FORMATTER.truncate_text(sys_info.get("userDir", "-"), 100)}',
]
)
if isinstance(cpu_info, dict):
lines.extend(
[
'cpu:',
f' cores: {cpu_info.get("cpuNum", "-")}',
f' used: {cpu_info.get("used", "-")}%',
f' sys: {cpu_info.get("sys", "-")}%',
f' free: {cpu_info.get("free", "-")}%',
]
)
if isinstance(mem_info, dict):
lines.extend(
[
'memory:',
f' total: {mem_info.get("total", "-")}',
f' used: {mem_info.get("used", "-")}',
f' free: {mem_info.get("free", "-")}',
f' usage: {mem_info.get("usage", "-")}%',
]
)
if isinstance(py_info, dict):
lines.extend(
[
'python:',
f' name: {py_info.get("name", "-")}',
f' version: {py_info.get("version", "-")}',
f' start_time: {py_info.get("startTime", "-")}',
f' run_time: {py_info.get("runTime", "-")}',
f' home: {SHELL_TEXT_FORMATTER.truncate_text(py_info.get("home", "-"), 100)}',
f' process_memory: {py_info.get("used", "-")} / {py_info.get("total", "-")} ({py_info.get("usage", "-")}%)',
]
)
if isinstance(sys_files, list):
lines.append(f'disks: {len(sys_files)}')
if sys_files:
lines.append('disk_samples:')
lines.extend(
f' - {item.get("dirName", "-")} | used: {item.get("used", "-")} / {item.get("total", "-")} | usage: {item.get("usage", "-")}'
for item in sys_files[:10]
if isinstance(item, dict)
)
return '\n'.join(lines)
def build_dependencies_text(self, payload: dict[str, object]) -> str:
"""
将依赖版本检查结果渲染为文本摘要。
:param payload: 依赖版本检查结果字典
:return: 文本摘要
"""
packages = payload.get('packages')
lines = [
f'ok: {str(payload.get("ok", False)).lower()}',
f'message: {payload.get("message", "-")}',
f'include_dev: {str(payload.get("includeDev", False)).lower()}',
]
missing_required = payload.get('missingRequired')
if isinstance(missing_required, list) and missing_required:
lines.append('missing_required:')
lines.extend(f' - {item}' for item in missing_required)
else:
lines.append('missing_required: none')
if not isinstance(packages, dict) or not packages:
lines.append('packages: none')
return '\n'.join(lines)
lines.append('packages:')
for package_name in sorted(packages):
dependency_payload = packages.get(package_name)
if isinstance(dependency_payload, dict):
lines.append(self._build_dependency_line(package_name, dependency_payload))
return '\n'.join(lines)
@staticmethod
def _build_check_status_line(name: str, status_payload: dict[str, object] | None) -> str:
"""
构建单项检查结果摘要行。
:param name: 检查项名称
:param status_payload: 检查结果字典
:return: 摘要行文本
"""
if not isinstance(status_payload, dict):
return f' {name}: unknown'
ok = str(status_payload.get('ok', False)).lower()
message = status_payload.get('message', '-') or '-'
error = status_payload.get('error')
if error:
return f' {name}: {ok} | {message} | error: {SHELL_TEXT_FORMATTER.truncate_text(error, 120)}'
return f' {name}: {ok} | {message}'
@staticmethod
def _build_dependency_line(name: str, dependency_payload: dict[str, object] | None) -> str:
"""
构建单个依赖项的文本摘要行。
:param name: 依赖项名称
:param dependency_payload: 依赖项结果字典
:return: 文本摘要行
"""
if not isinstance(dependency_payload, dict):
return f' {name}: not-installed'
installed = str(dependency_payload.get('installed', False)).lower()
version = dependency_payload.get('version', '-') or '-'
required = str(dependency_payload.get('required', False)).lower()
distribution = dependency_payload.get('distribution', '') or name
return f' {name}: {installed} | version: {version} | required: {required} | dist: {distribution}'