fix: redis cache bug

This commit is contained in:
Liujian committed 2025-10-17 15:26:01 +08:00
1 parent 0ae689f9fe
commit 7c75c07216
9 files changed
+120 -61

No files matched your search

+3 -3
View File
@@ -4,9 +4,9 @@
FROM python:3.12.11-alpine3.22
RUN apk add nodejs=~22 npm uv nginx
ENV TZ=Asia/Shanghai
RUN ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone
# ENV TZ=Asia/Shanghai
# RUN ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
# && echo "Asia/Shanghai" > /etc/timezone
ARG APP XPack-MCP-Market
ARG VERSION latest
+2 -2
View File
@@ -72,8 +72,8 @@ clean_build_cache() {
frontend_build() {
echo_info "Begin frontend build..."
cd "${FRONTEND_DIR}" || exit 1
echo_debug "Running command: pnpm install --frozen-lockfile"
pnpm install --frozen-lockfile || exit 1
echo_debug "Running command: pnpm install"
pnpm install || exit 1
echo_debug "Running command: pnpm build"
pnpm build || exit 1
+4 -8
View File
@@ -39,8 +39,7 @@ MYSQL_DATA_MOUNT="/var/lib/xpack/mysql"
REDIS_PASSWORD="redis_6sJZDm"
REDIS_MAP_PORT=6379
XPACK_MCP_MARKET_WEB_MAP_PORT=3000
XPACK_MCP_MARKET_MCP_MAP_PORT=8002
XPACK_MCP_MARKET_MAP_PORT=3000
RABBITMQ_USER="rabbitmq"
RABBITMQ_PASSWORD="rabbitmq_Gs123dA"
@@ -881,14 +880,13 @@ upgrade_xpack_mcp_market() {
run_xpack_mcp_market() {
imageName=$(download_package_docker "program.xpack_mcp_market")
dockerCmd="docker run -dt --name ${XPACK_MCP_MARKET_CONTAINER_NAME} --restart=always --privileged=true \
--network=${NETWORK_NAME} -p ${XPACK_MCP_MARKET_WEB_MAP_PORT}:3000 -p ${XPACK_MCP_MARKET_MCP_MAP_PORT}:8002 \
--network=${NETWORK_NAME} -p ${XPACK_MCP_MARKET_MAP_PORT}:80 \
${imageName}"
echo -e `${dockerCmd}`
write_env_var ${ENV_XPACK_MCP_MARKET_WEB_PORT} ${XPACK_MCP_MARKET_WEB_MAP_PORT}
write_env_var ${ENV_XPACK_MCP_MARKET_MCP_PORT} ${XPACK_MCP_MARKET_MCP_MAP_PORT}
write_env_var ${ENV_XPACK_MCP_MARKET_WEB_PORT} ${XPACK_MCP_MARKET_MAP_PORT}
wait_for "XPACK MCP MARKET" "curl -s -o /dev/null http://127.0.0.1:${XPACK_MCP_MARKET_WEB_MAP_PORT}"
wait_for "XPACK MCP MARKET" "curl -s -o /dev/null http://127.0.0.1:${XPACK_MCP_MARKET_MAP_PORT}"
}
install_xpack_mcp_market() {
@@ -951,14 +949,12 @@ print_xpack_mcp_market_info() {
webPort=$(read_env_var ${ENV_XPACK_MCP_MARKET_WEB_PORT})
mcpPort=$(read_env_var ${ENV_XPACK_MCP_MARKET_MCP_PORT})
echo_pass "XPack MCP Market has run successfully. Version is ${XPACK_VERSION}."
echo_info "The Web UI information is as follows:"
echo_info "Homepage: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}"
echo_info "Admin dashboard: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}/admin"
echo_info "Admin Username: admin"
echo_info "Admin Password: 123456789"
echo_info "MCP endpoint: http://$(read_env_var ${ENV_EXTERNAL_IP}):${mcpPort}"
}
valid_port() {
+14 -14
View File
@@ -1,6 +1,6 @@
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `mcp_call_log` MODIFY COLUMN `process_status` enum('pending','processed','failed') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT 'pending' COMMENT '处理状态,\'pending\',\'processed\',\'failed\'' AFTER `call_end_time`;
ALTER TABLE `mcp_call_log` MODIFY COLUMN `process_status` enum('pending','processed','failed') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT 'pending' COMMENT 'Processing status: pending, processed, failed' AFTER `call_end_time`;
ALTER TABLE `mcp_service` ADD COLUMN `headers` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT 'headers config,like: [{\"name\":\"name\",\"value\":\"value\",\"description\":\"description\"}]' AFTER `auth_token`;
@@ -39,39 +39,39 @@ END;
CREATE TABLE `onboarding_task` (
`id` bigint NOT NULL AUTO_INCREMENT,
`task_id` char(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '任务ID',
`user_id` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户ID',
`task_status` tinyint NOT NULL COMMENT '任务状态,0:未完成,1:已完成',
`task_id` char(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Task ID',
`user_id` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'User ID',
`task_status` tinyint NOT NULL COMMENT 'Task status: 0 = incomplete, 1 = completed',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk`(`task_id` ASC, `user_id` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '新手引导任务表' ROW_FORMAT = DYNAMIC;
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'Onboarding task table' ROW_FORMAT = DYNAMIC;
CREATE TABLE `stats_mcp_service_date` (
`stats_date` datetime NOT NULL,
`service_id` char(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`call_count` int NOT NULL DEFAULT '0' COMMENT '调用次数',
`call_count` int NOT NULL DEFAULT '0' COMMENT 'Call count',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
UNIQUE KEY `uk_stats` (`stats_date`,`service_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC;
ALTER TABLE `temp_mcp_service` ADD COLUMN `headers` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '请求头配置,[{\"name\":\"name\",\"value\":\"value\",\"description\":\"description\"}]' AFTER `auth_token`;
ALTER TABLE `temp_mcp_service` ADD COLUMN `headers` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT 'Request headers configuration,[{\"name\":\"name\",\"value\":\"value\",\"description\":\"description\"}]' AFTER `auth_token`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `id` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '主键,服务ID' FIRST;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `id` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Primary key, service ID' FIRST;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `auth_method` enum('free','apikey','token') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '废弃,鉴权方式:free(免费)、apikey(API 密钥)、token(令牌)' AFTER `base_url`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `auth_method` enum('free','apikey','token') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'Deprecated, authentication method: free, apikey, token' AFTER `base_url`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `auth_header` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '废弃,鉴权请求头名称' AFTER `auth_method`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `auth_header` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'Deprecated, authentication header name' AFTER `auth_method`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `auth_token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '废弃,鉴权令牌值' AFTER `auth_header`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `auth_token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'Deprecated, authentication token value' AFTER `auth_header`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `input_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT '输入token价钱' AFTER `price`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `input_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'Input token price' AFTER `price`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `output_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT '输出token价钱' AFTER `input_token_price`;
ALTER TABLE `temp_mcp_service` MODIFY COLUMN `output_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'Output token price' AFTER `input_token_price`;
ALTER TABLE `user` MODIFY COLUMN `role_id` int NOT NULL COMMENT '角色 ID:0:未确定、1(租户)、2(租户下的普通用户)' AFTER `register_type`;
ALTER TABLE `user` MODIFY COLUMN `role_id` int NOT NULL COMMENT 'Role ID: 0 = unspecified, 1 = tenant, 2 = tenant user' AFTER `register_type`;
DELETE FROM sys_config WHERE `key` = "mcp_server_prefix";
@@ -241,7 +241,7 @@ class BillingMessageHandler:
new_balance: New balance
"""
try:
cache_key = f"wallet:balance:{user_id}"
cache_key = f"xpack:wallet:balance:{user_id}"
self.redis.set(cache_key, str(new_balance), ex=300) # 5 minutes expiration
except Exception as e:
logger.warning(f"Failed to update wallet cache - User ID: {user_id}: {str(e)}")
@@ -14,6 +14,7 @@ from services.common.models.mcp_tool_api import McpToolApi, HttpMethod
from services.common.models.temp_mcp_service import TempMcpService, AuthMethod as TempAuthMethod, ChargeType as TempChargeType
from services.common.models.temp_mcp_tool_api import TempMcpToolApi, HttpMethod as TempHttpMethod
from services.admin_service.services.openapi_helper import OpenApiForAI
from services.common.redis import redis_client
logger = logging.getLogger(__name__)
@@ -76,6 +77,21 @@ class McpManagerService:
self.mcp_tool_api_repository = McpToolApiRepository(db)
self.temp_mcp_service_repository = TempMcpServiceRepository(db)
self.temp_mcp_tool_api_repository = TempMcpToolApiRepository(db)
self.redis = redis_client
def _delete_service_price_cache(self, user_id: str) -> None:
"""
Update wallet balance cache in Redis
Args:
user_id: User ID
new_balance: New balance
"""
try:
cache_key = f"xpack:service:price:{user_id}"
self.redis.delete(cache_key) # 5 minutes expiration
except Exception as e:
logger.warning(f"Failed to delete service price cache - Service ID: {user_id}: {str(e)}")
def update_enabled(self, id: str, enabled: int) -> McpService:
return self.mcp_service_repository.update_enabled(id, enabled)
@@ -173,25 +189,33 @@ class McpManagerService:
if "base_url" in body and body["base_url"] is not None:
existing_service.base_url = body["base_url"]
if "charge_type" in body and body["charge_type"] is not None:
charge_type_value = body["charge_type"]
try:
old_charge_type = existing_service.charge_type
if isinstance(charge_type_value, str):
existing_service.charge_type = ChargeType(charge_type_value.lower())
else:
existing_service.charge_type = charge_type_value
if old_charge_type != existing_service.charge_type:
self._delete_service_price_cache(service_id)
except ValueError:
# If the provided value is not a valid ChargeType, default to FREE
existing_service.charge_type = ChargeType.FREE
match existing_service.charge_type:
case ChargeType.PER_CALL:
if "price" in body and body["price"] is not None:
if body["price"] != existing_service.price:
self._delete_service_price_cache(service_id)
existing_service.price = body["price"]
case ChargeType.PER_TOKEN:
if "input_token_price" in body and body["input_token_price"] is not None:
if body["input_token_price"] != existing_service.input_token_price:
self._delete_service_price_cache(service_id)
existing_service.input_token_price = body["input_token_price"]
if "output_token_price" in body and body["output_token_price"] is not None:
if body["output_token_price"] != existing_service.output_token_price:
self._delete_service_price_cache(service_id)
existing_service.output_token_price = body["output_token_price"]
if "tags" in body and body["tags"] is not None:
# If provided as array, convert to string for storage
@@ -3,6 +3,7 @@ import logging
import asyncio
from uuid import uuid4
from typing import Optional
from decimal import Decimal
from sqlalchemy.orm import Session
from services.admin_service.repositories.user_repository import UserRepository
from services.admin_service.repositories.user_wallet_repository import UserWalletRepository
@@ -14,6 +15,7 @@ from services.admin_service.utils.wxpay_client import WxPayClient,WxPayConfig
from services.admin_service.constants.sys_config_key import (
KEY_PLATFORM_NAME
)
from services.common.redis import redis_client
logger = logging.getLogger(__name__)
@@ -25,6 +27,7 @@ class PaymentService:
self.user_wallet_history_repository = UserWalletHistoryRepository(db)
self.payment_channel_service = PaymentChannelService(db)
self.sys_config_repository = SysConfigRepository(db)
self.redis = redis_client
def _get_stripe_config(self) -> Optional[dict]:
"""Get Stripe configuration"""
@@ -257,6 +260,7 @@ class PaymentService:
return False
if status == 1:
# Add wallet balance and complete the deposit
return self._add_wallet_balance(payment_id, payment_channel_id)
self.user_wallet_history_repository.set_status(payment_id, payment_channel_id, status)
return True
@@ -311,6 +315,7 @@ class PaymentService:
)
if success:
self._delete_wallet_cache(user_id)
# Create wallet history record after successful balance update
return self.user_wallet_history_repository.deposit_complete(payment_id, payment_channel_id)
else:
@@ -327,6 +332,20 @@ class PaymentService:
logger.error(f"Failed to update balance after {max_retries} attempts for user_id {user_id}")
return False
def _delete_wallet_cache(self, user_id: str) -> None:
"""
Update wallet balance cache in Redis
Args:
user_id: User ID
new_balance: New balance
"""
try:
cache_key = f"xpack:wallet:balance:{user_id}"
self.redis.delete(cache_key) # 5 minutes expiration
except Exception as e:
logger.warning(f"Failed to delete wallet cache - User ID: {user_id}: {str(e)}")
def platform_payment(self, user_id: str, amount: float, transaction_id: str, typ: str = "incr", payment_method: str = "platform", max_retries: int = 3) -> bool:
"""
Process platform payment for user wallet with high-concurrency transaction safety.
@@ -389,7 +408,7 @@ class PaymentService:
self.user_wallet_history_repository.set_balance(
user_id=user_id, amount=amount, payment_method=payment_method, transaction_id=transaction_id,status=1
)
self._delete_wallet_cache(user_id)
logger.info(f"Successfully updated balance for user_id {user_id}: {current_wallet.balance} -> {new_balance}")
return True
@@ -179,7 +179,7 @@ class BillingService:
Tuple[Decimal, ChargeType]: Price and charge type
"""
# Try to get from Redis cache
cache_key = f"service:price:{service_id}"
cache_key = f"xpack:service:price:{service_id}"
cached_data = self.redis.get(cache_key)
if cached_data:
try:
@@ -235,7 +235,7 @@ class BillingService:
Decimal: User balance
"""
# Try to get from Redis cache
cache_key = f"wallet:balance:{user_id}"
cache_key = f"xpack:wallet:balance:{user_id}"
cached_balance = self.redis.get(cache_key)
if cached_balance:
@@ -273,7 +273,7 @@ class BillingService:
user_id: User ID
new_balance: New balance
"""
cache_key = f"wallet:balance:{user_id}"
cache_key = f"xpack:wallet:balance:{user_id}"
self.redis.set(cache_key, str(new_balance), ex=self.WALLET_CACHE_EXPIRE)
@asynccontextmanager
@@ -112,7 +112,6 @@ class McpServerFactory:
List[types.Content]: Execution result
"""
call_start_time = datetime.now(timezone.utc)
call_log_id = str(uuid.uuid4())
logger.info(f"Received tool call request with billing - User ID: {user_id}, Service ID: {service_id}, Tool name: {name}")
logger.debug(f"Tool arguments: {arguments}")
@@ -124,10 +123,29 @@ class McpServerFactory:
error_msg = f"Billing check failed: {pre_deduct_result.message}"
# Send failed billing message
# Lookup tool API id for logging
api_id_for_log = None
db_lookup = next(get_db())
try:
mcp_service = self._create_mcp_service(db_lookup)
tool_cfg = mcp_service.get_tool_by_name(service_id, name)
if tool_cfg:
api_id_for_log = tool_cfg.id
else:
logger.error(f"Unknown tool for billing log: {name}")
except Exception as lookup_err:
logger.error(f"Failed to lookup tool API id for billing log: {lookup_err}")
finally:
db_lookup.close()
# If tool API id not found, skip sending billing message to avoid FK errors
if not api_id_for_log:
return [types.TextContent(type="text", text=error_msg)]
call_log = ApiCallLogInfo(
user_id=user_id,
service_id=service_id,
api_id=call_log_id,
api_id=api_id_for_log,
tool_name=name,
input_params=json.dumps(arguments),
unit_price=pre_deduct_result.service_price,
@@ -163,18 +181,18 @@ class McpServerFactory:
# Calculate input token amount (prices are per million tokens)
input_token_amount = (Decimal(str(estimated_input_tokens)) / Decimal("1000000")) * pre_deduct_result.input_token_price
amount = input_token_amount
# Create service instance and find tool configuration before try/except
mcp_service = self._create_mcp_service(db)
tool_config = mcp_service.get_tool_by_name(service_id, name)
if not tool_config:
error_msg = f"Unknown tool: {name}"
logger.error(error_msg)
# Close DB and return error without sending billing message to avoid FK violation
db.close()
return [types.TextContent(type="text", text=error_msg)]
try:
# Create service instance
mcp_service = self._create_mcp_service(db)
# Find tool configuration
tool_config = mcp_service.get_tool_by_name(service_id, name)
if not tool_config:
error_msg = f"Unknown tool: {name}"
logger.error(error_msg)
raise ValueError(error_msg)
logger.info(f"Found tool configuration: {tool_config.name}")
# Get service authentication info
@@ -210,22 +228,24 @@ class McpServerFactory:
# 3. Send billing message
call_end_time = datetime.now(timezone.utc)
call_log = ApiCallLogInfo(
user_id=user_id,
service_id=service_id,
api_id=call_log_id,
tool_name=name,
input_params=json.dumps(arguments),
unit_price=amount.quantize(Decimal('0.000001')),
input_token=Decimal(str(input_token)).quantize(Decimal('0')),
output_token=Decimal(str(output_token)).quantize(Decimal('0')),
charge_type=pre_deduct_result.charge_type,
call_start_time=call_start_time,
call_end_time=call_end_time,
apikey_id=apikey_id,
)
# Send billing message only when tool_config was found (api_id exists)
if tool_config:
call_log = ApiCallLogInfo(
user_id=user_id,
service_id=service_id,
api_id=tool_config.id,
tool_name=name,
input_params=json.dumps(arguments),
unit_price=amount.quantize(Decimal('0.000001')),
input_token=Decimal(str(input_token)).quantize(Decimal('0')),
output_token=Decimal(str(output_token)).quantize(Decimal('0')),
charge_type=pre_deduct_result.charge_type,
call_start_time=call_start_time,
call_end_time=call_end_time,
apikey_id=apikey_id,
)
await self.billing_service.send_billing_message(call_log, call_success, call_end_time)
await self.billing_service.send_billing_message(call_log, call_success, call_end_time)
logger.info(f"Billing message sent - User ID: {user_id}, Tool: {name}, Success: {call_success}")
# Ensure return type is correct