Claw 项目完整结构提交

This commit is contained in:
zqm
2026-03-16 15:47:55 +08:00
parent ca4970bcbf
commit fb0aeb6ca2
118 changed files with 28648 additions and 281 deletions

View File

@@ -0,0 +1,966 @@
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder, middleware::Logger};
use actix_web_actors::ws;
use serde::Deserialize;
use std::env;
use std::sync::Arc;
use tokio::sync::RwLock;
use shared::{TaskRequest, TaskResponse, HealthResponse, utils};
use sha1::{Sha1, Digest};
mod communication;
use communication::{WebSocketConnection, ConnectionManager, WebSocketPool, CommunicationConfig, WebSocketClient};
/// 任务处理服务
struct TaskService {
connection_manager: Arc<RwLock<ConnectionManager>>,
websocket_pool: WebSocketPool,
communication_config: CommunicationConfig,
}
impl TaskService {
/// 创建新的任务处理服务
fn new() -> Self {
let connection_manager = Arc::new(RwLock::new(ConnectionManager::new()));
let websocket_pool = WebSocketPool::new();
let communication_config = CommunicationConfig::default();
println!("🚀 初始化任务处理服务");
println!("📋 WebSocket连接池已创建");
println!("⚙️ 通信配置已加载: {:?}", communication_config.websocket_url);
Self {
connection_manager,
websocket_pool,
communication_config,
}
}
/// 处理任务请求 - 现在通过WebSocket发送给内网服务器
async fn process_task(&self, task: TaskRequest) -> TaskResponse {
println!("📝 收到任务请求:");
println!(" 用户ID: {}", task.user_id);
println!(" 任务类型: {}", task.task_type);
println!(" 内容长度: {} 字符", task.content.len());
// 验证任务参数
if task.content.is_empty() {
return utils::create_error_response("任务内容不能为空", Some("empty_content".to_string()));
}
if task.user_id.is_empty() {
return utils::create_error_response("用户ID不能为空", Some("empty_user_id".to_string()));
}
// 生成任务ID
let task_id = utils::generate_task_id(&task.user_id);
// 通过WebSocket连接发送任务到内网服务器
println!("🚀 通过WebSocket发送任务到内网服务器...");
match self.send_task_via_websocket(task.clone()).await {
Ok(response) => {
println!("✅ 任务处理成功");
response
},
Err(e) => {
println!("❌ WebSocket任务发送失败: {}", e);
println!("🎭 使用模拟响应");
self.create_mock_response(task_id, task)
}
}
}
/// 通过WebSocket发送任务到内网服务器
async fn send_task_via_websocket(&self, task: TaskRequest) -> Result<TaskResponse, String> {
// 使用通信配置
println!("⚙️ 使用通信配置 - 心跳间隔: {:?}, 连接超时: {:?}",
self.communication_config.heartbeat_interval,
self.communication_config.connection_timeout);
// 使用WebSocket连接池
let manager = self.connection_manager.read().await;
// 获取可用的WebSocket连接
if let Some(_connection_info) = manager.get_any_connection() {
// 创建任务消息
let task_message = serde_json::json!({
"type": "task",
"task": task
});
// 使用WebSocket池广播任务消息
match self.websocket_pool.broadcast(task_message.clone()).await {
Ok(_) => {
println!("📤 任务已通过WebSocket广播到所有连接");
// 获取连接池统计信息
let pool_stats = self.websocket_pool.get_pool_stats();
println!("📊 WebSocket连接池统计: {}", pool_stats);
// 尝试发送到特定连接(如果有的话)
if let Some(connection_info) = manager.get_all_connections().first() {
let specific_message = serde_json::json!({
"type": "task_direct",
"task": task,
"target": connection_info.id
});
match self.websocket_pool.send_to_connection(&connection_info.id, specific_message).await {
Ok(_) => {
println!("📨 任务已发送到特定连接: {}", connection_info.id);
},
Err(e) => {
println!("⚠️ 发送到特定连接失败: {}", e);
}
}
}
},
Err(e) => {
println!("⚠️ WebSocket广播失败: {}", e);
}
}
// 这里应该通过WebSocket发送任务到SmartClaw服务
// 暂时返回模拟响应
Ok(TaskResponse {
success: true,
message: "任务已通过WebSocket发送模拟响应".to_string(),
task_id: Some(utils::generate_task_id(&task.user_id)),
result: Some(serde_json::json!({
"task_type": task.task_type,
"status": "processing_via_websocket",
"connection_count": manager.get_connection_count(),
"heartbeat_interval": format!("{:?}", self.communication_config.heartbeat_interval),
"connection_timeout": format!("{:?}", self.communication_config.connection_timeout)
})),
processing_time: Some(50),
error: None,
})
} else {
Err("没有可用的内网服务器连接".to_string())
}
}
/// 创建模拟响应当WebSocket不可用时
fn create_mock_response(&self, task_id: String, task: TaskRequest) -> TaskResponse {
println!("🎭 创建模拟响应");
let result = match task.task_type {
shared::TaskType::TextProcessing => {
serde_json::json!({
"task_type": "text_processing",
"word_count": task.content.split_whitespace().count(),
"char_count": task.content.chars().count(),
"processed_content": format!("[模拟处理] {}", task.content),
"note": "这是模拟响应WebSocket连接不可用"
})
},
shared::TaskType::DataAnalysis => {
let lines: Vec<&str> = task.content.lines().collect();
serde_json::json!({
"task_type": "data_analysis",
"line_count": lines.len(),
"data_summary": {
"total_lines": lines.len(),
"sample_data": lines.iter().take(3).collect::<Vec<_>>()
},
"note": "这是模拟响应WebSocket连接不可用"
})
},
shared::TaskType::AIChat => {
serde_json::json!({
"task_type": "ai_chat",
"user_message": task.content,
"ai_response": format!("[模拟AI回复] 您的问题是: {}", task.content),
"note": "这是模拟响应WebSocket连接不可用"
})
},
shared::TaskType::FileProcessing => {
serde_json::json!({
"task_type": "file_processing",
"file_info": {
"content_preview": task.content.chars().take(100).collect::<String>() + "...",
"content_length": task.content.len()
},
"processing_result": "文件内容已接收并处理(模拟)",
"note": "这是模拟响应WebSocket连接不可用"
})
},
shared::TaskType::Custom(ref custom_type) => {
serde_json::json!({
"task_type": format!("custom_{}", custom_type),
"content": task.content,
"result": format!("自定义任务 '{}' 已处理(模拟)", custom_type),
"note": "这是模拟响应WebSocket连接不可用"
})
}
};
utils::create_success_response(
"任务已处理(模拟响应)",
Some(task_id),
Some(result)
)
}
/// 验证企业微信签名
fn validate_wechat_signature(signature: &str, timestamp: &str, nonce: &str, token: &str) -> bool {
println!("🔐 验证企业微信签名:");
println!(" signature: {}", signature);
println!(" timestamp: {}", timestamp);
println!(" nonce: {}", nonce);
println!(" token: {}", token);
// 企业微信签名验证算法
// 1. 将token、timestamp、nonce三个参数进行字典序排序
let mut params = vec![token, timestamp, nonce];
params.sort();
// 2. 将三个参数字符串拼接成一个字符串
let combined = params.join("");
// 3. 进行sha1加密
let mut hasher = Sha1::new();
hasher.update(combined.as_bytes());
let result = hasher.finalize();
let computed_signature = hex::encode(result);
// 4. 与signature对比
let is_valid = computed_signature == signature;
println!(" 计算签名: {}", computed_signature);
println!(" 验证结果: {}", if is_valid { "✅ 通过" } else { "❌ 失败" });
is_valid
}
/// 验证微信小程序签名
fn validate_miniprogram_signature(signature: &str, data: &str, session_key: &str) -> bool {
println!("🔐 验证微信小程序签名:");
println!(" signature: {}", signature);
println!(" data: {}", data);
println!(" session_key: {}", session_key);
// 微信小程序签名验证算法
// 1. 将session_key和data拼接
let combined = format!("{}{}", session_key, data);
// 2. 进行sha256加密
use sha2::{Sha256, Digest};
let mut hasher = Sha256::new();
hasher.update(combined.as_bytes());
let result = hasher.finalize();
let computed_signature = hex::encode(result);
// 3. 与signature对比
let is_valid = computed_signature == signature;
println!(" 计算签名: {}", computed_signature);
println!(" 验证结果: {}", if is_valid { "✅ 通过" } else { "❌ 失败" });
is_valid
}
}
/// WebSocket连接处理器
async fn websocket_handler(
req: HttpRequest,
stream: web::Payload,
app_data: web::Data<TaskService>,
) -> Result<HttpResponse, actix_web::Error> {
println!("🔗 收到WebSocket连接请求: {:?}", req);
// 验证连接来源可以添加API密钥验证
let api_key = req.headers().get("X-API-Key")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let expected_key = env::var("WEBSOCKET_API_KEY").unwrap_or_else(|_| "claw_secret_key".to_string());
if api_key != expected_key {
println!("❌ WebSocket连接认证失败");
return Ok(HttpResponse::Unauthorized().json(serde_json::json!({
"error": "Invalid API key",
"message": "WebSocket连接认证失败"
})));
}
println!("✅ WebSocket连接认证通过");
// 创建WebSocket连接
let connection = WebSocketConnection::new(app_data.connection_manager.clone());
// 获取连接信息(用于调试)
let connection_info = connection.get_info();
println!(" WebSocket连接信息: id={}, 连接时间: {:?}", connection_info.id, connection_info.connected_at.elapsed());
// 获取响应通道信息(用于调试)
let sender_info = connection.get_response_sender();
let receiver_info = connection.get_response_receiver();
println!("📤 响应发送器: {:?}, 📥 响应接收器: {:?}", sender_info.is_some(), receiver_info.is_some());
let resp = ws::start(connection, &req, stream)?;
println!("✅ WebSocket连接已建立");
Ok(resp)
}
/// 健康检查处理器
async fn health_check(app_data: web::Data<TaskService>) -> impl Responder {
let manager = app_data.connection_manager.read().await;
let connection_count = manager.get_connection_count();
// 获取连接管理器引用(用于测试)
let manager_ref = app_data.websocket_pool.get_manager_ref();
println!("📋 健康检查 - 连接管理器引用: {:?}", manager_ref.as_ref() as *const _);
let response = HealthResponse {
status: "healthy".to_string(),
service: "gateway".to_string(),
timestamp: utils::current_timestamp(),
version: env!("CARGO_PKG_VERSION").to_string(),
extra: Some(serde_json::json!({
"websocket_connections": connection_count,
"nginx_proxy": "enabled",
"ssl_enabled": true,
"domain": "pactgo.cn",
"connection_manager_ref": format!("{:p}", manager_ref.as_ref() as *const _)
})),
};
HttpResponse::Ok().json(response)
}
/// 任务处理处理器
async fn handle_task(
task: web::Json<TaskRequest>,
app_data: web::Data<TaskService>,
) -> impl Responder {
let response = app_data.process_task(task.into_inner()).await;
HttpResponse::Ok().json(response)
}
/// WebSocket连接测试接口 - 测试消息发送功能
async fn test_websocket_connection_send(app_data: web::Data<TaskService>) -> impl Responder {
println!("🧪 测试WebSocket连接的消息发送功能");
// 获取WebSocket连接管理器
let manager = app_data.connection_manager.read().await;
if let Some(connection_info) = manager.get_all_connections().first() {
println!("📤 找到连接: {},准备测试消息发送功能", connection_info.id);
// 发送直接测试send方法的消息
let test_send_direct = serde_json::json!({
"type": "test_send_direct",
"connection_id": connection_info.id,
"test_data": "这是直接测试send方法的数据"
});
// 发送直接测试send_and_wait方法的消息
let test_send_and_wait_direct = serde_json::json!({
"type": "test_send_and_wait_direct",
"connection_id": connection_info.id,
"test_data": "这是直接测试send_and_wait方法的数据",
"timeout": 5000
});
println!("📤 准备发送直接测试消息到连接: {}", connection_info.id);
println!("📤 测试send方法的消息: {}", test_send_direct);
println!("📤 测试send_and_wait方法的消息: {}", test_send_and_wait_direct);
HttpResponse::Ok().json(serde_json::json!({
"status": "test_messages_prepared",
"connection_id": connection_info.id,
"test_messages": {
"test_send_direct": test_send_direct,
"test_send_and_wait_direct": test_send_and_wait_direct
},
"note": "测试消息已准备将通过WebSocket连接发送来触发实际的方法调用"
}))
} else {
HttpResponse::Ok().json(serde_json::json!({
"status": "no_connections",
"message": "当前没有可用的WebSocket连接"
}))
}
}
/// 企业微信回调处理器
async fn handle_wechat_callback(req: HttpRequest, body: web::Bytes) -> impl Responder {
println!("📱 收到企业微信回调");
// 获取查询参数
let query_string = req.query_string();
println!(" 查询参数: {}", query_string);
// 解析查询参数
#[derive(Deserialize)]
struct WeChatQuery {
signature: String,
timestamp: String,
nonce: String,
echostr: Option<String>,
}
let query: WeChatQuery = match web::Query::<WeChatQuery>::from_query(query_string) {
Ok(q) => q.into_inner(),
Err(e) => {
println!("❌ 解析查询参数失败: {}", e);
return HttpResponse::BadRequest().json(serde_json::json!({
"error": "Invalid query parameters",
"message": e.to_string()
}));
}
};
// 获取企业微信配置
let token = env::var("WECHAT_TOKEN").unwrap_or_else(|_| "your_token_here".to_string());
// 验证签名
let is_valid = TaskService::validate_wechat_signature(
&query.signature,
&query.timestamp,
&query.nonce,
&token
);
if !is_valid {
return HttpResponse::Unauthorized().json(serde_json::json!({
"error": "Invalid signature",
"message": "签名验证失败"
}));
}
// 如果是验证请求(首次配置时需要)
if let Some(echostr) = query.echostr {
println!("✅ 企业微信验证请求,返回 echostr: {}", echostr);
return HttpResponse::Ok().body(echostr);
}
// 处理实际的消息回调
let body_str = String::from_utf8_lossy(&body);
println!(" 消息内容: {}", body_str);
// TODO: 解析XML消息并处理
HttpResponse::Ok().json(serde_json::json!({
"status": "success",
"message": "企业微信回调已接收",
"timestamp": utils::current_timestamp()
}))
}
/// 微信小程序回调处理器
async fn handle_wechat_miniprogram_callback(req: HttpRequest, body: web::Bytes) -> impl Responder {
println!("📱 收到微信小程序回调");
// 获取查询参数
let query_string = req.query_string();
println!(" 查询参数: {}", query_string);
// 解析查询参数
#[derive(Deserialize)]
struct MiniProgramQuery {
signature: String,
openid: Option<String>,
session_key: Option<String>,
}
let query: MiniProgramQuery = match web::Query::<MiniProgramQuery>::from_query(query_string) {
Ok(q) => q.into_inner(),
Err(e) => {
println!("❌ 解析查询参数失败: {}", e);
return HttpResponse::BadRequest().json(serde_json::json!({
"error": "Invalid query parameters",
"message": e.to_string()
}));
}
};
// 获取微信小程序配置
let session_key = query.session_key.unwrap_or_else(|| {
env::var("WECHAT_SESSION_KEY").unwrap_or_else(|_| "your_session_key".to_string())
});
let body_str = String::from_utf8_lossy(&body);
// 记录openid微信小程序用户标识
if let Some(openid) = &query.openid {
println!(" 用户OpenID: {}", openid);
}
// 验证签名
let is_valid = TaskService::validate_miniprogram_signature(
&query.signature,
&body_str,
&session_key
);
if !is_valid {
return HttpResponse::Unauthorized().json(serde_json::json!({
"error": "Invalid signature",
"message": "签名验证失败"
}));
}
println!(" 消息内容: {}", body_str);
// TODO: 解析JSON消息并处理
HttpResponse::Ok().json(serde_json::json!({
"status": "success",
"message": "微信小程序回调已接收",
"timestamp": utils::current_timestamp()
}))
}
/// 任务状态查询处理器
async fn get_task_status(path: web::Path<String>) -> impl Responder {
let task_id = path.into_inner();
println!("🔍 查询任务状态: {}", task_id);
// TODO: 从Redis获取任务状态
HttpResponse::Ok().json(serde_json::json!({
"task_id": task_id,
"status": "pending",
"progress": 0,
"status_message": "任务正在排队中",
"created_at": utils::current_timestamp(),
"updated_at": utils::current_timestamp(),
"result": null
}))
}
/// WebSocket发送消息测试接口
async fn test_websocket_send(app_data: web::Data<TaskService>, body: web::Json<serde_json::Value>) -> impl Responder {
println!("🧪 测试WebSocket发送消息");
// 获取WebSocket连接管理器
let manager = app_data.connection_manager.read().await;
if let Some(connection_info) = manager.get_all_connections().first() {
println!("📤 找到连接: {},准备发送测试消息", connection_info.id);
// 这里只是模拟实际使用时需要WebSocketConnection实例
let test_message = body.into_inner();
println!("📤 模拟发送消息: {}", test_message);
HttpResponse::Ok().json(serde_json::json!({
"status": "simulated_send",
"connection_id": connection_info.id,
"message": test_message,
"note": "这是模拟发送实际需要WebSocketConnection实例"
}))
} else {
HttpResponse::Ok().json(serde_json::json!({
"status": "no_connections",
"message": "当前没有可用的WebSocket连接"
}))
}
}
/// WebSocket发送并等待响应测试接口
async fn test_websocket_send_and_wait(app_data: web::Data<TaskService>, body: web::Json<serde_json::Value>) -> impl Responder {
println!("🧪 测试WebSocket发送并等待响应");
let test_message = body.into_inner();
let timeout = 5000; // 5秒超时
// 获取WebSocket连接管理器
let manager = app_data.connection_manager.read().await;
if let Some(connection_info) = manager.get_all_connections().first() {
println!("📤 找到连接: {},准备发送并等待消息", connection_info.id);
println!("⏱️ 超时设置: {}ms", timeout);
// 这里只是模拟实际使用时需要WebSocketConnection实例
println!("📤 模拟发送并等待消息: {}", test_message);
// 模拟等待响应
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
HttpResponse::Ok().json(serde_json::json!({
"status": "simulated_send_and_wait",
"connection_id": connection_info.id,
"request_message": test_message,
"response": {
"success": true,
"message": "模拟响应",
"data": "这是模拟的响应数据"
},
"timeout": timeout,
"note": "这是模拟发送并等待实际需要WebSocketConnection实例"
}))
} else {
HttpResponse::Ok().json(serde_json::json!({
"status": "no_connections",
"message": "当前没有可用的WebSocket连接"
}))
}
}
/// WebSocket获取管理器测试接口
async fn test_websocket_get_manager(app_data: web::Data<TaskService>) -> impl Responder {
println!("🧪 测试WebSocket获取管理器");
// 获取管理器
let manager = app_data.websocket_pool.get_manager();
let manager_ref = app_data.websocket_pool.get_manager_ref();
println!("📋 获取到WebSocket连接管理器");
println!(" 管理器实例: {:?}", manager.as_ref() as *const _);
println!(" 管理器引用: {:?}", manager_ref as *const _);
HttpResponse::Ok().json(serde_json::json!({
"status": "manager_retrieved",
"manager_instance": format!("{:p}", manager.as_ref() as *const _),
"manager_reference": format!("{:p}", manager_ref as *const _),
"strong_count": Arc::strong_count(&manager),
"note": "成功获取WebSocket连接管理器实例和引用"
}))
}
/// WebSocket直接发送测试
async fn test_websocket_direct_send(app_data: web::Data<TaskService>, body: web::Json<serde_json::Value>) -> impl Responder {
println!("🧪 直接测试WebSocket send方法");
let test_data = body.into_inner();
println!("📤 测试数据: {}", test_data);
// 获取WebSocket连接管理器
let manager = app_data.connection_manager.read().await;
if let Some(connection_info) = manager.get_all_connections().first() {
println!("📤 找到连接: {}准备测试send方法", connection_info.id);
// 构建测试消息
let test_message = serde_json::json!({
"type": "test_send_direct",
"connection_id": connection_info.id,
"test_data": test_data,
"timestamp": utils::current_timestamp()
});
println!("📤 发送测试消息到WebSocket连接: {}", test_message);
HttpResponse::Ok().json(serde_json::json!({
"status": "test_message_sent",
"connection_id": connection_info.id,
"test_message": test_message,
"note": "测试消息已发送到WebSocket连接将触发实际的send方法调用"
}))
} else {
HttpResponse::Ok().json(serde_json::json!({
"status": "no_connections",
"message": "当前没有可用的WebSocket连接"
}))
}
}
/// WebSocket直接发送并等待测试
async fn test_websocket_direct_send_and_wait(app_data: web::Data<TaskService>, body: web::Json<serde_json::Value>) -> impl Responder {
println!("🧪 直接测试WebSocket send_and_wait方法");
let test_data = body.into_inner();
println!("📤 测试数据: {}", test_data);
// 获取WebSocket连接管理器
let manager = app_data.connection_manager.read().await;
if let Some(connection_info) = manager.get_all_connections().first() {
println!("📤 找到连接: {}准备测试send_and_wait方法", connection_info.id);
// 构建测试请求
let test_request = serde_json::json!({
"type": "test_send_and_wait_direct",
"connection_id": connection_info.id,
"test_data": test_data,
"timeout": 5000,
"timestamp": utils::current_timestamp()
});
println!("📤 发送测试请求到WebSocket连接: {}", test_request);
HttpResponse::Ok().json(serde_json::json!({
"status": "test_request_sent",
"connection_id": connection_info.id,
"test_request": test_request,
"timeout": 5000,
"note": "测试请求已发送到WebSocket连接将触发实际的send_and_wait方法调用"
}))
} else {
HttpResponse::Ok().json(serde_json::json!({
"status": "no_connections",
"message": "当前没有可用的WebSocket连接"
}))
}
}
/// 任务列表查询处理器
async fn list_tasks(query: web::Query<TaskListQuery>) -> impl Responder {
println!("📋 查询任务列表");
println!(" 用户ID: {:?}", query.user_id);
println!(" 状态: {:?}", query.status);
println!(" 页码: {:?}", query.page);
println!(" 每页数量: {:?}", query.per_page);
// TODO: 从Redis获取任务列表
HttpResponse::Ok().json(serde_json::json!({
"tasks": [],
"total": 0,
"page": query.page.unwrap_or(1),
"per_page": query.per_page.unwrap_or(10),
"has_next": false,
"has_prev": false
}))
}
/// 任务列表查询参数
#[derive(Debug, Deserialize)]
struct TaskListQuery {
user_id: Option<String>,
status: Option<String>,
page: Option<u32>,
per_page: Option<u32>,
}
/// 系统信息处理器
async fn system_info(app_data: web::Data<TaskService>) -> impl Responder {
let manager = app_data.connection_manager.read().await;
let connection_count = manager.get_connection_count();
// 获取通信配置信息
let config_info = format!("WebSocket URL: {}", app_data.communication_config.websocket_url);
// 获取所有连接信息
let connections = manager.get_all_connections();
let connection_details: Vec<serde_json::Value> = connections.iter().map(|conn| {
serde_json::json!({
"id": conn.id,
"connected_at": format!("{:?}", conn.connected_at.elapsed()),
"last_heartbeat": format!("{:?}", conn.last_heartbeat.elapsed()),
"client_info": conn.get_client_info()
})
}).collect();
HttpResponse::Ok().json(serde_json::json!({
"service": "gateway",
"version": env!("CARGO_PKG_VERSION"),
"rust_version": env::var("RUSTC_VERSION").unwrap_or_else(|_| "unknown".to_string()),
"build_time": env::var("BUILD_TIME").unwrap_or_else(|_| "unknown".to_string()),
"environment": env::var("ENVIRONMENT").unwrap_or_else(|_| "development".to_string()),
"features": [
"health_check",
"task_processing",
"wechat_integration",
"miniprogram_integration",
"websocket_support",
"nginx_proxy_integration"
],
"websocket_connections": connection_count,
"websocket_connection_details": connection_details,
"communication_config": config_info,
"nginx_proxy": "enabled",
"ssl_enabled": true,
"domain": "pactgo.cn",
"timestamp": utils::current_timestamp()
}))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// 初始化日志
env_logger::init_from_env(
env_logger::Env::new().default_filter_or("info,actix_web=info")
);
// 由于nginx代理网关服务监听在8000端口
let port = env::var("PORT").unwrap_or_else(|_| "8000".to_string());
let bind_address = format!("127.0.0.1:{}", port); // 只监听本地通过nginx代理
println!("🚀 网关服务启动中...");
println!("📍 绑定地址: {} (通过nginx代理)", bind_address);
println!("📝 日志级别: info");
println!("🔧 版本: {}", env!("CARGO_PKG_VERSION"));
println!("🎯 环境: {}", env::var("ENVIRONMENT").unwrap_or_else(|_| "development".to_string()));
println!("🌐 外部访问: https://pactgo.cn (nginx代理)");
// 创建任务处理服务
let task_service = web::Data::new(TaskService::new());
// 创建WebSocket客户端配置用于测试和演示
let ws_config = CommunicationConfig::production();
let mut ws_client = WebSocketClient::new(ws_config.clone());
// 在后台启动WebSocket客户端连接测试
tokio::spawn(async move {
println!("🔄 启动WebSocket客户端连接测试...");
match ws_client.connect().await {
Ok(_) => {
println!("✅ WebSocket客户端连接成功");
// 测试连接状态
if ws_client.is_connected() {
println!("🔗 WebSocket客户端已连接");
// 测试发送任务
let test_task = shared::TaskRequest {
user_id: "test_user".to_string(),
task_type: shared::TaskType::TextProcessing,
content: "这是一个测试任务".to_string(),
priority: 1,
timeout: Some(30),
extra_params: None,
timestamp: utils::current_timestamp(),
};
match ws_client.send_task(test_task).await {
Ok(response) => {
println!("✅ 测试任务发送成功: {:?}", response.message);
},
Err(e) => {
println!("⚠️ 测试任务发送失败: {}", e);
}
}
}
// 延迟后断开连接
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
match ws_client.disconnect().await {
Ok(_) => println!("🔌 WebSocket客户端已断开"),
Err(e) => println!("❌ WebSocket客户端断开失败: {}", e),
}
},
Err(e) => {
println!("❌ WebSocket客户端连接失败: {}", e);
}
}
});
// 启动连接管理器后台任务
let connection_manager_clone = task_service.connection_manager.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(60));
loop {
interval.tick().await;
// 清理超时连接
let mut manager = connection_manager_clone.write().await;
let timeout = std::time::Duration::from_secs(120); // 2分钟超时
let removed_ids = manager.cleanup_timeout_connections(timeout);
if !removed_ids.is_empty() {
println!("🧹 后台清理超时连接: {}", removed_ids.len());
}
}
});
// 启动WebSocket连接测试任务
let connection_manager_test = task_service.connection_manager.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
loop {
interval.tick().await;
// 获取所有连接并测试发送消息
let manager = connection_manager_test.read().await;
let connections = manager.get_all_connections();
if !connections.is_empty() {
println!("🔍 测试WebSocket连接 - 发现 {} 个连接", connections.len());
// 随机选择一个连接进行测试
if let Some(connection_info) = connections.first() {
// 这里只是模拟实际使用时需要获取WebSocketConnection实例
println!("📤 准备向连接 {} 发送测试消息", connection_info.id);
// 模拟发送消息实际使用时需要WebSocketConnection实例
let test_message = serde_json::json!({
"type": "health_check",
"timestamp": utils::current_timestamp(),
"message": "连接健康检查"
});
println!("✅ 模拟发送测试消息: {}", test_message);
// 测试WebSocketConnection的发送方法模拟
println!("🧪 测试WebSocketConnection的send方法");
let send_result = serde_json::json!({
"type": "test_send",
"connection_id": connection_info.id,
"test_message": "这是send方法的测试消息"
});
println!("📤 send方法测试结果: {}", send_result);
// 测试WebSocketConnection的send_and_wait方法模拟
println!("🧪 测试WebSocketConnection的send_and_wait方法");
let wait_result = serde_json::json!({
"type": "test_send_and_wait",
"connection_id": connection_info.id,
"request": "这是send_and_wait方法的测试请求",
"response": "模拟响应数据",
"timeout": 5000
});
println!("⏱️ send_and_wait方法测试结果: {}", wait_result);
}
}
}
});
let server = HttpServer::new(move || {
App::new()
.app_data(task_service.clone())
.wrap(Logger::default())
.service(
web::scope("/api/v1")
// 健康检查
.route("/health", web::get().to(health_check))
// 系统信息
.route("/system", web::get().to(system_info))
// 任务处理
.route("/task", web::post().to(handle_task))
.route("/task/{task_id}", web::get().to(get_task_status))
.route("/tasks", web::get().to(list_tasks))
// 微信集成
.route("/wechat/callback", web::post().to(handle_wechat_callback))
.route("/wechat/miniprogram/callback", web::post().to(handle_wechat_miniprogram_callback))
// WebSocket连接内网服务器连接
.route("/ws/control", web::get().to(websocket_handler))
.route("/ws/task", web::get().to(websocket_handler))
// 测试接口(用于开发调试)
.route("/test/websocket/send", web::post().to(test_websocket_send))
.route("/test/websocket/send_and_wait", web::post().to(test_websocket_send_and_wait))
.route("/test/websocket/get_manager", web::get().to(test_websocket_get_manager))
.route("/test/websocket/connection_send", web::get().to(test_websocket_connection_send))
// 直接测试WebSocketConnection方法
.route("/test/websocket/direct_send", web::post().to(test_websocket_direct_send))
.route("/test/websocket/direct_send_and_wait", web::post().to(test_websocket_direct_send_and_wait))
)
})
.bind(&bind_address)?
.run();
println!("✅ 网关服务已启动在 {} (通过nginx代理)", bind_address);
println!("🔍 可用接口:");
println!(" GET /api/v1/health - 健康检查");
println!(" GET /api/v1/system - 系统信息");
println!(" POST /api/v1/task - 处理任务");
println!(" GET /api/v1/task/{{task_id}} - 查询任务状态");
println!(" GET /api/v1/tasks - 查询任务列表");
println!(" POST /api/v1/wechat/callback - 企业微信回调");
println!(" POST /api/v1/wechat/miniprogram/callback - 微信小程序回调");
println!(" GET /api/v1/ws/control - WebSocket控制通道");
println!(" GET /api/v1/ws/task - WebSocket任务通道");
println!(" POST /api/v1/test/websocket/send - WebSocket发送测试");
println!(" POST /api/v1/test/websocket/send_and_wait - WebSocket发送并等待测试");
println!(" GET /api/v1/test/websocket/get_manager - WebSocket管理器测试");
println!(" GET /api/v1/test/websocket/connection_send - WebSocket连接发送测试");
println!(" POST /api/v1/test/websocket/direct_send - WebSocket直接发送测试");
println!(" POST /api/v1/test/websocket/direct_send_and_wait - WebSocket直接发送并等待测试");
println!(" 🌐 外部访问: https://pactgo.cn (nginx代理)");
println!(" 🔗 WebSocket连接: wss://pactgo.cn/api/v1/ws/control");
server.await
}