Compare commits

..
1 Commits
Author SHA1 Message Date
jinghui d18adf035b feat(billing): per-service and platform-wide free call limits
release / release (release) Canceled after 0s
- mcp_service.free_daily_limit: per service, per user per day (NULL/0 = unlimited)
- sys_config free_global_daily_limit: applies to every free service
- effective limit = smaller of the two, so a service without its own value
  still inherits the global one
- admin: Pricing tab input, System Settings > Business > Free Call Limits
- submission review pages and endpoints (scaffolding, not yet published end to end)
- allow LAN IPs in http_utils, add docker-compose.yml
2026-11-13 10:20:25 +08:00
24 changed files with 720 additions and 24 deletions

No files matched your search

+3
View File
@@ -42,3 +42,6 @@ local_settings.py
/.secrets
/uploads/
/.vercel/
# Local deployment data
mysql-data/
+62
View File
@@ -0,0 +1,62 @@
version: '3'
services:
xpack-mysql:
image: mysql:8.0.37
privileged: true
restart: always
container_name: xpack-mysql
hostname: xpack-mysql
command:
- "--character-set-server=utf8mb4"
- "--collation-server=utf8mb4_unicode_ci"
ports:
- "33306:3306"
environment:
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
- MYSQL_DATABASE=xpack
volumes:
- /vol3/1000/HD3/docker/xpack-mcp/mysql-data:/var/lib/mysql
networks:
- xpack
xpack-mcp-market:
image: xpackai/xpack-mcp-market:zhcn
container_name: xpack-mcp-market
privileged: true
restart: always
networks:
- xpack
ports:
- "8010:80"
depends_on:
- xpack-mysql
- xpack-redis
- xpack-rabbitmq
xpack-redis:
container_name: xpack-redis
image: redis:7.2.4
hostname: xpack-redis
privileged: true
restart: always
command:
- bash
- -c
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
networks:
- xpack
xpack-rabbitmq:
container_name: xpack-rabbitmq
image: rabbitmq:4.1.2-alpine
privileged: true
restart: always
environment:
- RABBITMQ_DEFAULT_USER=rabbitmq
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
networks:
- xpack
networks:
xpack:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.101.0.0/24
+14 -3
View File
@@ -483,7 +483,6 @@
"Enter server ID": "Enter server ID",
"Modifying the ID will affect the MCP access URL. Please modify with caution.": "Modifying the ID will affect the MCP access URL. Please modify with caution.",
"You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?": "You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?",
"The header name for the API key (e.g., X-API-Key, Authorization)": "The header name for the API key (e.g., X-API-Key, Authorization)",
"Enter API key": "Enter API key",
"Enter bearer token": "Enter bearer token",
@@ -891,5 +890,17 @@
"Auth key name \"{{name}}\" already exists": "Auth key name \"{{name}}\" already exists",
"Start date must be before end date": "Start date must be before end date",
"Start date cannot be earlier than 30 days ago": "Start date cannot be earlier than 30 days ago",
"Resource Groups": "Resource Groups"
}
"Resource Groups": "Resource Groups",
"Daily call limit per user": "Daily call limit per user",
"Max calls per user per day (Beijing time). Leave blank or 0 for unlimited": "Max calls per user per day (Beijing time). Leave blank or 0 for unlimited",
"e.g. 50": "e.g. 50",
"Free Call Limits": "Free Call Limits",
"Global daily call cap for free services": "Global daily call cap for free services",
"Platform-wide daily call limit per user": "Platform-wide daily call limit per user",
"Applies to every free service, leave blank or 0 for unlimited": "Applies to every free service, leave blank or 0 for unlimited",
"If a service also has its own limit, the smaller number wins": "If a service also has its own limit, the smaller number wins",
"Example 100": "Example 100",
"Enter a non-negative integer": "Enter a non-negative integer",
"Free call limit saved": "Free call limit saved",
"Failed to save free call limit": "Failed to save free call limit"
}
+14 -3
View File
@@ -485,7 +485,6 @@
"Enter server ID": "输入服务器ID",
"Modifying the ID will affect the MCP access URL. Please modify with caution.": "修改ID会影响MCP的访问地址,需要谨慎修改。",
"You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?": "您已修改了服务器ID。这将影响MCP访问地址,可能会破坏现有的集成。您确定要继续吗?",
"The header name for the API key (e.g., X-API-Key, Authorization)": "API密钥的头部名称(例如:X-API-Key, Authorization)",
"Enter API key": "输入API密钥",
"Enter bearer token": "输入Bearer令牌",
@@ -957,5 +956,17 @@
"Resource group name \"{{name}}\" already exists": "资源组名称 \"{{name}}\" 已存在",
"Auth key name \"{{name}}\" already exists": "认证密钥 \"{{name}}\" 已存在",
"Start date must be before end date": "开始日期必须早于结束日期",
"Start date cannot be earlier than 30 days ago": "开始日期不能早于30天前"
}
"Start date cannot be earlier than 30 days ago": "开始日期不能早于30天前",
"Daily call limit per user": "每用户每日调用上限",
"Max calls per user per day (Beijing time). Leave blank or 0 for unlimited": "每个用户每天最多调用次数(北京时间)。留空或填 0 表示不限",
"e.g. 50": "如 50",
"Free Call Limits": "免费调用限制",
"Global daily call cap for free services": "免费服务的全局每日调用上限",
"Platform-wide daily call limit per user": "全站每用户每日调用上限",
"Applies to every free service, leave blank or 0 for unlimited": "对所有免费服务生效,留空或填 0 表示不限",
"If a service also has its own limit, the smaller number wins": "若单个服务也设置了上限,两者取更小值",
"Example 100": "如 100",
"Enter a non-negative integer": "请输入非负整数",
"Free call limit saved": "免费调用上限已保存",
"Failed to save free call limit": "保存免费调用上限失败"
}
@@ -0,0 +1,55 @@
"use client";
import React, { useEffect, useState } from "react";
export default function AdminSubmissionsPage() {
const [list, setList] = useState<any[]>([]);
const [status, setStatus] = useState("pending");
const load = async () => {
const res = await fetch(`/api/submission/admin/submissions?status=${status}`, { credentials: "include" });
const data = await res.json();
setList(data?.data || []);
};
useEffect(() => { load(); }, [status]);
const approve = async (id: string) => {
await fetch(`/api/submission/admin/submission/${id}/approve`, { method: "PUT", credentials: "include" });
load();
};
const reject = async (id: string) => {
await fetch(`/api/submission/admin/submission/${id}/reject`, { method: "PUT", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ note: "rejected" }) });
load();
};
return (
<div className="max-w-4xl mx-auto p-6">
<h1 className="text-2xl font-bold mb-4">提交审核</h1>
<select value={status} onChange={e => setStatus(e.target.value)} className="border p-2 mb-4">
<option value="pending">待审核</option>
<option value="approved">已通过</option>
<option value="rejected">已拒绝</option>
</select>
<table className="w-full border">
<thead><tr><th>名称</th><th>类型</th><th>状态</th><th>操作</th></tr></thead>
<tbody>
{list.map((s: any) => (
<tr key={s.id} className="border-t">
<td className="p-2">{s.name}</td>
<td className="p-2">{s.type}</td>
<td className="p-2">{s.status}</td>
<td className="p-2">
{s.status === "pending" && (
<>
<button onClick={() => approve(s.id)} className="text-green-600 mr-2">通过</button>
<button onClick={() => reject(s.id)} className="text-red-600">拒绝</button>
</>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
+2 -2
View File
@@ -27,12 +27,12 @@ export default async function RootLayout({
const platformConfig = await getCachedPlatformConfig();
return (
<html lang="en" suppressHydrationWarning data-color-mode="light">
<html lang="zh-CN" suppressHydrationWarning data-color-mode="light">
<head>
<script
dangerouslySetInnerHTML={{
__html: `
window.localStorage.setItem("i18nextLng", "${platformConfig?.platform?.language || "en"}");
window.localStorage.setItem("i18nextLng", "${platformConfig?.platform?.language || "zh-CN"}");
`,
}}
/>
+40
View File
@@ -0,0 +1,40 @@
"use client";
import React, { useState } from "react";
export default function SubmitPage() {
const [type, setType] = useState("mcp");
const [name, setName] = useState("");
const [desc, setDesc] = useState("");
const [file, setFile] = useState<File | null>(null);
const [msg, setMsg] = useState("");
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const fd = new FormData();
fd.append("type", type);
fd.append("name", name);
if (desc) fd.append("description", desc);
if (file) fd.append("file", file);
const res = await fetch("/api/submission/submission", { method: "POST", body: fd, credentials: "include" });
const data = await res.json();
setMsg(JSON.stringify(data));
};
return (
<div className="max-w-xl mx-auto p-6">
<h1 className="text-2xl font-bold mb-4">上传 MCP / Skill / Plugin</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<select value={type} onChange={e => setType(e.target.value)} className="border p-2 w-full">
<option value="mcp">MCP 服务</option>
<option value="skill">AI 技能</option>
<option value="plugin">AI 插件</option>
</select>
<input value={name} onChange={e => setName(e.target.value)} placeholder="名称" className="border p-2 w-full" required />
<textarea value={desc} onChange={e => setDesc(e.target.value)} placeholder="描述" className="border p-2 w-full" />
<input type="file" onChange={e => setFile(e.target.files?.[0] || null)} className="border p-2 w-full" />
<button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded">提交</button>
</form>
{msg && <pre className="mt-4 text-sm">{msg}</pre>}
</div>
);
}
@@ -26,6 +26,7 @@ import {
Captions,
Code,
CreditCard,
Gauge,
GhostIcon,
GlobeIcon,
LockIcon,
@@ -181,6 +182,12 @@ const SystemSettingsModal: React.FC<SystemSettingsModalProps> = ({
icon: <CreditCard size={16} />,
description: "Configure payment channels",
},
{
key: SettingModalTab.FREE_QUOTA,
label: "Free Call Limits",
icon: <Gauge size={16} />,
description: "Global daily call cap for free services",
},
{
key: SettingModalTab.XPACK_EXPLORE,
label: "XPack Explore",
@@ -256,6 +263,7 @@ const SystemSettingsModal: React.FC<SystemSettingsModalProps> = ({
title: "Business",
items: groupItems([
SettingModalTab.PAYMENT,
SettingModalTab.FREE_QUOTA,
SettingModalTab.XPACK_EXPLORE,
]),
},
@@ -31,6 +31,7 @@ import { AdminConfig, EmailConfig } from "@/types/system";
import { LoginSettingsContent } from "./LoginSettingsContent";
import { EmailConfigForm } from "@/components/system-setting/EmailConfigForm";
import { LanguageSetting } from "@/components/system-setting/LanguageSetting";
import { FreeQuotaSettings } from "@/components/system-setting/FreeQuotaSettings";
import { TagsBarSetting } from "../system-setting/TagsBarSetting";
interface SystemSettingsRightContentProps {
@@ -221,6 +222,8 @@ const SystemSettingsRightContent: React.FC<SystemSettingsRightContentProps> = ({
<PaymentChannelsContent labelPlacement="outside" />
)}
{section.key === "free-quota" && <FreeQuotaSettings />}
{section.key === "xpack-explore" && (
<ExplorePanel
isEnabled={!!platformConfig.is_showcased}
@@ -5,6 +5,7 @@ export enum SettingModalTab {
BRANDING = "branding",
THEME = "theme",
PAYMENT = "payment",
FREE_QUOTA = "free-quota",
CODE_INJECTION = "code-injection",
XPACK_EXPLORE = "xpack-explore",
NAVIGATION = "navigation",
@@ -30,6 +30,7 @@ const _DefaultFormData: MCPServiceFormData = {
auth_token: "",
charge_type: ChargeType.Free,
price: "",
free_daily_limit: "",
enabled: 0,
tags: [],
apis: [],
@@ -46,12 +47,18 @@ const isValidUrl = (url: string) => {
}
};
// Helper function to validate domain format
// Helper function to validate domain format (allow domain or IP address including LAN IPs)
const isValidDomain = (url: string) => {
if (!url) return false;
try {
const parsed = new URL(url);
const hostname = parsed.hostname;
// Allow IPv4 addresses (including private/lan IPs like 192.168.x.x, 10.x.x.x, 172.x.x.x)
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipv4Regex.test(hostname)) return true;
// Allow IPv6 (simplified)
if (hostname.includes(":")) return true;
// Domain format
const domainRegex = /^(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$/;
return domainRegex.test(hostname);
} catch {
@@ -0,0 +1,111 @@
"use client";
import React, { useEffect, useState } from "react";
import { Button, Input } from "@nextui-org/react";
import { fetchAdminAPI } from "@/rpc/admin-api";
import { useTranslation } from "@/shared/lib/useTranslation";
import toast from "react-hot-toast";
interface FreeQuotaResponse {
free_global_daily_limit: number | null;
}
/**
* Platform-wide daily call cap for free services.
*
* Stored in sys_config under free_global_daily_limit. The billing service takes
* the smaller of this value and any per-service limit, so a service with no
* limit of its own still inherits this one.
*/
export const FreeQuotaSettings: React.FC = () => {
const { t } = useTranslation();
const [value, setValue] = useState<string>("");
const [loading, setLoading] = useState<boolean>(true);
const [saving, setSaving] = useState<boolean>(false);
useEffect(() => {
let mounted = true;
(async () => {
const res = await fetchAdminAPI<FreeQuotaResponse>(
"/api/sysconfig/free-quota",
{ method: "GET" }
);
if (!mounted) return;
if (res.success) {
const n = res.data?.free_global_daily_limit;
setValue(n && n > 0 ? String(n) : "");
} else if (res.error_message) {
toast.error(res.error_message);
}
setLoading(false);
})();
return () => {
mounted = false;
};
}, []);
const handleSave = async () => {
const raw = value.trim();
let payload: number | null = null;
if (raw !== "") {
const n = Number(raw);
if (!Number.isInteger(n) || n < 0) {
toast.error(t("Enter a non-negative integer"));
return;
}
payload = n;
}
setSaving(true);
const res = await fetchAdminAPI<FreeQuotaResponse>(
"/api/sysconfig/free-quota",
{ method: "PUT", body: { free_global_daily_limit: payload } as unknown as BodyInit }
);
setSaving(false);
if (res.success) {
const n = res.data?.free_global_daily_limit;
setValue(n && n > 0 ? String(n) : "");
toast.success(t("Free call limit saved"));
} else {
toast.error(res.error_message || t("Failed to save free call limit"));
}
};
return (
<div className="space-y-4">
<Input
type="number"
min={0}
step={1}
labelPlacement="outside"
label={t("Platform-wide daily call limit per user")}
placeholder={t("Example 100")}
value={value}
isDisabled={loading || saving}
onValueChange={setValue}
description={t(
"Applies to every free service, leave blank or 0 for unlimited"
)}
/>
<p className="text-xs text-default-400">
{t("If a service also has its own limit, the smaller number wins")}
</p>
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={saving}
size="sm"
>
{t("Save")}
</Button>
</div>
</div>
);
};
export default FreeQuotaSettings;
@@ -65,6 +65,27 @@ export const PricingTab: React.FC<PricingTabProps> = ({
</SelectItem>
</Select>
{formData.charge_type === ChargeType.Free && (
<Input
type="number"
min="0"
step="1"
value={
formData.free_daily_limit === null ||
formData.free_daily_limit === undefined
? ""
: String(formData.free_daily_limit)
}
onChange={(e) => onInputChange("free_daily_limit", e.target.value)}
description={t(
"Max calls per user per day (Beijing time). Leave blank or 0 for unlimited"
)}
placeholder={t("e.g. 50")}
label={t("Daily call limit per user")}
labelPlacement="outside"
/>
)}
{formData.charge_type !== ChargeType.Free && (
<>
{formData.charge_type === ChargeType.PerToken ? (
+1
View File
@@ -68,6 +68,7 @@ export interface MCPServiceFormData {
price?: string;
input_token_price?: string; // Price for input tokens when charge_type is PerToken
output_token_price?: string; // Price for output tokens when charge_type is PerToken
free_daily_limit?: string | number | null; // free services only: max calls per user per day (Beijing time), blank/0 = unlimited
enabled: EnabledEnum; // API requires string type
apis: MCPServiceAPIItem[];
headers?: MCPAuthHeaderItem[]; // add headers to form data
+3 -3
View File
@@ -15,8 +15,8 @@ const getUrlLanguage = (): string | null => {
const getBrowserDefaultLanguage = (): string => {
if (typeof window === "undefined") {
// SSR时根据Accept-Language header判断,这里先返回英语
return "en";
// SSR时根据Accept-Language header判断,这里先返回中文
return "zh-CN";
}
const browserLang = navigator.language;
@@ -31,7 +31,7 @@ const getBrowserDefaultLanguage = (): string => {
const langPrefix = browserLang.split("-")[0];
const match = supportedLanguages.find((lang) => lang.startsWith(langPrefix));
return match || "en"; // 最后才fallback到英语
return match || "zh-CN"; // 最后才fallback到中文
};
export const getDefaultLanguage = (): string => {
@@ -44,4 +44,7 @@ KEY_SOCIAL_ACCOUNT_X_URL = "social_account_x_url"
KEY_CNAME_A_IP = "cname_a_ip"
KEY_DEFAULT_RESOURCE_GROUP = "default_resource_group"
KEY_DEFAULT_RESOURCE_GROUP = "default_resource_group"
# Platform-wide daily cap on free MCP services (see api_service billing_service)
KEY_FREE_GLOBAL_DAILY_LIMIT = "free_global_daily_limit"
@@ -0,0 +1,144 @@
"""User submission controller for MCP/Skill/Plugin marketplace."""
import logging
import os
import uuid
from fastapi import APIRouter, Depends, Request, UploadFile, File, Form, HTTPException
from sqlalchemy.orm import Session
from services.common.database import get_db
from services.common.utils.response_utils import ResponseUtils
from services.common.utils.validation_utils import ValidationUtils
from services.admin_service.utils.user_utils import UserUtils
from services.common import error_msg
from services.common.models.submission import Submission
logger = logging.getLogger(__name__)
router = APIRouter()
UPLOAD_DIR = "/tmp/submission_uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
@router.post("/submission", summary="User submit MCP/Skill/Plugin")
async def create_submission(
request: Request,
type: str = Form(...),
name: str = Form(...),
description: str = Form(None),
file: UploadFile = File(None),
db: Session = Depends(get_db),
):
try:
user_id = UserUtils.get_request_user_id(request)
except Exception:
user_id = None
if not user_id:
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
if type not in ("mcp", "skill", "plugin"):
return ResponseUtils.error(error_msg=error_msg.INVALID_PARAMETER)
file_path = None
if file:
safe_name = f"{uuid.uuid4()}_{file.filename}"
file_path = os.path.join(UPLOAD_DIR, safe_name)
with open(file_path, "wb") as f:
f.write(await file.read())
sub = Submission(
user_id=user_id,
type=type,
name=name,
description=description,
file_path=file_path,
status="pending",
)
db.add(sub)
db.commit()
db.refresh(sub)
return ResponseUtils.success(data={"id": sub.id, "status": sub.status})
@router.get("/submissions", summary="List user submissions")
def list_submissions(request: Request, db: Session = Depends(get_db)):
try:
user_id = UserUtils.get_request_user_id(request)
except Exception:
user_id = None
if not user_id:
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
subs = db.query(Submission).filter(Submission.user_id == user_id).order_by(Submission.created_at.desc()).all()
data = [
{
"id": s.id,
"type": s.type,
"name": s.name,
"description": s.description,
"status": s.status,
"created_at": s.created_at.isoformat() if s.created_at else None,
"review_note": s.review_note,
}
for s in subs
]
return ResponseUtils.success(data=data)
# Admin endpoints
@router.get("/admin/submissions", summary="Admin list submissions")
def admin_list_submissions(request: Request, status: str = None, db: Session = Depends(get_db)):
if not UserUtils.is_admin(request):
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
q = db.query(Submission)
if status:
q = q.filter(Submission.status == status)
subs = q.order_by(Submission.created_at.desc()).all()
data = [
{
"id": s.id,
"user_id": s.user_id,
"type": s.type,
"name": s.name,
"description": s.description,
"file_path": s.file_path,
"status": s.status,
"created_at": s.created_at.isoformat() if s.created_at else None,
"review_note": s.review_note,
}
for s in subs
]
return ResponseUtils.success(data=data)
@router.put("/admin/submission/{sub_id}/approve", summary="Approve submission")
def approve_submission(sub_id: str, request: Request, db: Session = Depends(get_db)):
if not UserUtils.is_admin(request):
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
sub = db.query(Submission).filter(Submission.id == sub_id).first()
if not sub:
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
sub.status = "approved"
sub.reviewer_id = UserUtils.get_request_user_id(request)
from datetime import datetime
sub.reviewed_at = datetime.utcnow()
db.commit()
return ResponseUtils.success()
@router.put("/admin/submission/{sub_id}/reject", summary="Reject submission")
def reject_submission(sub_id: str, request: Request, body: dict = None, db: Session = Depends(get_db)):
if not UserUtils.is_admin(request):
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
sub = db.query(Submission).filter(Submission.id == sub_id).first()
if not sub:
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
sub.status = "rejected"
sub.reviewer_id = UserUtils.get_request_user_id(request)
from datetime import datetime
sub.reviewed_at = datetime.utcnow()
if body:
sub.review_note = body.get("note")
db.commit()
return ResponseUtils.success()
@@ -34,6 +34,58 @@ def get_sysconfig_service(db: Session = Depends(get_db)) -> SysConfigService:
def get_user_service(db: Session = Depends(get_db)) -> UserService:
return UserService(db)
@router.get("/free-quota")
def get_free_quota(
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
):
"""Platform-wide daily cap applied to every free service (None = unlimited)."""
raw = sysconfig_service.get_value_by_key(sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT)
limit = None
if raw not in (None, ""):
try:
limit = int(raw)
except (TypeError, ValueError):
limit = None
if limit is not None and limit <= 0:
limit = None
return ResponseUtils.success(data={"free_global_daily_limit": limit})
@router.put("/free-quota")
def set_free_quota(
request: Request,
body: dict = Body(...),
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
):
"""Update the platform-wide daily cap. Empty value clears it (unlimited)."""
if not UserUtils.is_admin(request):
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
raw = body.get("free_global_daily_limit")
if raw in (None, ""):
sysconfig_service.set_value_by_key(
sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT, "", "Global free daily limit"
)
return ResponseUtils.success(data={"free_global_daily_limit": None})
try:
limit = int(raw)
except (TypeError, ValueError):
return ResponseUtils.error(
message="free_global_daily_limit must be a non-negative integer", code=400
)
if limit < 0:
return ResponseUtils.error(
message="free_global_daily_limit must be a non-negative integer", code=400
)
sysconfig_service.set_value_by_key(
sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT, str(limit), "Global free daily limit"
)
return ResponseUtils.success(data={"free_global_daily_limit": limit})
@router.get("/homepage")
def get_homepage(
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
+2
View File
@@ -26,6 +26,7 @@ from services.admin_service.controllers import email_test
from services.admin_service.controllers import upload
from services.admin_service.controllers import user_task
from services.admin_service.controllers import resource_group
from services.admin_service.controllers import submission
@@ -170,6 +171,7 @@ app.include_router(email_test.router, prefix="/api/email_test")
app.include_router(upload.router, prefix="/api/upload")
app.include_router(user_task.router, prefix="/api/onboarding")
app.include_router(resource_group.router, prefix="/api/resource_group")
app.include_router(submission.router, prefix="/api/submission")
@@ -228,6 +228,21 @@ class McpManagerService:
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 "free_daily_limit" in body:
raw_limit = body["free_daily_limit"]
if raw_limit in (None, ""):
new_limit = None
else:
try:
new_limit = int(raw_limit)
except (TypeError, ValueError):
raise ValueError("free_daily_limit must be a non-negative integer")
if new_limit < 0:
raise ValueError("free_daily_limit must be a non-negative integer")
if new_limit != existing_service.free_daily_limit:
# api_service reads this out of the 1h price cache
self._delete_service_price_cache(service_id)
existing_service.free_daily_limit = new_limit
if "tags" in body and body["tags"] is not None:
# If provided as array, convert to string for storage
if isinstance(body["tags"], list):
@@ -316,6 +331,7 @@ class McpManagerService:
"input_token_price": str(float(service.input_token_price)) if service.input_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
"output_token_price": str(float(service.output_token_price)) if service.output_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
"enabled": service.enabled,
"free_daily_limit": service.free_daily_limit,
"tags": parse_tags_to_array(service.tags),
"apis": [{"id": api.id, "name": api.name, "description": api.description,"url":api.path} for api in apis],
}
@@ -12,13 +12,16 @@ from typing import Tuple, Optional
from contextlib import asynccontextmanager
from services.common.redis import redis_client
from services.common.redis_keys import RedisKeys
from services.common.rabbitmq import rabbitmq_client
from services.common.models.billing import BillingMessage, PreDeductResult, ApiCallLogInfo
from services.common.models.mcp_service import ChargeType
from services.common.models.sys_config import SysConfig
from services.common.models.user_wallet import UserWallet
from services.common.database import get_db
from services.api_service.repositories.mcp_service_repository import McpServiceRepository
from services.api_service.repositories.user_wallet_repository import UserWalletRepository
from services.admin_service.constants import sys_config_key
from services.common.logging_config import get_logger
logger = get_logger(__name__)
@@ -51,10 +54,45 @@ class BillingService:
"""
try:
# Get service price information
price, input_token_price, output_token_price, charge_type = await self._get_service_price(service_id)
price, input_token_price, output_token_price, charge_type, free_daily_limit = await self._get_service_price(service_id)
service_price = price
match charge_type:
case ChargeType.FREE:
# Free services are not billed, but may be limited to N calls
# per user per day (Beijing time) to stop one user draining them.
# The platform-wide cap (sys_config) applies to every free service
# and wins whenever it is the smaller of the two, so a service
# with no per-service value still inherits the global one.
limits = [
(value, scope)
for value, scope in (
(free_daily_limit, "service"),
(self._get_global_free_limit(), "platform"),
)
if value and value > 0
]
if limits:
limit, scope = min(limits, key=lambda item: item[0])
allowed, used = self._check_free_quota(user_id, service_id, limit)
if not allowed:
scope_note = " (platform-wide limit)" if scope == "platform" else ""
logger.warning(
f"Free daily limit reached - User ID: {user_id}, Service ID: {service_id}, "
f"Limit: {limit}{scope_note}, Used: {used}"
)
return PreDeductResult(
success=False,
message=(
f"Free daily limit reached: {limit} calls per day{scope_note}. "
f"Used {used} today, please try again after midnight (Beijing time) "
f"or upgrade to a paid plan"
),
service_price=Decimal("0"),
user_balance=Decimal("0"),
input_token_price=input_token_price,
output_token_price=output_token_price,
charge_type=charge_type.value
)
logger.info(f"Free service, skip billing check - User ID: {user_id}, Service ID: {service_id}")
return PreDeductResult(
success=True,
@@ -168,7 +206,76 @@ class BillingService:
logger.error(f"Failed to send billing message: {str(e)}", exc_info=True)
# Consider saving failed messages to local queue for retry
async def _get_service_price(self, service_id: str) -> Tuple[Decimal, Decimal, Decimal, ChargeType]:
def _check_free_quota(self, user_id: str, service_id: str, limit: int) -> tuple[bool, int]:
"""Count today's calls for a free service and say whether this one is still allowed.
One Redis key per service/user/Beijing-day, so the counter costs a single
INCR and expires by itself after midnight (no cleanup job).
Returns (allowed, used_today). A rejected call is counted too, otherwise a
client could loop past the limit by simply retrying.
"""
from datetime import timedelta
tz_cst = timezone(timedelta(hours=8))
now_cst = datetime.now(tz_cst)
day = now_cst.strftime("%Y%m%d")
key = f"xpack:free:calls:{service_id}:{user_id}:{day}"
try:
used = int(self.redis.incr(key))
if used == 1:
# seconds until the next Beijing midnight, plus a day of slack
next_midnight = (now_cst + timedelta(days=1)).replace(
hour=0, minute=0, second=0, microsecond=0
)
ttl = int((next_midnight - now_cst).total_seconds()) + 86400
self.redis.expire(key, ttl)
except Exception as e:
# Redis being down must not lock paying/free users out of their tools
logger.warning(f"Free quota counter unavailable, allowing call - User ID: {user_id}: {e}")
return True, 0
return used <= limit, used
def _get_global_free_limit(self) -> Optional[int]:
"""Platform-wide daily cap on free services, stored in sys_config.
Reads the same cache key the admin service invalidates on save, so a new
value takes effect on the very next call. Unset / empty / unparsable all
mean "no platform cap" and never fail the request.
"""
cache_key = RedisKeys.sys_config_key(sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT)
raw = None
try:
cached = self.redis.get(cache_key)
if cached is not None:
raw = None if cached == "__NULL__" else str(cached)
else:
db = next(get_db())
try:
row = (
db.query(SysConfig)
.filter(SysConfig.key == sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT)
.first()
)
raw = row.value if row is not None else None
finally:
db.close()
# Cache the miss too, so an unset key costs no query per call
self.redis.set(cache_key, "__NULL__" if raw in (None, "") else raw, ex=3600)
except Exception as e:
logger.warning(f"Global free limit unavailable, treating as unset: {e}")
return None
if raw in (None, "", "__NULL__"):
return None
try:
value = int(raw)
except (TypeError, ValueError):
return None
return value if value > 0 else None
async def _get_service_price(self, service_id: str) -> Tuple[Decimal, Decimal, Decimal, ChargeType, Optional[int]]:
"""
Get service price and charge type
@@ -184,7 +291,15 @@ class BillingService:
if cached_data:
try:
data = json.loads(cached_data)
return Decimal(data["price"]), Decimal(data["input_token_price"]), Decimal(data["output_token_price"]), ChargeType(data["charge_type"])
# free_daily_limit was added later; older cache entries simply lack it
free_daily_limit = data.get("free_daily_limit")
return (
Decimal(data["price"]),
Decimal(data["input_token_price"]),
Decimal(data["output_token_price"]),
ChargeType(data["charge_type"]),
int(free_daily_limit) if free_daily_limit not in (None, "") else None,
)
except (json.JSONDecodeError, KeyError, ValueError):
logger.warning(f"Service price cache data anomaly, re-fetch from database - Service ID: {service_id}")
@@ -209,17 +324,20 @@ class BillingService:
input_token_price = Decimal(str(service.input_token_price))
output_token_price = Decimal(str(service.output_token_price))
charge_type = service.charge_type
free_daily_limit = getattr(service, "free_daily_limit", None)
free_daily_limit = int(free_daily_limit) if free_daily_limit else None
# Cache to Redis
cache_data = {
"price": str(price),
"input_token_price": str(input_token_price),
"output_token_price":str(output_token_price),
"charge_type": charge_type.value
"charge_type": charge_type.value,
"free_daily_limit": free_daily_limit
}
self.redis.set(cache_key, json.dumps(cache_data), ex=self.SERVICE_CACHE_EXPIRE)
return price,input_token_price,output_token_price, charge_type
return price,input_token_price,output_token_price, charge_type, free_daily_limit
finally:
db.close()
+5
View File
@@ -33,6 +33,11 @@ class McpService(Base):
Numeric(10, 2), nullable=True, comment="Output token price (2 decimal places, for per_token charge type)"
)
enabled: Mapped[int] = mapped_column(Integer, nullable=True, comment="Service status: 0=disabled, 1=enabled")
free_daily_limit: Mapped[int] = mapped_column(
Integer,
nullable=True,
comment="Free service: max calls per user per day (Beijing time). NULL or 0 = unlimited",
)
tags: Mapped[str] = mapped_column(String, nullable=True, comment="Tags")
service_type: Mapped[str] = mapped_column(String(255), nullable=True, comment="Service type",default="openapi")
created_at: Mapped[datetime] = mapped_column(
+22
View File
@@ -0,0 +1,22 @@
"""User submission model for MCP/Skill/Plugin marketplace."""
from sqlalchemy import Column, String, Text, DateTime, JSON, Enum
from sqlalchemy.sql import func
from services.common.models.base import Base
import uuid
class Submission(Base):
__tablename__ = "submission"
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
user_id = Column(String(36), nullable=False, index=True)
type = Column(Enum("mcp", "skill", "plugin", name="submission_type"), nullable=False)
name = Column(String(255), nullable=False)
description = Column(Text, nullable=True)
file_path = Column(String(512), nullable=True)
metadata_json = Column(JSON, nullable=True)
status = Column(Enum("pending", "approved", "rejected", name="submission_status"), default="pending", nullable=False)
reviewer_id = Column(String(36), nullable=True)
review_note = Column(Text, nullable=True)
created_at = Column(DateTime, server_default=func.now())
reviewed_at = Column(DateTime, nullable=True)
+6 -6
View File
@@ -66,9 +66,9 @@ class HttpUtils:
if parsed.scheme not in ("http", "https"):
raise ValidationException("URL scheme must be http or https")
host = (parsed.hostname or "").lower()
private_prefixes = ("127.", "10.", "192.168.")
if host in ("localhost", "127.0.0.1") or host.startswith(private_prefixes) or host.startswith("172."):
raise ValidationException("Access to local/private addresses is not allowed")
# Allow LAN/private IPs (user request), only block loopback
if host in ("localhost", "127.0.0.1", "::1") or host.startswith("127."):
raise ValidationException("Access to loopback addresses is not allowed")
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=timeout),
@@ -193,9 +193,9 @@ class HttpUtils:
if parsed.scheme not in ("http", "https"):
raise ValidationException("URL scheme must be http or https")
host = (parsed.hostname or "").lower()
private_prefixes = ("127.", "10.", "192.168.")
if host in ("localhost", "127.0.0.1") or host.startswith(private_prefixes) or host.startswith("172."):
raise ValidationException("Access to local/private addresses is not allowed")
# Allow LAN/private IPs (user request), only block loopback
if host in ("localhost", "127.0.0.1", "::1") or host.startswith("127."):
raise ValidationException("Access to loopback addresses is not allowed")
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=timeout),