feat: Phase 3 - 工具层 + 测试 + 数据库迁移

This commit is contained in:
2026-03-14 20:14:59 +08:00
parent 1836d118fe
commit 6bafd21e02
14 changed files with 1191 additions and 0 deletions

48
migrations/alembic.ini Normal file
View File

@@ -0,0 +1,48 @@
[alembic]
# 脚本位置
script_location = migrations
# 模板文件
template_file =
# 最大保留版本数
max_num = 10
# 数据库 URL运行时覆盖
sqlalchemy.url = sqlite:///pit_router.db
[post_write_hooks]
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

68
migrations/env.py Normal file
View File

@@ -0,0 +1,68 @@
"""
Alembic 环境配置
"""
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
import os
import sys
# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.extensions import db
from app.config import Config
# Alembic Config 对象
config = context.config
# 配置日志
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# 模型元数据
target_metadata = db.Model.metadata
def get_url():
"""获取数据库 URL"""
return os.getenv('DATABASE_URL', 'sqlite:///pit_router.db')
def run_migrations_offline() -> None:
"""离线迁移"""
url = get_url()
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""在线迁移"""
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@@ -0,0 +1,134 @@
"""
初始化迁移脚本
Revision ID: initial
Revises:
Create Date: 2026-03-14
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers
revision = 'initial'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
"""创建表"""
# 用户表
op.create_table(
'users',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('username', sa.String(80), unique=True, nullable=False),
sa.Column('password_hash', sa.String(256), nullable=False),
sa.Column('email', sa.String(120), unique=True, nullable=False),
sa.Column('nickname', sa.String(80)),
sa.Column('role', sa.String(20), default='user'),
sa.Column('status', sa.String(20), default='active'),
sa.Column('created_at', sa.DateTime, default=sa.func.now()),
sa.Column('last_login_at', sa.DateTime),
)
# Gateway 表
op.create_table(
'gateways',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('name', sa.String(80), unique=True, nullable=False),
sa.Column('url', sa.String(256), nullable=False),
sa.Column('token_hash', sa.String(256)),
sa.Column('status', sa.String(20), default='offline'),
sa.Column('agent_count', sa.Integer, default=0),
sa.Column('connection_limit', sa.Integer, default=10),
sa.Column('heartbeat_interval', sa.Integer, default=60),
sa.Column('allowed_ips', sa.JSON),
sa.Column('last_heartbeat', sa.DateTime),
sa.Column('created_at', sa.DateTime, default=sa.func.now()),
)
# Agent 表
op.create_table(
'agents',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('name', sa.String(80), nullable=False),
sa.Column('display_name', sa.String(80)),
sa.Column('gateway_id', sa.String(36), sa.ForeignKey('gateways.id')),
sa.Column('socket_id', sa.String(100)),
sa.Column('model', sa.String(80)),
sa.Column('capabilities', sa.JSON),
sa.Column('status', sa.String(20), default='offline'),
sa.Column('priority', sa.Integer, default=5),
sa.Column('weight', sa.Integer, default=10),
sa.Column('connection_limit', sa.Integer, default=5),
sa.Column('current_sessions', sa.Integer, default=0),
sa.Column('last_heartbeat', sa.DateTime),
sa.Column('created_at', sa.DateTime, default=sa.func.now()),
)
# 会话表
op.create_table(
'sessions',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('user_id', sa.String(36), sa.ForeignKey('users.id'), nullable=False),
sa.Column('primary_agent_id', sa.String(36), sa.ForeignKey('agents.id')),
sa.Column('participating_agent_ids', sa.JSON),
sa.Column('user_socket_id', sa.String(100)),
sa.Column('title', sa.String(200)),
sa.Column('channel_type', sa.String(20), default='web'),
sa.Column('status', sa.String(20), default='active'),
sa.Column('message_count', sa.Integer, default=0),
sa.Column('unread_count', sa.Integer, default=0),
sa.Column('created_at', sa.DateTime, default=sa.func.now()),
sa.Column('updated_at', sa.DateTime),
sa.Column('last_active_at', sa.DateTime),
)
# 消息表
op.create_table(
'messages',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('session_id', sa.String(36), sa.ForeignKey('sessions.id'), nullable=False),
sa.Column('sender_type', sa.String(20), nullable=False),
sa.Column('sender_id', sa.String(36), nullable=False),
sa.Column('message_type', sa.String(20), default='text'),
sa.Column('content', sa.Text),
sa.Column('content_type', sa.String(20), default='markdown'),
sa.Column('reply_to', sa.String(36)),
sa.Column('status', sa.String(20), default='sent'),
sa.Column('ack_status', sa.String(20), default='pending'),
sa.Column('retry_count', sa.Integer, default=0),
sa.Column('created_at', sa.DateTime, default=sa.func.now()),
sa.Column('delivered_at', sa.DateTime),
)
# 连接表
op.create_table(
'connections',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('socket_id', sa.String(100), unique=True, nullable=False),
sa.Column('connection_type', sa.String(20), nullable=False),
sa.Column('entity_id', sa.String(36), nullable=False),
sa.Column('entity_type', sa.String(20), nullable=False),
sa.Column('ip_address', sa.String(45)),
sa.Column('user_agent', sa.String(500)),
sa.Column('status', sa.String(20), default='connected'),
sa.Column('auth_token', sa.String(500)),
sa.Column('connected_at', sa.DateTime, default=sa.func.now()),
sa.Column('last_activity', sa.DateTime),
sa.Column('disconnected_at', sa.DateTime),
)
# 创建索引
op.create_index('ix_messages_session_id', 'messages', ['session_id'])
op.create_index('ix_sessions_user_id', 'sessions', ['user_id'])
op.create_index('ix_sessions_status', 'sessions', ['status'])
def downgrade():
"""删除表"""
op.drop_table('connections')
op.drop_table('messages')
op.drop_table('sessions')
op.drop_table('agents')
op.drop_table('gateways')
op.drop_table('users')