初始提交

This commit is contained in:
焦龙言
2026-07-24 09:43:10 +08:00
commit b5b4721456
793 changed files with 116305 additions and 0 deletions
@@ -0,0 +1,3 @@
from .command import app
__all__ = ['app']
+163
View File
@@ -0,0 +1,163 @@
import typer
from cli.completion.providers import COMPLETION_PROVIDER_GATEWAY
from cli.context import AllowProdOption, DryRunOption, EnvOption, OutputOption, YesOption
from .controller import CacheCommandController
app = typer.Typer(
help='缓存相关命令',
no_args_is_help=True,
context_settings={'help_option_names': ['-h', '--help']},
)
_CACHE_COMMAND_CONTROLLER = CacheCommandController()
@app.command('stats', help='查看缓存统计信息')
def stats(
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
查看缓存统计信息。
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_CACHE_COMMAND_CONTROLLER.stats(env, output)
@app.command('keys', help='查看指定缓存名称下的键名列表')
def keys(
cache_name: str = typer.Argument(
...,
help='缓存名称',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_cache_names,
),
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
查看指定缓存名称下的键名列表。
:param cache_name: 缓存名称
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_CACHE_COMMAND_CONTROLLER.keys(cache_name, env, output)
@app.command('get', help='查看指定缓存内容')
def get(
cache_name: str = typer.Argument(
...,
help='缓存名称',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_cache_names,
),
cache_key: str = typer.Argument(
...,
help='缓存键名',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_cache_keys,
),
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
查看指定缓存内容。
:param cache_name: 缓存名称
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_CACHE_COMMAND_CONTROLLER.get(cache_name, cache_key, env, output)
@app.command('clear', help='执行缓存清理')
def clear(
env: EnvOption = 'dev',
output: OutputOption = 'text',
allow_prod: AllowProdOption = False,
yes: YesOption = False,
dry_run: DryRunOption = False,
cache_name: str = typer.Option(
'',
'--cache-name',
help='按缓存名称前缀清理',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_cache_names,
),
cache_key: str = typer.Option('', '--cache-key', help='按缓存键名模糊清理'),
clear_all: bool = typer.Option(False, '--all', help='清理全部缓存并重建系统基础缓存'),
) -> None:
"""
清理缓存。
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param cache_name: 缓存名称前缀
:param cache_key: 缓存键名
:param clear_all: 是否清理全部缓存
:return: None
"""
_CACHE_COMMAND_CONTROLLER.clear(
env,
output,
allow_prod,
yes,
dry_run,
cache_name=cache_name,
cache_key=cache_key,
clear_all=clear_all,
)
@app.command('ttl', help='查看指定缓存键的剩余过期时间')
def ttl(
cache_name: str = typer.Argument(
...,
help='缓存名称',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_cache_names,
),
cache_key: str = typer.Argument(
...,
help='缓存键名',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_cache_keys,
),
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
查看指定缓存键的剩余过期时间。
:param cache_name: 缓存名称
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_CACHE_COMMAND_CONTROLLER.ttl(cache_name, cache_key, env, output)
@app.command('warmup', help='执行系统缓存预热')
def warmup(
env: EnvOption = 'dev',
output: OutputOption = 'text',
allow_prod: AllowProdOption = False,
yes: YesOption = False,
) -> None:
"""
执行系统缓存预热。
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:return: None
"""
_CACHE_COMMAND_CONTROLLER.warmup(env, output, allow_prod, yes)
+183
View File
@@ -0,0 +1,183 @@
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
CliExecutionService,
)
from cli.runtime.cache import CACHE_RUNTIME, CacheRuntimeService
from .presenter import CacheCommandPresenter
class CacheCommandController:
"""
缓存命令控制器。
该控制器负责组织 `cache` 命令组的上下文准备、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: CacheCommandPresenter | None = None,
runtime_service: CacheRuntimeService | None = None,
) -> None:
"""
初始化缓存命令控制器。
:param context_factory: CLI 上下文工厂
:param execution_service: CLI 执行服务
:param presenter: 缓存命令文本渲染器
:param runtime_service: 缓存运行时服务
: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 CacheCommandPresenter()
self.runtime_service = runtime_service or CACHE_RUNTIME
def stats(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.runtime_service.get_cache_stats())
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_cache_stats_text,
text_condition=lambda result_data: bool(result_data.get('ok', False)),
)
def keys(self, cache_name: str, env: str, output: str) -> None:
"""
查看指定缓存名称下的键名列表。
:param cache_name: 缓存名称
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.list_cache_keys(cache_name))
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_cache_keys_text,
text_condition=lambda result_data: bool(result_data.get('ok', False)),
)
def get(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
"""
查看指定缓存内容。
:param cache_name: 缓存名称
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_cache_value(cache_name, cache_key))
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_cache_value_text,
text_condition=lambda result_data: bool(result_data.get('ok', False)),
)
def clear(
self,
env: str,
output: str,
allow_prod: bool,
yes: bool,
dry_run: bool,
*,
cache_name: str,
cache_key: str,
clear_all: bool,
) -> None:
"""
清理缓存。
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param cache_name: 缓存名称前缀
:param cache_key: 缓存键名
:param clear_all: 是否清理全部缓存
:return: None
"""
ctx = self.context_factory.build_dangerous(
env,
output,
allow_prod,
yes,
dry_run,
command_name='cache clear',
)
self.execution_service.complete_payload(
ctx,
self.execution_service.run_async(
self.runtime_service.clear_cache(
cache_name=cache_name,
cache_key=cache_key,
clear_all=clear_all,
dry_run=dry_run,
)
),
)
def ttl(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
"""
查看指定缓存键的剩余过期时间。
:param cache_name: 缓存名称
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_cache_ttl(cache_name, cache_key))
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_cache_ttl_text,
text_condition=lambda result_data: 'error' not in result_data,
)
def warmup(self, env: str, output: str, allow_prod: bool, yes: bool) -> None:
"""
执行系统缓存预热。
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:return: None
"""
ctx = self.context_factory.build_dangerous(
env,
output,
allow_prod,
yes,
False,
command_name='cache warmup',
)
self.execution_service.complete_payload(
ctx, self.execution_service.run_async(self.runtime_service.warmup_cache())
)
+150
View File
@@ -0,0 +1,150 @@
from cli.utils import SHELL_TEXT_FORMATTER
class CacheCommandPresenter:
"""
缓存命令文本渲染器。
该渲染器负责将 `cache` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
def build_cache_stats_text(self, payload: dict[str, object]) -> str:
"""
将缓存统计结果渲染为文本摘要。
:param payload: 缓存统计结果
:return: 文本摘要
"""
info = payload.get('info')
command_stats = payload.get('commandStats')
cache_names = payload.get('cacheNames')
redis_version = '-'
connected_clients = '-'
used_memory = '-'
uptime_seconds = '-'
keyspace_hits = '-'
keyspace_misses = '-'
if isinstance(info, dict):
redis_version = info.get('redis_version', '-')
connected_clients = info.get('connected_clients', '-')
used_memory = info.get('used_memory_human', info.get('used_memory', '-'))
uptime_seconds = info.get('uptime_in_seconds', '-')
keyspace_hits = info.get('keyspace_hits', '-')
keyspace_misses = info.get('keyspace_misses', '-')
lines = [
f'ok: {str(payload.get("ok", False)).lower()}',
f'db_size: {payload.get("dbSize", 0)}',
'redis:',
f' version: {redis_version}',
f' connected_clients: {connected_clients}',
f' used_memory: {used_memory}',
f' uptime_seconds: {uptime_seconds}',
f' keyspace_hits: {keyspace_hits}',
f' keyspace_misses: {keyspace_misses}',
]
if isinstance(command_stats, list) and command_stats:
lines.append('command_stats_top10:')
lines.extend(
f' - {item.get("name", "-")}: {item.get("value", 0)}'
for item in command_stats[:10]
if isinstance(item, dict)
)
else:
lines.append('command_stats_top10: none')
if isinstance(cache_names, list) and cache_names:
lines.append(f'cache_names: {len(cache_names)}')
lines.append('cache_name_samples:')
lines.extend(
f' - {item.get("cacheName", "-")}: {self._build_cache_name_remark(item.get("remark", ""))}'
for item in cache_names[:10]
if isinstance(item, dict)
)
else:
lines.append('cache_names: 0')
return '\n'.join(lines)
def build_cache_keys_text(self, payload: dict[str, object]) -> str:
"""
将缓存键列表结果渲染为文本摘要。
:param payload: 缓存键列表结果
:return: 文本摘要
"""
keys = payload.get('keys')
lines = [
f'ok: {str(payload.get("ok", False)).lower()}',
f'cache_name: {payload.get("cacheName", "")}',
f'count: {payload.get("count", 0)}',
]
if not isinstance(keys, list) or not keys:
lines.append('keys: none')
return '\n'.join(lines)
lines.append('keys:')
lines.extend(f' - {key}' for key in keys)
return '\n'.join(lines)
def build_cache_value_text(self, payload: dict[str, object]) -> str:
"""
将缓存值读取结果渲染为文本摘要。
:param payload: 缓存值读取结果字典
:return: 文本摘要
"""
cache_value = '' if payload.get('cacheValue') is None else str(payload.get('cacheValue'))
cache_value_lines = cache_value.splitlines() if cache_value else []
if not cache_value_lines:
rendered_value_lines = [' -']
elif len(cache_value_lines) == 1:
rendered_value_lines = [f' {SHELL_TEXT_FORMATTER.truncate_text(cache_value_lines[0], 200)}']
else:
rendered_value_lines = [' |', *[f' {line}' for line in cache_value_lines]]
return '\n'.join(
[
f'ok: {str(payload.get("ok", False)).lower()}',
f'cache_name: {payload.get("cacheName", "")}',
f'cache_key: {payload.get("cacheKey", "")}',
f'full_cache_key: {payload.get("fullCacheKey", "")}',
'cache_value:',
*rendered_value_lines,
]
)
@staticmethod
def build_cache_ttl_text(payload: dict[str, object]) -> str:
"""
将缓存 TTL 结果渲染为文本摘要。
:param payload: 缓存 TTL 结果字典
:return: 文本摘要
"""
return '\n'.join(
[
f'ok: {str(payload.get("ok", False)).lower()}',
f'cache_name: {payload.get("cacheName", "")}',
f'cache_key: {payload.get("cacheKey", "")}',
f'full_cache_key: {payload.get("fullCacheKey", "")}',
f'message: {payload.get("message", "-")}',
f'ttl_seconds: {payload.get("ttlSeconds", "-")}',
f'persistent: {str(payload.get("persistent", False)).lower()}',
f'expires: {str(payload.get("expires", False)).lower()}',
]
)
@staticmethod
def _build_cache_name_remark(remark: object) -> str:
"""
规范化缓存名称备注文本。
:param remark: 原始备注
:return: 规范化后的备注
"""
text = '' if remark is None else str(remark).strip()
return text or '-'