Compare commits
113 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 294bdf4577 | |||
| fd522b6c71 | |||
| a1184ef5ed | |||
| 7c6efe9dfe | |||
| c0ece054a0 | |||
| 0d57450283 | |||
| f2033fd4b9 | |||
| 3284cb45f0 | |||
| 6041bc3419 | |||
| 4581a6fc17 | |||
| 2bdce44e12 | |||
| 4fa9fcd232 | |||
| f6911965dc | |||
| c4b2ebf7e1 | |||
| f946504cb8 | |||
| 7d2f98b7c9 | |||
| 8bc8e81e95 | |||
| 54daa923da | |||
| 463d3e2315 | |||
| 559d59b4f8 | |||
| d4f0d559cf | |||
| cbb451d18c | |||
| 595e4c62f9 | |||
| 9dd5dcb9d2 | |||
| 110c97ada4 | |||
| d748a7e75d | |||
| cf70838142 | |||
| 280437be91 | |||
| 59b7056a20 | |||
| 769622f087 | |||
| 91935e3109 | |||
| 3b3ed7b3c1 | |||
| b52e01eaa2 | |||
| 32e3dc3c73 | |||
| 6b64e8c461 | |||
| 47696b9e68 | |||
| 79427c9f4c | |||
| bcefb274ab | |||
| 3ae85f68ea | |||
| ac57272018 | |||
| 68c7b0a8ec | |||
| 0ec0e2b9d2 | |||
| ab38cd4943 | |||
| 5b49aa8242 | |||
| 9db4762904 | |||
| ae62ecc6b3 | |||
| 4b73cd4d3c | |||
| 2c9833df58 | |||
| 23a7a292ef | |||
| f1bfc78d66 | |||
| 9912df9ac6 | |||
| bafb13cf06 | |||
| 9a8ae8b6fd | |||
| c8258dc93b | |||
| c0d839deb9 | |||
| 800f9c8460 | |||
| 954b19c332 | |||
| 62cf68b49b | |||
| e818ac8764 | |||
| 98d8525fa9 | |||
| 19777df2ed | |||
| d586bbeabb | |||
| 92f278d38b | |||
| 3417da2a9e | |||
| 2362b67634 | |||
| 06e4698888 | |||
| e51dbea7c7 | |||
| c8f172dc0e | |||
| 52aaaf4de5 | |||
| 877a471e24 | |||
| 40cfe46ba8 | |||
| 5733ebe40d | |||
| 0b1e6ce3c3 | |||
| 3167465865 | |||
| 8838fc51f8 | |||
| ea34718a0b | |||
| 98972401c2 | |||
| abc9864d46 | |||
| fd48afd0ab | |||
| e3cd0643e1 | |||
| 6724e341b8 | |||
| 202c1c18d7 | |||
| e0b2be2058 | |||
| d351d9e436 | |||
| d072217e85 | |||
| 2a9c01ff8b | |||
| df7303738a | |||
| a9205cc3fc | |||
| 1dbc3a81e9 | |||
| 3b4e882965 | |||
| 26c9ff2f0f | |||
| aaacb47dad | |||
| eb414749c3 | |||
| 1a08949c80 | |||
| 0f28f4995f | |||
| 8398865bd3 | |||
| 6f6943f295 | |||
| 507ee16a30 | |||
| 2db2bc0860 | |||
| 2bdda7558c | |||
| 89e0c03fec | |||
| 315c59e5b7 | |||
| cee97ae630 | |||
| e5c8e965af | |||
| c431393266 | |||
| 4a2501a3d1 | |||
| 774fce6147 | |||
| d63b943964 | |||
| b43dcd8dab | |||
| 95830eae8a | |||
| 62b8c67261 | |||
| f111b36389 | |||
| 7fe7243c24 |
@@ -1,38 +0,0 @@
|
||||
# .agents Directory
|
||||
|
||||
This directory contains agent configuration and skills for OpenAI Codex CLI.
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
.agents/
|
||||
config.toml # Main configuration file
|
||||
skills/ # Skill definitions
|
||||
skill-name/
|
||||
SKILL.md # Skill instructions
|
||||
scripts/ # Optional scripts
|
||||
docs/ # Optional documentation
|
||||
README.md # This file
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The `config.toml` file controls:
|
||||
- Model selection
|
||||
- Approval policies
|
||||
- Sandbox modes
|
||||
- MCP server connections
|
||||
- Skills configuration
|
||||
|
||||
## Skills
|
||||
|
||||
Skills are invoked using `$skill-name` syntax. Each skill has:
|
||||
- YAML frontmatter with metadata
|
||||
- Trigger and skip conditions
|
||||
- Commands and examples
|
||||
|
||||
## Documentation
|
||||
|
||||
- Main instructions: `AGENTS.md` (project root)
|
||||
- Local overrides: `.codex/AGENTS.override.md` (gitignored)
|
||||
- Claude Flow: https://github.com/ruvnet/claude-flow
|
||||
@@ -1,298 +0,0 @@
|
||||
# =============================================================================
|
||||
# Claude Flow V3 - Codex Configuration
|
||||
# =============================================================================
|
||||
# Generated by: @claude-flow/codex
|
||||
# Documentation: https://github.com/ruvnet/claude-flow
|
||||
#
|
||||
# This file configures the Codex CLI for Claude Flow integration.
|
||||
# Place in .agents/config.toml (project) or .codex/config.toml (user).
|
||||
# =============================================================================
|
||||
|
||||
# =============================================================================
|
||||
# Core Settings
|
||||
# =============================================================================
|
||||
|
||||
# Model selection - the AI model to use for code generation
|
||||
# Options: gpt-5.3-codex, gpt-4o, claude-sonnet, claude-opus
|
||||
model = "gpt-5.3-codex"
|
||||
|
||||
# Approval policy determines when human approval is required
|
||||
# - untrusted: Always require approval
|
||||
# - on-failure: Require approval only after failures
|
||||
# - on-request: Require approval for significant changes
|
||||
# - never: Auto-approve all actions (use with caution)
|
||||
approval_policy = "on-request"
|
||||
|
||||
# Sandbox mode controls file system access
|
||||
# - read-only: Can only read files, no modifications
|
||||
# - workspace-write: Can write within workspace directory
|
||||
# - danger-full-access: Full file system access (dangerous)
|
||||
sandbox_mode = "workspace-write"
|
||||
|
||||
# Web search enables internet access for research
|
||||
# - disabled: No web access
|
||||
# - cached: Use cached results when available
|
||||
# - live: Always fetch fresh results
|
||||
web_search = "cached"
|
||||
|
||||
# =============================================================================
|
||||
# Project Documentation
|
||||
# =============================================================================
|
||||
|
||||
# Maximum bytes to read from AGENTS.md files
|
||||
project_doc_max_bytes = 65536
|
||||
|
||||
# Fallback filenames if AGENTS.md not found
|
||||
project_doc_fallback_filenames = [
|
||||
"AGENTS.md",
|
||||
"TEAM_GUIDE.md",
|
||||
".agents.md"
|
||||
]
|
||||
|
||||
# =============================================================================
|
||||
# Features
|
||||
# =============================================================================
|
||||
|
||||
[features]
|
||||
# Enable child AGENTS.md guidance
|
||||
child_agents_md = true
|
||||
|
||||
# Cache shell environment for faster repeated commands
|
||||
shell_snapshot = true
|
||||
|
||||
# Smart approvals based on request context
|
||||
request_rule = true
|
||||
|
||||
# Enable remote compaction for large histories
|
||||
remote_compaction = true
|
||||
|
||||
# =============================================================================
|
||||
# MCP Servers
|
||||
# =============================================================================
|
||||
|
||||
[mcp_servers.claude-flow]
|
||||
command = "npx"
|
||||
args = ["-y", "@claude-flow/cli@latest"]
|
||||
enabled = true
|
||||
tool_timeout_sec = 120
|
||||
|
||||
# =============================================================================
|
||||
# Skills Configuration
|
||||
# =============================================================================
|
||||
|
||||
[[skills.config]]
|
||||
path = ".agents/skills/swarm-orchestration"
|
||||
enabled = true
|
||||
|
||||
[[skills.config]]
|
||||
path = ".agents/skills/memory-management"
|
||||
enabled = true
|
||||
|
||||
[[skills.config]]
|
||||
path = ".agents/skills/sparc-methodology"
|
||||
enabled = true
|
||||
|
||||
[[skills.config]]
|
||||
path = ".agents/skills/security-audit"
|
||||
enabled = true
|
||||
|
||||
# =============================================================================
|
||||
# Profiles
|
||||
# =============================================================================
|
||||
|
||||
# Development profile - more permissive for local work
|
||||
[profiles.dev]
|
||||
approval_policy = "never"
|
||||
sandbox_mode = "danger-full-access"
|
||||
web_search = "live"
|
||||
|
||||
# Safe profile - maximum restrictions
|
||||
[profiles.safe]
|
||||
approval_policy = "untrusted"
|
||||
sandbox_mode = "read-only"
|
||||
web_search = "disabled"
|
||||
|
||||
# CI profile - for automated pipelines
|
||||
[profiles.ci]
|
||||
approval_policy = "never"
|
||||
sandbox_mode = "workspace-write"
|
||||
web_search = "cached"
|
||||
|
||||
# =============================================================================
|
||||
# History
|
||||
# =============================================================================
|
||||
|
||||
[history]
|
||||
# Save all session transcripts
|
||||
persistence = "save-all"
|
||||
|
||||
# =============================================================================
|
||||
# Shell Environment
|
||||
# =============================================================================
|
||||
|
||||
[shell_environment_policy]
|
||||
# Inherit environment variables
|
||||
inherit = "core"
|
||||
|
||||
# Exclude sensitive variables
|
||||
exclude = ["*_KEY", "*_SECRET", "*_TOKEN", "*_PASSWORD"]
|
||||
|
||||
# =============================================================================
|
||||
# Sandbox Workspace Write Settings
|
||||
# =============================================================================
|
||||
|
||||
[sandbox_workspace_write]
|
||||
# Additional writable paths beyond workspace
|
||||
writable_roots = []
|
||||
|
||||
# Allow network access
|
||||
network_access = true
|
||||
|
||||
# Exclude temp directories
|
||||
exclude_slash_tmp = false
|
||||
|
||||
# =============================================================================
|
||||
# Security Settings
|
||||
# =============================================================================
|
||||
|
||||
[security]
|
||||
# Enable input validation for all user inputs
|
||||
input_validation = true
|
||||
|
||||
# Prevent directory traversal attacks
|
||||
path_traversal_prevention = true
|
||||
|
||||
# Scan for hardcoded secrets
|
||||
secret_scanning = true
|
||||
|
||||
# Scan dependencies for known CVEs
|
||||
cve_scanning = true
|
||||
|
||||
# Maximum file size for operations (bytes)
|
||||
max_file_size = 10485760
|
||||
|
||||
# Allowed file extensions (empty = allow all)
|
||||
allowed_extensions = []
|
||||
|
||||
# Blocked file patterns (regex)
|
||||
blocked_patterns = ["\\.env$", "credentials\\.json$", "\\.pem$", "\\.key$"]
|
||||
|
||||
# =============================================================================
|
||||
# Performance Settings
|
||||
# =============================================================================
|
||||
|
||||
[performance]
|
||||
# Maximum concurrent agents
|
||||
max_agents = 8
|
||||
|
||||
# Task timeout in seconds
|
||||
task_timeout = 300
|
||||
|
||||
# Memory limit per agent
|
||||
memory_limit = "512MB"
|
||||
|
||||
# Enable response caching
|
||||
cache_enabled = true
|
||||
|
||||
# Cache TTL in seconds
|
||||
cache_ttl = 3600
|
||||
|
||||
# Enable parallel task execution
|
||||
parallel_execution = true
|
||||
|
||||
# =============================================================================
|
||||
# Logging Settings
|
||||
# =============================================================================
|
||||
|
||||
[logging]
|
||||
# Log level: debug, info, warn, error
|
||||
level = "info"
|
||||
|
||||
# Log format: json, text, pretty
|
||||
format = "pretty"
|
||||
|
||||
# Log destination: stdout, file, both
|
||||
destination = "stdout"
|
||||
|
||||
# =============================================================================
|
||||
# Neural Intelligence Settings
|
||||
# =============================================================================
|
||||
|
||||
[neural]
|
||||
# Enable SONA (Self-Optimizing Neural Architecture)
|
||||
sona_enabled = true
|
||||
|
||||
# Enable HNSW vector search
|
||||
hnsw_enabled = true
|
||||
|
||||
# HNSW index parameters
|
||||
hnsw_m = 16
|
||||
hnsw_ef_construction = 200
|
||||
hnsw_ef_search = 100
|
||||
|
||||
# Enable pattern learning
|
||||
pattern_learning = true
|
||||
|
||||
# Learning rate for neural adaptation
|
||||
learning_rate = 0.01
|
||||
|
||||
# =============================================================================
|
||||
# Swarm Orchestration Settings
|
||||
# =============================================================================
|
||||
|
||||
[swarm]
|
||||
# Default topology: hierarchical, mesh, ring, star
|
||||
default_topology = "hierarchical"
|
||||
|
||||
# Default strategy: balanced, specialized, adaptive
|
||||
default_strategy = "specialized"
|
||||
|
||||
# Consensus algorithm: raft, byzantine, gossip
|
||||
consensus = "raft"
|
||||
|
||||
# Enable anti-drift measures
|
||||
anti_drift = true
|
||||
|
||||
# Checkpoint interval (tasks)
|
||||
checkpoint_interval = 10
|
||||
|
||||
# =============================================================================
|
||||
# Hooks Configuration
|
||||
# =============================================================================
|
||||
|
||||
[hooks]
|
||||
# Enable lifecycle hooks
|
||||
enabled = true
|
||||
|
||||
# Pre-task hook
|
||||
pre_task = true
|
||||
|
||||
# Post-task hook (for learning)
|
||||
post_task = true
|
||||
|
||||
# Enable neural training on post-edit
|
||||
train_on_edit = true
|
||||
|
||||
# =============================================================================
|
||||
# Background Workers
|
||||
# =============================================================================
|
||||
|
||||
[workers]
|
||||
# Enable background workers
|
||||
enabled = true
|
||||
|
||||
# Worker configuration
|
||||
[workers.audit]
|
||||
enabled = true
|
||||
priority = "critical"
|
||||
interval = 300
|
||||
|
||||
[workers.optimize]
|
||||
enabled = true
|
||||
priority = "high"
|
||||
interval = 600
|
||||
|
||||
[workers.consolidate]
|
||||
enabled = true
|
||||
priority = "low"
|
||||
interval = 1800
|
||||
@@ -1,126 +0,0 @@
|
||||
---
|
||||
name: memory-management
|
||||
description: >
|
||||
AgentDB memory system with HNSW vector search. Provides 150x-12,500x faster pattern retrieval, persistent storage, and semantic search capabilities for learning and knowledge management.
|
||||
Use when: need to store successful patterns, searching for similar solutions, semantic lookup of past work, learning from previous tasks, sharing knowledge between agents, building knowledge base.
|
||||
Skip when: no learning needed, ephemeral one-off tasks, external data sources available, read-only exploration.
|
||||
---
|
||||
|
||||
# Memory Management Skill
|
||||
|
||||
## Purpose
|
||||
AgentDB memory system with HNSW vector search. Provides 150x-12,500x faster pattern retrieval, persistent storage, and semantic search capabilities for learning and knowledge management.
|
||||
|
||||
## When to Trigger
|
||||
- need to store successful patterns
|
||||
- searching for similar solutions
|
||||
- semantic lookup of past work
|
||||
- learning from previous tasks
|
||||
- sharing knowledge between agents
|
||||
- building knowledge base
|
||||
|
||||
## When to Skip
|
||||
- no learning needed
|
||||
- ephemeral one-off tasks
|
||||
- external data sources available
|
||||
- read-only exploration
|
||||
|
||||
## Commands
|
||||
|
||||
### Store Pattern
|
||||
Store a pattern or knowledge item in memory
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory store --key "[key]" --value "[value]" --namespace patterns
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli memory store --key "auth-jwt-pattern" --value "JWT validation with refresh tokens" --namespace patterns
|
||||
```
|
||||
|
||||
### Semantic Search
|
||||
Search memory using semantic similarity
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory search --query "[search terms]" --limit 10
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli memory search --query "authentication best practices" --limit 5
|
||||
```
|
||||
|
||||
### Retrieve Entry
|
||||
Retrieve a specific memory entry by key
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory get --key "[key]" --namespace [namespace]
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli memory get --key "auth-jwt-pattern" --namespace patterns
|
||||
```
|
||||
|
||||
### List Entries
|
||||
List all entries in a namespace
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory list --namespace [namespace]
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli memory list --namespace patterns --limit 20
|
||||
```
|
||||
|
||||
### Delete Entry
|
||||
Delete a memory entry
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory delete --key "[key]" --namespace [namespace]
|
||||
```
|
||||
|
||||
### Initialize HNSW Index
|
||||
Initialize HNSW vector search index
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory init --enable-hnsw
|
||||
```
|
||||
|
||||
### Memory Stats
|
||||
Show memory usage statistics
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory stats
|
||||
```
|
||||
|
||||
### Export Memory
|
||||
Export memory to JSON
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli memory export --output memory-backup.json
|
||||
```
|
||||
|
||||
|
||||
## Scripts
|
||||
|
||||
| Script | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| `memory-backup` | `.agents/scripts/memory-backup.sh` | Backup memory to external storage |
|
||||
| `memory-consolidate` | `.agents/scripts/memory-consolidate.sh` | Consolidate and optimize memory |
|
||||
|
||||
|
||||
## References
|
||||
|
||||
| Document | Path | Description |
|
||||
|----------|------|-------------|
|
||||
| `HNSW Guide` | `docs/hnsw.md` | HNSW vector search configuration |
|
||||
| `Memory Schema` | `docs/memory-schema.md` | Memory namespace and schema reference |
|
||||
|
||||
## Best Practices
|
||||
1. Check memory for existing patterns before starting
|
||||
2. Use hierarchical topology for coordination
|
||||
3. Store successful patterns after completion
|
||||
4. Document any new learnings
|
||||
@@ -1,135 +0,0 @@
|
||||
---
|
||||
name: security-audit
|
||||
description: >
|
||||
Comprehensive security scanning and vulnerability detection. Includes input validation, path traversal prevention, CVE detection, and secure coding pattern enforcement.
|
||||
Use when: authentication implementation, authorization logic, payment processing, user data handling, API endpoint creation, file upload handling, database queries, external API integration.
|
||||
Skip when: read-only operations on public data, internal development tooling, static documentation, styling changes.
|
||||
---
|
||||
|
||||
# Security Audit Skill
|
||||
|
||||
## Purpose
|
||||
Comprehensive security scanning and vulnerability detection. Includes input validation, path traversal prevention, CVE detection, and secure coding pattern enforcement.
|
||||
|
||||
## When to Trigger
|
||||
- authentication implementation
|
||||
- authorization logic
|
||||
- payment processing
|
||||
- user data handling
|
||||
- API endpoint creation
|
||||
- file upload handling
|
||||
- database queries
|
||||
- external API integration
|
||||
|
||||
## When to Skip
|
||||
- read-only operations on public data
|
||||
- internal development tooling
|
||||
- static documentation
|
||||
- styling changes
|
||||
|
||||
## Commands
|
||||
|
||||
### Full Security Scan
|
||||
Run comprehensive security analysis on the codebase
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security scan --depth full
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli security scan --depth full --output security-report.json
|
||||
```
|
||||
|
||||
### Input Validation Check
|
||||
Check for input validation issues
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security scan --check input-validation
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli security scan --check input-validation --path ./src/api
|
||||
```
|
||||
|
||||
### Path Traversal Check
|
||||
Check for path traversal vulnerabilities
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security scan --check path-traversal
|
||||
```
|
||||
|
||||
### SQL Injection Check
|
||||
Check for SQL injection vulnerabilities
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security scan --check sql-injection
|
||||
```
|
||||
|
||||
### XSS Check
|
||||
Check for cross-site scripting vulnerabilities
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security scan --check xss
|
||||
```
|
||||
|
||||
### CVE Scan
|
||||
Scan dependencies for known CVEs
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security cve --scan
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli security cve --scan --severity high
|
||||
```
|
||||
|
||||
### Security Audit Report
|
||||
Generate full security audit report
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security audit --report
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli security audit --report --format markdown --output SECURITY.md
|
||||
```
|
||||
|
||||
### Threat Modeling
|
||||
Run threat modeling analysis
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security threats --analyze
|
||||
```
|
||||
|
||||
### Validate Secrets
|
||||
Check for hardcoded secrets
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli security validate --check secrets
|
||||
```
|
||||
|
||||
|
||||
## Scripts
|
||||
|
||||
| Script | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| `security-scan` | `.agents/scripts/security-scan.sh` | Run full security scan pipeline |
|
||||
| `cve-remediate` | `.agents/scripts/cve-remediate.sh` | Auto-remediate known CVEs |
|
||||
|
||||
|
||||
## References
|
||||
|
||||
| Document | Path | Description |
|
||||
|----------|------|-------------|
|
||||
| `Security Checklist` | `docs/security-checklist.md` | Security review checklist |
|
||||
| `OWASP Guide` | `docs/owasp-top10.md` | OWASP Top 10 mitigation guide |
|
||||
|
||||
## Best Practices
|
||||
1. Check memory for existing patterns before starting
|
||||
2. Use hierarchical topology for coordination
|
||||
3. Store successful patterns after completion
|
||||
4. Document any new learnings
|
||||
@@ -1,118 +0,0 @@
|
||||
---
|
||||
name: sparc-methodology
|
||||
description: >
|
||||
SPARC development workflow: Specification, Pseudocode, Architecture, Refinement, Completion. A structured approach for complex implementations that ensures thorough planning before coding.
|
||||
Use when: new feature implementation, complex implementations, architectural changes, system redesign, integration work, unclear requirements.
|
||||
Skip when: simple bug fixes, documentation updates, configuration changes, well-defined small tasks, routine maintenance.
|
||||
---
|
||||
|
||||
# Sparc Methodology Skill
|
||||
|
||||
## Purpose
|
||||
SPARC development workflow: Specification, Pseudocode, Architecture, Refinement, Completion. A structured approach for complex implementations that ensures thorough planning before coding.
|
||||
|
||||
## When to Trigger
|
||||
- new feature implementation
|
||||
- complex implementations
|
||||
- architectural changes
|
||||
- system redesign
|
||||
- integration work
|
||||
- unclear requirements
|
||||
|
||||
## When to Skip
|
||||
- simple bug fixes
|
||||
- documentation updates
|
||||
- configuration changes
|
||||
- well-defined small tasks
|
||||
- routine maintenance
|
||||
|
||||
## Commands
|
||||
|
||||
### Specification Phase
|
||||
Define requirements, acceptance criteria, and constraints
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "specification: [requirements]"
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "specification: user authentication with OAuth2, MFA, and session management"
|
||||
```
|
||||
|
||||
### Pseudocode Phase
|
||||
Write high-level pseudocode for the implementation
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "pseudocode: [feature]"
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "pseudocode: OAuth2 login flow with token refresh"
|
||||
```
|
||||
|
||||
### Architecture Phase
|
||||
Design system structure, interfaces, and dependencies
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "architecture: [design]"
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "architecture: auth module with service layer, repository, and API endpoints"
|
||||
```
|
||||
|
||||
### Refinement Phase
|
||||
Iterate on the design based on feedback
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "refinement: [feedback]"
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "refinement: add rate limiting and brute force protection"
|
||||
```
|
||||
|
||||
### Completion Phase
|
||||
Finalize implementation with tests and documentation
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "completion: [final checks]"
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "completion: verify all tests pass, update API docs, security review"
|
||||
```
|
||||
|
||||
### SPARC Coordinator
|
||||
Spawn SPARC coordinator agent
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli agent spawn --type sparc-coord --name sparc-lead
|
||||
```
|
||||
|
||||
|
||||
## Scripts
|
||||
|
||||
| Script | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| `sparc-init` | `.agents/scripts/sparc-init.sh` | Initialize SPARC workflow for a new feature |
|
||||
| `sparc-review` | `.agents/scripts/sparc-review.sh` | Run SPARC phase review checklist |
|
||||
|
||||
|
||||
## References
|
||||
|
||||
| Document | Path | Description |
|
||||
|----------|------|-------------|
|
||||
| `SPARC Overview` | `docs/sparc.md` | Complete SPARC methodology guide |
|
||||
| `Phase Templates` | `docs/sparc-templates.md` | Templates for each SPARC phase |
|
||||
|
||||
## Best Practices
|
||||
1. Check memory for existing patterns before starting
|
||||
2. Use hierarchical topology for coordination
|
||||
3. Store successful patterns after completion
|
||||
4. Document any new learnings
|
||||
@@ -1,114 +0,0 @@
|
||||
---
|
||||
name: swarm-orchestration
|
||||
description: >
|
||||
Multi-agent swarm coordination for complex tasks. Uses hierarchical topology with specialized agents to break down and execute complex work across multiple files and modules.
|
||||
Use when: 3+ files need changes, new feature implementation, cross-module refactoring, API changes with tests, security-related changes, performance optimization across codebase, database schema changes.
|
||||
Skip when: single file edits, simple bug fixes (1-2 lines), documentation updates, configuration changes, quick exploration.
|
||||
---
|
||||
|
||||
# Swarm Orchestration Skill
|
||||
|
||||
## Purpose
|
||||
Multi-agent swarm coordination for complex tasks. Uses hierarchical topology with specialized agents to break down and execute complex work across multiple files and modules.
|
||||
|
||||
## When to Trigger
|
||||
- 3+ files need changes
|
||||
- new feature implementation
|
||||
- cross-module refactoring
|
||||
- API changes with tests
|
||||
- security-related changes
|
||||
- performance optimization across codebase
|
||||
- database schema changes
|
||||
|
||||
## When to Skip
|
||||
- single file edits
|
||||
- simple bug fixes (1-2 lines)
|
||||
- documentation updates
|
||||
- configuration changes
|
||||
- quick exploration
|
||||
|
||||
## Commands
|
||||
|
||||
### Initialize Swarm
|
||||
Start a new swarm with hierarchical topology (anti-drift)
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli swarm init --topology hierarchical --max-agents 8 --strategy specialized
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli swarm init --topology hierarchical --max-agents 6 --strategy specialized
|
||||
```
|
||||
|
||||
### Route Task
|
||||
Route a task to the appropriate agents based on task type
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "[task description]"
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli hooks route --task "implement OAuth2 authentication flow"
|
||||
```
|
||||
|
||||
### Spawn Agent
|
||||
Spawn a specific agent type
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli agent spawn --type [type] --name [name]
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli agent spawn --type coder --name impl-auth
|
||||
```
|
||||
|
||||
### Monitor Status
|
||||
Check the current swarm status
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli swarm status --verbose
|
||||
```
|
||||
|
||||
### Orchestrate Task
|
||||
Orchestrate a task across multiple agents
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli task orchestrate --task "[task]" --strategy adaptive
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
npx @claude-flow/cli task orchestrate --task "refactor auth module" --strategy parallel --max-agents 4
|
||||
```
|
||||
|
||||
### List Agents
|
||||
List all active agents
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli agent list --filter active
|
||||
```
|
||||
|
||||
|
||||
## Scripts
|
||||
|
||||
| Script | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| `swarm-start` | `.agents/scripts/swarm-start.sh` | Initialize swarm with default settings |
|
||||
| `swarm-monitor` | `.agents/scripts/swarm-monitor.sh` | Real-time swarm monitoring dashboard |
|
||||
|
||||
|
||||
## References
|
||||
|
||||
| Document | Path | Description |
|
||||
|----------|------|-------------|
|
||||
| `Agent Types` | `docs/agents.md` | Complete list of agent types and capabilities |
|
||||
| `Topology Guide` | `docs/topology.md` | Swarm topology configuration guide |
|
||||
|
||||
## Best Practices
|
||||
1. Check memory for existing patterns before starting
|
||||
2. Use hierarchical topology for coordination
|
||||
3. Store successful patterns after completion
|
||||
4. Document any new learnings
|
||||
@@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/conf"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var c config.Config
|
||||
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||
ctx := svc.NewServiceContext(c)
|
||||
const key = "cache:auth:method:device"
|
||||
before, _ := ctx.Redis.Get(ctx.DB.Statement.Context, key).Result()
|
||||
fmt.Printf("cache before=%q\n", before)
|
||||
m, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
|
||||
fmt.Printf("model err=%v enabled_nil=%v", err, m == nil || m.Enabled == nil)
|
||||
if m != nil && m.Enabled != nil { fmt.Printf(" enabled=%v", *m.Enabled) }
|
||||
if m != nil { fmt.Printf(" config=%s", m.Config) }
|
||||
fmt.Println()
|
||||
after, _ := ctx.Redis.Get(ctx.DB.Statement.Context, key).Result()
|
||||
fmt.Printf("cache after=%q\n", after)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
initpkg "github.com/perfect-panel/server/initialize"
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/conf"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var c config.Config
|
||||
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||
ctx := svc.NewServiceContext(c)
|
||||
method, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("db auth_method.enabled=%v config=%s\n", *method.Enabled, method.Config)
|
||||
initpkg.Device(ctx)
|
||||
fmt.Printf("ctx.Config.Device.Enable=%v SecuritySecret=%q EnableSecurity=%v\n", ctx.Config.Device.Enable, ctx.Config.Device.SecuritySecret, ctx.Config.Device.EnableSecurity)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/conf"
|
||||
)
|
||||
|
||||
type row struct {
|
||||
ID int64
|
||||
Method string
|
||||
Enabled int
|
||||
Config string
|
||||
}
|
||||
|
||||
func main() {
|
||||
var c config.Config
|
||||
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||
ctx := svc.NewServiceContext(c)
|
||||
|
||||
var rows []row
|
||||
if err := ctx.DB.Raw("SELECT id, method, enabled, config FROM auth_method WHERE method = ?", "device").Scan(&rows).Error; err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("raw rows: %+v\n", rows)
|
||||
|
||||
m, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
|
||||
fmt.Printf("model err=%v\n", err)
|
||||
if err == nil && m != nil && m.Enabled != nil {
|
||||
fmt.Printf("model row: id=%d method=%s enabled=%v config=%s\n", m.Id, m.Method, *m.Enabled, m.Config)
|
||||
} else {
|
||||
fmt.Printf("model row nil or no enabled ptr: %#v\n", m)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
authmodel "github.com/perfect-panel/server/internal/model/auth"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/conf"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var c config.Config
|
||||
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||
ctx := svc.NewServiceContext(c)
|
||||
|
||||
var a1 authmodel.Auth
|
||||
err1 := ctx.DB.Model(&authmodel.Auth{}).Where("method = ?", "device").First(&a1).Error
|
||||
fmt.Printf("gorm direct err=%v enabled_nil=%v", err1, a1.Enabled == nil)
|
||||
if a1.Enabled != nil { fmt.Printf(" enabled=%v", *a1.Enabled) }
|
||||
fmt.Printf(" config=%s\n", a1.Config)
|
||||
|
||||
var a2 authmodel.Auth
|
||||
err2 := ctx.DB.Table("auth_method").Where("method = ?", "device").First(&a2).Error
|
||||
fmt.Printf("gorm table err=%v enabled_nil=%v", err2, a2.Enabled == nil)
|
||||
if a2.Enabled != nil { fmt.Printf(" enabled=%v", *a2.Enabled) }
|
||||
fmt.Printf(" config=%s\n", a2.Config)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"extends": ["@commitlint/config-conventional"]
|
||||
}
|
||||
@@ -9,3 +9,10 @@ GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
||||
|
||||
# PPanel Server 镜像标签(留空使用 latest)
|
||||
PPANEL_SERVER_TAG=latest
|
||||
|
||||
# AWS 区域(香港)
|
||||
AWS_REGION=ap-east-1
|
||||
|
||||
# Grafana 公开域名(如需反代)
|
||||
GRAFANA_DOMAIN=logs-new.hifast.biz
|
||||
GRAFANA_ROOT_URL=https://logs-new.hifast.biz
|
||||
|
||||
+26
-23
@@ -14,11 +14,12 @@ on:
|
||||
env:
|
||||
# Docker镜像仓库
|
||||
REPO: ${{ vars.REPO || 'registry.kxsw.us/vpn-server' }}
|
||||
# SSH连接信息 (根据分支自动选择)
|
||||
# SSH连接信息 (根据分支自动选择服务器和用户)
|
||||
SSH_HOST: ${{ github.ref_name == 'main' && vars.SSH_HOST || vars.DEV_SSH_HOST }}
|
||||
SSH_PORT: ${{ vars.SSH_PORT }}
|
||||
SSH_USER: ${{ vars.SSH_USER }}
|
||||
SSH_PASSWORD: ${{ github.ref_name == 'main' && vars.SSH_PASSWORD || vars.DEV_SSH_PASSWORD }}
|
||||
SSH_USER: ${{ github.ref_name == 'main' && 'ubuntu' || 'root' }}
|
||||
# SSH私钥(Gitea Secret 名称:AWS)
|
||||
SSH_KEY: ${{ secrets.AWS }}
|
||||
# TG通知
|
||||
TG_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0
|
||||
TG_CHAT_ID: "-4940243803"
|
||||
@@ -49,7 +50,7 @@ jobs:
|
||||
if [ "${{ github.ref_name }}" = "main" ]; then
|
||||
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
|
||||
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
|
||||
echo "DEPLOY_PATH=/root/bindbox" >> $GITHUB_ENV
|
||||
echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV
|
||||
echo "为 main 分支设置生产环境变量"
|
||||
elif [ "${{ github.ref_name }}" = "internal" ]; then
|
||||
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
|
||||
@@ -137,17 +138,15 @@ jobs:
|
||||
|
||||
echo "镜像推送完成"
|
||||
|
||||
# 调试: 打印 SSH 连接信息
|
||||
- name: 🔍 调试 - 打印 SSH 连接信息
|
||||
# 调试: 打印部署目标(不输出敏感信息)
|
||||
- name: 🔍 调试 - 打印部署目标
|
||||
run: |
|
||||
echo "========== SSH 连接信息调试 =========="
|
||||
echo "========== 部署目标调试 =========="
|
||||
echo "当前分支: ${{ github.ref_name }}"
|
||||
echo "SSH_HOST: ${{ env.SSH_HOST }}"
|
||||
echo "SSH_PORT: ${{ env.SSH_PORT }}"
|
||||
echo "SSH_USER: ${{ env.SSH_USER }}"
|
||||
echo "SSH_PASSWORD 长度: ${#SSH_PASSWORD}"
|
||||
echo "SSH_PASSWORD 前3位: $(echo "$SSH_PASSWORD" | cut -c1-3)***"
|
||||
echo "SSH_PASSWORD 完整值: ${{ env.SSH_PASSWORD }}"
|
||||
echo "SSH认证方式: 私钥 (AWS)"
|
||||
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
|
||||
echo "====================================="
|
||||
|
||||
@@ -157,10 +156,10 @@ jobs:
|
||||
with:
|
||||
host: ${{ env.SSH_HOST }}
|
||||
username: ${{ env.SSH_USER }}
|
||||
password: ${{ env.SSH_PASSWORD }}
|
||||
key: ${{ env.SSH_KEY }}
|
||||
port: ${{ env.SSH_PORT }}
|
||||
source: "docker-compose.cloud.yml"
|
||||
target: "${{ env.DEPLOY_PATH }}/"
|
||||
target: "/tmp/ppanel-deploy/"
|
||||
|
||||
# 步骤6: 连接服务器更新并启动
|
||||
- name: 🚀 连接服务器更新并启动
|
||||
@@ -168,7 +167,7 @@ jobs:
|
||||
with:
|
||||
host: ${{ env.SSH_HOST }}
|
||||
username: ${{ env.SSH_USER }}
|
||||
password: ${{ env.SSH_PASSWORD }}
|
||||
key: ${{ env.SSH_KEY }}
|
||||
port: ${{ env.SSH_PORT }}
|
||||
timeout: 300s
|
||||
command_timeout: 600s
|
||||
@@ -176,23 +175,27 @@ jobs:
|
||||
echo "连接服务器成功,开始部署..."
|
||||
echo "部署目录: ${{ env.DEPLOY_PATH }}"
|
||||
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
||||
echo "登录用户: ${{ env.SSH_USER }}"
|
||||
|
||||
# 进入部署目录
|
||||
if [ "${{ github.ref_name }}" = "main" ]; then
|
||||
sudo mkdir -p ${{ env.DEPLOY_PATH }}
|
||||
sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
||||
cd ${{ env.DEPLOY_PATH }}
|
||||
echo "📥 拉取镜像..."
|
||||
sudo docker-compose -f docker-compose.cloud.yml pull ppanel-server
|
||||
echo "🚀 启动服务..."
|
||||
sudo docker-compose -f docker-compose.cloud.yml up -d ppanel-server
|
||||
sudo docker image prune -f || true
|
||||
else
|
||||
mkdir -p ${{ env.DEPLOY_PATH }}
|
||||
cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
||||
cd ${{ env.DEPLOY_PATH }}
|
||||
|
||||
# 创建/更新环境变量文件
|
||||
# echo "PPANEL_SERVER_TAG=${{ env.DOCKER_TAG_SUFFIX }}" > .env
|
||||
|
||||
# 拉取最新镜像
|
||||
echo "📥 拉取镜像..."
|
||||
docker-compose -f docker-compose.cloud.yml pull ppanel-server
|
||||
|
||||
# 启动服务
|
||||
echo "🚀 启动服务..."
|
||||
docker-compose -f docker-compose.cloud.yml up -d ppanel-server
|
||||
|
||||
# 清理未使用的镜像
|
||||
docker image prune -f || true
|
||||
fi
|
||||
|
||||
echo "✅ 部署命令执行完成"
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="go build github.com/perfect-panel/server" type="GoApplicationRunConfiguration" factoryName="Go Application" nameIsGenerated="true">
|
||||
<module name="server" />
|
||||
<working_directory value="$PROJECT_DIR$" />
|
||||
<parameters value="run --config etc/ppanel-dev.yaml" />
|
||||
<kind value="PACKAGE" />
|
||||
<package value="github.com/perfect-panel/server" />
|
||||
<directory value="$PROJECT_DIR$" />
|
||||
<filePath value="$PROJECT_DIR$/ppanel.go" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -1,145 +0,0 @@
|
||||
# ppanel-server
|
||||
|
||||
> Multi-agent orchestration framework for agentic coding
|
||||
|
||||
## Project Overview
|
||||
|
||||
A Claude Flow powered project
|
||||
|
||||
**Tech Stack**: TypeScript, Node.js
|
||||
**Architecture**: Domain-Driven Design with bounded contexts
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### Build
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Test
|
||||
```bash
|
||||
npm test
|
||||
```
|
||||
|
||||
### Development
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## Agent Coordination
|
||||
|
||||
### Swarm Configuration
|
||||
|
||||
This project uses hierarchical swarm coordination for complex tasks:
|
||||
|
||||
| Setting | Value | Purpose |
|
||||
|---------|-------|---------|
|
||||
| Topology | `hierarchical` | Queen-led coordination (anti-drift) |
|
||||
| Max Agents | 8 | Optimal team size |
|
||||
| Strategy | `specialized` | Clear role boundaries |
|
||||
| Consensus | `raft` | Leader-based consistency |
|
||||
|
||||
### When to Use Swarms
|
||||
|
||||
**Invoke swarm for:**
|
||||
- Multi-file changes (3+ files)
|
||||
- New feature implementation
|
||||
- Cross-module refactoring
|
||||
- API changes with tests
|
||||
- Security-related changes
|
||||
- Performance optimization
|
||||
|
||||
**Skip swarm for:**
|
||||
- Single file edits
|
||||
- Simple bug fixes (1-2 lines)
|
||||
- Documentation updates
|
||||
- Configuration changes
|
||||
|
||||
### Available Skills
|
||||
|
||||
Use `$skill-name` syntax to invoke:
|
||||
|
||||
| Skill | Use Case |
|
||||
|-------|----------|
|
||||
| `$swarm-orchestration` | Multi-agent task coordination |
|
||||
| `$memory-management` | Pattern storage and retrieval |
|
||||
| `$sparc-methodology` | Structured development workflow |
|
||||
| `$security-audit` | Security scanning and CVE detection |
|
||||
|
||||
### Agent Types
|
||||
|
||||
| Type | Role | Use Case |
|
||||
|------|------|----------|
|
||||
| `researcher` | Requirements analysis | Understanding scope |
|
||||
| `architect` | System design | Planning structure |
|
||||
| `coder` | Implementation | Writing code |
|
||||
| `tester` | Test creation | Quality assurance |
|
||||
| `reviewer` | Code review | Security and quality |
|
||||
|
||||
## Code Standards
|
||||
|
||||
### File Organization
|
||||
- **NEVER** save to root folder
|
||||
- `/src` - Source code files
|
||||
- `/tests` - Test files
|
||||
- `/docs` - Documentation
|
||||
- `/config` - Configuration files
|
||||
|
||||
### Quality Rules
|
||||
- Files under 500 lines
|
||||
- No hardcoded secrets
|
||||
- Input validation at boundaries
|
||||
- Typed interfaces for public APIs
|
||||
- TDD London School (mock-first) preferred
|
||||
|
||||
### Commit Messages
|
||||
```
|
||||
<type>(<scope>): <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
Co-Authored-By: claude-flow <ruv@ruv.net>
|
||||
```
|
||||
|
||||
Types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `chore`
|
||||
|
||||
## Security
|
||||
|
||||
### Critical Rules
|
||||
- NEVER commit secrets, credentials, or .env files
|
||||
- NEVER hardcode API keys
|
||||
- Always validate user input
|
||||
- Use parameterized queries for SQL
|
||||
- Sanitize output to prevent XSS
|
||||
|
||||
### Path Security
|
||||
- Validate all file paths
|
||||
- Prevent directory traversal (../)
|
||||
- Use absolute paths internally
|
||||
|
||||
## Memory System
|
||||
|
||||
### Storing Patterns
|
||||
```bash
|
||||
npx @claude-flow/cli memory store \
|
||||
--key "pattern-name" \
|
||||
--value "pattern description" \
|
||||
--namespace patterns
|
||||
```
|
||||
|
||||
### Searching Memory
|
||||
```bash
|
||||
npx @claude-flow/cli memory search \
|
||||
--query "search terms" \
|
||||
--namespace patterns
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- Documentation: https://github.com/ruvnet/claude-flow
|
||||
- Issues: https://github.com/ruvnet/claude-flow/issues
|
||||
+1
-1
@@ -28,7 +28,7 @@ FROM scratch
|
||||
|
||||
# Copy CA certificates and timezone data
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/Asia/Shanghai
|
||||
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
|
||||
|
||||
ENV TZ=Asia/Shanghai
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
upstream api_backend {
|
||||
server 127.0.0.1:8080;
|
||||
}
|
||||
|
||||
server {
|
||||
|
||||
listen 80;
|
||||
server_name api.hifast.biz 4d3vsw888xgaen.hifast.biz;
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/html;
|
||||
allow all;
|
||||
}
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name api.hifast.biz;
|
||||
client_max_body_size 150M;
|
||||
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
|
||||
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
|
||||
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Frame-Options "DENY";
|
||||
|
||||
add_header X-Content-Type-Options nosniff;
|
||||
if ($http_user_agent ~* '(9999|91\.78)') {
|
||||
return 444;
|
||||
}
|
||||
location ~ ^/v1/common/client/download/file/(?<download_name>Hi快VPN-(?<os>windows|mac|android)-1.0.0-ic-.*\.(?<ext>exe|dmg|apk))$ {
|
||||
alias /var/www/download/Hi快VPN-$os-1.0.0.$ext;
|
||||
charset utf-8;
|
||||
add_header Content-Disposition 'attachment; filename="$download_name"';
|
||||
add_header Content-Type application/octet-stream;
|
||||
}
|
||||
|
||||
location /v1/common/client/download/file/ {
|
||||
alias /var/www/download/;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://api_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name 4d3vsw888xgaen.hifast.biz;
|
||||
client_max_body_size 150M;
|
||||
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
|
||||
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
|
||||
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Frame-Options DENY;
|
||||
add_header X-Content-Type-Options nosniff;
|
||||
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json image/svg+xml;
|
||||
root /var/www/admin;
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -163,5 +163,9 @@ service ppanel {
|
||||
@doc "Query quota task list"
|
||||
@handler QueryQuotaTaskList
|
||||
get /quota/list (QueryQuotaTaskListRequest) returns (QueryQuotaTaskListResponse)
|
||||
|
||||
@doc "Query quota task status"
|
||||
@handler QueryQuotaTaskStatus
|
||||
post /quota/status (QueryQuotaTaskStatusRequest) returns (QueryQuotaTaskStatusResponse)
|
||||
}
|
||||
|
||||
|
||||
+35
-4
@@ -44,13 +44,13 @@ type (
|
||||
Balance int64 `json:"balance"`
|
||||
Commission int64 `json:"commission"`
|
||||
ReferralPercentage uint8 `json:"referral_percentage"`
|
||||
OnlyFirstPurchase bool `json:"only_first_purchase"`
|
||||
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
||||
GiftAmount int64 `json:"gift_amount"`
|
||||
Telegram int64 `json:"telegram"`
|
||||
ReferCode string `json:"refer_code"`
|
||||
RefererId int64 `json:"referer_id"`
|
||||
Enable bool `json:"enable"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
Enable *bool `json:"enable"`
|
||||
IsAdmin *bool `json:"is_admin"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
UpdateUserNotifySettingRequest {
|
||||
@@ -93,6 +93,9 @@ type (
|
||||
Upload int64 `json:"upload"`
|
||||
Token string `json:"token"`
|
||||
Status uint8 `json:"status"`
|
||||
EffectiveSpeed int64 `json:"effective_speed"`
|
||||
IsThrottled bool `json:"is_throttled"`
|
||||
ThrottleRule string `json:"throttle_rule,omitempty"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
@@ -227,6 +230,23 @@ type (
|
||||
FamilyId int64 `json:"family_id" validate:"required,gt=0"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
GetWithdrawalListRequest {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
UserId *int64 `form:"user_id,omitempty"`
|
||||
Status *uint8 `form:"status,omitempty"`
|
||||
}
|
||||
GetWithdrawalListResponse {
|
||||
List []WithdrawalLog `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
ApproveWithdrawalRequest {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
}
|
||||
RejectWithdrawalRequest {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
Reason string `json:"reason" validate:"required,max=500"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
@@ -367,5 +387,16 @@ service ppanel {
|
||||
@doc "Dissolve family"
|
||||
@handler DissolveFamily
|
||||
put /family/dissolve (DissolveFamilyRequest)
|
||||
}
|
||||
|
||||
@doc "Get withdrawal list"
|
||||
@handler GetWithdrawalList
|
||||
get /withdrawal/list (GetWithdrawalListRequest) returns (GetWithdrawalListResponse)
|
||||
|
||||
@doc "Approve withdrawal"
|
||||
@handler ApproveWithdrawal
|
||||
post /withdrawal/approve (ApproveWithdrawalRequest)
|
||||
|
||||
@doc "Reject withdrawal"
|
||||
@handler RejectWithdrawal
|
||||
post /withdrawal/reject (RejectWithdrawalRequest)
|
||||
}
|
||||
|
||||
+35
-11
@@ -20,6 +20,7 @@ type (
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
CaptchaId string `json:"captcha_id,optional"`
|
||||
CaptchaCode string `json:"captcha_code,optional"`
|
||||
SliderToken string `json:"slider_token,optional"`
|
||||
}
|
||||
// Check user is exist request
|
||||
CheckUserRequest {
|
||||
@@ -42,6 +43,7 @@ type (
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
CaptchaId string `json:"captcha_id,optional"`
|
||||
CaptchaCode string `json:"captcha_code,optional"`
|
||||
SliderToken string `json:"slider_token,optional"`
|
||||
}
|
||||
// User reset password request
|
||||
ResetPasswordRequest {
|
||||
@@ -55,17 +57,18 @@ type (
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
CaptchaId string `json:"captcha_id,optional"`
|
||||
CaptchaCode string `json:"captcha_code,optional"`
|
||||
SliderToken string `json:"slider_token,optional"`
|
||||
}
|
||||
// Email login request
|
||||
EmailLoginRequest {
|
||||
Identifier string `json:"identifier"`
|
||||
Email string `json:"email" validate:"required"`
|
||||
Code string `json:"code" validate:"required"`
|
||||
Invite string `json:"invite,optional"`
|
||||
Identifier string `json:"identifier" form:"identifier"`
|
||||
Email string `json:"email" form:"email" validate:"required,email"`
|
||||
Code string `json:"code" form:"code" validate:"required"`
|
||||
Invite string `json:"invite,optional" form:"invite"`
|
||||
IP string `header:"X-Original-Forwarded-For"`
|
||||
UserAgent string `header:"User-Agent"`
|
||||
LoginType string `header:"Login-Type"`
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
CfToken string `json:"cf_token,optional" form:"cf_token"`
|
||||
}
|
||||
LoginResponse {
|
||||
Token string `json:"token"`
|
||||
@@ -94,6 +97,7 @@ type (
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
CaptchaId string `json:"captcha_id,optional"`
|
||||
CaptchaCode string `json:"captcha_code,optional"`
|
||||
SliderToken string `json:"slider_token,optional"`
|
||||
}
|
||||
// Check user is exist request
|
||||
TelephoneCheckUserRequest {
|
||||
@@ -118,6 +122,7 @@ type (
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
CaptchaId string `json:"captcha_id,optional"`
|
||||
CaptchaCode string `json:"captcha_code,optional"`
|
||||
SliderToken string `json:"slider_token,optional"`
|
||||
}
|
||||
// User login response
|
||||
TelephoneResetPasswordRequest {
|
||||
@@ -132,6 +137,7 @@ type (
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
CaptchaId string `json:"captcha_id,optional"`
|
||||
CaptchaCode string `json:"captcha_code,optional"`
|
||||
SliderToken string `json:"slider_token,optional"`
|
||||
}
|
||||
AppleLoginCallbackRequest {
|
||||
Code string `form:"code"`
|
||||
@@ -148,11 +154,22 @@ type (
|
||||
UserAgent string `json:"user_agent" validate:"required"`
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
ShortCode string `json:"short_code,optional"`
|
||||
BasePayload string `json:"base_payload,optional"`
|
||||
}
|
||||
GenerateCaptchaResponse {
|
||||
Id string `json:"id"`
|
||||
Image string `json:"image"`
|
||||
Type string `json:"type"`
|
||||
BlockImage string `json:"block_image,omitempty"`
|
||||
}
|
||||
SliderVerifyCaptchaRequest {
|
||||
Id string `json:"id" validate:"required"`
|
||||
X int `json:"x" validate:"required"`
|
||||
Y int `json:"y" validate:"required"`
|
||||
Trail string `json:"trail"`
|
||||
}
|
||||
SliderVerifyCaptchaResponse {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
)
|
||||
|
||||
@@ -191,20 +208,24 @@ service ppanel {
|
||||
get /check/telephone (TelephoneCheckUserRequest) returns (TelephoneCheckUserResponse)
|
||||
|
||||
@doc "User Telephone register"
|
||||
@handler TelephoneUserRegister
|
||||
@handler TelephoneRegister
|
||||
post /register/telephone (TelephoneRegisterRequest) returns (LoginResponse)
|
||||
|
||||
@doc "Reset password"
|
||||
@doc "Reset password by telephone"
|
||||
@handler TelephoneResetPassword
|
||||
post /reset/telephone (TelephoneResetPasswordRequest) returns (LoginResponse)
|
||||
|
||||
@doc "Device Login"
|
||||
@handler DeviceLogin
|
||||
post /login/device (DeviceLoginRequest) returns (LoginResponse)
|
||||
|
||||
@doc "Generate captcha"
|
||||
@handler GenerateCaptcha
|
||||
post /captcha/generate returns (GenerateCaptchaResponse)
|
||||
|
||||
@doc "Device Login"
|
||||
@handler DeviceLogin
|
||||
post /login/device (DeviceLoginRequest) returns (LoginResponse)
|
||||
@doc "Verify slider captcha"
|
||||
@handler SliderVerifyCaptcha
|
||||
post /captcha/slider/verify (SliderVerifyCaptchaRequest) returns (SliderVerifyCaptchaResponse)
|
||||
}
|
||||
|
||||
@server (
|
||||
@@ -224,6 +245,10 @@ service ppanel {
|
||||
@doc "Generate captcha"
|
||||
@handler AdminGenerateCaptcha
|
||||
post /captcha/generate returns (GenerateCaptchaResponse)
|
||||
|
||||
@doc "Verify slider captcha"
|
||||
@handler AdminSliderVerifyCaptcha
|
||||
post /captcha/slider/verify (SliderVerifyCaptchaRequest) returns (SliderVerifyCaptchaResponse)
|
||||
}
|
||||
|
||||
@server (
|
||||
@@ -243,4 +268,3 @@ service ppanel {
|
||||
@handler AppleLoginCallback
|
||||
post /callback/apple (AppleLoginCallbackRequest)
|
||||
}
|
||||
|
||||
|
||||
@@ -96,6 +96,48 @@ type (
|
||||
Message string `json:"message,omitempty"`
|
||||
Timestamp int64 `json:"timestamp,omitempty"`
|
||||
}
|
||||
GetDownloadLinkRequest {
|
||||
InviteCode string `form:"invite_code,optional"`
|
||||
Platform string `form:"platform" validate:"required,oneof=windows mac ios android"`
|
||||
}
|
||||
GetDownloadLinkResponse {
|
||||
Url string `json:"url"`
|
||||
}
|
||||
ContactRequest {
|
||||
Name string `json:"name" validate:"required,max=100"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
OtherContact string `json:"other_contact" validate:"max=200"`
|
||||
Notes string `json:"notes" validate:"max=2000"`
|
||||
}
|
||||
ReportLogMessageRequest {
|
||||
Platform string `json:"platform" validate:"required,max=32"`
|
||||
AppVersion string `json:"app_version" validate:"required,max=64"`
|
||||
OsName string `json:"os_name" validate:"max=64"`
|
||||
OsVersion string `json:"os_version" validate:"max=64"`
|
||||
DeviceId string `json:"device_id" validate:"required,max=255"`
|
||||
UserId int64 `json:"user_id"`
|
||||
SessionId string `json:"session_id" validate:"max=255"`
|
||||
Level uint8 `json:"level"`
|
||||
ErrorCode string `json:"error_code" validate:"max=128"`
|
||||
Message string `json:"message" validate:"required,max=65535"`
|
||||
Stack string `json:"stack" validate:"max=1048576"`
|
||||
Context interface{} `json:"context"`
|
||||
OccurredAt int64 `json:"occurred_at"`
|
||||
}
|
||||
ReportLogMessageResponse {
|
||||
Id int64 `json:"id"`
|
||||
}
|
||||
LegacyCheckVerificationCodeRequest {
|
||||
Method string `json:"method" form:"method" validate:"omitempty,oneof=email mobile"`
|
||||
Account string `json:"account" form:"account"`
|
||||
Email string `json:"email" form:"email"`
|
||||
Code string `json:"code" form:"code" validate:"required"`
|
||||
Type uint8 `json:"type" form:"type" validate:"required"`
|
||||
}
|
||||
LegacyCheckVerificationCodeResponse {
|
||||
Status bool `json:"status"`
|
||||
Exist bool `json:"exist"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
@@ -143,5 +185,25 @@ service ppanel {
|
||||
@doc "Heartbeat"
|
||||
@handler Heartbeat
|
||||
get /heartbeat returns (HeartbeatResponse)
|
||||
|
||||
@doc "Get Download Link"
|
||||
@handler GetDownloadLink
|
||||
get /client/download (GetDownloadLinkRequest) returns (GetDownloadLinkResponse)
|
||||
|
||||
@doc "Submit Contact"
|
||||
@handler SubmitContact
|
||||
post /contact (ContactRequest)
|
||||
|
||||
@doc "Report log message"
|
||||
@handler ReportLogMessage
|
||||
post /log/report (ReportLogMessageRequest) returns (ReportLogMessageResponse)
|
||||
|
||||
@doc "Check verification code (legacy v1)"
|
||||
@handler CheckCodeLegacy
|
||||
post /check_code (LegacyCheckVerificationCodeRequest) returns (LegacyCheckVerificationCodeResponse)
|
||||
|
||||
@doc "Check verification code (legacy v2, consume code)"
|
||||
@handler CheckCodeLegacyV2
|
||||
post /check_code/v2 (LegacyCheckVerificationCodeRequest) returns (LegacyCheckVerificationCodeResponse)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
syntax = "v1"
|
||||
|
||||
info (
|
||||
title: "File API"
|
||||
desc: "API for ppanel file upload"
|
||||
author: "Codex"
|
||||
email: "codex@openai.com"
|
||||
version: "0.0.1"
|
||||
)
|
||||
|
||||
import "../types.api"
|
||||
|
||||
type (
|
||||
FileUploadRequest {
|
||||
BizType string `form:"biz_type" validate:"required"`
|
||||
}
|
||||
|
||||
FileUploadResponse {
|
||||
FileId string `json:"file_id"`
|
||||
FileName string `json:"file_name"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
Size int64 `json:"size"`
|
||||
ContentType string `json:"content_type"`
|
||||
Etag string `json:"etag"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
FileUploadInitRequest {
|
||||
BizType string `json:"biz_type" validate:"required"`
|
||||
FileName string `json:"file_name" validate:"required"`
|
||||
ContentType string `json:"content_type" validate:"required"`
|
||||
Size int64 `json:"size" validate:"required"`
|
||||
Sha256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
FileUploadInitResponse {
|
||||
FileId string `json:"file_id"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
UploadURL string `json:"upload_url"`
|
||||
Method string `json:"method"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
ExpiredAt int64 `json:"expired_at"`
|
||||
}
|
||||
|
||||
FileUploadCompleteRequest {
|
||||
FileId string `json:"file_id" validate:"required"`
|
||||
}
|
||||
|
||||
FileUploadCompleteResponse {
|
||||
FileId string `json:"file_id"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
Size int64 `json:"size"`
|
||||
ContentType string `json:"content_type"`
|
||||
Etag string `json:"etag"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
prefix: v1/public/file
|
||||
group: public/file
|
||||
middleware: AuthMiddleware,DeviceMiddleware
|
||||
)
|
||||
service ppanel {
|
||||
@doc "Upload file to RustFS"
|
||||
@handler FileUpload
|
||||
post /upload (FileUploadRequest) returns (FileUploadResponse)
|
||||
|
||||
@doc "Init file upload"
|
||||
@handler FileUploadInit
|
||||
post /upload/init (FileUploadInitRequest) returns (FileUploadInitResponse)
|
||||
|
||||
@doc "Complete file upload"
|
||||
@handler FileUploadComplete
|
||||
post /upload/complete (FileUploadCompleteRequest) returns (FileUploadCompleteResponse)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
syntax = "v1"
|
||||
|
||||
info (
|
||||
title: "recovery API"
|
||||
desc: "API for order recovery"
|
||||
author: "Tension"
|
||||
email: "tension@ppanel.com"
|
||||
version: "0.0.1"
|
||||
)
|
||||
|
||||
import "../types.api"
|
||||
|
||||
type (
|
||||
RecoverySendCodeRequest {
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
}
|
||||
RecoverOrderRequest {
|
||||
OrderNo string `json:"order_no" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Code string `json:"code" validate:"required"`
|
||||
}
|
||||
RecoverOrderResponse {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
prefix: v1/public/recovery
|
||||
group: public/recovery
|
||||
middleware: DeviceMiddleware
|
||||
)
|
||||
service ppanel {
|
||||
@doc "Send recovery verification code"
|
||||
@handler SendCode
|
||||
post /send_code (RecoverySendCodeRequest) returns (SendCodeResponse)
|
||||
|
||||
@doc "Recover order subscription"
|
||||
@handler RecoverOrder
|
||||
post /order (RecoverOrderRequest) returns (RecoverOrderResponse)
|
||||
}
|
||||
@@ -71,5 +71,9 @@ service ppanel {
|
||||
@doc "Get user subscribe node info"
|
||||
@handler QueryUserSubscribeNodeList
|
||||
get /node/list returns (QueryUserSubscribeNodeListResponse)
|
||||
|
||||
@doc "Get subscribe group list"
|
||||
@handler QuerySubscribeGroupList
|
||||
get /group/list returns (QuerySubscribeGroupListResponse)
|
||||
}
|
||||
|
||||
|
||||
+21
-1
@@ -220,6 +220,22 @@ type (
|
||||
FriendlyCount int64 `json:"friendly_count"`
|
||||
HistoryCount int64 `json:"history_count"`
|
||||
}
|
||||
GetUserTrafficStatsRequest {
|
||||
UserSubscribeId string `form:"user_subscribe_id" validate:"required"`
|
||||
Days int `form:"days" validate:"required,oneof=7 30"`
|
||||
}
|
||||
DailyTrafficStats {
|
||||
Date string `json:"date"`
|
||||
Upload int64 `json:"upload"`
|
||||
Download int64 `json:"download"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
GetUserTrafficStatsResponse {
|
||||
List []DailyTrafficStats `json:"list"`
|
||||
TotalUpload int64 `json:"total_upload"`
|
||||
TotalDownload int64 `json:"total_download"`
|
||||
TotalTraffic int64 `json:"total_traffic"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
@@ -374,11 +390,15 @@ service ppanel {
|
||||
|
||||
@doc "Get Subscribe Status"
|
||||
@handler GetSubscribeStatus
|
||||
get /subscribe_status (GetSubscribeStatusRequest) returns (GetSubscribeStatusResponse)
|
||||
post /subscribe_status (GetSubscribeStatusRequest) returns (GetSubscribeStatusResponse)
|
||||
|
||||
@doc "Get User Invite Stats"
|
||||
@handler GetUserInviteStats
|
||||
get /invite_stats (GetUserInviteStatsRequest) returns (GetUserInviteStatsResponse)
|
||||
|
||||
@doc "Get User Traffic Statistics"
|
||||
@handler GetUserTrafficStats
|
||||
get /traffic_stats (GetUserTrafficStatsRequest) returns (GetUserTrafficStatsResponse)
|
||||
}
|
||||
|
||||
@server (
|
||||
|
||||
+5
-1
@@ -27,6 +27,7 @@ type (
|
||||
EnableLoginNotify bool `json:"enable_login_notify"`
|
||||
EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
|
||||
EnableTradeNotify bool `json:"enable_trade_notify"`
|
||||
UseStatus bool `json:"use_status"` // Whether to show the "bind email to get free trial" prompt
|
||||
AuthMethods []UserAuthMethod `json:"auth_methods"`
|
||||
UserDevices []UserDevice `json:"user_devices"`
|
||||
Rules []string `json:"rules"`
|
||||
@@ -227,6 +228,7 @@ type (
|
||||
SubscribeDiscount {
|
||||
Quantity int64 `json:"quantity"`
|
||||
Discount float64 `json:"discount"`
|
||||
MapApple string `json:"map_apple"`
|
||||
}
|
||||
TrafficLimit {
|
||||
StatType string `json:"stat_type"`
|
||||
@@ -567,6 +569,7 @@ type (
|
||||
FamilyId int64 `json:"family_id"`
|
||||
OwnerUserId int64 `json:"owner_user_id"`
|
||||
OwnerIdentifier string `json:"owner_identifier"`
|
||||
OwnerAuthType string `json:"owner_auth_type"`
|
||||
Status string `json:"status"`
|
||||
ActiveMemberCount int64 `json:"active_member_count"`
|
||||
MaxMembers int64 `json:"max_members"`
|
||||
@@ -576,7 +579,9 @@ type (
|
||||
FamilyMemberItem {
|
||||
UserId int64 `json:"user_id"`
|
||||
Identifier string `json:"identifier"`
|
||||
AuthType string `json:"auth_type"`
|
||||
DeviceNo string `json:"device_no"`
|
||||
DeviceType string `json:"device_type"`
|
||||
Role uint8 `json:"role"`
|
||||
RoleName string `json:"role_name"`
|
||||
Status uint8 `json:"status"`
|
||||
@@ -1000,4 +1005,3 @@ type (
|
||||
ConfigSnapshot map[string]interface{} `json:"config_snapshot,omitempty"`
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,796 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
logmodel "github.com/perfect-panel/server/internal/model/log"
|
||||
ordermodel "github.com/perfect-panel/server/internal/model/order"
|
||||
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/pkg/conf"
|
||||
"github.com/perfect-panel/server/pkg/orm"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/spf13/cobra"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func init() {
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroAgentIdStr, "agent-id", "", "目标代理用户 ID,或 * 表示所有 referral_percentage>0 的代理(必填)")
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroPoolStart, "pool-start", "2025-05-04", "自然流量订单起始时间,格式 YYYY-MM-DD 或 'YYYY-MM-DD HH:MM:SS'(默认 2025-05-04)")
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroPoolEnd, "pool-end", "", "自然流量订单截止时间,格式 YYYY-MM-DD 或 'YYYY-MM-DD HH:MM:SS'(默认今天)")
|
||||
retroactiveReferralCmd.Flags().IntVar(&retroPercentage, "percentage", 120, "补偿百分比,例如 120 表示 120%(默认 120)")
|
||||
retroactiveReferralCmd.Flags().IntVar(&retroForceCommissionPct, "force-commission-pct", 50, "强制指定发佣比例(0=使用数据库/配置,非0时覆盖代理设置,默认 50%)")
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroOutput, "output", "retro_result.txt", "结果输出到指定 txt 文件(默认 retro_result.txt)")
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroConfigPath, "config", "etc/ppanel.yaml", "配置文件路径")
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroAgentCreatedAfter, "agent-created-after", "", "仅处理在此日期之后注册的代理,格式 YYYY-MM-DD(留空=不限)")
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroLossStart, "loss-start", "2026-05-06", "数据丢失起始时间,丢失时长=现在-此时间(默认 2026-05-06)")
|
||||
retroactiveReferralCmd.Flags().StringVar(&retroOrderStart, "order-start", "2026-05-01", "池内用户至少有一笔 updated_at >= 此时间的订单才入池(默认 2026-05-01)")
|
||||
retroactiveReferralCmd.Flags().BoolVar(&retroDryRun, "dry-run", false, "仅预览,不执行写入")
|
||||
rootCmd.AddCommand(retroactiveReferralCmd)
|
||||
}
|
||||
|
||||
var (
|
||||
retroAgentIdStr string
|
||||
retroAgentCreatedAfter string
|
||||
retroLossStart string
|
||||
retroOrderStart string
|
||||
retroPoolStart string
|
||||
retroPoolEnd string
|
||||
retroPercentage int
|
||||
retroForceCommissionPct int
|
||||
retroConfigPath string
|
||||
retroDryRun bool
|
||||
retroOutput string
|
||||
)
|
||||
|
||||
var retroactiveReferralCmd = &cobra.Command{
|
||||
Use: "retro-referral",
|
||||
Short: "补单:按代理历史日均佣金补偿指定比例的用户",
|
||||
Long: `统计代理从首次邀请到 pool-end 的日均佣金,
|
||||
按指定百分比计算目标补偿金额,
|
||||
从 pool-start 到 pool-end 的自然流量用户中随机抽取匹配的用户数量挂载到该代理。
|
||||
--agent-id 支持单个 ID 或 *(处理所有 referral_percentage>0 的代理)。`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if retroAgentIdStr == "" {
|
||||
return fmt.Errorf("--agent-id 必填(单个 ID 或 *)")
|
||||
}
|
||||
return runRetroactiveReferral()
|
||||
},
|
||||
}
|
||||
|
||||
// commissionRule holds resolved commission settings for an agent.
|
||||
type commissionRule struct {
|
||||
Percentage uint8
|
||||
OnlyFirstPurchase bool
|
||||
}
|
||||
|
||||
// candidateUser holds a pool user plus their pre-calculated qualifying orders.
|
||||
type candidateUser struct {
|
||||
Id int64
|
||||
CreatedAt time.Time
|
||||
Identifier string
|
||||
Orders []ordermodel.Order
|
||||
CommissionTotal int64
|
||||
}
|
||||
|
||||
// agentPlan holds one agent's computed allocation plan (preview phase output).
|
||||
type agentPlan struct {
|
||||
Agent *usermodel.User
|
||||
Rule commissionRule
|
||||
Selected []candidateUser
|
||||
TargetAmt float64 // in cents
|
||||
PreviewCommission int64
|
||||
}
|
||||
|
||||
func runRetroactiveReferral() error {
|
||||
// ── 0. 初始化输出(终端 + 可选文件)─────────────────────────
|
||||
var w io.Writer = os.Stdout
|
||||
if retroOutput != "" {
|
||||
f, err := os.Create(retroOutput)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建输出文件失败: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
w = io.MultiWriter(os.Stdout, f)
|
||||
fmt.Printf("结果将同步写入: %s\n\n", retroOutput)
|
||||
}
|
||||
|
||||
// ── 1. 加载配置 ──────────────────────────────────────────────
|
||||
var c config.Config
|
||||
conf.MustLoad(retroConfigPath, &c)
|
||||
|
||||
// ── 2. 初始化 DB + Redis ──────────────────────────────────────
|
||||
db, err := orm.ConnectMysql(orm.Mysql{Config: c.MySQL})
|
||||
if err != nil {
|
||||
return fmt.Errorf("连接数据库失败: %w", err)
|
||||
}
|
||||
rds := redis.NewClient(&redis.Options{
|
||||
Addr: c.Redis.Host,
|
||||
Password: c.Redis.Pass,
|
||||
DB: c.Redis.DB,
|
||||
})
|
||||
ctx := context.Background()
|
||||
if err = rds.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("连接 Redis 失败: %w", err)
|
||||
}
|
||||
um := usermodel.NewModel(db, rds)
|
||||
|
||||
// ── 3. 解析时间参数 ───────────────────────────────────────────
|
||||
poolStart, err := parseFlexibleTime(retroPoolStart)
|
||||
if err != nil {
|
||||
return fmt.Errorf("--pool-start 格式错误: %w", err)
|
||||
}
|
||||
poolEnd := time.Now()
|
||||
if retroPoolEnd != "" {
|
||||
poolEnd, err = parseFlexibleTime(retroPoolEnd)
|
||||
if err != nil {
|
||||
return fmt.Errorf("--pool-end 格式错误: %w", err)
|
||||
}
|
||||
}
|
||||
if !poolEnd.After(poolStart) {
|
||||
return fmt.Errorf("--pool-end 必须晚于 --pool-start")
|
||||
}
|
||||
|
||||
// ── 4. 确定代理列表 ───────────────────────────────────────────
|
||||
var agents []*usermodel.User
|
||||
if retroAgentIdStr == "*" {
|
||||
agents, err = queryAllActiveAgents(ctx, db, retroAgentCreatedAfter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询代理列表失败: %w", err)
|
||||
}
|
||||
if len(agents) == 0 {
|
||||
return fmt.Errorf("没有找到任何 referral_percentage>0 的代理用户")
|
||||
}
|
||||
fmt.Fprintf(w, "模式:全量代理,共找到 %d 个代理(referral_percentage>0)\n\n", len(agents))
|
||||
} else {
|
||||
agentID, parseErr := strconv.ParseInt(retroAgentIdStr, 10, 64)
|
||||
if parseErr != nil || agentID <= 0 {
|
||||
return fmt.Errorf("--agent-id 必须是正整数或 *")
|
||||
}
|
||||
agent, findErr := um.FindOne(ctx, agentID)
|
||||
if findErr != nil {
|
||||
return fmt.Errorf("查询代理用户失败: %w", findErr)
|
||||
}
|
||||
if agent.DeletedAt.Valid {
|
||||
return fmt.Errorf("代理用户 %d 已被删除", agentID)
|
||||
}
|
||||
agents = []*usermodel.User{agent}
|
||||
}
|
||||
|
||||
if retroForceCommissionPct > 0 {
|
||||
fmt.Fprintf(w, "⚠️ 强制覆盖所有代理佣金比例为 %d%%\n\n", retroForceCommissionPct)
|
||||
}
|
||||
|
||||
// ── 5. 查询自然流量用户池(所有代理共用同一个池)────────────
|
||||
// 先用 50% 规则(或强制值)预加载池,以便预览;执行时每个代理用自身规则
|
||||
var orderStart time.Time
|
||||
if retroOrderStart != "" {
|
||||
orderStart, err = parseFlexibleTime(retroOrderStart)
|
||||
if err != nil {
|
||||
return fmt.Errorf("--order-start 格式错误: %w", err)
|
||||
}
|
||||
}
|
||||
previewRule := commissionRule{Percentage: uint8(retroForceCommissionPct), OnlyFirstPurchase: false}
|
||||
pool, err := queryNaturalTrafficPool(ctx, db, poolStart, poolEnd, orderStart, previewRule)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询自然流量用户池失败: %w", err)
|
||||
}
|
||||
orderStartDesc := ""
|
||||
if !orderStart.IsZero() {
|
||||
orderStartDesc = fmt.Sprintf(",订单 updated_at >= %s", orderStart.Format("2006-01-02"))
|
||||
}
|
||||
fmt.Fprintf(w, "自然流量用户池(%s ~ %s,referer_id=0,有已支付订单%s):共 %d 人\n\n",
|
||||
poolStart.Format("2006-01-02 15:04"), poolEnd.Format("2006-01-02 15:04"), orderStartDesc, len(pool))
|
||||
if len(pool) == 0 {
|
||||
return fmt.Errorf("自然流量用户池为空,无法补充")
|
||||
}
|
||||
|
||||
// ── 6. 逐代理生成分配计划(预览阶段)────────────────────────
|
||||
// 池按顺序分配:每个代理从剩余池中取用户,避免重复分配
|
||||
remainingPool := make([]candidateUser, len(pool))
|
||||
copy(remainingPool, pool)
|
||||
|
||||
plans := make([]agentPlan, 0, len(agents))
|
||||
for _, agent := range agents {
|
||||
plan, planErr := buildAgentPlan(w, ctx, db, c, agent, remainingPool, poolEnd)
|
||||
if planErr != nil {
|
||||
fmt.Fprintf(w, "⚠️ 代理 %d 跳过: %v\n\n", agent.Id, planErr)
|
||||
continue
|
||||
}
|
||||
// 从剩余池中移除已分配给该代理的用户
|
||||
assignedSet := make(map[int64]struct{}, len(plan.Selected))
|
||||
for _, u := range plan.Selected {
|
||||
assignedSet[u.Id] = struct{}{}
|
||||
}
|
||||
newRemaining := remainingPool[:0]
|
||||
for _, u := range remainingPool {
|
||||
if _, used := assignedSet[u.Id]; !used {
|
||||
newRemaining = append(newRemaining, u)
|
||||
}
|
||||
}
|
||||
remainingPool = newRemaining
|
||||
plans = append(plans, plan)
|
||||
}
|
||||
|
||||
if len(plans) == 0 {
|
||||
return fmt.Errorf("所有代理均无法生成分配计划")
|
||||
}
|
||||
|
||||
// ── 7. 汇总预览 ───────────────────────────────────────────────
|
||||
var grandTotalUsers int
|
||||
var grandTotalCommission int64
|
||||
var grandTargetAmt float64
|
||||
for _, p := range plans {
|
||||
grandTotalUsers += len(p.Selected)
|
||||
grandTotalCommission += p.PreviewCommission
|
||||
grandTargetAmt += p.TargetAmt
|
||||
}
|
||||
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||
fmt.Fprintf(w, "汇总:共 %d 个代理,补充 %d 个用户\n", len(plans), grandTotalUsers)
|
||||
fmt.Fprintf(w, " 预计追溯佣金总额: $%.2f(目标补偿金额: $%.2f)\n",
|
||||
float64(grandTotalCommission)/100, grandTargetAmt/100)
|
||||
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||
fmt.Fprintln(w)
|
||||
|
||||
if retroDryRun {
|
||||
fmt.Fprintln(w, "[dry-run] 预览完成,未执行任何写入。")
|
||||
return nil
|
||||
}
|
||||
|
||||
// ── 8. 执行前汇总打印 ─────────────────────────────────────────
|
||||
fmt.Fprintf(w, "\n┌─────────────────────────────────────────────┐\n")
|
||||
fmt.Fprintf(w, "│ 即将写入数据库 │\n")
|
||||
fmt.Fprintf(w, "│ 代理数量 : %-4d 个 │\n", len(plans))
|
||||
fmt.Fprintf(w, "│ 补充用户 : %-4d 人 │\n", grandTotalUsers)
|
||||
fmt.Fprintf(w, "│ 赠送金额 : $%-10.2f │\n", float64(grandTotalCommission)/100)
|
||||
fmt.Fprintf(w, "└─────────────────────────────────────────────┘\n\n")
|
||||
fmt.Printf("确认执行?(yes/no): ")
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
answer, _ := reader.ReadString('\n')
|
||||
answer = strings.TrimSpace(strings.ToLower(answer))
|
||||
if answer != "yes" && answer != "y" {
|
||||
fmt.Fprintln(w, "已取消。")
|
||||
return nil
|
||||
}
|
||||
|
||||
// ── 9. 逐代理执行 ─────────────────────────────────────────────
|
||||
var totalSuccess, totalFailed int
|
||||
var totalCreditedOrder, totalCreditedAmt int64
|
||||
|
||||
for _, plan := range plans {
|
||||
fmt.Fprintf(w, "\n── 执行代理 %d ──────────────────────────────────────────────\n", plan.Agent.Id)
|
||||
var sc, fc int
|
||||
var co, ca int64
|
||||
for _, eu := range plan.Selected {
|
||||
if eu.Id == plan.Agent.Id {
|
||||
fmt.Fprintf(w, "[SKIP] 用户 %d 与代理相同,跳过\n", eu.Id)
|
||||
fc++
|
||||
continue
|
||||
}
|
||||
credited, amount, execErr := processOneUser(ctx, db, um, plan.Agent.Id, eu.Id, plan.Rule, orderStart)
|
||||
if execErr != nil {
|
||||
fmt.Fprintf(w, "[FAIL] 用户 %d: %v\n", eu.Id, execErr)
|
||||
fc++
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(w, "[OK] 用户 %d → 代理 %d,发佣 %d 单,金额 $%.2f\n",
|
||||
eu.Id, plan.Agent.Id, credited, float64(amount)/100)
|
||||
sc++
|
||||
co += credited
|
||||
ca += amount
|
||||
}
|
||||
// 直接删除代理的缓存 key,下次请求时从 DB 重新加载(避免 FindOne 读到旧缓存再写回)
|
||||
if sc > 0 {
|
||||
cacheKey := fmt.Sprintf("cache:user:id:%d", plan.Agent.Id)
|
||||
_ = rds.Del(ctx, cacheKey).Err()
|
||||
}
|
||||
fmt.Fprintf(w, " 代理 %d 小计:成功 %d 人,失败 %d 人,佣金 $%.2f\n", plan.Agent.Id, sc, fc, float64(ca)/100)
|
||||
totalSuccess += sc
|
||||
totalFailed += fc
|
||||
totalCreditedOrder += co
|
||||
totalCreditedAmt += ca
|
||||
}
|
||||
|
||||
// ── 10. 全局汇总 ──────────────────────────────────────────────
|
||||
fmt.Fprintf(w, "\n══════════════════════════════════════════════\n")
|
||||
fmt.Fprintf(w, " 成功挂载 : %d 人\n", totalSuccess)
|
||||
fmt.Fprintf(w, " 失败/跳过 : %d 人\n", totalFailed)
|
||||
fmt.Fprintf(w, " 追溯佣金 : %d 单,总额 $%.2f\n", totalCreditedOrder, float64(totalCreditedAmt)/100)
|
||||
fmt.Fprintf(w, "══════════════════════════════════════════════\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildAgentPlan 计算一个代理的补单预览,同时打印预览内容,返回分配计划。
|
||||
func buildAgentPlan(w io.Writer, ctx context.Context, db *gorm.DB, c config.Config,
|
||||
agent *usermodel.User, pool []candidateUser, poolEnd time.Time) (agentPlan, error) {
|
||||
|
||||
rule := resolveCommissionRule(agent, c)
|
||||
if retroForceCommissionPct > 0 {
|
||||
rule.Percentage = uint8(retroForceCommissionPct)
|
||||
}
|
||||
// 补单场景:不区分新购/续费,所有已支付订单均参与佣金计算
|
||||
rule.OnlyFirstPurchase = false
|
||||
|
||||
firstReferralTime, lastReferralTime, agentCreatedAt, totalReferred, totalOrders, totalCommission, err :=
|
||||
queryAgentStats(ctx, db, agent.Id, poolEnd)
|
||||
if err != nil {
|
||||
return agentPlan{}, fmt.Errorf("查询历史数据失败: %w", err)
|
||||
}
|
||||
if totalReferred == 0 {
|
||||
return agentPlan{}, fmt.Errorf("在 %s 之前没有任何邀请记录", poolEnd.Format("2006-01-02"))
|
||||
}
|
||||
|
||||
lossStartTime, err := parseFlexibleTime(retroLossStart)
|
||||
if err != nil {
|
||||
return agentPlan{}, fmt.Errorf("--loss-start 格式错误: %w", err)
|
||||
}
|
||||
lossHours := time.Now().Sub(lossStartTime).Hours()
|
||||
|
||||
statsDays := lastReferralTime.Sub(firstReferralTime).Hours() / 24
|
||||
if statsDays < 1 {
|
||||
statsDays = 1
|
||||
}
|
||||
dailyAvgOrders := float64(totalOrders) / statsDays
|
||||
avgOrdersPerUser := float64(totalOrders) / float64(totalReferred)
|
||||
if avgOrdersPerUser < 1 {
|
||||
avgOrdersPerUser = 1
|
||||
}
|
||||
dailyAvgCommission := float64(totalCommission) / statsDays
|
||||
|
||||
// 用用户池自身的平均佣金估算人数(避免历史费率与当前50%费率不匹配导致超发)
|
||||
var poolAvgCommissionPerUser float64
|
||||
if len(pool) > 0 {
|
||||
var poolCommTotal int64
|
||||
for _, u := range pool {
|
||||
poolCommTotal += u.CommissionTotal
|
||||
}
|
||||
poolAvgCommissionPerUser = float64(poolCommTotal) / float64(len(pool))
|
||||
}
|
||||
if poolAvgCommissionPerUser < 1 {
|
||||
poolAvgCommissionPerUser = 1
|
||||
}
|
||||
|
||||
estimatedLostCommission := dailyAvgCommission * (lossHours / 24)
|
||||
targetCommission := estimatedLostCommission * (float64(retroPercentage) / 100)
|
||||
extraCount := int(targetCommission/poolAvgCommissionPerUser + 0.5)
|
||||
if extraCount < 1 {
|
||||
extraCount = 1
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "\n═══════════════════════════════════════════════════════════\n")
|
||||
fmt.Fprintf(w, " 代理 ID : %d(注册于 %s)\n", agent.Id, agentCreatedAt.Format("2006-01-02 15:04:05"))
|
||||
fmt.Fprintf(w, " 统计起点 : %s(首次邀请时间)\n", firstReferralTime.Format("2006-01-02 15:04:05"))
|
||||
fmt.Fprintf(w, " 统计截止 : %s(最后邀请时间)\n", lastReferralTime.Format("2006-01-02 15:04:05"))
|
||||
fmt.Fprintf(w, " 统计天数 : %.2f 天\n", statsDays)
|
||||
fmt.Fprintf(w, " 历史邀请总人数 : %d 人\n", totalReferred)
|
||||
fmt.Fprintf(w, " 下线总订单数 : %d 单(所有下线,不限时间)\n", totalOrders)
|
||||
fmt.Fprintf(w, " 日均订单 : %.4f 单/天\n", dailyAvgOrders)
|
||||
fmt.Fprintf(w, " 每用户平均订单 : %.4f 单\n", avgOrdersPerUser)
|
||||
fmt.Fprintf(w, " 历史佣金总额 : $%.2f\n", float64(totalCommission)/100)
|
||||
fmt.Fprintf(w, " 日均佣金 : $%.4f\n", dailyAvgCommission/100)
|
||||
fmt.Fprintf(w, " 池内用户均佣金 : $%.4f\n", poolAvgCommissionPerUser/100)
|
||||
fmt.Fprintf(w, " 佣金规则 : %d%% 仅首单=%v\n", rule.Percentage, rule.OnlyFirstPurchase)
|
||||
fmt.Fprintf(w, "───────────────────────────────────────────────────────────\n")
|
||||
fmt.Fprintf(w, " 丢失时长 : %.2f 小时(%s → 现在)\n",
|
||||
lossHours, lossStartTime.Format("2006-01-02 15:04:05"))
|
||||
fmt.Fprintf(w, " 预估丢失佣金 : $%.4f($%.4f × %.2f/24)\n",
|
||||
estimatedLostCommission/100, dailyAvgCommission/100, lossHours)
|
||||
fmt.Fprintf(w, " 目标补偿金额 : $%.4f(× %d%%)\n",
|
||||
targetCommission/100, retroPercentage)
|
||||
fmt.Fprintf(w, " 需补充人数 : %d 人($%.4f ÷ $%.4f)\n",
|
||||
extraCount, targetCommission/100, poolAvgCommissionPerUser/100)
|
||||
fmt.Fprintf(w, "═══════════════════════════════════════════════════════════\n\n")
|
||||
|
||||
// 重新按当前代理规则计算池内用户佣金(pool 由调用方传入,已是当前规则计算好的)
|
||||
if len(pool) == 0 {
|
||||
return agentPlan{}, fmt.Errorf("剩余用户池为空")
|
||||
}
|
||||
if len(pool) < extraCount {
|
||||
fmt.Fprintf(w, "⚠️ 剩余用户池只有 %d 人,少于需要的 %d 人,将全部分配\n\n", len(pool), extraCount)
|
||||
extraCount = len(pool)
|
||||
}
|
||||
|
||||
selected := randomSampleCandidates(pool, extraCount)
|
||||
|
||||
// 兜底追加:确保佣金合计 >= 目标
|
||||
{
|
||||
selectedSet := make(map[int64]struct{}, len(selected))
|
||||
var selectedCommTotal int64
|
||||
for _, u := range selected {
|
||||
selectedSet[u.Id] = struct{}{}
|
||||
selectedCommTotal += u.CommissionTotal
|
||||
}
|
||||
if selectedCommTotal < int64(targetCommission) {
|
||||
remaining := make([]candidateUser, 0, len(pool)-len(selected))
|
||||
for _, u := range pool {
|
||||
if _, used := selectedSet[u.Id]; !used {
|
||||
remaining = append(remaining, u)
|
||||
}
|
||||
}
|
||||
// 按佣金从小到大排序,追加时精准补足,减少超发
|
||||
sort.Slice(remaining, func(i, j int) bool {
|
||||
return remaining[i].CommissionTotal < remaining[j].CommissionTotal
|
||||
})
|
||||
for _, u := range remaining {
|
||||
if selectedCommTotal >= int64(targetCommission) {
|
||||
break
|
||||
}
|
||||
selected = append(selected, u)
|
||||
selectedCommTotal += u.CommissionTotal
|
||||
}
|
||||
if selectedCommTotal < int64(targetCommission) {
|
||||
fmt.Fprintf(w, "⚠️ 用户池佣金不足,已抽取全部可用用户(实际 $%.2f < 目标 $%.2f)\n\n",
|
||||
float64(selectedCommTotal)/100, targetCommission/100)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 打印选中用户明细
|
||||
var previewTotalCommission int64
|
||||
fmt.Fprintf(w, "随机抽取 %d 个用户(含待追溯佣金订单):\n", len(selected))
|
||||
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||
for i, u := range selected {
|
||||
fmt.Fprintf(w, "[%d] 用户 %-10d 注册: %s %s\n",
|
||||
i+1, u.Id, u.CreatedAt.Format("2006-01-02 15:04:05"), u.Identifier)
|
||||
if len(u.Orders) == 0 {
|
||||
fmt.Fprintln(w, " (无符合条件的订单)")
|
||||
} else {
|
||||
fmt.Fprintf(w, " %-38s %10s %8s %10s %s\n", "订单号", "金额", "手续费", "佣金", "类型")
|
||||
fmt.Fprintf(w, " %s\n", strings.Repeat("-", 72))
|
||||
for _, od := range u.Orders {
|
||||
commAmt := calcCommissionAmount(od.Amount, od.FeeAmount, rule.Percentage)
|
||||
orderType := "首购"
|
||||
if od.Type == 2 {
|
||||
orderType = "续费"
|
||||
}
|
||||
fmt.Fprintf(w, " %-38s $%8.2f $%6.2f $%8.2f %s\n",
|
||||
od.OrderNo,
|
||||
float64(od.Amount)/100,
|
||||
float64(od.FeeAmount)/100,
|
||||
float64(commAmt)/100,
|
||||
orderType)
|
||||
}
|
||||
fmt.Fprintf(w, " 本用户追溯佣金合计: $%.2f\n", float64(u.CommissionTotal)/100)
|
||||
}
|
||||
previewTotalCommission += u.CommissionTotal
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||
fmt.Fprintf(w, "预计追溯佣金总额: $%.2f(目标补偿金额: $%.2f)\n\n",
|
||||
float64(previewTotalCommission)/100, targetCommission/100)
|
||||
|
||||
return agentPlan{
|
||||
Agent: agent,
|
||||
Rule: rule,
|
||||
Selected: selected,
|
||||
TargetAmt: targetCommission,
|
||||
PreviewCommission: previewTotalCommission,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// queryAllActiveAgents returns all agents with referral_percentage > 0, optionally filtered by created_after.
|
||||
func queryAllActiveAgents(ctx context.Context, db *gorm.DB, createdAfter string) ([]*usermodel.User, error) {
|
||||
q := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||
Where("referral_percentage > 0 AND deleted_at IS NULL")
|
||||
if createdAfter != "" {
|
||||
t, err := parseFlexibleTime(createdAfter)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("--agent-created-after 格式错误: %w", err)
|
||||
}
|
||||
q = q.Where("created_at >= ?", t)
|
||||
}
|
||||
var agents []*usermodel.User
|
||||
if err := q.Order("id ASC").Find(&agents).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return agents, nil
|
||||
}
|
||||
|
||||
// parseFlexibleTime parses "YYYY-MM-DD HH:MM:SS" or "YYYY-MM-DD".
|
||||
func parseFlexibleTime(s string) (time.Time, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if t, err := time.ParseInLocation("2006-01-02 15:04:05", s, time.Local); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
return time.ParseInLocation("2006-01-02", s, time.Local)
|
||||
}
|
||||
|
||||
// queryAgentStats returns (firstReferralTime, lastReferralTime, agentCreatedAt, totalReferred, totalOrders, totalCommission, error).
|
||||
func queryAgentStats(ctx context.Context, db *gorm.DB, agentID int64, endTime time.Time) (time.Time, time.Time, time.Time, int64, int64, int64, error) {
|
||||
var agent usermodel.User
|
||||
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||
Where("id = ?", agentID).
|
||||
First(&agent).Error; err != nil {
|
||||
return time.Time{}, time.Time{}, time.Time{}, 0, 0, 0, err
|
||||
}
|
||||
agentCreatedAt := agent.CreatedAt
|
||||
|
||||
var firstUser usermodel.User
|
||||
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
|
||||
agentID, agentCreatedAt, endTime).
|
||||
Order("created_at ASC").
|
||||
First(&firstUser).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, nil
|
||||
}
|
||||
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||
}
|
||||
|
||||
var lastUser usermodel.User
|
||||
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
|
||||
agentID, agentCreatedAt, endTime).
|
||||
Order("created_at DESC").
|
||||
First(&lastUser).Error; err != nil {
|
||||
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||
}
|
||||
|
||||
var totalReferred int64
|
||||
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
|
||||
agentID, agentCreatedAt, endTime).
|
||||
Count(&totalReferred).Error; err != nil {
|
||||
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||
}
|
||||
|
||||
var totalOrders int64
|
||||
if err := db.WithContext(ctx).Model(&ordermodel.Order{}).
|
||||
Joins("JOIN user u ON u.id = `order`.user_id").
|
||||
Where("u.referer_id = ?", agentID).
|
||||
Where("`order`.status IN (2, 5)").
|
||||
Count(&totalOrders).Error; err != nil {
|
||||
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||
}
|
||||
|
||||
type commResult struct{ Total int64 }
|
||||
var result commResult
|
||||
err := db.WithContext(ctx).Raw(`
|
||||
SELECT COALESCE(SUM(
|
||||
CAST(JSON_UNQUOTE(JSON_EXTRACT(content, '$.amount')) AS SIGNED)
|
||||
), 0) AS total
|
||||
FROM system_logs
|
||||
WHERE type = 33
|
||||
AND object_id = ?
|
||||
AND created_at <= ?
|
||||
AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.type')) IN ('331', '332')
|
||||
`, agentID, endTime).Scan(&result).Error
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||
}
|
||||
|
||||
return firstUser.CreatedAt, lastUser.CreatedAt, agentCreatedAt, totalReferred, totalOrders, result.Total, nil
|
||||
}
|
||||
|
||||
// queryNaturalTrafficPool returns pool candidates with pre-loaded qualifying orders.
|
||||
// orderStart (可为零值):若非零,则只收录至少有一笔 updated_at >= orderStart 订单的用户,
|
||||
// 且只加载/统计 updated_at >= orderStart 的订单(确保分配后代理能在对应月份的销售报表中看到记录)。
|
||||
func queryNaturalTrafficPool(ctx context.Context, db *gorm.DB, start, end time.Time, orderStart time.Time, rule commissionRule) ([]candidateUser, error) {
|
||||
type userRow struct {
|
||||
Id int64
|
||||
CreatedAt time.Time
|
||||
AuthIdentifier string
|
||||
}
|
||||
var userRows []userRow
|
||||
q := db.WithContext(ctx).
|
||||
Table("user u").
|
||||
Select("u.id, u.created_at, COALESCE(am.auth_identifier, '') AS auth_identifier").
|
||||
Joins("JOIN `order` o ON o.user_id = u.id AND o.status IN (2, 5)").
|
||||
Joins("LEFT JOIN user_auth_methods am ON am.user_id = u.id AND am.auth_type = 'email'").
|
||||
Where("u.created_at >= ? AND u.created_at <= ?", start, end).
|
||||
Where("u.referer_id = 0").
|
||||
Where("u.deleted_at IS NULL")
|
||||
if !orderStart.IsZero() {
|
||||
// 只入池那些在 orderStart 之后有过订单的用户(保证代理销售报表里能看到)
|
||||
q = q.Where("o.updated_at >= ?", orderStart)
|
||||
}
|
||||
if err := q.Group("u.id, u.created_at, am.auth_identifier").
|
||||
Order("u.id ASC").
|
||||
Scan(&userRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(userRows) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
userIDs := make([]int64, len(userRows))
|
||||
for i, r := range userRows {
|
||||
userIDs[i] = r.Id
|
||||
}
|
||||
orderQuery := db.WithContext(ctx).Model(&ordermodel.Order{}).
|
||||
Where("user_id IN ? AND status IN (2, 5)", userIDs)
|
||||
if !orderStart.IsZero() {
|
||||
// 只加载 orderStart 之后的订单:保证佣金统计和销售记录对齐
|
||||
orderQuery = orderQuery.Where("updated_at >= ?", orderStart)
|
||||
}
|
||||
var allOrders []ordermodel.Order
|
||||
if err := orderQuery.Order("user_id ASC, created_at ASC").Find(&allOrders).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ordersByUser := make(map[int64][]ordermodel.Order, len(userRows))
|
||||
for _, od := range allOrders {
|
||||
ordersByUser[od.UserId] = append(ordersByUser[od.UserId], od)
|
||||
}
|
||||
|
||||
candidates := make([]candidateUser, 0, len(userRows))
|
||||
for _, r := range userRows {
|
||||
orders := ordersByUser[r.Id]
|
||||
var commTotal int64
|
||||
for i := range orders {
|
||||
if canCreditOrder(rule, &orders[i]) {
|
||||
commTotal += calcCommissionAmount(orders[i].Amount, orders[i].FeeAmount, rule.Percentage)
|
||||
}
|
||||
}
|
||||
candidates = append(candidates, candidateUser{
|
||||
Id: r.Id,
|
||||
CreatedAt: r.CreatedAt,
|
||||
Identifier: r.AuthIdentifier,
|
||||
Orders: orders,
|
||||
CommissionTotal: commTotal,
|
||||
})
|
||||
}
|
||||
return candidates, nil
|
||||
}
|
||||
|
||||
// randomSampleCandidates picks n random elements from pool without replacement.
|
||||
func randomSampleCandidates(pool []candidateUser, n int) []candidateUser {
|
||||
if n >= len(pool) {
|
||||
return append([]candidateUser{}, pool...)
|
||||
}
|
||||
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
indices := rng.Perm(len(pool))[:n]
|
||||
result := make([]candidateUser, n)
|
||||
for i, idx := range indices {
|
||||
result[i] = pool[idx]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// processOneUser assigns agentId as referer and retroactively credits commission for qualifying orders.
|
||||
func processOneUser(
|
||||
ctx context.Context,
|
||||
db *gorm.DB,
|
||||
um usermodel.Model,
|
||||
agentID, userID int64,
|
||||
rule commissionRule,
|
||||
orderStart time.Time,
|
||||
) (int64, int64, error) {
|
||||
var creditedOrders, creditedAmount int64
|
||||
|
||||
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var target usermodel.User
|
||||
if e := tx.Model(&usermodel.User{}).
|
||||
Where("id = ? AND referer_id = 0 AND deleted_at IS NULL", userID).
|
||||
First(&target).Error; e != nil {
|
||||
if e == gorm.ErrRecordNotFound {
|
||||
return fmt.Errorf("用户不存在或已有代理或已删除")
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
var orders []ordermodel.Order
|
||||
oq := tx.Model(&ordermodel.Order{}).
|
||||
Where("user_id = ? AND status IN (2, 5)", userID)
|
||||
if !orderStart.IsZero() {
|
||||
oq = oq.Where("updated_at >= ?", orderStart)
|
||||
}
|
||||
if e := oq.Order("created_at ASC, id ASC").Find(&orders).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if len(orders) == 0 {
|
||||
return fmt.Errorf("无合格订单")
|
||||
}
|
||||
|
||||
if e := tx.Model(&usermodel.User{}).
|
||||
Where("id = ? AND referer_id = 0 AND deleted_at IS NULL", userID).
|
||||
Updates(map[string]interface{}{
|
||||
"referer_id": agentID,
|
||||
"updated_at": time.Now(),
|
||||
}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
for i := range orders {
|
||||
od := &orders[i]
|
||||
if !canCreditOrder(rule, od) {
|
||||
continue
|
||||
}
|
||||
amount := calcCommissionAmount(od.Amount, od.FeeAmount, rule.Percentage)
|
||||
if amount <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var existCount int64
|
||||
if e := tx.Model(&logmodel.SystemLog{}).
|
||||
Where("type = ? AND object_id = ? AND content LIKE ?",
|
||||
logmodel.TypeCommission.Uint8(), agentID,
|
||||
fmt.Sprintf("%%\"%s\"%%", od.OrderNo),
|
||||
).Count(&existCount).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if existCount > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if e := tx.Model(&usermodel.User{}).
|
||||
Where("id = ? AND deleted_at IS NULL", agentID).
|
||||
UpdateColumn("commission", gorm.Expr("commission + ?", amount)).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
commType := logmodel.CommissionTypePurchase
|
||||
if od.Type == 2 {
|
||||
commType = logmodel.CommissionTypeRenewal
|
||||
}
|
||||
payload := &logmodel.Commission{
|
||||
Type: commType,
|
||||
Amount: amount,
|
||||
OrderNo: od.OrderNo,
|
||||
Timestamp: od.CreatedAt.UnixMilli(),
|
||||
}
|
||||
content, _ := payload.Marshal()
|
||||
if e := tx.Create(&logmodel.SystemLog{
|
||||
Type: logmodel.TypeCommission.Uint8(),
|
||||
Date: od.CreatedAt.Format("2006-01-02"),
|
||||
ObjectID: agentID,
|
||||
Content: string(content),
|
||||
CreatedAt: od.CreatedAt,
|
||||
}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
creditedOrders++
|
||||
creditedAmount += amount
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
if updated, e := um.FindOne(ctx, userID); e == nil {
|
||||
_ = um.UpdateUserCache(ctx, updated)
|
||||
}
|
||||
return creditedOrders, creditedAmount, nil
|
||||
}
|
||||
|
||||
func resolveCommissionRule(agent *usermodel.User, c config.Config) commissionRule {
|
||||
if agent.ReferralPercentage > 0 {
|
||||
onlyFirst := true
|
||||
if agent.OnlyFirstPurchase != nil {
|
||||
onlyFirst = *agent.OnlyFirstPurchase
|
||||
}
|
||||
return commissionRule{Percentage: agent.ReferralPercentage, OnlyFirstPurchase: onlyFirst}
|
||||
}
|
||||
return commissionRule{
|
||||
Percentage: uint8(c.Invite.ReferralPercentage),
|
||||
OnlyFirstPurchase: c.Invite.OnlyFirstPurchase,
|
||||
}
|
||||
}
|
||||
|
||||
func canCreditOrder(rule commissionRule, od *ordermodel.Order) bool {
|
||||
if rule.Percentage == 0 {
|
||||
return false
|
||||
}
|
||||
if rule.OnlyFirstPurchase && !od.IsNew {
|
||||
return false
|
||||
}
|
||||
return od.Status == 2 || od.Status == 5
|
||||
}
|
||||
|
||||
func calcCommissionAmount(amount, feeAmount int64, percentage uint8) int64 {
|
||||
base := amount - feeAmount
|
||||
if base <= 0 || percentage == 0 {
|
||||
return 0
|
||||
}
|
||||
return int64(float64(base) * float64(percentage) / 100)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
# MySQL 8.0 master/replica compose for two separate servers.
|
||||
#
|
||||
# Master server:
|
||||
# COMPOSE_PROFILES=master docker compose -f config/docker-compose.mysql-replication.yml up -d
|
||||
#
|
||||
# Replica server:
|
||||
# MASTER_HOST=<master_public_or_private_ip> COMPOSE_PROFILES=replica docker compose -f config/docker-compose.mysql-replication.yml up -d
|
||||
#
|
||||
# Required env on both servers:
|
||||
# MYSQL_ROOT_PASSWORD=<strong-root-password>
|
||||
# MYSQL_REPLICATION_PASSWORD=<strong-replication-password>
|
||||
#
|
||||
# Optional env:
|
||||
# MYSQL_DATABASE=ppanel
|
||||
# MYSQL_REPLICATION_USER=repl
|
||||
# MYSQL_MASTER_PORT=3306
|
||||
# MYSQL_REPLICA_PORT=3306
|
||||
# MYSQL_SERVER_ID=1 # master default
|
||||
# MYSQL_REPLICA_ID=2 # replica default
|
||||
#
|
||||
# If the master already has data, import a GTID-aware dump into the replica
|
||||
# before starting replication. Fresh empty deployments can start master first,
|
||||
# then replica, then point the application at the master.
|
||||
|
||||
services:
|
||||
mysql-master:
|
||||
image: mysql:8.0
|
||||
container_name: ppanel-mysql-master
|
||||
profiles:
|
||||
- master
|
||||
restart: always
|
||||
ports:
|
||||
- "${MYSQL_MASTER_PORT:-3306}:3306"
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?please set MYSQL_ROOT_PASSWORD}"
|
||||
MYSQL_DATABASE: "${MYSQL_DATABASE:-ppanel}"
|
||||
MYSQL_REPLICATION_USER: "${MYSQL_REPLICATION_USER:-repl}"
|
||||
MYSQL_REPLICATION_PASSWORD: "${MYSQL_REPLICATION_PASSWORD:?please set MYSQL_REPLICATION_PASSWORD}"
|
||||
TZ: Asia/Shanghai
|
||||
command:
|
||||
- --default-authentication-plugin=mysql_native_password
|
||||
- --server-id=${MYSQL_SERVER_ID:-1}
|
||||
- --log-bin=mysql-bin
|
||||
- --binlog-format=ROW
|
||||
- --gtid-mode=ON
|
||||
- --enforce-gtid-consistency=ON
|
||||
- --log-replica-updates=ON
|
||||
- --binlog-expire-logs-seconds=604800
|
||||
- --max_connections=1000
|
||||
- --character-set-server=utf8mb4
|
||||
- --collation-server=utf8mb4_unicode_ci
|
||||
volumes:
|
||||
- mysql_master_data:/var/lib/mysql
|
||||
configs:
|
||||
- source: mysql_master_init
|
||||
target: /docker-entrypoint-initdb.d/01-create-replication-user.sh
|
||||
mode: 0755
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$${MYSQL_ROOT_PASSWORD}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
|
||||
mysql-replica:
|
||||
image: mysql:8.0
|
||||
container_name: ppanel-mysql-replica
|
||||
profiles:
|
||||
- replica
|
||||
restart: always
|
||||
ports:
|
||||
- "${MYSQL_REPLICA_PORT:-3306}:3306"
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?please set MYSQL_ROOT_PASSWORD}"
|
||||
MYSQL_DATABASE: "${MYSQL_DATABASE:-ppanel}"
|
||||
TZ: Asia/Shanghai
|
||||
command:
|
||||
- --default-authentication-plugin=mysql_native_password
|
||||
- --server-id=${MYSQL_REPLICA_ID:-2}
|
||||
- --relay-log=mysql-relay-bin
|
||||
- --read-only=ON
|
||||
- --super-read-only=ON
|
||||
- --gtid-mode=ON
|
||||
- --enforce-gtid-consistency=ON
|
||||
- --log-replica-updates=ON
|
||||
- --binlog-format=ROW
|
||||
- --max_connections=1000
|
||||
- --character-set-server=utf8mb4
|
||||
- --collation-server=utf8mb4_unicode_ci
|
||||
volumes:
|
||||
- mysql_replica_data:/var/lib/mysql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$${MYSQL_ROOT_PASSWORD}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
|
||||
mysql-replica-init:
|
||||
image: mysql:8.0
|
||||
container_name: ppanel-mysql-replica-init
|
||||
profiles:
|
||||
- replica
|
||||
restart: "no"
|
||||
depends_on:
|
||||
mysql-replica:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?please set MYSQL_ROOT_PASSWORD}"
|
||||
MYSQL_REPLICATION_USER: "${MYSQL_REPLICATION_USER:-repl}"
|
||||
MYSQL_REPLICATION_PASSWORD: "${MYSQL_REPLICATION_PASSWORD:?please set MYSQL_REPLICATION_PASSWORD}"
|
||||
MASTER_HOST: "${MASTER_HOST:?please set MASTER_HOST to the master server ip or hostname}"
|
||||
MASTER_PORT: "${MASTER_PORT:-3306}"
|
||||
entrypoint:
|
||||
- /bin/sh
|
||||
- -ec
|
||||
- |
|
||||
mysql -hmysql-replica -uroot -p"$${MYSQL_ROOT_PASSWORD}" <<SQL
|
||||
STOP REPLICA;
|
||||
CHANGE REPLICATION SOURCE TO
|
||||
SOURCE_HOST='$${MASTER_HOST}',
|
||||
SOURCE_PORT=$${MASTER_PORT},
|
||||
SOURCE_USER='$${MYSQL_REPLICATION_USER}',
|
||||
SOURCE_PASSWORD='$${MYSQL_REPLICATION_PASSWORD}',
|
||||
SOURCE_AUTO_POSITION=1,
|
||||
GET_SOURCE_PUBLIC_KEY=1;
|
||||
START REPLICA;
|
||||
SQL
|
||||
|
||||
configs:
|
||||
mysql_master_init:
|
||||
content: |
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
mysql -uroot -p"$${MYSQL_ROOT_PASSWORD}" <<SQL
|
||||
CREATE USER IF NOT EXISTS '$${MYSQL_REPLICATION_USER}'@'%' IDENTIFIED WITH mysql_native_password BY '$${MYSQL_REPLICATION_PASSWORD}';
|
||||
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO '$${MYSQL_REPLICATION_USER}'@'%';
|
||||
FLUSH PRIVILEGES;
|
||||
SQL
|
||||
|
||||
volumes:
|
||||
mysql_master_data:
|
||||
mysql_replica_data:
|
||||
@@ -0,0 +1,20 @@
|
||||
EC2 SSH 连接资料
|
||||
|
||||
服务器名称: hifast-hk-app-01
|
||||
公网 IP: 43.198.248.161
|
||||
登录用户: ubuntu
|
||||
|
||||
私钥文件:
|
||||
- hifast-hk-app-01-reset
|
||||
|
||||
公钥文件:
|
||||
- hifast-hk-app-01-reset.pub
|
||||
|
||||
连接命令:
|
||||
ssh -i hifast-hk-app-01-reset ubuntu@43.198.248.161
|
||||
|
||||
如果在 Mac / Linux 上使用,先执行:
|
||||
chmod 600 hifast-hk-app-01-reset
|
||||
|
||||
如果要给别人使用,只需要把私钥文件 hifast-hk-app-01-reset 发给对方即可。
|
||||
出于安全考虑,建议通过安全渠道传输,并在后续需要时重新轮换密钥。
|
||||
@@ -0,0 +1,8 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACDb6msDqmSHLv0mWgCP4vfjQ3A552qv95uQdsH94RnoCgAAAKjy5KDa8uSg
|
||||
2gAAAAtzc2gtZWQyNTUxOQAAACDb6msDqmSHLv0mWgCP4vfjQ3A552qv95uQdsH94RnoCg
|
||||
AAAEDwSb0b/0S6Tw8Od5hAtIKqt1JvomqQQS44Ty3xL+FjPtvqawOqZIcu/SZaAI/i9+ND
|
||||
cDnnaq/3m5B2wf3hGegKAAAAIWhpZmFzdC1oay1hcHAtMDEtcmVzZXQtMjAyNi0wNS0xMA
|
||||
ECAwQ=
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINvqawOqZIcu/SZaAI/i9+NDcDnnaq/3m5B2wf3hGegK hifast-hk-app-01-reset-2026-05-10
|
||||
@@ -0,0 +1,363 @@
|
||||
# PPanel 香港区新 AWS 账号部署说明
|
||||
|
||||
本目录用于在 **新 AWS 账号** 中按 **香港区 `ap-east-1`** 重建一套全新空环境。
|
||||
|
||||
目标架构:
|
||||
|
||||
`DNS -> ALB -> WAF -> EC2(Nginx + ppanel-server + Redis + observability) -> RDS MySQL`
|
||||
|
||||
## 1. 资源清单
|
||||
|
||||
按下面顺序创建资源:
|
||||
|
||||
1. VPC
|
||||
2. 2 个公有子网 + 2 个私有子网
|
||||
3. Internet Gateway
|
||||
4. 公有 / 私有路由表
|
||||
5. 安全组
|
||||
6. RDS MySQL
|
||||
7. EC2 本机 Redis Docker
|
||||
8. EC2
|
||||
9. ACM 证书
|
||||
10. ALB + Target Group
|
||||
11. WAF Web ACL
|
||||
12. 平行环境域名
|
||||
|
||||
建议命名:
|
||||
|
||||
- VPC: `ppanel-hk-prod`
|
||||
- EC2: `ppanel-app-hk-01`
|
||||
- RDS: `ppanel-mysql-hk`
|
||||
- Redis container: `hifast-redis`
|
||||
- ALB: `ppanel-alb-hk`
|
||||
- WAF: `ppanel-waf-hk`
|
||||
|
||||
## 2. 默认规格
|
||||
|
||||
### EC2
|
||||
|
||||
- Region: `ap-east-1`
|
||||
- OS: Ubuntu 24.04 LTS
|
||||
- Instance type: `t4g.large` 起步
|
||||
- Disk: `gp3 80GB`
|
||||
- Public subnet: 是
|
||||
- IAM Role: 允许读取 CloudWatch / SSM(如使用)
|
||||
- 如果要在 AWS EC2 本机执行 S3 备份:额外允许写入专用备份桶
|
||||
|
||||
### RDS MySQL
|
||||
|
||||
- Engine: MySQL 8.0
|
||||
- Class: `db.r7g.xlarge`
|
||||
- Storage: `gp3 100GB`
|
||||
- DB name: `hifast`
|
||||
- Username: `admin`
|
||||
- Public access: `No`
|
||||
- Charset: `utf8mb4`
|
||||
- Backup: `7-14 days`
|
||||
|
||||
### Redis
|
||||
|
||||
- 部署位置:业务 EC2 本机
|
||||
- 部署方式:Docker
|
||||
- 版本:`redis:8.2.1`
|
||||
- 监听:`0.0.0.0:6379`
|
||||
- 应用连接:`127.0.0.1:6379`
|
||||
- 安全组:仅对白名单备用节点或同机应用开放
|
||||
|
||||
## 3. 网络与安全组
|
||||
|
||||
### 子网布局
|
||||
|
||||
- `public-a`, `public-b`: ALB / EC2
|
||||
- `private-a`, `private-b`: RDS
|
||||
|
||||
### 安全组建议
|
||||
|
||||
#### `sg-alb`
|
||||
|
||||
- Inbound
|
||||
- `80/tcp` from `0.0.0.0/0`
|
||||
- `443/tcp` from `0.0.0.0/0`
|
||||
- Outbound
|
||||
- `80/tcp` to `sg-ec2`
|
||||
|
||||
#### `sg-ec2`
|
||||
|
||||
- Inbound
|
||||
- `80/tcp` from `sg-alb`
|
||||
- `22/tcp` from `你的固定运维 IP`
|
||||
- Outbound
|
||||
- all
|
||||
|
||||
说明:
|
||||
|
||||
- 应用容器监听 `127.0.0.1:8080`
|
||||
- EC2 对外只让 Nginx 监听 `80`
|
||||
- Grafana / Prometheus / Tempo 仅监听 `127.0.0.1`
|
||||
|
||||
#### `sg-rds`
|
||||
|
||||
- Inbound
|
||||
- `3306/tcp` from `sg-ec2`
|
||||
|
||||
#### `sg-ec2` 额外说明
|
||||
|
||||
- 如果需要外部备用节点复制 Redis,再额外放行:
|
||||
- `6379/tcp` from `104.238.220.230/32`
|
||||
|
||||
## 4. ALB / Target Group / 健康检查
|
||||
|
||||
### Target Group
|
||||
|
||||
- Type: `Instance`
|
||||
- Protocol: `HTTP`
|
||||
- Port: `80`
|
||||
- Health check path: `/v1/common/heartbeat`
|
||||
- Success code: `200`
|
||||
|
||||
这个路径已由项目现有接口提供,无需额外改代码。
|
||||
|
||||
### ALB 监听器
|
||||
|
||||
- `80` -> redirect to `443`
|
||||
- `443` -> forward 到 target group
|
||||
|
||||
### ACM
|
||||
|
||||
- 在 `ap-east-1` 申请证书
|
||||
- 先给平行环境域名,例如:
|
||||
- `api-new.hifast.biz`
|
||||
- `logs-new.hifast.biz`
|
||||
|
||||
## 5. WAF 规则
|
||||
|
||||
首版至少启用:
|
||||
|
||||
1. `AWSManagedRulesCommonRuleSet`
|
||||
2. `AWSManagedRulesKnownBadInputsRuleSet`
|
||||
3. `AWSManagedRulesAmazonIpReputationList`
|
||||
4. 全站 rate-based rule
|
||||
5. 针对高风险路径的 rate-based rule
|
||||
|
||||
建议的第一版限流:
|
||||
|
||||
- 全站:每 IP `2000 / 5 分钟`
|
||||
- `/v1/public/user/subscribe`:每 IP `300 / 5 分钟`
|
||||
- 登录 / 注册 / 验证码接口:每 IP `100 / 5 分钟`
|
||||
|
||||
节点上报接口建议后续补:
|
||||
|
||||
- `/v1/server/status`
|
||||
- `/v1/server/online`
|
||||
- `/v1/server/traffic`
|
||||
|
||||
优先用节点出口 IP 白名单;没有固定出口 IP 的节点暂时保留 `secret_key`,但不要把它当成唯一防线。
|
||||
|
||||
## 6. EC2 文件落地
|
||||
|
||||
在 EC2 上建议使用:
|
||||
|
||||
- 应用目录:`/opt/ppanel`
|
||||
- Nginx 配置:`/etc/nginx/sites-available/ppanel-api.conf`
|
||||
|
||||
需要上传这些文件 / 目录:
|
||||
|
||||
- `docker-compose.cloud.yml`
|
||||
- `deploy/aws/ap-east-1/configs/ppanel.yaml.example` -> 重命名为 `configs/ppanel.yaml`
|
||||
- `deploy/aws/ap-east-1/nginx/ppanel-api.conf`
|
||||
- `grafana/`
|
||||
- `loki/`
|
||||
- `prometheus/`
|
||||
- `tempo/`
|
||||
- `.env.example` -> 重命名为 `.env`
|
||||
|
||||
目标目录示例:
|
||||
|
||||
```text
|
||||
/opt/ppanel/
|
||||
docker-compose.cloud.yml
|
||||
.env
|
||||
configs/ppanel.yaml
|
||||
grafana/
|
||||
loki/
|
||||
prometheus/
|
||||
tempo/
|
||||
logs/
|
||||
cache/
|
||||
tempo_data/
|
||||
```
|
||||
|
||||
## 7. 应用配置
|
||||
|
||||
基线模板见:
|
||||
|
||||
- [`configs/ppanel.yaml.example`](./configs/ppanel.yaml.example)
|
||||
- [`nginx/ppanel-api.conf`](./nginx/ppanel-api.conf)
|
||||
|
||||
关键值必须替换:
|
||||
|
||||
- `MySQL.Addr`
|
||||
- `MySQL.Password`
|
||||
- `Redis.Host`
|
||||
- `Redis.Pass`
|
||||
- `JwtAuth.AccessSecret`
|
||||
- `Administrator.Email`
|
||||
- `Administrator.Password`
|
||||
- `AppSignature.AppSecrets.*`
|
||||
- `device.security_secret`
|
||||
- `Site.Host`
|
||||
- `Site.SiteName`
|
||||
|
||||
Redis 约定保持不变:
|
||||
|
||||
- 业务缓存:DB `0`
|
||||
- Asynq:DB `5`(代码内部已固定使用)
|
||||
|
||||
## 8. 部署步骤
|
||||
|
||||
### 8.1 初始化 EC2
|
||||
|
||||
把脚本上传到 EC2 后执行:
|
||||
|
||||
## 9. 104 灾备节点常用运维脚本
|
||||
|
||||
如果你要在 `104.238.220.230` 上执行数据迁移、主从重拉、主库提升,可以直接复用仓库里的这几份脚本:
|
||||
|
||||
- 数据导出 / 导入交互工具:
|
||||
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
|
||||
- MySQL 主从运维工具:
|
||||
- [`deploy/scripts/mysql_replica_ops.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/mysql_replica_ops.sh)
|
||||
- Redis 主从运维工具:
|
||||
- [`deploy/scripts/redis_replica_ops.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/redis_replica_ops.sh)
|
||||
- 统一总入口:
|
||||
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
|
||||
- 主从运维环境模板:
|
||||
- [`deploy/aws/ap-east-1/configs/replica-ops.env.example`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/aws/ap-east-1/configs/replica-ops.env.example)
|
||||
|
||||
### 9.1 数据迁移工具
|
||||
|
||||
支持:
|
||||
|
||||
- 备份 MySQL 到 S3
|
||||
- 备份 Redis 到 S3
|
||||
- 从正式库导出 MySQL `sql.gz`
|
||||
- 把 `sql.gz` 导入 AWS RDS
|
||||
- 从正式 Redis 导出 `RDB`
|
||||
- 将 `RDB` 导入 Docker Redis 或宿主机 Redis
|
||||
- 查看 MySQL / Redis 当前主从状态
|
||||
- 强制重拉 MySQL / Redis 主从
|
||||
- 把 MySQL / Redis 从库提升为可写主库
|
||||
|
||||
示例:
|
||||
|
||||
```bash
|
||||
bash deploy/scripts/hifast_data_sync_tool.sh /root/replica-ops.env
|
||||
```
|
||||
|
||||
```bash
|
||||
chmod +x deploy/scripts/bootstrap_aws_ec2.sh
|
||||
sudo APP_DIR=/opt/ppanel deploy/scripts/bootstrap_aws_ec2.sh
|
||||
```
|
||||
|
||||
### 8.2 安装 Nginx 配置
|
||||
|
||||
```bash
|
||||
sudo cp deploy/aws/ap-east-1/nginx/ppanel-api.conf /etc/nginx/sites-available/ppanel-api.conf
|
||||
sudo ln -sf /etc/nginx/sites-available/ppanel-api.conf /etc/nginx/sites-enabled/ppanel-api.conf
|
||||
sudo nginx -t
|
||||
sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
### 8.3 启动容器
|
||||
|
||||
```bash
|
||||
cd /opt/ppanel
|
||||
docker compose -f docker-compose.cloud.yml up -d
|
||||
```
|
||||
|
||||
### 8.4 预检
|
||||
|
||||
```bash
|
||||
chmod +x deploy/scripts/preflight_aws_hk.sh
|
||||
APP_DIR=/opt/ppanel \
|
||||
RDS_HOST=<new-rds-endpoint> \
|
||||
REDIS_HOST=127.0.0.1 \
|
||||
deploy/scripts/preflight_aws_hk.sh
|
||||
```
|
||||
|
||||
## 9. 平行环境验证
|
||||
|
||||
先验证 `api-new.hifast.biz`,不要直接切正式域名。
|
||||
|
||||
必测项:
|
||||
|
||||
1. `ALB target` 为 healthy
|
||||
2. `GET /v1/common/heartbeat` 返回 200
|
||||
3. 管理员登录
|
||||
4. 用户注册 / 登录
|
||||
5. 订阅查询
|
||||
6. 节点上报 `/v1/server/status`
|
||||
7. 本机 Redis 可写缓存
|
||||
8. Asynq 可入队并消费
|
||||
|
||||
## 10. 正式切换
|
||||
|
||||
切换前检查:
|
||||
|
||||
1. ALB 5xx 为 0
|
||||
2. EC2 CPU / Memory 正常
|
||||
3. RDS CPU / Connections 正常
|
||||
4. 本机 Redis CPU / Connections / Memory 正常
|
||||
5. WAF 已挂到 ALB
|
||||
6. EC2 安全组没有对公网放 `8080/3333/9090/4317`
|
||||
|
||||
切换方式:
|
||||
|
||||
1. 保持新环境先跑平行域名
|
||||
2. 正式域名切到新 ALB
|
||||
3. 观察至少 1 小时
|
||||
4. 确认无误后再处理旧环境
|
||||
|
||||
## 11. 监控建议
|
||||
|
||||
至少建这些 CloudWatch / Grafana 观测项:
|
||||
|
||||
- ALB `RequestCount`, `HTTPCode_ELB_5XX_Count`, `TargetResponseTime`
|
||||
- EC2 `CPUUtilization`, `NetworkIn`, `NetworkOut`, `StatusCheckFailed`
|
||||
- RDS `CPUUtilization`, `DatabaseConnections`, `ReadLatency`, `WriteLatency`
|
||||
- Redis 容器 CPU / Memory / restart count
|
||||
|
||||
## 12. 这次方案的边界
|
||||
|
||||
本目录交付的是:
|
||||
|
||||
- 香港区新账号的部署模板
|
||||
- 新空环境启动与验证流程
|
||||
- ALB / WAF / EC2 / RDS / 本机 Redis 的落地约定
|
||||
|
||||
不包含:
|
||||
|
||||
- 旧数据迁移
|
||||
- Terraform / CloudFormation 自动建资源
|
||||
- Redis 托管版改造
|
||||
- 多活 / 自动扩缩容
|
||||
|
||||
## 13. S3 备份补强
|
||||
|
||||
当前已落地的 S3 备份桶:
|
||||
|
||||
- `hifast-prod-backups-200810848252-ap-east-1`
|
||||
|
||||
建议与现网结合方式:
|
||||
|
||||
1. `RDS automated backup` 继续保留,作为第一层恢复能力
|
||||
2. `104` 外部 MySQL 从库执行逻辑备份并上传到 S3,作为第二层可下载备份
|
||||
3. `104` 外部 Redis 从库按需导出 `RDB` 到 S3,补齐缓存类灾备材料
|
||||
|
||||
仓库中已补充:
|
||||
|
||||
- 环境变量模板:[`configs/backup-to-s3.env.example`](./configs/backup-to-s3.env.example)
|
||||
- MySQL 备份脚本:[`../../scripts/mysql_backup_to_s3.sh`](../../scripts/mysql_backup_to_s3.sh)
|
||||
- Redis 备份脚本:[`../../scripts/redis_rdb_backup_to_s3.sh`](../../scripts/redis_rdb_backup_to_s3.sh)
|
||||
|
||||
建议把 MySQL 备份脚本优先部署到 `104`,因为它直接连接本地只读从库,对 AWS 主库扰动最小。
|
||||
@@ -0,0 +1,18 @@
|
||||
AWS_REGION=ap-east-1
|
||||
S3_BUCKET=hifast-prod-backups-200810848252-ap-east-1
|
||||
S3_PREFIX=mysql
|
||||
BACKUP_DIR=/var/backups/hifast
|
||||
HOST_TAG=104-standby
|
||||
KEEP_LOCAL_DAYS=3
|
||||
CHECK_REPLICA=1
|
||||
|
||||
MYSQL_HOST=127.0.0.1
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER=backup_reader
|
||||
MYSQL_PASSWORD=CHANGE_ME
|
||||
MYSQL_SOCKET=
|
||||
MYSQL_DATABASE=hifast
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=CHANGE_ME
|
||||
@@ -0,0 +1,20 @@
|
||||
PRIMARY_HOST=hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com
|
||||
PRIMARY_PORT=3306
|
||||
PRIMARY_USER=admin
|
||||
PRIMARY_PASSWORD=CHANGE_ME
|
||||
PRIMARY_DB=hifast
|
||||
|
||||
PRIMARY_REPL_USER=repl
|
||||
PRIMARY_REPL_PASSWORD=CHANGE_ME
|
||||
PRIMARY_REPL_HOST=104.238.220.230
|
||||
PRIMARY_BINLOG_RETENTION_HOURS=24
|
||||
|
||||
REPLICA_HOST=127.0.0.1
|
||||
REPLICA_PORT=3306
|
||||
REPLICA_USER=root
|
||||
REPLICA_PASSWORD=
|
||||
REPLICA_SOCKET=/var/run/mysqld/mysqld.sock
|
||||
REPLICA_DB=hifast
|
||||
REPLICA_SOURCE_SSL=1
|
||||
|
||||
DUMP_FILE=
|
||||
@@ -0,0 +1,111 @@
|
||||
Host: 0.0.0.0
|
||||
Port: 8080
|
||||
Debug: false
|
||||
|
||||
JwtAuth:
|
||||
AccessSecret: CHANGE_ME_TO_A_LONG_RANDOM_SECRET
|
||||
AccessExpire: 604800
|
||||
|
||||
Logger:
|
||||
ServiceName: PPanel
|
||||
Mode: console
|
||||
Encoding: plain
|
||||
TimeFormat: "2006-01-02 15:04:05.000"
|
||||
Path: logs
|
||||
Level: info
|
||||
MaxContentLength: 0
|
||||
Compress: false
|
||||
Stat: true
|
||||
KeepDays: 7
|
||||
StackCooldownMillis: 100
|
||||
MaxBackups: 7
|
||||
MaxSize: 100
|
||||
Rotation: daily
|
||||
FileTimeFormat: "2006-01-02T15:04:05.000Z07:00"
|
||||
|
||||
MySQL:
|
||||
Addr: YOUR_RDS_ENDPOINT:3306
|
||||
Dbname: hifast
|
||||
Username: admin
|
||||
Password: CHANGE_ME_TO_RDS_PASSWORD
|
||||
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
|
||||
MaxIdleConns: 10
|
||||
MaxOpenConns: 100
|
||||
SlowThreshold: 1000
|
||||
|
||||
Redis:
|
||||
Host: 127.0.0.1:6379
|
||||
Pass: CHANGE_ME_TO_REDIS_PASSWORD
|
||||
DB: 0
|
||||
PoolSize: 100
|
||||
MinIdleConns: 10
|
||||
MaxRetries: 3
|
||||
PoolTimeout: 4
|
||||
IdleTimeout: 300
|
||||
MaxConnAge: 0
|
||||
DialTimeout: 5
|
||||
ReadTimeout: 3
|
||||
WriteTimeout: 3
|
||||
|
||||
Trace:
|
||||
Name: ppanel-server
|
||||
Endpoint: 127.0.0.1:4317
|
||||
Sampler: 0.1
|
||||
Batcher: otlpgrpc
|
||||
|
||||
Site:
|
||||
Host: api-new.hifast.biz
|
||||
SiteName: HiFastVPN
|
||||
|
||||
Administrator:
|
||||
Email: admin@example.com
|
||||
Password: CHANGE_ME_TO_STRONG_ADMIN_PASSWORD
|
||||
|
||||
Telegram:
|
||||
Enable: false
|
||||
BotID: 0
|
||||
BotName: ""
|
||||
BotToken: ""
|
||||
GroupChatID: ""
|
||||
EnableNotify: false
|
||||
WebHookDomain: ""
|
||||
|
||||
Kutt:
|
||||
Enable: false
|
||||
ApiURL: ""
|
||||
ApiKey: ""
|
||||
TargetURL: ""
|
||||
Domain: ""
|
||||
|
||||
OpenInstall:
|
||||
Enable: false
|
||||
AppKey: ""
|
||||
ApiKey: ""
|
||||
|
||||
Loki:
|
||||
Enable: true
|
||||
URL: "http://localhost:3100"
|
||||
|
||||
AppSignature:
|
||||
AppSecrets:
|
||||
android-client: CHANGE_ME_ANDROID_SIGNATURE_SECRET
|
||||
ios-client: CHANGE_ME_IOS_SIGNATURE_SECRET
|
||||
web-client: CHANGE_ME_WEB_SIGNATURE_SECRET
|
||||
ValidWindowSeconds: 300
|
||||
SkipPrefixes:
|
||||
- /v1/notify/
|
||||
- /v1/iap/notifications
|
||||
- /v1/telegram/webhook
|
||||
- /v1/subscribe/config
|
||||
|
||||
Signature:
|
||||
EnableSignature: false
|
||||
|
||||
device:
|
||||
enable: true
|
||||
security_secret: CHANGE_ME_DEVICE_SECURITY_SECRET
|
||||
|
||||
Register:
|
||||
EnableTrial: true
|
||||
EnableTrialEmailWhitelist: true
|
||||
TrialEmailDomainWhitelist: "gmail.com,outlook.com,icloud.com,qq.com,163.com"
|
||||
@@ -0,0 +1,23 @@
|
||||
MYSQL_HOST=127.0.0.1
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER=root
|
||||
MYSQL_PASSWORD=CHANGE_ME
|
||||
MYSQL_SOCKET=
|
||||
|
||||
REPL_SOURCE_HOST=hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com
|
||||
REPL_SOURCE_PORT=3306
|
||||
REPL_SOURCE_USER=repl
|
||||
REPL_SOURCE_PASSWORD=CHANGE_ME
|
||||
REPL_SOURCE_SSL=1
|
||||
REPL_SOURCE_LOG_FILE=
|
||||
REPL_SOURCE_LOG_POS=
|
||||
REPL_SOURCE_AUTO_POSITION=1
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=CHANGE_ME
|
||||
|
||||
REDIS_SOURCE_HOST=18.163.33.75
|
||||
REDIS_SOURCE_PORT=6379
|
||||
REDIS_SOURCE_USER=
|
||||
REDIS_SOURCE_PASSWORD=CHANGE_ME
|
||||
@@ -0,0 +1,33 @@
|
||||
server {
|
||||
listen 80 default_server;
|
||||
listen [::]:80 default_server;
|
||||
server_name _;
|
||||
|
||||
client_max_body_size 20m;
|
||||
|
||||
access_log /var/log/nginx/ppanel-access.log;
|
||||
error_log /var/log/nginx/ppanel-error.log warn;
|
||||
|
||||
location / {
|
||||
proxy_http_version 1.1;
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_send_timeout 60s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
location = /nginx_status {
|
||||
stub_status;
|
||||
access_log off;
|
||||
allow 127.0.0.1;
|
||||
deny all;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
# 邀请赠送与购买订阅逻辑说明
|
||||
|
||||
本文档说明当前代码中的购买订阅、订单激活、邀请佣金、邀请赠送时间、家庭组归属逻辑。重点覆盖每个主要分支,方便排查“重复订单/重复订阅/邀请未赠时/赠时落点错误”等问题。
|
||||
|
||||
涉及核心文件:
|
||||
|
||||
- `internal/logic/public/order/purchaseLogic.go`
|
||||
- `queue/logic/order/activateOrderLogic.go`
|
||||
- `internal/logic/common/familyEntitlement.go`
|
||||
- `internal/model/user/model.go`
|
||||
|
||||
## 1. 核心概念
|
||||
|
||||
### 1.1 订单状态
|
||||
|
||||
| 状态 | 含义 |
|
||||
| --- | --- |
|
||||
| `1` | pending,已创建未支付 |
|
||||
| `2` | paid,已支付待激活 |
|
||||
| `3` | close,已关闭 |
|
||||
| `4` | failed/claimed,代码里同时用于失败和 worker 临时领取 |
|
||||
| `5` | finished,激活完成 |
|
||||
|
||||
### 1.2 订单类型
|
||||
|
||||
| 类型 | 含义 |
|
||||
| --- | --- |
|
||||
| `1` | 新购套餐 |
|
||||
| `2` | 续费/换套餐 |
|
||||
| `3` | 重置流量 |
|
||||
| `4` | 余额充值 |
|
||||
| `5` | 兑换码激活 |
|
||||
|
||||
### 1.3 用户 ID 与订阅归属
|
||||
|
||||
订单有两个重要用户字段:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `user_id` | 发起订单/付款的用户 |
|
||||
| `subscription_user_id` | 订阅权益归属用户;`0` 表示同 `user_id` |
|
||||
|
||||
家庭组规则:
|
||||
|
||||
- 普通用户下单:`subscription_user_id = user_id`。
|
||||
- 家庭组成员下单:`subscription_user_id = 家主用户 ID`。
|
||||
- 家庭组主账号下单:`subscription_user_id = 家主用户 ID`。
|
||||
|
||||
当前代码使用 `ResolveEntitlementUser` 判断家庭归属:
|
||||
|
||||
- 只有有效家庭组、有效成员关系、角色为 member 时,权益归家主。
|
||||
- 家主本人不会被改写到别人名下。
|
||||
|
||||
## 2. 购买订阅下单逻辑
|
||||
|
||||
入口:`Purchase(req *types.PurchaseOrderRequest)`
|
||||
|
||||
这里只是创建订单和安排关闭任务,不直接发放订阅。真正发放订阅在订单支付后由队列激活处理。
|
||||
|
||||
### 2.1 登录用户检查
|
||||
|
||||
分支:
|
||||
|
||||
- 上下文没有当前用户:返回 `InvalidAccess`。
|
||||
- 当前用户存在:继续。
|
||||
|
||||
### 2.2 解析订阅权益归属
|
||||
|
||||
调用 `ResolveEntitlementUser`:
|
||||
|
||||
| 场景 | `effective_user_id` | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 普通用户 | 本人 ID | 订阅归本人 |
|
||||
| 家庭组主账号 | 本人 ID | 订阅归本人 |
|
||||
| 家庭组成员 | 家主 ID | 订阅归家主 |
|
||||
|
||||
后续查询已有订阅、quota、创建订单里的 `subscription_user_id` 都会使用这个归属结果。
|
||||
|
||||
### 2.3 数量校验
|
||||
|
||||
分支:
|
||||
|
||||
- `quantity <= 0`:自动改成 `1`。
|
||||
- `quantity > MaxQuantity`:返回参数错误。
|
||||
- 合法:继续。
|
||||
|
||||
### 2.4 单订阅模式路由
|
||||
|
||||
先默认:
|
||||
|
||||
```text
|
||||
order_type = 1
|
||||
target_subscribe_id = req.subscribe_id
|
||||
parent_order_id = 0
|
||||
subscribe_token = ""
|
||||
```
|
||||
|
||||
如果开启 `Subscribe.SingleModel`:
|
||||
|
||||
| 查询结果 | 行为 |
|
||||
| --- | --- |
|
||||
| 找到已有 anchor 订阅 | 下单路由为续费:`order_type=2`,保留新请求套餐 ID,设置 parent/order token |
|
||||
| 没找到已有订阅 | 保持新购:`order_type=1` |
|
||||
| 查询异常 | 返回数据库错误 |
|
||||
|
||||
说明:即使是换套餐,只要单订阅模式已有订阅,也走续费语义,后续激活会更新套餐 ID 和流量配置。
|
||||
|
||||
### 2.5 非 SingleModel 的全局单订阅兜底
|
||||
|
||||
如果未开启 `SingleModel`,且当前还是新购 `order_type=1`:
|
||||
|
||||
- 查询 `effective_user_id` 名下已有付费订阅:
|
||||
|
||||
```sql
|
||||
user_id = effective_user_id
|
||||
AND token != ''
|
||||
AND (order_id > 0 OR token LIKE 'iap:%')
|
||||
```
|
||||
|
||||
| 查询结果 | 行为 |
|
||||
| --- | --- |
|
||||
| 找到已有订阅 | 路由为续费:`order_type=2`,用已有订阅 token |
|
||||
| 没找到 | 仍然新购 |
|
||||
|
||||
目的:避免同一个权益归属用户购买不同套餐后出现多条订阅权益。
|
||||
|
||||
### 2.6 pending 订单处理
|
||||
|
||||
当前只有一个分支会主动关闭旧 pending 单:
|
||||
|
||||
```text
|
||||
SingleModel = true
|
||||
AND order_type = 1
|
||||
AND 存在同 user_id + subscribe_id + status=1 的订单
|
||||
```
|
||||
|
||||
行为:
|
||||
|
||||
- 关闭旧 pending 订单。
|
||||
- 继续创建新订单。
|
||||
|
||||
注意:
|
||||
|
||||
- 如果订单已被路由为 `order_type=2`,这里不会关闭旧 pending。
|
||||
- 非 `SingleModel` 下也不会走这段 pending 关闭逻辑。
|
||||
|
||||
### 2.7 套餐校验
|
||||
|
||||
分支:
|
||||
|
||||
| 条件 | 行为 |
|
||||
| --- | --- |
|
||||
| 套餐不存在 | 返回数据库错误 |
|
||||
| `sell=false` | 返回套餐不可售 |
|
||||
| 新购且库存为 `0` | 返回库存不足 |
|
||||
| 续费/换套餐 | 不检查库存为 0 的拦截分支 |
|
||||
|
||||
### 2.8 新用户优惠与新用户限定
|
||||
|
||||
调用 `resolveNewUserDiscountEligibility`:
|
||||
|
||||
| 分支 | 行为 |
|
||||
| --- | --- |
|
||||
| 解析失败 | 返回错误 |
|
||||
| 有折扣且符合条件 | 按折扣计算金额 |
|
||||
| 有折扣但不符合条件 | 按原价 |
|
||||
| 新用户限定且不是新用户窗口 | 新购事务内再次校验,不通过则失败 |
|
||||
|
||||
### 2.9 优惠券逻辑
|
||||
|
||||
如果 `req.coupon` 为空:跳过。
|
||||
|
||||
如果不为空:
|
||||
|
||||
| 校验 | 不通过行为 |
|
||||
| --- | --- |
|
||||
| 优惠券存在 | 返回 `CouponNotExist` |
|
||||
| 总使用次数未超限 | 返回使用次数不足 |
|
||||
| 用户使用次数未超限 | 返回用户次数不足 |
|
||||
| 套餐适用 | 返回不适用 |
|
||||
|
||||
通过后计算 `coupon_discount`,从订单金额中扣除。
|
||||
|
||||
### 2.10 支付手续费与礼品余额抵扣
|
||||
|
||||
流程:
|
||||
|
||||
1. 找支付方式。
|
||||
2. 如果金额大于 0,计算手续费并加到订单金额。
|
||||
3. 如果用户 `gift_amount > 0`,继续抵扣订单金额。
|
||||
4. 抵扣金额记录到订单 `gift_amount`。
|
||||
|
||||
事务内如果有礼品余额抵扣:
|
||||
|
||||
- 扣减用户 `gift_amount`。
|
||||
- 写 `system_logs` 的 gift reduce 日志。
|
||||
|
||||
### 2.11 `is_new` 首单标记
|
||||
|
||||
创建订单前调用:
|
||||
|
||||
```sql
|
||||
SELECT COUNT(*)
|
||||
FROM `order`
|
||||
WHERE user_id = 当前付款用户
|
||||
AND status IN (2, 5)
|
||||
```
|
||||
|
||||
| 结果 | `is_new` |
|
||||
| --- | --- |
|
||||
| count = 0 | `true` |
|
||||
| count > 0 | `false` |
|
||||
|
||||
注意:
|
||||
|
||||
- 判断口径是付款用户 `user_id`,不是 `subscription_user_id`。
|
||||
- pending/closed 订单不影响 `is_new`。
|
||||
- 续费订单也可能是 `is_new=true`,例如单订阅模式下首次购买被路由为续费。
|
||||
|
||||
### 2.12 事务内创建订单
|
||||
|
||||
事务内执行:
|
||||
|
||||
1. 新购且套餐有 quota 时,再查一次 `effective_user_id` 名下订阅数量防并发。
|
||||
2. 新购且新用户限定时,再查一次新用户资格。
|
||||
3. 如有礼品余额抵扣,扣减余额并写日志。
|
||||
4. 新购且库存不是 `-1` 时扣库存。
|
||||
5. 插入订单。
|
||||
|
||||
订单核心字段:
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| `user_id` | 当前付款用户 |
|
||||
| `subscription_user_id` | 权益归属用户 |
|
||||
| `type` | 新购 `1` 或续费 `2` |
|
||||
| `subscribe_id` | 本次购买的套餐 ID |
|
||||
| `subscribe_token` | 续费时已有订阅 token |
|
||||
| `is_new` | 首单标记 |
|
||||
| `status` | `1` pending |
|
||||
|
||||
### 2.13 延迟关单任务
|
||||
|
||||
订单创建成功后,发送 `DeferCloseOrder` 任务:
|
||||
|
||||
- 延迟时间:15 分钟。
|
||||
- 作用:未支付订单自动关闭。
|
||||
|
||||
## 3. 订单支付后的激活逻辑
|
||||
|
||||
入口:`ActivateOrderLogic.ProcessTask`
|
||||
|
||||
### 3.1 任务解析和订单领取
|
||||
|
||||
分支:
|
||||
|
||||
| 分支 | 行为 |
|
||||
| --- | --- |
|
||||
| payload 解析失败 | 记录错误,不重试 |
|
||||
| 订单不存在 | 返回错误,允许重试 |
|
||||
| 订单已 finished | 幂等跳过 |
|
||||
| 订单不是 paid | 跳过 |
|
||||
| paid 订单 | 原子更新为 claimed 状态后处理 |
|
||||
|
||||
### 3.2 按订单类型分发
|
||||
|
||||
| 订单类型 | 处理函数 |
|
||||
| --- | --- |
|
||||
| 新购 `1` | `NewPurchase` |
|
||||
| 续费 `2` | `Renewal` |
|
||||
| 重置流量 `3` | `ResetTraffic` |
|
||||
| 充值 `4` | `Recharge` |
|
||||
| 兑换码 `5` | `RedemptionActivate` |
|
||||
|
||||
处理成功后:
|
||||
|
||||
1. 执行订阅合并兜底 `reconcilePostOrderSubscriptions`。
|
||||
2. 更新优惠券使用次数。
|
||||
3. 更新订单为 `finished`。
|
||||
|
||||
如果处理失败:
|
||||
|
||||
- 把订单从 claimed 释放回 paid。
|
||||
- 返回错误给队列重试。
|
||||
|
||||
## 4. 新购订单激活与订阅发放
|
||||
|
||||
入口:`NewPurchase`
|
||||
|
||||
### 4.1 获取用户
|
||||
|
||||
分支:
|
||||
|
||||
| 订单 user_id | 行为 |
|
||||
| --- | --- |
|
||||
| 不为 0 | 查询已有用户 |
|
||||
| 为 0 | 从 Redis 临时订单创建游客用户 |
|
||||
|
||||
游客订单创建用户时:
|
||||
|
||||
- 创建用户和 auth method。
|
||||
- 生成 refer code。
|
||||
- 把订单 `user_id` 更新为新用户 ID。
|
||||
- 如果临时订单有邀请码,绑定 `referer_id`。
|
||||
|
||||
### 4.2 新用户限定激活时复查
|
||||
|
||||
如果套餐是新用户限定,激活时再次校验:
|
||||
|
||||
- 不符合则激活失败,订单回到 paid 等待重试/处理。
|
||||
- 符合继续。
|
||||
|
||||
### 4.3 SingleModel 下复用 anchor 订阅
|
||||
|
||||
如果 `Subscribe.SingleModel=true`:
|
||||
|
||||
| 分支 | 行为 |
|
||||
| --- | --- |
|
||||
| 找到 anchor 订阅 | 更新订单 parent_id;用续费逻辑延长/换套餐 |
|
||||
| 找不到 | 继续后续分支 |
|
||||
| 查询异常 | 记录错误,继续后续分支 |
|
||||
|
||||
家庭组场景下查 anchor 的用户 ID:
|
||||
|
||||
- 优先 `subscription_user_id`。
|
||||
- 没有则用 `user_id`。
|
||||
|
||||
### 4.4 复用赠送订阅
|
||||
|
||||
如果还没有可复用订阅:
|
||||
|
||||
- 查找权益归属用户名下 `order_id=0` 的赠送订阅。
|
||||
- 找到后将它升级为付费订阅:
|
||||
- `order_id` 改为当前订单 ID。
|
||||
- 延长到期时间。
|
||||
- 状态改为 active。
|
||||
- 如果套餐变更,更新套餐 ID、流量额度,并清空已用流量。
|
||||
|
||||
### 4.5 兜底复用已有订阅
|
||||
|
||||
如果仍未复用到订阅:
|
||||
|
||||
- 候选用户 ID:
|
||||
- `order.user_id`
|
||||
- 如果 `subscription_user_id` 存在且不同,也加入候选。
|
||||
- 查找这些用户名下 `token != ''` 的订阅。
|
||||
|
||||
找到后:
|
||||
|
||||
- 如果订阅 owner 不是当前 `subscription_user_id`,先把 `user_id` 修正为权益归属用户。
|
||||
- 用续费逻辑延长/换套餐。
|
||||
|
||||
目的:家庭组绑定前后 owner 变化时,也尽量复用旧记录,避免创建重复订阅。
|
||||
|
||||
### 4.6 创建新订阅
|
||||
|
||||
如果以上都没有复用成功,才创建新 `user_subscribe`:
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| `user_id` | `subscription_user_id`,没有则 `order.user_id` |
|
||||
| `order_id` | 当前订单 ID |
|
||||
| `subscribe_id` | 当前订单套餐 ID |
|
||||
| `start_time` | 当前时间 |
|
||||
| `expire_time` | 按套餐时间单位和数量计算 |
|
||||
| `traffic` | 套餐流量 |
|
||||
| `token` | 基于订单号生成 |
|
||||
| `uuid` | 新 UUID |
|
||||
| `status` | `1` active |
|
||||
|
||||
创建前如果套餐有 quota,会再按订阅 owner 统计数量。
|
||||
|
||||
### 4.7 新购激活后的异步逻辑
|
||||
|
||||
订阅发放后:
|
||||
|
||||
1. 后台触发用户分组重算。
|
||||
2. 后台异步处理邀请佣金和赠送时间。
|
||||
3. 清套餐缓存。
|
||||
|
||||
注意:邀请逻辑在 goroutine 中执行,不阻塞订单激活。
|
||||
|
||||
## 5. 续费/换套餐激活逻辑
|
||||
|
||||
入口:`Renewal`
|
||||
|
||||
### 5.1 获取用户和订阅
|
||||
|
||||
- 查询订单 `user_id` 对应用户。
|
||||
- 通过 `subscribe_token` 查订阅。
|
||||
- 查询订单 `subscribe_id` 对应套餐。
|
||||
|
||||
### 5.2 Apple IAP 与普通续费分支
|
||||
|
||||
| 分支 | 行为 |
|
||||
| --- | --- |
|
||||
| `iap_expire_at > 0` | 使用 IAP 到期时间兜底,但仍按累计加时语义 |
|
||||
| 普通续费 | `updateSubscriptionForRenewal` |
|
||||
|
||||
### 5.3 普通续费/换套餐规则
|
||||
|
||||
`updateSubscriptionForRenewal`:
|
||||
|
||||
- 如果当前订阅已过期,先把基准时间改为现在。
|
||||
- 如果套餐 ID 变化:
|
||||
- 更新订阅套餐 ID。
|
||||
- 更新流量额度。
|
||||
- 清空已用流量。
|
||||
- 如果套餐没变:
|
||||
- 如果套餐设置 renewal reset,或今天是重置日,则清空已用流量。
|
||||
- 清理 `finished_at`。
|
||||
- `order_id` 改为当前订单 ID。
|
||||
- 按套餐时间单位和数量延长到期时间。
|
||||
- 状态改为 active。
|
||||
- 清空过期流量字段。
|
||||
|
||||
### 5.4 续费后的邀请逻辑
|
||||
|
||||
续费成功后也会调用 `handleCommission`:
|
||||
|
||||
- 是否发佣金由邀请配置和 `order.is_new` 决定。
|
||||
- 是否赠时同样由邀请配置和 `order.is_new` 决定。
|
||||
|
||||
注意:如果 `OnlyFirstPurchase=true`,非首单续费通常不会发佣金,也不会赠首单时间。
|
||||
|
||||
## 6. 邀请关系绑定逻辑
|
||||
|
||||
### 6.1 注册/登录时的邀请码
|
||||
|
||||
新用户注册、游客订单创建用户时,如果带邀请码:
|
||||
|
||||
- 根据邀请码查邀请人。
|
||||
- 设置新用户 `referer_id = 邀请人 ID`。
|
||||
|
||||
### 6.2 用户后绑邀请码
|
||||
|
||||
入口:`BindInviteCode`
|
||||
|
||||
分支:
|
||||
|
||||
| 分支 | 行为 |
|
||||
| --- | --- |
|
||||
| 当前用户不存在 | 返回无权限 |
|
||||
| 当前用户已有 `referer_id` | 返回已绑定 |
|
||||
| 邀请码不存在 | 返回邀请码错误 |
|
||||
| 邀请码属于自己 | 返回不允许绑定自己 |
|
||||
| 通过 | 更新当前用户 `referer_id` |
|
||||
|
||||
注意:
|
||||
|
||||
- `referer_id` 始终记录实际邀请码所有者。
|
||||
- 邀请人是家庭成员时,`referer_id` 仍然是该成员 ID,不自动改为家主 ID。
|
||||
|
||||
## 7. 邀请佣金与赠送时间逻辑
|
||||
|
||||
入口:`handleCommission(userInfo, orderInfo)`
|
||||
|
||||
这里的 `userInfo` 是订单付款用户,也就是被邀请人。
|
||||
|
||||
### 7.1 总入口分支
|
||||
|
||||
先调用 `shouldProcessCommission(userInfo, orderInfo.IsNew)`。
|
||||
|
||||
| 结果 | 行为 |
|
||||
| --- | --- |
|
||||
| `false` | 不发佣金;如果 `is_new=true`,走双方赠时 |
|
||||
| `true` | 发佣金;如果 `is_new=true`,被邀请人赠时 |
|
||||
|
||||
### 7.2 什么时候发佣金
|
||||
|
||||
`shouldProcessCommission` 规则:
|
||||
|
||||
| 条件 | 结果 |
|
||||
| --- | --- |
|
||||
| 被邀请人为空 | 不发 |
|
||||
| 被邀请人 `referer_id=0` | 不发 |
|
||||
| 查不到邀请人 | 不发 |
|
||||
| 邀请人自定义 `referral_percentage > 0`,且只首购但不是首单 | 不发 |
|
||||
| 邀请人自定义 `referral_percentage > 0`,且通过首购限制 | 发佣金 |
|
||||
| 邀请人无自定义比例,系统 `ReferralPercentage=0` | 不发 |
|
||||
| 系统 `OnlyFirstPurchase=true` 且不是首单 | 不发 |
|
||||
| 系统有比例且通过首购限制 | 发佣金 |
|
||||
|
||||
### 7.3 发佣金路径
|
||||
|
||||
如果 `shouldProcessCommission=true`:
|
||||
|
||||
1. 查询邀请人,也就是 `userInfo.referer_id` 对应用户。
|
||||
2. 佣金比例:
|
||||
- 邀请人自定义比例优先。
|
||||
- 否则用系统配置 `Invite.ReferralPercentage`。
|
||||
3. 佣金金额:
|
||||
|
||||
```text
|
||||
(order.amount - order.fee_amount) * referral_percentage / 100
|
||||
```
|
||||
|
||||
4. 事务内幂等检查:
|
||||
- 如果已有同订单佣金日志,则跳过。
|
||||
- 否则增加邀请人的 `commission`。
|
||||
- 写 `system_logs type=33` 佣金日志。
|
||||
5. 更新邀请人缓存。
|
||||
6. 如果 `order.is_new=true`:
|
||||
- 给被邀请人赠送订阅时间。
|
||||
|
||||
当前保持不变的行为:
|
||||
|
||||
- 邀请人是家庭成员时,佣金仍然给实际邀请人成员本人。
|
||||
- 佣金不归并到家主。
|
||||
- 有佣金路径下,邀请人不额外赠送订阅时间。
|
||||
|
||||
### 7.4 不发佣金路径
|
||||
|
||||
如果 `shouldProcessCommission=false`:
|
||||
|
||||
| `order.is_new` | 行为 |
|
||||
| --- | --- |
|
||||
| `true` | 被邀请人和邀请人双方赠送订阅时间 |
|
||||
| `false` | 不赠送时间 |
|
||||
|
||||
双方赠时具体为:
|
||||
|
||||
1. 被邀请人赠时:
|
||||
- 如果被邀请人是家庭成员,加到被邀请人家主套餐。
|
||||
- 否则加到被邀请人本人套餐。
|
||||
2. 邀请人赠时:
|
||||
- 如果邀请人是家庭成员,加到邀请人家主套餐。
|
||||
- 否则加到邀请人本人套餐。
|
||||
|
||||
## 8. 赠送时间目标解析
|
||||
|
||||
入口:`resolveGiftTargetUser(source, forcedOwnerID)`
|
||||
|
||||
### 8.1 强制 owner 分支
|
||||
|
||||
如果 `forcedOwnerID > 0`:
|
||||
|
||||
- 赠送目标直接使用 `forcedOwnerID`。
|
||||
- 典型场景:订单里已有 `subscription_user_id`。
|
||||
- 这保证了家庭成员购买时,被邀请人的赠时落到家主。
|
||||
|
||||
### 8.2 自动家庭组解析分支
|
||||
|
||||
如果没有强制 owner:
|
||||
|
||||
- 调用 `ResolveEntitlementUser(source.Id)`。
|
||||
- 如果 source 是有效家庭成员,目标改为家主。
|
||||
- 否则目标为本人。
|
||||
|
||||
典型场景:
|
||||
|
||||
- 无佣金路径下,邀请人也赠时。
|
||||
- 邀请人如果是家庭成员,赠时会加到邀请人家主套餐。
|
||||
|
||||
### 8.3 目标用户查询失败
|
||||
|
||||
如果解析出来的目标用户查不到:
|
||||
|
||||
- 记录错误日志。
|
||||
- 回退为 source 本人。
|
||||
|
||||
## 9. 赠送时间落库逻辑
|
||||
|
||||
入口:`grantGiftDays(u, days, orderNo, remark)`
|
||||
|
||||
### 9.1 空值和配置分支
|
||||
|
||||
| 条件 | 行为 |
|
||||
| --- | --- |
|
||||
| 目标用户为空 | 直接返回,不写日志 |
|
||||
| `days <= 0` | 直接返回,不写日志 |
|
||||
|
||||
### 9.2 幂等检查
|
||||
|
||||
按下面条件查 gift 日志:
|
||||
|
||||
```sql
|
||||
type = 34
|
||||
AND object_id = 目标用户 ID
|
||||
AND content LIKE '%订单号%'
|
||||
```
|
||||
|
||||
| 结果 | 行为 |
|
||||
| --- | --- |
|
||||
| 已存在 | 跳过,不重复赠时 |
|
||||
| 不存在 | 继续 |
|
||||
|
||||
### 9.3 查目标用户活跃订阅
|
||||
|
||||
调用 `FindActiveSubscribe`。
|
||||
|
||||
当前活跃口径:
|
||||
|
||||
```sql
|
||||
user_id = 目标用户 ID
|
||||
AND status IN (0, 1)
|
||||
AND (
|
||||
expire_time > NOW()
|
||||
OR expire_time = FROM_UNIXTIME(0)
|
||||
)
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `expire_time > NOW()` 是普通未过期订阅。
|
||||
- `expire_time = FROM_UNIXTIME(0)` 是永久/不限时订阅。
|
||||
|
||||
### 9.4 没有活跃订阅
|
||||
|
||||
如果查不到活跃订阅:
|
||||
|
||||
- 不创建新订阅。
|
||||
- 写一条 `system_logs type=34` 日志。
|
||||
- 日志 remark 为:
|
||||
|
||||
```text
|
||||
邀请赠送 skipped: no active subscription
|
||||
```
|
||||
|
||||
这表示邀请赠时触发过,但目标用户当时没有可加时的套餐。
|
||||
|
||||
### 9.5 找到普通活跃订阅
|
||||
|
||||
如果目标订阅不是永久订阅:
|
||||
|
||||
- `expire_time += days * 24h`
|
||||
- 更新订阅。
|
||||
- 写 `system_logs type=34` gift increase 日志。
|
||||
|
||||
### 9.6 找到永久订阅
|
||||
|
||||
如果目标订阅 `expire_time = FROM_UNIXTIME(0)`:
|
||||
|
||||
- 不改变 `expire_time`,因为永久订阅没有可延长的到期时间。
|
||||
- 仍写 `system_logs type=34` gift increase 日志,表示赠送逻辑已识别并处理。
|
||||
|
||||
### 9.7 赠时失败日志
|
||||
|
||||
发佣金路径和无佣金路径都会检查 `grantGiftDays` 返回错误。
|
||||
|
||||
如果出错,会写应用日志:
|
||||
|
||||
```text
|
||||
Grant invite gift days failed
|
||||
```
|
||||
|
||||
附带字段:
|
||||
|
||||
- `stage`
|
||||
- `target_user_id`
|
||||
- `order_no`
|
||||
- `error`
|
||||
|
||||
## 10. 家庭组下的完整分支示例
|
||||
|
||||
### 10.1 被邀请人是普通用户,邀请人普通用户,有佣金
|
||||
|
||||
条件:
|
||||
|
||||
- 被邀请人 `referer_id != 0`
|
||||
- 系统或邀请人佣金比例大于 0
|
||||
- `order.is_new=true`
|
||||
|
||||
结果:
|
||||
|
||||
- 佣金给邀请人本人。
|
||||
- 被邀请人本人套餐加赠送时间。
|
||||
- 邀请人不加赠送时间。
|
||||
|
||||
### 10.2 被邀请人是家庭成员,邀请人普通用户,有佣金
|
||||
|
||||
结果:
|
||||
|
||||
- 佣金给邀请人本人。
|
||||
- 被邀请人的赠送时间加到被邀请人家主套餐。
|
||||
- 被邀请人成员本人不单独加订阅时间。
|
||||
|
||||
### 10.3 被邀请人普通用户,邀请人是家庭成员,有佣金
|
||||
|
||||
结果:
|
||||
|
||||
- 佣金给邀请人成员本人。
|
||||
- 被邀请人本人套餐加赠送时间。
|
||||
- 邀请人不加赠送时间。
|
||||
- 邀请人家主不拿佣金,也不因该佣金路径加赠时。
|
||||
|
||||
### 10.4 被邀请人是家庭成员,邀请人也是家庭成员,有佣金
|
||||
|
||||
结果:
|
||||
|
||||
- 佣金给邀请人成员本人。
|
||||
- 被邀请人的赠送时间加到被邀请人家主套餐。
|
||||
- 邀请人不加赠送时间。
|
||||
- 邀请人家主不拿佣金。
|
||||
|
||||
### 10.5 无佣金路径,被邀请人普通用户,邀请人普通用户
|
||||
|
||||
触发条件示例:
|
||||
|
||||
- `ReferralPercentage=0`
|
||||
- 或因首购限制导致不发佣金
|
||||
- 且 `order.is_new=true`
|
||||
|
||||
结果:
|
||||
|
||||
- 被邀请人本人套餐加赠送时间。
|
||||
- 邀请人本人套餐加赠送时间。
|
||||
|
||||
### 10.6 无佣金路径,被邀请人是家庭成员
|
||||
|
||||
结果:
|
||||
|
||||
- 被邀请人的赠送时间加到被邀请人家主套餐。
|
||||
- 邀请人的赠时按邀请人自己的家庭归属解析。
|
||||
|
||||
### 10.7 无佣金路径,邀请人是家庭成员
|
||||
|
||||
结果:
|
||||
|
||||
- 被邀请人的赠时按被邀请人的家庭归属解析。
|
||||
- 邀请人的赠送时间加到邀请人家主套餐。
|
||||
- 邀请人成员本人不单独加订阅时间。
|
||||
|
||||
### 10.8 被邀请人没有活跃订阅
|
||||
|
||||
结果:
|
||||
|
||||
- 不创建新订阅。
|
||||
- 写 skipped gift 日志。
|
||||
- 后续即使用户后来有订阅,也不会自动补赠,除非另行补偿。
|
||||
|
||||
### 10.9 被邀请人或目标家主是永久订阅
|
||||
|
||||
结果:
|
||||
|
||||
- 识别为活跃订阅。
|
||||
- 不改变到期时间。
|
||||
- 写 gift increase 日志。
|
||||
|
||||
## 11. 排查 SQL
|
||||
|
||||
### 11.1 查邀请配置
|
||||
|
||||
```sql
|
||||
SELECT `key`, `value`, `updated_at`
|
||||
FROM system
|
||||
WHERE category = 'invite'
|
||||
AND `key` IN ('GiftDays', 'OnlyFirstPurchase', 'ReferralPercentage');
|
||||
```
|
||||
|
||||
### 11.2 查某邀请人的被邀请用户
|
||||
|
||||
```sql
|
||||
SELECT id, referer_id, created_at
|
||||
FROM `user`
|
||||
WHERE referer_id = 23944
|
||||
ORDER BY id DESC
|
||||
LIMIT 100;
|
||||
```
|
||||
|
||||
### 11.3 查被邀请人的订单和首单标记
|
||||
|
||||
```sql
|
||||
SELECT u.id AS invited_user_id,
|
||||
o.id AS order_id,
|
||||
o.order_no,
|
||||
o.type,
|
||||
o.status,
|
||||
o.amount,
|
||||
o.is_new,
|
||||
o.subscribe_id,
|
||||
o.subscription_user_id,
|
||||
o.created_at
|
||||
FROM `user` u
|
||||
LEFT JOIN `order` o
|
||||
ON o.user_id = u.id
|
||||
AND o.type IN (1, 2)
|
||||
WHERE u.referer_id = 23944
|
||||
ORDER BY u.id DESC, o.id ASC
|
||||
LIMIT 200;
|
||||
```
|
||||
|
||||
### 11.4 查某订单佣金和赠时日志
|
||||
|
||||
```sql
|
||||
SELECT id, type, object_id, content, created_at
|
||||
FROM system_logs
|
||||
WHERE content LIKE '%202604281812556044982351822%'
|
||||
ORDER BY id DESC;
|
||||
```
|
||||
|
||||
### 11.5 查某用户订阅
|
||||
|
||||
```sql
|
||||
SELECT id, user_id, order_id, subscribe_id, status,
|
||||
expire_time, finished_at, token, created_at, updated_at
|
||||
FROM user_subscribe
|
||||
WHERE user_id = 24425
|
||||
ORDER BY id DESC;
|
||||
```
|
||||
|
||||
### 11.6 查首单但没有赠时日志的被邀请人
|
||||
|
||||
```sql
|
||||
SELECT first_orders.user_id AS invited_user_id,
|
||||
first_orders.order_no,
|
||||
first_orders.is_new,
|
||||
first_orders.status,
|
||||
first_orders.subscription_user_id,
|
||||
first_orders.created_at,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM system_logs sl
|
||||
WHERE sl.type = 34
|
||||
AND sl.content LIKE CONCAT('%', first_orders.order_no, '%')
|
||||
) AS gift_log_count,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM system_logs sl
|
||||
WHERE sl.type = 33
|
||||
AND sl.content LIKE CONCAT('%', first_orders.order_no, '%')
|
||||
) AS commission_log_count
|
||||
FROM (
|
||||
SELECT o.*
|
||||
FROM `order` o
|
||||
JOIN (
|
||||
SELECT user_id, MIN(id) AS first_order_id
|
||||
FROM `order`
|
||||
WHERE type IN (1, 2)
|
||||
AND status IN (2, 5)
|
||||
GROUP BY user_id
|
||||
) fo ON fo.first_order_id = o.id
|
||||
) first_orders
|
||||
JOIN `user` u ON u.id = first_orders.user_id
|
||||
WHERE u.referer_id = 23944
|
||||
ORDER BY first_orders.created_at DESC
|
||||
LIMIT 100;
|
||||
```
|
||||
|
||||
## 12. 部署注意事项
|
||||
|
||||
邀请配置存在两层状态:
|
||||
|
||||
1. Redis 缓存:`system:invite_config`
|
||||
2. 服务进程内存:`svc.Config.Invite`
|
||||
|
||||
如果直接修改数据库或 Redis,已经运行的 `ppanel-server` 进程不会自动刷新内存配置。订单激活和赠时发生在服务进程/队列 worker 内,所以修改邀请配置或部署赠时逻辑后,需要重启服务。
|
||||
|
||||
推荐步骤:
|
||||
|
||||
```bash
|
||||
docker exec ppanel-redis redis-cli DEL system:invite_config system:global_config
|
||||
docker restart ppanel-server
|
||||
```
|
||||
|
||||
确认启动时间:
|
||||
|
||||
```bash
|
||||
docker inspect --format '{{.Name}} {{.State.StartedAt}} {{.Config.Image}}' ppanel-server
|
||||
docker ps --filter name=ppanel-server
|
||||
```
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# TAPI 文件上传接入说明
|
||||
|
||||
本文档说明 `https://tapi.hifast.biz/v1/public/file/upload` 相关上传接口的推荐接入方式、签名规则与常见排查方式。
|
||||
|
||||
## 总览
|
||||
|
||||
上传能力包含两类接入方式:
|
||||
|
||||
- 推荐方式:`init -> S3 PUT -> complete`
|
||||
- 兼容方式:`/upload` multipart 直传
|
||||
|
||||
推荐优先使用预签名三段式,因为:
|
||||
|
||||
- 现有签名串包含 `BODY_SHA256`
|
||||
- `/upload` 是 `multipart/form-data`
|
||||
- multipart 原始 body 的签名和调试成本更高
|
||||
- `init` 和 `complete` 是 JSON,更适合客户端和 Apifox 调试
|
||||
|
||||
## 签名生效逻辑
|
||||
|
||||
项目保持现有旧逻辑,不做强制签名改造:
|
||||
|
||||
- `Signature.EnableSignature = false` 时:不校验签名
|
||||
- `Signature.EnableSignature = true` 且未携带 `X-App-Id` 时:不校验签名,兼容老客户端
|
||||
- `Signature.EnableSignature = true` 且携带 `X-App-Id` 时:必须同时携带并校验
|
||||
- `X-Timestamp`
|
||||
- `X-Nonce`
|
||||
- `X-Signature`
|
||||
|
||||
这意味着:
|
||||
|
||||
- 新客户端建议始终带完整签名头
|
||||
- 老客户端如果没有 `X-App-Id`,仍可按旧逻辑访问
|
||||
|
||||
## 签名头定义
|
||||
|
||||
- `X-App-Id`: 客户端标识,例如 `ios-client`
|
||||
- `X-Timestamp`: Unix 秒级时间戳
|
||||
- `X-Nonce`: 每次请求唯一随机串
|
||||
- `X-Signature`: `HMAC-SHA256` 结果的十六进制小写字符串
|
||||
|
||||
## StringToSign 规则
|
||||
|
||||
StringToSign 由下面 7 段按换行符 `\n` 拼接:
|
||||
|
||||
```text
|
||||
METHOD
|
||||
PATH
|
||||
CANONICAL_QUERY
|
||||
BODY_SHA256
|
||||
X-App-Id
|
||||
X-Timestamp
|
||||
X-Nonce
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `METHOD`:HTTP 方法大写,例如 `POST`
|
||||
- `PATH`:请求路径,例如 `/v1/public/file/upload/init`
|
||||
- `CANONICAL_QUERY`:按 key 排序后的 query string,没有 query 则为空字符串
|
||||
- `BODY_SHA256`:请求体原始字节的 SHA-256 十六进制小写
|
||||
- 其余三项直接使用请求头值
|
||||
|
||||
签名计算方式:
|
||||
|
||||
```text
|
||||
signature = hex_lower(HMAC_SHA256(app_secret, string_to_sign))
|
||||
```
|
||||
|
||||
时间窗与防重放:
|
||||
|
||||
- `X-Timestamp` 默认有效时间窗是 300 秒
|
||||
- `X-Nonce` 在有效时间窗内不能重复使用
|
||||
|
||||
## 推荐接入:预签名三段式
|
||||
|
||||
### 1. 初始化上传
|
||||
|
||||
请求:
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/init' \
|
||||
-H 'Accept: application/json, text/plain, */*' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H 'authorization: your-token' \
|
||||
-H 'X-App-Id: ios-client' \
|
||||
-H 'X-Timestamp: 1778776400' \
|
||||
-H 'X-Nonce: nonce-001' \
|
||||
-H 'X-Signature: your-signature' \
|
||||
-d '{
|
||||
"biz_type": "app-package",
|
||||
"file_name": "demo.zip",
|
||||
"content_type": "application/zip",
|
||||
"size": 123456,
|
||||
"sha256": ""
|
||||
}'
|
||||
```
|
||||
|
||||
典型返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"data": {
|
||||
"file_id": "c29274ee26ab5aa211e0396e",
|
||||
"object_key": "app-upload/app-package/519/2026/05/c29274ee26ab5aa211e0396e_demo.zip",
|
||||
"upload_url": "https://bucket.s3.ap-east-1.amazonaws.com/...",
|
||||
"method": "PUT",
|
||||
"headers": {
|
||||
"Content-Type": "application/zip"
|
||||
},
|
||||
"expired_at": 1778776715
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 直传 S3
|
||||
|
||||
这一步是直接上传二进制文件到 S3,不走业务签名中间件。
|
||||
|
||||
```bash
|
||||
curl -X PUT 'https://bucket.s3.ap-east-1.amazonaws.com/...' \
|
||||
-H 'Content-Type: application/zip' \
|
||||
--upload-file '/tmp/demo.zip'
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `Content-Type` 需和 `init` 返回的 `headers.Content-Type` 一致
|
||||
- `upload_url` 有过期时间,通常 300 秒
|
||||
- 成功时 S3 常见返回 `200` 或 `204`
|
||||
|
||||
### 3. 完成上传
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/complete' \
|
||||
-H 'Accept: application/json, text/plain, */*' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H 'authorization: your-token' \
|
||||
-H 'X-App-Id: ios-client' \
|
||||
-H 'X-Timestamp: 1778776405' \
|
||||
-H 'X-Nonce: nonce-002' \
|
||||
-H 'X-Signature: your-signature' \
|
||||
-d '{
|
||||
"file_id": "c29274ee26ab5aa211e0396e"
|
||||
}'
|
||||
```
|
||||
|
||||
## 兼容接入:单接口 multipart 直传
|
||||
|
||||
接口:
|
||||
|
||||
- `POST /v1/public/file/upload`
|
||||
|
||||
表单字段:
|
||||
|
||||
- `biz_type`
|
||||
- `file`
|
||||
|
||||
说明:
|
||||
|
||||
- 该接口继续保留,兼容旧客户端
|
||||
- 如果请求带了 `X-App-Id`,就按现有逻辑验签
|
||||
- 如果没有 `X-App-Id`,仍按旧逻辑放行
|
||||
- 如果要给该接口加签,签名时必须对原始 multipart body 计算 `BODY_SHA256`
|
||||
|
||||
## 常见错误码
|
||||
|
||||
- `200`: 成功
|
||||
- `400`: 参数错误
|
||||
- `40008`: 缺少签名头
|
||||
- `40009`: 签名已过期
|
||||
- `40010`: 签名无效
|
||||
- `40011`: nonce 重放
|
||||
- `10001`: 上传元数据不存在或对象不存在
|
||||
|
||||
## 排查建议
|
||||
|
||||
- `40008`:确认带了 `X-App-Id` 后,也同时带上 `X-Timestamp / X-Nonce / X-Signature`
|
||||
- `40009`:检查客户端时间是否偏差过大
|
||||
- `40010`:确认 `PATH`、query 排序、body 原始字节、secret 是否完全一致
|
||||
- `40011`:确保每次请求都生成新的 `X-Nonce`
|
||||
- `complete` 失败:确认 S3 `PUT` 已成功,且上传大小与 `init.size` 一致
|
||||
+20
-133
@@ -6,9 +6,9 @@
|
||||
# 4. 运行: docker-compose -f docker-compose.cloud.yml up -d
|
||||
#
|
||||
# 网络说明:
|
||||
# ppanel-server 使用 host 网络(可出外网,访问 MySQL/Redis/Tempo 用 127.0.0.1)
|
||||
# 监控服务(MySQL/Redis/Loki/Tempo/Grafana/Prometheus)在 ppanel_net bridge 网络中
|
||||
# MySQL(3306)/Redis(6379)/Tempo(4317) 将端口映射到 127.0.0.1,ppanel-server 通过 host 网络访问
|
||||
# ppanel-server 使用 host 网络(可出外网,直接访问 AWS RDS / 本机 Redis)
|
||||
# 监控服务(Loki/Tempo/Grafana/Prometheus)在 ppanel_net bridge 网络中
|
||||
# Tempo(4317) 将端口映射到 127.0.0.1,ppanel-server 通过 host 网络访问
|
||||
# 监控端口绑定 127.0.0.1,需通过 SSH 隧道或 Nginx 反代访问
|
||||
#
|
||||
# 未来多开 ppanel-server 时:
|
||||
@@ -18,7 +18,7 @@
|
||||
services:
|
||||
# ----------------------------------------------------
|
||||
# 1. 业务后端 (PPanel Server)
|
||||
# host 网络:可出外网,通过 127.0.0.1 访问 MySQL/Redis/Tempo
|
||||
# host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo
|
||||
# ----------------------------------------------------
|
||||
ppanel-server:
|
||||
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:-latest}
|
||||
@@ -37,10 +37,6 @@ services:
|
||||
soft: 65535
|
||||
hard: 65535
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
tempo:
|
||||
condition: service_started
|
||||
logging:
|
||||
@@ -50,81 +46,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 2. MySQL Database
|
||||
# ----------------------------------------------------
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
container_name: ppanel-mysql
|
||||
restart: always
|
||||
ports:
|
||||
- "3306:3306" # 仅宿主机可访问,ppanel-server(host网络)通过127.0.0.1连接
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?请在 .env 文件中设置 MYSQL_ROOT_PASSWORD}"
|
||||
MYSQL_DATABASE: "ppanel"
|
||||
TZ: Asia/Shanghai
|
||||
command:
|
||||
- --default-authentication-plugin=mysql_native_password
|
||||
- --innodb_buffer_pool_size=16G
|
||||
- --innodb_buffer_pool_instances=16
|
||||
- --innodb_log_file_size=2G
|
||||
- --innodb_flush_log_at_trx_commit=2
|
||||
- --innodb_io_capacity=5000
|
||||
- --max_connections=5000
|
||||
volumes:
|
||||
- mysql_data:/var/lib/mysql
|
||||
ulimits:
|
||||
nproc: 65535
|
||||
nofile:
|
||||
soft: 65535
|
||||
hard: 65535
|
||||
networks:
|
||||
- ppanel_net
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${MYSQL_ROOT_PASSWORD}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 3. Redis
|
||||
# ----------------------------------------------------
|
||||
redis:
|
||||
image: redis:8.2.1
|
||||
container_name: ppanel-redis
|
||||
restart: always
|
||||
ports:
|
||||
- "127.0.0.1:6379:6379" # 仅宿主机可访问,ppanel-server(host网络)通过127.0.0.1连接
|
||||
command:
|
||||
- redis-server
|
||||
- --tcp-backlog 65535
|
||||
- --maxmemory-policy allkeys-lru
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
ulimits:
|
||||
nproc: 65535
|
||||
nofile:
|
||||
soft: 65535
|
||||
hard: 65535
|
||||
networks:
|
||||
- ppanel_net
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 4. Tempo (链路追踪存储)
|
||||
# 2. Tempo (链路追踪存储)
|
||||
# ----------------------------------------------------
|
||||
tempo:
|
||||
image: grafana/tempo:2.4.1
|
||||
@@ -148,7 +70,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 5. Loki (日志存储)
|
||||
# 3. Loki (日志存储)
|
||||
# ----------------------------------------------------
|
||||
loki:
|
||||
image: grafana/loki:3.0.0
|
||||
@@ -168,7 +90,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 6. Promtail (日志采集)
|
||||
# 4. Promtail (日志采集)
|
||||
# ----------------------------------------------------
|
||||
promtail:
|
||||
image: grafana/promtail:3.0.0
|
||||
@@ -192,7 +114,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 7. Grafana (可观测面板)
|
||||
# 5. Grafana (可观测面板)
|
||||
# 访问: ssh -L 3333:localhost:3333 your-server 后浏览器打开 http://localhost:3333
|
||||
# 或配置 Nginx 反代(建议加认证)
|
||||
# ----------------------------------------------------
|
||||
@@ -201,11 +123,18 @@ services:
|
||||
container_name: ppanel-grafana
|
||||
restart: always
|
||||
ports:
|
||||
- "127.0.0.1:3333:3000" # 仅本机可访问,需 SSH 隧道或 Nginx 反代
|
||||
- "3333:3000" # 仅本机可访问,需 SSH 隧道或 Nginx 反代
|
||||
environment:
|
||||
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:?请在 .env 文件中设置 GRAFANA_PASSWORD}
|
||||
- GF_USERS_ALLOW_SIGN_UP=false
|
||||
- GF_SERVER_DOMAIN=${GRAFANA_DOMAIN:-logsx.hifast.biz}
|
||||
- GF_SERVER_ROOT_URL=${GRAFANA_ROOT_URL:-https://logsx.hifast.biz}
|
||||
- GF_FEATURE_TOGGLES_ENABLE=appObservability
|
||||
- AWS_REGION=${AWS_REGION:-ap-east-1}
|
||||
- AWS_DEFAULT_REGION=${AWS_REGION:-ap-east-1}
|
||||
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:-}
|
||||
- AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY:-}
|
||||
- AWS_SESSION_TOKEN=${AWS_SESSION_TOKEN:-}
|
||||
volumes:
|
||||
- grafana_data:/var/lib/grafana
|
||||
- ./grafana/provisioning:/etc/grafana/provisioning
|
||||
@@ -222,7 +151,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 8. Prometheus (指标采集)
|
||||
# 6. Prometheus (指标采集)
|
||||
# ----------------------------------------------------
|
||||
prometheus:
|
||||
image: prom/prometheus:latest
|
||||
@@ -247,26 +176,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 9. Redis Exporter
|
||||
# ----------------------------------------------------
|
||||
redis-exporter:
|
||||
image: oliver006/redis_exporter:latest
|
||||
container_name: ppanel-redis-exporter
|
||||
restart: always
|
||||
environment:
|
||||
- REDIS_ADDR=redis://redis:6379
|
||||
networks:
|
||||
- ppanel_net
|
||||
depends_on:
|
||||
- redis
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 10. Nginx Exporter (监控宿主机 Nginx)
|
||||
# 7. Nginx Exporter (监控宿主机 Nginx)
|
||||
# ----------------------------------------------------
|
||||
nginx-exporter:
|
||||
image: nginx/nginx-prometheus-exporter:latest
|
||||
@@ -285,28 +195,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 11. MySQL Exporter
|
||||
# ----------------------------------------------------
|
||||
mysql-exporter:
|
||||
image: prom/mysqld-exporter:latest
|
||||
container_name: ppanel-mysql-exporter
|
||||
restart: always
|
||||
command:
|
||||
- --config.my-cnf=/etc/.my.cnf
|
||||
volumes:
|
||||
- ./mysql/.my.cnf:/etc/.my.cnf:ro
|
||||
networks:
|
||||
- ppanel_net
|
||||
depends_on:
|
||||
- mysql
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 12. Node Exporter (宿主机监控)
|
||||
# 8. Node Exporter (宿主机监控)
|
||||
# ----------------------------------------------------
|
||||
node-exporter:
|
||||
image: prom/node-exporter:latest
|
||||
@@ -329,7 +218,7 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
# ----------------------------------------------------
|
||||
# 13. cAdvisor (容器监控)
|
||||
# 9. cAdvisor (容器监控)
|
||||
# ----------------------------------------------------
|
||||
cadvisor:
|
||||
image: gcr.io/cadvisor/cadvisor:latest
|
||||
@@ -350,8 +239,6 @@ services:
|
||||
max-file: "3"
|
||||
|
||||
volumes:
|
||||
mysql_data:
|
||||
redis_data:
|
||||
loki_data:
|
||||
grafana_data:
|
||||
prometheus_data:
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
container_name: ppanel-mysql
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: ppanel_dev
|
||||
MYSQL_DATABASE: ppanel
|
||||
MYSQL_USER: ppanel
|
||||
MYSQL_PASSWORD: ppanel_dev
|
||||
ports:
|
||||
- "3306:3306"
|
||||
volumes:
|
||||
- ppanel_mysql_data:/var/lib/mysql
|
||||
command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-pppanel_dev"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: ppanel-redis
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6379:6379"
|
||||
volumes:
|
||||
- ppanel_redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
ppanel_mysql_data:
|
||||
ppanel_redis_data:
|
||||
+22
-2
@@ -15,10 +15,10 @@ Logger: # 日志配置
|
||||
Level: debug # 日志级别: debug, info, warn, error, panic, fatal
|
||||
|
||||
MySQL:
|
||||
Addr: 154.12.35.103:3306 # host 网络模式; bridge 模式改为 mysql:3306
|
||||
Addr: 45.43.29.127:3306 # host 网络模式; bridge 模式改为 mysql:3306
|
||||
Username: root # MySQL用户名
|
||||
Password: jpcV41ppanel # MySQL密码,与 .env MYSQL_ROOT_PASSWORD 一致
|
||||
Dbname: ppanel # MySQL数据库名
|
||||
Dbname: hifast # MySQL数据库名
|
||||
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
|
||||
MaxIdleConns: 10
|
||||
MaxOpenConns: 100
|
||||
@@ -61,6 +61,21 @@ Trace: # 链路追踪配置 (OpenTelemetry)
|
||||
Batcher: otlpgrpc # 本地开发留空""; 生产填 otlpgrpc
|
||||
Endpoint: "127.0.0.1:4317" # host 网络模式; bridge 模式改为 tempo:4317
|
||||
|
||||
S3:
|
||||
Enable: false
|
||||
Region: ""
|
||||
Bucket: ""
|
||||
Endpoint: ""
|
||||
AccessKey: ""
|
||||
SecretKey: ""
|
||||
SessionToken: ""
|
||||
Prefix: "app-upload"
|
||||
PublicBaseURL: ""
|
||||
UsePathStyle: false
|
||||
PresignExpireSeconds: 300
|
||||
MaxUploadSize: 104857600
|
||||
AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"
|
||||
|
||||
device:
|
||||
enable: true # 开启设备加密通信
|
||||
security_secret: "" # AES加密密钥,需要和App端一致,key=SHA256(security_secret)[:32]
|
||||
@@ -68,3 +83,8 @@ device:
|
||||
Administrator:
|
||||
Email: admin@ppanel.dev # 后台登录邮箱,请修改
|
||||
Password: CHANGE_ME_TO_STRONG_PASSWORD # 后台登录密码,请修改为强密码
|
||||
|
||||
Register:
|
||||
EnableTrial: true
|
||||
EnableTrialEmailWhitelist: true
|
||||
TrialEmailDomainWhitelist: "facebook.com,yahoo.com,qq.com,live.com,outlook.com,msn.com,example.com,go.com,aol.com,free.fr,aliyun.com,163.com,yandex.ru,indiatimes.com,alibaba.com,geocities.com,about.com,naver.com,netscape.com,yahoo.co.jp,earthlink.net,zoho.com,sky.com,mail.ru,angelfire.com,uol.com.br,spb.ru,yandex.com,globo.com,gmail.com,medscape.com,space.com,discovery.com,t-online.de,mac.com,icloud.com,homestead.com,lycos.com,web.id,nus.edu.sg,altavista.com,berlin.de,rambler.ru,pp.ua,comcast.net,sapo.pt,msk.ru,ancestry.com,daum.net,proton.me,law.com,bt.com,techspot.com,icq.com,sina.cn,libero.it,test.com,yourdomain.com,docomo.ne.jp,wp.pl,hotmail.com,orange.fr,onet.pl,me.com,india.com,kansascity.com,wanadoo.fr,fortunecity.com,web.de,terra.com.br,att.net,canada.com,skynet.be,ya.ru,excite.com,detik.com,compuserve.com,ig.com.br,zp.ua,gmx.net,xoom.com,mindspring.com,freeserve.co.uk,interia.pl,excite.co.jp,test.de,shaw.ca,virgilio.it,chez.com,rr.com,freenet.de,ntlworld.com,seznam.cz,arcor.de,tiscali.it,sympatico.ca,sina.com,gazeta.pl,care2.com,yam.com,r7.com,telenet.be,rcn.com,geek.com,sfr.fr,hotbot.com,cox.net,blueyonder.co.uk,tom.com,virginmedia.com,btinternet.com,iinet.net.au,rogers.com,ireland.com,pochta.ru,ozemail.com.au,catholic.org,bluewin.ch,chat.ru,virgin.net,verizon.net,erols.com,lycos.de,lycos.co.uk,protonmail.com,doityourself.com,home.nl,nate.com,casino.com,o2.co.uk,terra.es,mail.com,albawaba.com,126.com,www.com,planet.nl,sanook.com,21cn.com,online.de,name.com,i.ua,centrum.cz,rin.ru,aol.co.uk,voila.fr,walla.co.il,poste.it,netcom.com,parrot.com,charter.net,mydomain.com,mail-tester.com,myway.com,chello.nl,club-internet.fr,sdf.org,tiscali.co.uk,freeuk.com,unican.es,sci.fi,anonymize.com,sify.com,metacrawler.com,go.ro,ivillage.com,telus.net,dailypioneer.com,iespana.es,lycos.es,hey.com,sweb.cz,optusnet.com.au,alice.it,tpg.com.au,hamptonroads.com,saudia.com,lycos.nl,blackplanet.com,frontier.com,looksmart.com,pobox.com,prodigy.net,i.am,freeyellow.com,gmx.com,bigpond.com,crosswinds.net,dejanews.com,wanadoo.es,foxmail.com,eircom.net,islamonline.net,webindia123.com,oath.com,frontiernet.net,hetnet.nl,onmilwaukee.com,ukr.net,bugmenot.com,neuf.fr,kiwibox.com,za.com,iol.it,zonnet.nl,newmail.ru,pacbell.net,cogeco.ca,depechemode.com,concentric.net,aim.com,f5.si,yahoo.jp,terra.com,hot.ee,netzero.net,netins.net,sprynet.com,mailbox.org,mail2web.com,o2.pl,idirect.com,bigfoot.com,netspace.net.au,masrawy.com,supereva.it,yahoo.de,lycos.it,yeah.net,montevideo.com.uy,gmx.de,yahoo.co.uk,yahoofs.com,scubadiving.com,hushmail.com,iprimus.com.au,gportal.hu,swissinfo.org,inbox.com,bolt.com,telstra.com,bellsouth.net,spray.se,c3.hu,attbi.com,talktalk.co.uk,dynu.net,juno.com,yahoo.fr,msn.co.uk,fr.nf,pe.hu,bigpond.net.au,incredimail.com,adelphia.net,elvis.com,interfree.it,starmedia.com,seanet.com,yahoo.com.tw,zip.net,tds.net,she.com,forthnet.gr,land.ru,wow.com,dnsmadeeasy.com,webjump.com,singnet.com.sg,spacewar.com,tin.it,4mg.com,sp.nl,wowway.com,dmv.com,bangkok.com,fastmail.fm,sbcglobal.net,bright.net,usa.com,37.com,aeiou.pt,terra.cl,thirdage.com,btconnect.com,optimum.net,cableone.net,talkcity.com,blogos.com,c2i.net,iwon.com,aver.com,barcelona.com,ddnsfree.com,oi.com.br,lex.bg,roadrunner.com,airmail.net,lawyer.com,yahoo.com.cn,cu.cc,ananzi.co.za,au.ru,pipeline.com,cs.com,3ammagazine.com,gmx.at,qwest.net,btopenworld.com,easypost.com,westnet.com.au,nyc.com,korea.com,front.ru,inbox.lv,yahoo.com.br,ny.com,hispavista.com,abv.bg,mchsi.com,apollo.lv,everyone.net,terra.com.ar,singpost.com,doctor.com,garbage.com,bizhosting.com,go2net.com,clerk.com,games.com,charm.net,onlinehome.de,laposte.net" # 填你的白名单域名,逗号分隔
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
module github.com/perfect-panel/server
|
||||
|
||||
go 1.23.3
|
||||
go 1.24
|
||||
|
||||
require (
|
||||
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f
|
||||
github.com/alibabacloud-go/darabonba-openapi v0.1.18
|
||||
github.com/alibabacloud-go/dysmsapi-20170525/v2 v2.0.18
|
||||
github.com/alibabacloud-go/tea v1.2.2
|
||||
github.com/alicebob/miniredis/v2 v2.34.0
|
||||
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72
|
||||
github.com/andybalholm/brotli v1.1.1
|
||||
github.com/forgoer/openssl v1.6.0
|
||||
@@ -32,7 +31,6 @@ require (
|
||||
github.com/smartwalle/alipay/v3 v3.2.23
|
||||
github.com/spf13/cast v1.7.0 // indirect
|
||||
github.com/spf13/cobra v1.8.1
|
||||
github.com/stretchr/testify v1.10.0
|
||||
github.com/stripe/stripe-go/v81 v81.1.0
|
||||
github.com/twilio/twilio-go v1.23.11
|
||||
go.opentelemetry.io/otel v1.29.0
|
||||
@@ -51,15 +49,19 @@ require (
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/driver/mysql v1.5.7
|
||||
gorm.io/gorm v1.30.0
|
||||
gorm.io/plugin/soft_delete v1.2.1
|
||||
k8s.io/apimachinery v0.31.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Masterminds/sprig/v3 v3.3.0
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.7
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.17
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.16
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0
|
||||
github.com/fatih/color v1.18.0
|
||||
github.com/goccy/go-json v0.10.4
|
||||
github.com/golang-migrate/migrate/v4 v4.18.2
|
||||
github.com/mojocn/base64Captcha v1.3.8
|
||||
github.com/oschwald/geoip2-golang v1.13.0
|
||||
github.com/spaolacci/murmur3 v1.1.0
|
||||
google.golang.org/grpc v1.64.1
|
||||
@@ -79,8 +81,21 @@ require (
|
||||
github.com/alibabacloud-go/tea-utils v1.4.5 // indirect
|
||||
github.com/alibabacloud-go/tea-utils/v2 v2.0.7 // indirect
|
||||
github.com/alibabacloud-go/tea-xml v1.1.3 // indirect
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect
|
||||
github.com/aliyun/credentials-go v1.3.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 // indirect
|
||||
github.com/aws/smithy-go v1.25.1 // indirect
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
|
||||
github.com/bytedance/sonic v1.12.7 // indirect
|
||||
github.com/bytedance/sonic/loader v0.2.3 // indirect
|
||||
@@ -88,7 +103,6 @@ require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/clbanning/mxj/v2 v2.5.6 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sse v1.0.0 // indirect
|
||||
@@ -114,27 +128,22 @@ require (
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mojocn/base64Captcha v1.3.8 // indirect
|
||||
github.com/openzipkin/zipkin-go v0.4.2 // indirect
|
||||
github.com/oschwald/maxminddb-golang v1.13.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
github.com/smartwalle/ncrypto v1.0.4 // indirect
|
||||
github.com/smartwalle/ngx v1.0.9 // indirect
|
||||
github.com/smartwalle/nsign v1.0.9 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/stretchr/objx v0.5.2 // indirect
|
||||
github.com/tjfoc/gmsm v1.4.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.29.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.29.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.3.1 // indirect
|
||||
@@ -150,5 +159,4 @@ require (
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8 // indirect
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gorm.io/driver/sqlite v1.6.0 // indirect
|
||||
)
|
||||
|
||||
@@ -52,10 +52,6 @@ github.com/alibabacloud-go/tea-utils/v2 v2.0.7/go.mod h1:qxn986l+q33J5VkialKMqT/
|
||||
github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
|
||||
github.com/alibabacloud-go/tea-xml v1.1.3 h1:7LYnm+JbOq2B+T/B0fHC4Ies4/FofC4zHzYtqw7dgt0=
|
||||
github.com/alibabacloud-go/tea-xml v1.1.3/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE=
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
|
||||
github.com/alicebob/miniredis/v2 v2.34.0 h1:mBFWMaJSNL9RwdGRyEDoAAv8OQc5UlEhLDQggTglU/0=
|
||||
github.com/alicebob/miniredis/v2 v2.34.0/go.mod h1:kWShP4b58T1CW0Y5dViCd5ztzrDqRWqM3nksiyXk5s8=
|
||||
github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw=
|
||||
github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM=
|
||||
github.com/aliyun/credentials-go v1.3.10 h1:45Xxrae/evfzQL9V10zL3xX31eqgLWEaIdCoPipOEQA=
|
||||
@@ -64,6 +60,42 @@ github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72 h1:
|
||||
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72/go.mod h1:PsJICrlruG9QcJDYuZ0dO/2KtMDALzRbony8NkxZ2nE=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.17 h1:FpL4/758/diKwqbytU0prpuiu60fgXKUWCpDJtApclU=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.17/go.mod h1:OXqUMzgXytfoF9JaKkhrOYsyh72t9G+MJH8mMRaexOE=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.16 h1:r3RJBuU7X9ibt8RHbMjWE6y60QbKBiII6wSrXnapxSU=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.16/go.mod h1:6cx7zqDENJDbBIIWX6P8s0h6hqHC8Avbjh9Dseo27ug=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 h1:UuSfcORqNSz/ey3VPRS8TcVH2Ikf0/sC+Hdj400QI6U=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23/go.mod h1:+G/OSGiOFnSOkYloKj/9M35s74LgVAdJBSD5lsFfqKg=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23/go.mod h1:M8l3mwgx5ToK7wot2sBBce/ojzgnPzZXUV445gTSyE8=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 h1:etqBTKY581iwLL/H/S2sVgk3C9lAsTJFeXWFDsDcWOU=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0/go.mod h1:L2dcoOgS2VSgbPLvpak2NyUPsO1TBN7M45Z4H7DlRc4=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 h1:TdJ+HdzOBhU8+iVAOGUTU63VXopcumCOF1paFulHWZc=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11/go.mod h1:R82ZRExE/nheo0N+T8zHPcLRTcH8MGsnR3BiVGX0TwI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 h1:7byT8HUWrgoRp6sXjxtZwgOKfhss5fW6SkLBtqzgRoE=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17/go.mod h1:xNWknVi4Ezm1vg1QsB/5EWpAJURq22uqd38U8qKvOJc=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 h1:+1Kl1zx6bWi4X7cKi3VYh29h8BvsCoHQEQ6ST9X8w7w=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21/go.mod h1:4vIRDq+CJB2xFAXZ+YgGUTiEft7oAQlhIs71xcSeuVg=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 h1:F/M5Y9I3nwr2IEpshZgh1GeHpOItExNM9L1euNuh/fk=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1/go.mod h1:mTNxImtovCOEEuD65mKW7DCsL+2gjEH+RPEAexAzAio=
|
||||
github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
|
||||
github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A=
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04=
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw=
|
||||
@@ -226,8 +258,6 @@ github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
|
||||
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
@@ -258,9 +288,6 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||
@@ -365,8 +392,6 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
|
||||
github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
|
||||
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
|
||||
@@ -578,20 +603,9 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
|
||||
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
||||
gorm.io/driver/sqlite v1.1.3/go.mod h1:AKDgRWk8lcSQSw+9kxCJnX/yySj8G3rdwYlU57cB45c=
|
||||
gorm.io/driver/sqlite v1.4.4 h1:gIufGoR0dQzjkyqDyYSCvsYR6fba1Gw5YKDqKeChxFc=
|
||||
gorm.io/driver/sqlite v1.4.4/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.20.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
|
||||
gorm.io/gorm v1.23.0/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
|
||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
||||
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
||||
gorm.io/plugin/soft_delete v1.2.1 h1:qx9D/c4Xu6w5KT8LviX8DgLcB9hkKl6JC9f44Tj7cGU=
|
||||
gorm.io/plugin/soft_delete v1.2.1/go.mod h1:Zv7vQctOJTGOsJ/bWgrN1n3od0GBAZgnLjEx+cApLGk=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
k8s.io/apimachinery v0.31.1 h1:mhcUBbj7KUjaVhyXILglcVjuS4nYXiwC+KKFBgIVy7U=
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
apiVersion: 1
|
||||
|
||||
groups:
|
||||
- orgId: 1
|
||||
name: ppanel-core
|
||||
folder: PPanel
|
||||
interval: 1m
|
||||
rules:
|
||||
- uid: ppanel-target-down
|
||||
title: PPanel monitoring target down
|
||||
condition: C
|
||||
for: 2m
|
||||
noDataState: Alerting
|
||||
execErrState: Error
|
||||
annotations:
|
||||
summary: "Monitoring target is down"
|
||||
description: "{{ $labels.job }} on {{ $labels.instance }} has been down for more than 2 minutes."
|
||||
labels:
|
||||
severity: critical
|
||||
service: ppanel
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange:
|
||||
from: 300
|
||||
to: 0
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: prometheus
|
||||
editorMode: code
|
||||
expr: 'up{job=~"grafana|prometheus|node-exporter|cadvisor|nginx-exporter|loki|tempo"}'
|
||||
instant: true
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: A
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model:
|
||||
conditions:
|
||||
- evaluator:
|
||||
params:
|
||||
- 1
|
||||
type: lt
|
||||
operator:
|
||||
type: and
|
||||
query:
|
||||
params:
|
||||
- A
|
||||
reducer:
|
||||
type: last
|
||||
type: query
|
||||
datasource:
|
||||
type: __expr__
|
||||
uid: __expr__
|
||||
expression: A
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: C
|
||||
type: threshold
|
||||
|
||||
- uid: ppanel-host-disk-high
|
||||
title: PPanel host disk usage high
|
||||
condition: C
|
||||
for: 10m
|
||||
noDataState: NoData
|
||||
execErrState: Error
|
||||
annotations:
|
||||
summary: "Host disk usage is high"
|
||||
description: "{{ $labels.instance }} {{ $labels.mountpoint }} disk usage is above 85% for 10 minutes."
|
||||
labels:
|
||||
severity: warning
|
||||
service: ppanel
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange:
|
||||
from: 900
|
||||
to: 0
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: prometheus
|
||||
editorMode: code
|
||||
expr: '100 - (node_filesystem_avail_bytes{fstype!~"tmpfs|overlay|squashfs|aufs",mountpoint!~"/run.*|/var/lib/docker.*"} / node_filesystem_size_bytes{fstype!~"tmpfs|overlay|squashfs|aufs",mountpoint!~"/run.*|/var/lib/docker.*"} * 100)'
|
||||
instant: true
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: A
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model:
|
||||
conditions:
|
||||
- evaluator:
|
||||
params:
|
||||
- 85
|
||||
type: gt
|
||||
operator:
|
||||
type: and
|
||||
query:
|
||||
params:
|
||||
- A
|
||||
reducer:
|
||||
type: last
|
||||
type: query
|
||||
datasource:
|
||||
type: __expr__
|
||||
uid: __expr__
|
||||
expression: A
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: C
|
||||
type: threshold
|
||||
|
||||
- uid: ppanel-host-memory-high
|
||||
title: PPanel host memory usage high
|
||||
condition: C
|
||||
for: 10m
|
||||
noDataState: NoData
|
||||
execErrState: Error
|
||||
annotations:
|
||||
summary: "Host memory usage is high"
|
||||
description: "{{ $labels.instance }} memory usage is above 90% for 10 minutes."
|
||||
labels:
|
||||
severity: warning
|
||||
service: ppanel
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange:
|
||||
from: 900
|
||||
to: 0
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: prometheus
|
||||
editorMode: code
|
||||
expr: '(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100'
|
||||
instant: true
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: A
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model:
|
||||
conditions:
|
||||
- evaluator:
|
||||
params:
|
||||
- 90
|
||||
type: gt
|
||||
operator:
|
||||
type: and
|
||||
query:
|
||||
params:
|
||||
- A
|
||||
reducer:
|
||||
type: last
|
||||
type: query
|
||||
datasource:
|
||||
type: __expr__
|
||||
uid: __expr__
|
||||
expression: A
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: C
|
||||
type: threshold
|
||||
|
||||
- uid: ppanel-host-cpu-high
|
||||
title: PPanel host CPU usage high
|
||||
condition: C
|
||||
for: 10m
|
||||
noDataState: NoData
|
||||
execErrState: Error
|
||||
annotations:
|
||||
summary: "Host CPU usage is high"
|
||||
description: "{{ $labels.instance }} CPU usage is above 90% for 10 minutes."
|
||||
labels:
|
||||
severity: warning
|
||||
service: ppanel
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange:
|
||||
from: 900
|
||||
to: 0
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: prometheus
|
||||
editorMode: code
|
||||
expr: '100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)'
|
||||
instant: true
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: A
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model:
|
||||
conditions:
|
||||
- evaluator:
|
||||
params:
|
||||
- 90
|
||||
type: gt
|
||||
operator:
|
||||
type: and
|
||||
query:
|
||||
params:
|
||||
- A
|
||||
reducer:
|
||||
type: last
|
||||
type: query
|
||||
datasource:
|
||||
type: __expr__
|
||||
uid: __expr__
|
||||
expression: A
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: C
|
||||
type: threshold
|
||||
|
||||
- uid: ppanel-container-restarts
|
||||
title: PPanel container restarted
|
||||
condition: C
|
||||
for: 1m
|
||||
noDataState: NoData
|
||||
execErrState: Error
|
||||
annotations:
|
||||
summary: "Container restarted"
|
||||
description: "{{ $labels.name }} restarted or changed start time in the last hour."
|
||||
labels:
|
||||
severity: warning
|
||||
service: ppanel
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange:
|
||||
from: 3600
|
||||
to: 0
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: prometheus
|
||||
editorMode: code
|
||||
expr: 'sum by (name) (changes(container_start_time_seconds{name!=""}[1h]))'
|
||||
instant: true
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: A
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model:
|
||||
conditions:
|
||||
- evaluator:
|
||||
params:
|
||||
- 0
|
||||
type: gt
|
||||
operator:
|
||||
type: and
|
||||
query:
|
||||
params:
|
||||
- A
|
||||
reducer:
|
||||
type: last
|
||||
type: query
|
||||
datasource:
|
||||
type: __expr__
|
||||
uid: __expr__
|
||||
expression: A
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: C
|
||||
type: threshold
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: PPanel
|
||||
orgId: 1
|
||||
folder: PPanel
|
||||
folderUid: ppanel
|
||||
type: file
|
||||
disableDeletion: false
|
||||
allowUiUpdates: true
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /etc/grafana/provisioning/dashboards/json
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,520 @@
|
||||
{
|
||||
"annotations": {
|
||||
"list": [
|
||||
{
|
||||
"builtIn": 1,
|
||||
"datasource": {
|
||||
"type": "grafana",
|
||||
"uid": "-- Grafana --"
|
||||
},
|
||||
"enable": true,
|
||||
"hide": true,
|
||||
"iconColor": "rgba(0, 211, 255, 1)",
|
||||
"name": "Annotations & Alerts",
|
||||
"type": "dashboard"
|
||||
}
|
||||
]
|
||||
},
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 0,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 3,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 0
|
||||
},
|
||||
"id": 1,
|
||||
"options": {
|
||||
"content": "<b>AWS CloudWatch overview</b><br/>Region: ap-east-1 (Hong Kong)<br/>RDS DBInstanceIdentifier: hifast-mysql-prod-v2<br/>Redis: current production uses a local Docker Redis container (<code>hifast-redis</code>) on EC2 rather than AWS ElastiCache.<br/><br/>This dashboard keeps the RDS CloudWatch panels. Redis should be observed from the local ops dashboard via Prometheus/cAdvisor instead of ElastiCache metrics.",
|
||||
"mode": "html"
|
||||
},
|
||||
"pluginVersion": "11.0.0",
|
||||
"title": "Read Me",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 3
|
||||
},
|
||||
"id": 2,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||
},
|
||||
"metricName": "CPUUtilization",
|
||||
"namespace": "AWS/RDS",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "RDS CPU",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 3
|
||||
},
|
||||
"id": 3,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||
},
|
||||
"metricName": "DatabaseConnections",
|
||||
"namespace": "AWS/RDS",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "RDS Connections",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 3
|
||||
},
|
||||
"id": 4,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||
},
|
||||
"metricName": "FreeStorageSpace",
|
||||
"namespace": "AWS/RDS",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Minimum"
|
||||
}
|
||||
],
|
||||
"title": "RDS Free Storage",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 11
|
||||
},
|
||||
"id": 5,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||
},
|
||||
"metricName": "ReadLatency",
|
||||
"namespace": "AWS/RDS",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||
},
|
||||
"metricName": "WriteLatency",
|
||||
"namespace": "AWS/RDS",
|
||||
"period": "",
|
||||
"refId": "B",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "RDS Read / Write Latency",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "iops"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 11
|
||||
},
|
||||
"id": 6,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||
},
|
||||
"metricName": "ReadIOPS",
|
||||
"namespace": "AWS/RDS",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||
},
|
||||
"metricName": "WriteIOPS",
|
||||
"namespace": "AWS/RDS",
|
||||
"period": "",
|
||||
"refId": "B",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "RDS Read / Write IOPS",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 6,
|
||||
"x": 0,
|
||||
"y": 19
|
||||
},
|
||||
"id": 7,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"ReplicationGroupId": "hifastapp-redis"
|
||||
},
|
||||
"metricName": "CPUUtilization",
|
||||
"namespace": "AWS/ElastiCache",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "Redis Host CPU (Legacy ElastiCache)",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 6,
|
||||
"x": 6,
|
||||
"y": 19
|
||||
},
|
||||
"id": 8,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"ReplicationGroupId": "hifastapp-redis"
|
||||
},
|
||||
"metricName": "EngineCPUUtilization",
|
||||
"namespace": "AWS/ElastiCache",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "Redis Engine CPU (Legacy ElastiCache)",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 6,
|
||||
"x": 12,
|
||||
"y": 19
|
||||
},
|
||||
"id": 9,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"ReplicationGroupId": "hifastapp-redis"
|
||||
},
|
||||
"metricName": "CurrConnections",
|
||||
"namespace": "AWS/ElastiCache",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "Redis Connections (Legacy ElastiCache)",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 6,
|
||||
"x": 18,
|
||||
"y": 19
|
||||
},
|
||||
"id": 10,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "cloudwatch",
|
||||
"uid": "cloudwatch"
|
||||
},
|
||||
"dimensions": {
|
||||
"ReplicationGroupId": "hifastapp-redis"
|
||||
},
|
||||
"metricName": "DatabaseMemoryUsagePercentage",
|
||||
"namespace": "AWS/ElastiCache",
|
||||
"period": "",
|
||||
"refId": "A",
|
||||
"region": "ap-east-1",
|
||||
"statistic": "Average"
|
||||
}
|
||||
],
|
||||
"title": "Redis Memory Usage % (Legacy ElastiCache)",
|
||||
"type": "timeseries"
|
||||
}
|
||||
],
|
||||
"refresh": "30s",
|
||||
"schemaVersion": 39,
|
||||
"style": "dark",
|
||||
"tags": [
|
||||
"aws",
|
||||
"cloudwatch",
|
||||
"rds",
|
||||
"redis"
|
||||
],
|
||||
"templating": {
|
||||
"list": []
|
||||
},
|
||||
"time": {
|
||||
"from": "now-6h",
|
||||
"to": "now"
|
||||
},
|
||||
"timepicker": {},
|
||||
"timezone": "browser",
|
||||
"title": "AWS RDS & Redis Overview",
|
||||
"uid": "aws-rds-redis-overview",
|
||||
"version": 1,
|
||||
"weekStart": ""
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
{
|
||||
"annotations": {
|
||||
"list": [
|
||||
{
|
||||
"builtIn": 1,
|
||||
"datasource": {
|
||||
"type": "grafana",
|
||||
"uid": "-- Grafana --"
|
||||
},
|
||||
"enable": true,
|
||||
"hide": true,
|
||||
"iconColor": "rgba(0, 211, 255, 1)",
|
||||
"name": "Annotations & Alerts",
|
||||
"type": "dashboard"
|
||||
}
|
||||
]
|
||||
},
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 0,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"mappings": [
|
||||
{
|
||||
"options": {
|
||||
"0": {
|
||||
"text": "DOWN"
|
||||
},
|
||||
"1": {
|
||||
"text": "UP"
|
||||
}
|
||||
},
|
||||
"type": "value"
|
||||
}
|
||||
],
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "red",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "green",
|
||||
"value": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 4,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 0
|
||||
},
|
||||
"id": 1,
|
||||
"options": {
|
||||
"colorMode": "background",
|
||||
"graphMode": "none",
|
||||
"justifyMode": "center",
|
||||
"orientation": "horizontal",
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"showPercentChange": false,
|
||||
"textMode": "auto",
|
||||
"wideLayout": true
|
||||
},
|
||||
"pluginVersion": "13.0.1",
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "up{job=~\"prometheus|grafana|node-exporter|cadvisor|nginx-exporter|loki|tempo\"}",
|
||||
"instant": true,
|
||||
"legendFormat": "{{job}}",
|
||||
"range": false,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Service Availability",
|
||||
"type": "stat"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"max": 100,
|
||||
"min": 0,
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "orange",
|
||||
"value": 75
|
||||
},
|
||||
{
|
||||
"color": "red",
|
||||
"value": 90
|
||||
}
|
||||
]
|
||||
},
|
||||
"unit": "percent"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 4
|
||||
},
|
||||
"id": 2,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "100 - (avg by (instance) (rate(node_cpu_seconds_total{mode=\"idle\"}[5m])) * 100)",
|
||||
"legendFormat": "{{instance}} CPU",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Host CPU Usage",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"max": 100,
|
||||
"min": 0,
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "orange",
|
||||
"value": 80
|
||||
},
|
||||
{
|
||||
"color": "red",
|
||||
"value": 90
|
||||
}
|
||||
]
|
||||
},
|
||||
"unit": "percent"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 4
|
||||
},
|
||||
"id": 3,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100",
|
||||
"legendFormat": "{{instance}} memory",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Host Memory Usage",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"max": 100,
|
||||
"min": 0,
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "orange",
|
||||
"value": 80
|
||||
},
|
||||
{
|
||||
"color": "red",
|
||||
"value": 90
|
||||
}
|
||||
]
|
||||
},
|
||||
"unit": "percent"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 4
|
||||
},
|
||||
"id": 4,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "100 - (node_filesystem_avail_bytes{fstype!~\"tmpfs|overlay|squashfs|aufs\",mountpoint!~\"/run.*|/var/lib/docker.*\"} / node_filesystem_size_bytes{fstype!~\"tmpfs|overlay|squashfs|aufs\",mountpoint!~\"/run.*|/var/lib/docker.*\"} * 100)",
|
||||
"legendFormat": "{{mountpoint}}",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Host Disk Usage",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 12
|
||||
},
|
||||
"id": 5,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (name) (rate(container_cpu_usage_seconds_total{name!=\"\"}[5m]))",
|
||||
"legendFormat": "{{name}}",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Container CPU",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 12
|
||||
},
|
||||
"id": 6,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (name) (container_memory_working_set_bytes{name!=\"\"})",
|
||||
"legendFormat": "{{name}}",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Container Memory",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 12
|
||||
},
|
||||
"id": 7,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (name) (changes(container_start_time_seconds{name!=\"\"}[1h]))",
|
||||
"legendFormat": "{{name}}",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Container Restarts / Changes",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 20
|
||||
},
|
||||
"id": 8,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "single"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "rate(nginx_http_requests_total[5m])",
|
||||
"legendFormat": "requests",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Nginx Requests",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 20
|
||||
},
|
||||
"id": 9,
|
||||
"options": {
|
||||
"dedupStrategy": "none",
|
||||
"enableLogDetails": true,
|
||||
"prettifyLogMessage": false,
|
||||
"showCommonLabels": false,
|
||||
"showLabels": true,
|
||||
"showTime": true,
|
||||
"sortOrder": "Descending",
|
||||
"wrapLogMessage": true
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "{job=~\"ppanel-server|nginx|docker\"} |~ \"(?i)(error|panic|fatal|timeout|exception|failed)\"",
|
||||
"queryType": "range",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Recent Errors",
|
||||
"type": "logs"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 20
|
||||
},
|
||||
"id": 10,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (service_name) (rate(traces_spanmetrics_calls_total[5m]))",
|
||||
"legendFormat": "{{service_name}}",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Trace Span Calls",
|
||||
"type": "timeseries"
|
||||
}
|
||||
],
|
||||
"refresh": "30s",
|
||||
"schemaVersion": 42,
|
||||
"tags": [
|
||||
"ppanel",
|
||||
"ops",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo"
|
||||
],
|
||||
"templating": {
|
||||
"list": []
|
||||
},
|
||||
"time": {
|
||||
"from": "now-6h",
|
||||
"to": "now"
|
||||
},
|
||||
"timepicker": {},
|
||||
"timezone": "browser",
|
||||
"title": "PPanel Ops Overview",
|
||||
"uid": "ppanel-ops-overview",
|
||||
"version": 1,
|
||||
"weekStart": ""
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
{
|
||||
"annotations": {
|
||||
"list": [
|
||||
{
|
||||
"builtIn": 1,
|
||||
"datasource": {
|
||||
"type": "grafana",
|
||||
"uid": "-- Grafana --"
|
||||
},
|
||||
"enable": true,
|
||||
"hide": true,
|
||||
"iconColor": "rgba(0, 211, 255, 1)",
|
||||
"name": "Annotations & Alerts",
|
||||
"type": "dashboard"
|
||||
}
|
||||
]
|
||||
},
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 0,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 7,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 0
|
||||
},
|
||||
"id": 1,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum(count_over_time({compose_service=\"ppanel-server\"}[5m]))",
|
||||
"queryType": "range",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Matched Log Volume",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 7,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 0
|
||||
},
|
||||
"id": 2,
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "table",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum(count_over_time({compose_service=\"ppanel-server\"} |~ \"(?i)(error|panic|fatal)\" [5m]))",
|
||||
"queryType": "range",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Matched Error Volume",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 12,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 7
|
||||
},
|
||||
"id": 3,
|
||||
"options": {
|
||||
"dedupStrategy": "none",
|
||||
"enableLogDetails": true,
|
||||
"prettifyLogMessage": false,
|
||||
"showCommonLabels": false,
|
||||
"showLabels": true,
|
||||
"showTime": true,
|
||||
"sortOrder": "Descending",
|
||||
"wrapLogMessage": true
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "{compose_service=\"ppanel-server\"}",
|
||||
"queryType": "range",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Filtered Server Logs",
|
||||
"type": "logs"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 10,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 19
|
||||
},
|
||||
"id": 4,
|
||||
"options": {
|
||||
"dedupStrategy": "none",
|
||||
"enableLogDetails": true,
|
||||
"prettifyLogMessage": false,
|
||||
"showCommonLabels": false,
|
||||
"showLabels": true,
|
||||
"showTime": true,
|
||||
"sortOrder": "Descending",
|
||||
"wrapLogMessage": true
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "P8E80F9AEF21F6940"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "{compose_service=\"ppanel-server\"} |~ \"(?i)(error|panic|fatal)\"",
|
||||
"queryType": "range",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"title": "Filtered Server Errors",
|
||||
"type": "logs"
|
||||
}
|
||||
],
|
||||
"refresh": "30s",
|
||||
"schemaVersion": 42,
|
||||
"tags": [
|
||||
"ppanel",
|
||||
"logs",
|
||||
"server",
|
||||
"loki"
|
||||
],
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"current": {
|
||||
"selected": false,
|
||||
"text": ".",
|
||||
"value": "."
|
||||
},
|
||||
"description": "输入用户 ID;默认 . 表示不过滤",
|
||||
"hide": 0,
|
||||
"label": "用户ID",
|
||||
"name": "user_id",
|
||||
"options": [],
|
||||
"query": ".",
|
||||
"skipUrlSync": false,
|
||||
"type": "textbox"
|
||||
},
|
||||
{
|
||||
"current": {
|
||||
"selected": false,
|
||||
"text": ".",
|
||||
"value": "."
|
||||
},
|
||||
"description": "输入邮箱或邮箱片段;默认 . 表示不过滤",
|
||||
"hide": 0,
|
||||
"label": "邮箱",
|
||||
"name": "email",
|
||||
"options": [],
|
||||
"query": ".",
|
||||
"skipUrlSync": false,
|
||||
"type": "textbox"
|
||||
},
|
||||
{
|
||||
"current": {
|
||||
"selected": false,
|
||||
"text": ".",
|
||||
"value": "."
|
||||
},
|
||||
"description": "输入订单号/支付单号/交易号片段;默认 . 表示不过滤",
|
||||
"hide": 0,
|
||||
"label": "订单",
|
||||
"name": "order",
|
||||
"options": [],
|
||||
"query": ".",
|
||||
"skipUrlSync": false,
|
||||
"type": "textbox"
|
||||
},
|
||||
{
|
||||
"current": {
|
||||
"selected": true,
|
||||
"text": "All",
|
||||
"value": "."
|
||||
},
|
||||
"description": "日志等级",
|
||||
"hide": 0,
|
||||
"includeAll": false,
|
||||
"label": "等级",
|
||||
"multi": false,
|
||||
"name": "level",
|
||||
"options": [
|
||||
{
|
||||
"selected": true,
|
||||
"text": "All",
|
||||
"value": "."
|
||||
},
|
||||
{
|
||||
"selected": false,
|
||||
"text": "debug",
|
||||
"value": "debug"
|
||||
},
|
||||
{
|
||||
"selected": false,
|
||||
"text": "info",
|
||||
"value": "info"
|
||||
},
|
||||
{
|
||||
"selected": false,
|
||||
"text": "warn",
|
||||
"value": "warn"
|
||||
},
|
||||
{
|
||||
"selected": false,
|
||||
"text": "error",
|
||||
"value": "error"
|
||||
},
|
||||
{
|
||||
"selected": false,
|
||||
"text": "slow",
|
||||
"value": "slow"
|
||||
},
|
||||
{
|
||||
"selected": false,
|
||||
"text": "panic",
|
||||
"value": "panic"
|
||||
},
|
||||
{
|
||||
"selected": false,
|
||||
"text": "fatal",
|
||||
"value": "fatal"
|
||||
}
|
||||
],
|
||||
"query": "All : .,debug,info,warn,error,slow,panic,fatal",
|
||||
"queryValue": "",
|
||||
"skipUrlSync": false,
|
||||
"type": "custom"
|
||||
},
|
||||
{
|
||||
"current": {
|
||||
"selected": false,
|
||||
"text": ".",
|
||||
"value": "."
|
||||
},
|
||||
"description": "任意关键字;默认 . 表示不过滤",
|
||||
"hide": 0,
|
||||
"label": "关键字",
|
||||
"name": "keyword",
|
||||
"options": [],
|
||||
"query": ".",
|
||||
"skipUrlSync": false,
|
||||
"type": "textbox"
|
||||
}
|
||||
]
|
||||
},
|
||||
"time": {
|
||||
"from": "now-1h",
|
||||
"to": "now"
|
||||
},
|
||||
"timepicker": {},
|
||||
"timezone": "browser",
|
||||
"title": "PPanel Server Logs",
|
||||
"uid": "ppanel-server-logs",
|
||||
"version": 5,
|
||||
"weekStart": ""
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: true
|
||||
jsonData:
|
||||
httpMethod: POST
|
||||
manageAlerts: true
|
||||
prometheusType: Prometheus
|
||||
prometheusVersion: 2.50.0
|
||||
timeInterval: 15s
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: true
|
||||
jsonData:
|
||||
derivedFields:
|
||||
- datasourceUid: tempo
|
||||
matcherRegex: '"(?:trace|traceID|trace_id)"\s*:\s*"([a-f0-9]{32})"'
|
||||
name: TraceID
|
||||
url: '$${__value.raw}'
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: true
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
tags:
|
||||
- key: service.name
|
||||
value: service_name
|
||||
tracesToMetrics:
|
||||
datasourceUid: prometheus
|
||||
serviceMap:
|
||||
datasourceUid: prometheus
|
||||
|
||||
- name: CloudWatch
|
||||
uid: cloudwatch
|
||||
type: cloudwatch
|
||||
access: proxy
|
||||
editable: true
|
||||
jsonData:
|
||||
authType: default
|
||||
defaultRegion: ap-east-1
|
||||
@@ -449,7 +449,7 @@ CREATE TABLE IF NOT EXISTS `user_device`
|
||||
`subscribe_id` bigint DEFAULT NULL COMMENT 'Subscribe ID',
|
||||
`ip` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Ip.',
|
||||
`Identifier` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Identifier.',
|
||||
`user_agent` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device User Agent.',
|
||||
`user_agent` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device User Agent.',
|
||||
`online` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Online',
|
||||
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'EnableDeviceNumber',
|
||||
`created_at` datetime(3) DEFAULT NULL COMMENT 'Creation Time',
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `user_device` DROP COLUMN `base_payload`;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `user_device` ADD COLUMN `base_payload` TEXT DEFAULT NULL COMMENT 'Base Payload' AFTER `short_code`;
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS `order_recovery_claims`;
|
||||
@@ -0,0 +1,15 @@
|
||||
CREATE TABLE IF NOT EXISTS `order_recovery_claims` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`order_no` VARCHAR(255) NOT NULL COMMENT 'Recovered Order No',
|
||||
`email` VARCHAR(255) NOT NULL COMMENT 'Claim Email',
|
||||
`user_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'User ID',
|
||||
`subscribe_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'Subscribe ID',
|
||||
`order_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'Recovered Order ID',
|
||||
`user_subscribe_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'User Subscribe ID',
|
||||
`claimed_at` DATETIME(3) NOT NULL COMMENT 'Claimed Time',
|
||||
`created_at` DATETIME(3) DEFAULT NULL COMMENT 'Creation Time',
|
||||
`updated_at` DATETIME(3) DEFAULT NULL COMMENT 'Update Time',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `idx_order_recovery_claim_order_no` (`order_no`),
|
||||
KEY `idx_order_recovery_claim_email` (`email`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE `log_message`
|
||||
MODIFY COLUMN `app_version` VARCHAR(32) NULL,
|
||||
MODIFY COLUMN `os_name` VARCHAR(32) NULL,
|
||||
MODIFY COLUMN `os_version` VARCHAR(32) NULL,
|
||||
MODIFY COLUMN `device_id` VARCHAR(64) NULL,
|
||||
MODIFY COLUMN `session_id` VARCHAR(64) NULL,
|
||||
MODIFY COLUMN `error_code` VARCHAR(64) NULL;
|
||||
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE `log_message`
|
||||
MODIFY COLUMN `app_version` VARCHAR(64) NULL,
|
||||
MODIFY COLUMN `os_name` VARCHAR(64) NULL,
|
||||
MODIFY COLUMN `os_version` VARCHAR(64) NULL,
|
||||
MODIFY COLUMN `device_id` VARCHAR(255) NULL,
|
||||
MODIFY COLUMN `session_id` VARCHAR(255) NULL,
|
||||
MODIFY COLUMN `error_code` VARCHAR(128) NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `user_device`
|
||||
MODIFY COLUMN `user_agent` VARCHAR(64) NULL COMMENT 'Device User Agent.';
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `user_device`
|
||||
MODIFY COLUMN `user_agent` VARCHAR(255) NULL COMMENT 'Device User Agent.';
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
)
|
||||
@@ -17,7 +16,7 @@ func Register(ctx *svc.ServiceContext) {
|
||||
logger.Errorf("[Init Register Config] Get Register Config Error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
var registerConfig config.RegisterConfig
|
||||
registerConfig := ctx.Config.Register
|
||||
tool.SystemConfigSliceReflectToStruct(configs, ®isterConfig)
|
||||
ctx.Config.Register = registerConfig
|
||||
}
|
||||
|
||||
@@ -20,6 +20,14 @@ type schemaColumnPatch struct {
|
||||
ddl string
|
||||
}
|
||||
|
||||
type schemaColumnDefinitionPatch struct {
|
||||
table string
|
||||
column string
|
||||
dataType string
|
||||
characterMaxLen *int64
|
||||
ddl string
|
||||
}
|
||||
|
||||
func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
|
||||
tablePatches := []schemaTablePatch{
|
||||
{
|
||||
@@ -142,6 +150,17 @@ func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
|
||||
},
|
||||
}
|
||||
|
||||
varchar255 := int64(255)
|
||||
columnDefinitionPatches := []schemaColumnDefinitionPatch{
|
||||
{
|
||||
table: "user_device",
|
||||
column: "user_agent",
|
||||
dataType: "varchar",
|
||||
characterMaxLen: &varchar255,
|
||||
ddl: "ALTER TABLE `user_device` MODIFY COLUMN `user_agent` VARCHAR(255) NULL COMMENT 'Device User Agent.';",
|
||||
},
|
||||
}
|
||||
|
||||
for _, patch := range tablePatches {
|
||||
exists, err := tableExists(ctx.DB, patch.table)
|
||||
if err != nil {
|
||||
@@ -199,6 +218,27 @@ func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
|
||||
logger.Infof("[SchemaCompat] created missing index: %s.%s", patch.table, patch.index)
|
||||
}
|
||||
|
||||
for _, patch := range columnDefinitionPatches {
|
||||
tblExists, err := tableExists(ctx.DB, patch.table)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "check table %s failed", patch.table)
|
||||
}
|
||||
if !tblExists {
|
||||
continue
|
||||
}
|
||||
matches, err := columnDefinitionMatches(ctx.DB, patch.table, patch.column, patch.dataType, patch.characterMaxLen)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "check column definition %s.%s failed", patch.table, patch.column)
|
||||
}
|
||||
if matches {
|
||||
continue
|
||||
}
|
||||
if err = ctx.DB.Exec(patch.ddl).Error; err != nil {
|
||||
return errors.Wrapf(err, "modify column %s.%s failed", patch.table, patch.column)
|
||||
}
|
||||
logger.Infof("[SchemaCompat] repaired column definition: %s.%s", patch.table, patch.column)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -237,6 +277,38 @@ func indexExists(db *gorm.DB, table, index string) (bool, error) {
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func columnDefinitionMatches(db *gorm.DB, table, column, dataType string, characterMaxLen *int64) (bool, error) {
|
||||
type columnMeta struct {
|
||||
DataType string
|
||||
CharacterMaximumLen *int64
|
||||
}
|
||||
|
||||
var meta columnMeta
|
||||
err := db.Raw(
|
||||
`SELECT DATA_TYPE AS data_type, CHARACTER_MAXIMUM_LENGTH AS character_maximum_len
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
|
||||
table,
|
||||
column,
|
||||
).Scan(&meta).Error
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if meta.DataType == "" {
|
||||
return false, nil
|
||||
}
|
||||
if meta.DataType != dataType {
|
||||
return false, nil
|
||||
}
|
||||
if characterMaxLen == nil {
|
||||
return true, nil
|
||||
}
|
||||
if meta.CharacterMaximumLen == nil {
|
||||
return false, nil
|
||||
}
|
||||
return *meta.CharacterMaximumLen == *characterMaxLen, nil
|
||||
}
|
||||
|
||||
func _schemaCompatDebug(table, column string) string {
|
||||
if column == "" {
|
||||
return table
|
||||
|
||||
@@ -38,12 +38,29 @@ type Config struct {
|
||||
Log Log `yaml:"Log"`
|
||||
Currency Currency `yaml:"Currency"`
|
||||
Trace trace.Config `yaml:"Trace"`
|
||||
S3 S3Config `yaml:"S3"`
|
||||
Administrator struct {
|
||||
Email string `yaml:"Email" default:"admin@ppanel.dev"`
|
||||
Password string `yaml:"Password" default:"password"`
|
||||
} `yaml:"Administrator"`
|
||||
}
|
||||
|
||||
type S3Config struct {
|
||||
Enable bool `yaml:"Enable" default:"false"`
|
||||
Region string `yaml:"Region" default:""`
|
||||
Bucket string `yaml:"Bucket" default:""`
|
||||
Endpoint string `yaml:"Endpoint" default:""`
|
||||
AccessKey string `yaml:"AccessKey" default:""`
|
||||
SecretKey string `yaml:"SecretKey" default:""`
|
||||
SessionToken string `yaml:"SessionToken" default:""`
|
||||
Prefix string `yaml:"Prefix" default:"app-upload"`
|
||||
PublicBaseURL string `yaml:"PublicBaseURL" default:""`
|
||||
UsePathStyle bool `yaml:"UsePathStyle" default:"false"`
|
||||
PresignExpireSeconds int64 `yaml:"PresignExpireSeconds" default:"300"`
|
||||
MaxUploadSize int64 `yaml:"MaxUploadSize" default:"104857600"`
|
||||
AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"`
|
||||
}
|
||||
|
||||
type RedisConfig struct {
|
||||
Host string `yaml:"Host" default:"localhost:6379"`
|
||||
Pass string `yaml:"Pass" default:""`
|
||||
@@ -84,9 +101,11 @@ type SubscribeConfig struct {
|
||||
type RegisterConfig struct {
|
||||
StopRegister bool `yaml:"StopRegister" default:"false"`
|
||||
EnableTrial bool `yaml:"EnableTrial" default:"false"`
|
||||
EnableTrialEmailWhitelist bool `yaml:"EnableTrialEmailWhitelist" default:"true"`
|
||||
TrialSubscribe int64 `yaml:"TrialSubscribe" default:"0"`
|
||||
TrialTime int64 `yaml:"TrialTime" default:"0"`
|
||||
TrialTimeUnit string `yaml:"TrialTimeUnit" default:""`
|
||||
TrialEmailDomainWhitelist string `yaml:"TrialEmailDomainWhitelist" default:""`
|
||||
IpRegisterLimit int64 `yaml:"IpRegisterLimit" default:"0"`
|
||||
IpRegisterLimitDuration int64 `yaml:"IpRegisterLimitDuration" default:"0"`
|
||||
EnableIpRegisterLimit bool `yaml:"EnableIpRegisterLimit" default:"false"`
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Approve withdrawal
|
||||
func ApproveWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.ApproveWithdrawalRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewApproveWithdrawalLogic(c.Request.Context(), svcCtx)
|
||||
err := l.ApproveWithdrawal(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Get withdrawal list
|
||||
func GetWithdrawalListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetWithdrawalListRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewGetWithdrawalListLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetWithdrawalList(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Reject withdrawal
|
||||
func RejectWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.RejectWithdrawalRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewRejectWithdrawalLogic(c.Request.Context(), svcCtx)
|
||||
err := l.RejectWithdrawal(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/auth/admin"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Verify slider captcha
|
||||
func AdminSliderVerifyCaptchaHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.SliderVerifyCaptchaRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := admin.NewAdminSliderVerifyCaptchaLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.AdminSliderVerifyCaptcha(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/auth"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Verify slider captcha
|
||||
func SliderVerifyCaptchaHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.SliderVerifyCaptchaRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := auth.NewSliderVerifyCaptchaLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.SliderVerifyCaptcha(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/auth"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// User Telephone register
|
||||
func TelephoneRegisterHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.TelephoneRegisterRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := auth.NewTelephoneRegisterLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.TelephoneRegister(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/public/file"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Complete file upload
|
||||
func FileUploadCompleteHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.FileUploadCompleteRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := file.NewFileUploadCompleteLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.FileUploadComplete(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"mime/multipart"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/public/file"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Upload file to RustFS
|
||||
func FileUploadHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.FileUploadRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
fileHeader, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
fileReader, err := fileHeader.Open()
|
||||
if err != nil {
|
||||
result.HttpResult(c, nil, err)
|
||||
return
|
||||
}
|
||||
defer func(file multipart.File) {
|
||||
_ = file.Close()
|
||||
}(fileReader)
|
||||
|
||||
l := file.NewFileUploadLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.FileUpload(&req, fileHeader, fileReader)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/public/file"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Init file upload
|
||||
func FileUploadInitHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.FileUploadInitRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := file.NewFileUploadInitLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.FileUploadInit(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/public/recovery"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func RecoverOrderHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.RecoverOrderRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := recovery.NewRecoverOrderLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.RecoverOrder(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/public/recovery"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func SendCodeHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.RecoverySendCodeRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := recovery.NewSendCodeLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.SendCode(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -30,10 +30,12 @@ import (
|
||||
common "github.com/perfect-panel/server/internal/handler/common"
|
||||
publicAnnouncement "github.com/perfect-panel/server/internal/handler/public/announcement"
|
||||
publicDocument "github.com/perfect-panel/server/internal/handler/public/document"
|
||||
publicFile "github.com/perfect-panel/server/internal/handler/public/file"
|
||||
publicIapApple "github.com/perfect-panel/server/internal/handler/public/iap/apple"
|
||||
publicOrder "github.com/perfect-panel/server/internal/handler/public/order"
|
||||
publicPayment "github.com/perfect-panel/server/internal/handler/public/payment"
|
||||
publicPortal "github.com/perfect-panel/server/internal/handler/public/portal"
|
||||
publicRecovery "github.com/perfect-panel/server/internal/handler/public/recovery"
|
||||
publicRedemption "github.com/perfect-panel/server/internal/handler/public/redemption"
|
||||
publicSubscribe "github.com/perfect-panel/server/internal/handler/public/subscribe"
|
||||
publicTicket "github.com/perfect-panel/server/internal/handler/public/ticket"
|
||||
@@ -321,6 +323,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
|
||||
// Query quota task pre-count
|
||||
adminMarketingGroupRouter.POST("/quota/pre-count", adminMarketing.QueryQuotaTaskPreCountHandler(serverCtx))
|
||||
|
||||
// Query quota task status
|
||||
adminMarketingGroupRouter.POST("/quota/status", adminMarketing.QueryQuotaTaskStatusHandler(serverCtx))
|
||||
}
|
||||
|
||||
adminOrderGroupRouter := router.Group("/v1/admin/order")
|
||||
@@ -702,6 +707,15 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
|
||||
// Get admin user invite list
|
||||
adminUserGroupRouter.GET("/invite/list", adminUser.GetAdminUserInviteListHandler(serverCtx))
|
||||
|
||||
// Get withdrawal list
|
||||
adminUserGroupRouter.GET("/withdrawal/list", adminUser.GetWithdrawalListHandler(serverCtx))
|
||||
|
||||
// Approve withdrawal
|
||||
adminUserGroupRouter.POST("/withdrawal/approve", adminUser.ApproveWithdrawalHandler(serverCtx))
|
||||
|
||||
// Reject withdrawal
|
||||
adminUserGroupRouter.POST("/withdrawal/reject", adminUser.RejectWithdrawalHandler(serverCtx))
|
||||
}
|
||||
|
||||
authGroupRouter := router.Group("/v1/auth")
|
||||
@@ -711,6 +725,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
// Generate captcha
|
||||
authGroupRouter.POST("/captcha/generate", auth.GenerateCaptchaHandler(serverCtx))
|
||||
|
||||
// Verify slider captcha
|
||||
authGroupRouter.POST("/captcha/slider/verify", auth.SliderVerifyCaptchaHandler(serverCtx))
|
||||
|
||||
// Check user is exist
|
||||
authGroupRouter.GET("/check", auth.CheckUserHandler(serverCtx))
|
||||
|
||||
@@ -733,12 +750,12 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
authGroupRouter.POST("/register", auth.UserRegisterHandler(serverCtx))
|
||||
|
||||
// User Telephone register
|
||||
authGroupRouter.POST("/register/telephone", auth.TelephoneUserRegisterHandler(serverCtx))
|
||||
authGroupRouter.POST("/register/telephone", auth.TelephoneRegisterHandler(serverCtx))
|
||||
|
||||
// Reset password
|
||||
authGroupRouter.POST("/reset", auth.ResetPasswordHandler(serverCtx))
|
||||
|
||||
// Reset password
|
||||
// Reset password by telephone
|
||||
authGroupRouter.POST("/reset/telephone", auth.TelephoneResetPasswordHandler(serverCtx))
|
||||
}
|
||||
|
||||
@@ -749,6 +766,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
// Generate captcha
|
||||
authAdminGroupRouter.POST("/captcha/generate", authAdmin.AdminGenerateCaptchaHandler(serverCtx))
|
||||
|
||||
// Verify slider captcha
|
||||
authAdminGroupRouter.POST("/captcha/slider/verify", authAdmin.AdminSliderVerifyCaptchaHandler(serverCtx))
|
||||
|
||||
// Admin login
|
||||
authAdminGroupRouter.POST("/login", authAdmin.AdminLoginHandler(serverCtx))
|
||||
|
||||
@@ -808,6 +828,15 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
|
||||
// Submit contact info
|
||||
commonGroupRouter.POST("/contact", common.SubmitContactHandler(serverCtx))
|
||||
|
||||
// Report log message
|
||||
commonGroupRouter.POST("/log/report", common.ReportLogMessageHandler(serverCtx))
|
||||
|
||||
// Check verification code (legacy v1)
|
||||
commonGroupRouter.POST("/check_code", auth.CheckCodeLegacyV1Handler(serverCtx))
|
||||
|
||||
// Check verification code (legacy v2, consume code)
|
||||
commonGroupRouter.POST("/check_code/v2", auth.CheckCodeLegacyV2Handler(serverCtx))
|
||||
}
|
||||
|
||||
publicAnnouncementGroupRouter := router.Group("/v1/public/announcement")
|
||||
@@ -846,6 +875,20 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
publicDocumentGroupRouter.GET("/list", publicDocument.QueryDocumentListHandler(serverCtx))
|
||||
}
|
||||
|
||||
publicFileGroupRouter := router.Group("/v1/public/file")
|
||||
publicFileGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||
|
||||
{
|
||||
// Upload file to RustFS
|
||||
publicFileGroupRouter.POST("/upload", publicFile.FileUploadHandler(serverCtx))
|
||||
|
||||
// Init file upload
|
||||
publicFileGroupRouter.POST("/upload/init", publicFile.FileUploadInitHandler(serverCtx))
|
||||
|
||||
// Complete file upload
|
||||
publicFileGroupRouter.POST("/upload/complete", publicFile.FileUploadCompleteHandler(serverCtx))
|
||||
}
|
||||
|
||||
publicOrderGroupRouter := router.Group("/v1/public/order")
|
||||
publicOrderGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||
|
||||
@@ -914,6 +957,17 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
publicRedemptionGroupRouter.POST("/", publicRedemption.RedeemCodeHandler(serverCtx))
|
||||
}
|
||||
|
||||
publicRecoveryGroupRouter := router.Group("/v1/public/recovery")
|
||||
publicRecoveryGroupRouter.Use(middleware.DeviceMiddleware(serverCtx))
|
||||
|
||||
{
|
||||
// Send recovery verification code
|
||||
publicRecoveryGroupRouter.POST("/send_code", publicRecovery.SendCodeHandler(serverCtx))
|
||||
|
||||
// Recover order subscription
|
||||
publicRecoveryGroupRouter.POST("/order", publicRecovery.RecoverOrderHandler(serverCtx))
|
||||
}
|
||||
|
||||
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
||||
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||
|
||||
@@ -923,6 +977,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
|
||||
// Get user subscribe node info
|
||||
publicSubscribeGroupRouter.GET("/node/list", publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
||||
|
||||
// Get subscribe group list
|
||||
publicSubscribeGroupRouter.GET("/group/list", publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
||||
}
|
||||
|
||||
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
||||
@@ -957,11 +1014,11 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
|
||||
// Get Agent Downloads
|
||||
publicUserGroupRouter.GET("/agent_downloads", publicUser.GetAgentDownloadsHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/agent/downloads", publicUser.GetAgentDownloadsHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/agent/downloads", publicUser.GetAgentDownloadsHandler(serverCtx)) // alias: backward-compat
|
||||
|
||||
// Get Agent Realtime
|
||||
publicUserGroupRouter.GET("/agent_realtime", publicUser.GetAgentRealtimeHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/agent/realtime", publicUser.GetAgentRealtimeHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/agent/realtime", publicUser.GetAgentRealtimeHandler(serverCtx)) // alias: backward-compat
|
||||
|
||||
// Query User Balance Log
|
||||
publicUserGroupRouter.GET("/balance_log", publicUser.QueryUserBalanceLogHandler(serverCtx))
|
||||
@@ -1010,11 +1067,11 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
|
||||
// Get Invite Sales
|
||||
publicUserGroupRouter.GET("/invite_sales", publicUser.GetInviteSalesHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/invite/sales", publicUser.GetInviteSalesHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/invite/sales", publicUser.GetInviteSalesHandler(serverCtx)) // alias: backward-compat
|
||||
|
||||
// Get User Invite Stats
|
||||
publicUserGroupRouter.GET("/invite_stats", publicUser.GetUserInviteStatsHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/invite/stats", publicUser.GetUserInviteStatsHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/invite/stats", publicUser.GetUserInviteStatsHandler(serverCtx)) // alias: backward-compat
|
||||
|
||||
// Get Login Log
|
||||
publicUserGroupRouter.GET("/login_log", publicUser.GetLoginLogHandler(serverCtx))
|
||||
@@ -1099,10 +1156,10 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
serverGroupRouter.GET("/user", server.GetServerUserListHandler(serverCtx))
|
||||
}
|
||||
|
||||
serverV2GroupRouter := router.Group("/v2/server")
|
||||
serverGroupRouterV2 := router.Group("/v2/server")
|
||||
|
||||
{
|
||||
// Get Server Protocol Config
|
||||
serverV2GroupRouter.GET("/:server_id", server.QueryServerProtocolConfigHandler(serverCtx))
|
||||
serverGroupRouterV2.GET("/:server_id", server.QueryServerProtocolConfigHandler(serverCtx))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,13 +196,10 @@ func (l *PreviewUserNodesLogic) PreviewUserNodes(req *types.PreviewUserNodesRequ
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 6. 过滤出包含至少一个匹配节点组的节点
|
||||
// node_group_ids 为空 = 公共节点,所有人可见
|
||||
// node_group_ids 与订阅的 node_group_id 匹配 = 该节点可见
|
||||
// 6. 过滤出包含至少一个匹配节点组的节点(仅显示用户真正所在分组的节点,不包含公共节点)
|
||||
for _, n := range dbNodes {
|
||||
// 公共节点(node_group_ids 为空),所有人可见
|
||||
// 节点未配置节点组(公共节点),预览时不显示
|
||||
if len(n.NodeGroupIds) == 0 {
|
||||
filteredNodes = append(filteredNodes, n)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -453,14 +450,9 @@ func (l *PreviewUserNodesLogic) PreviewUserNodes(req *types.PreviewUserNodesRequ
|
||||
}
|
||||
}
|
||||
|
||||
// 添加公共节点组(如果有)
|
||||
// 预览模式不显示公共节点(node_group_ids 为空的节点),只展示用户真正所在分组的节点
|
||||
if len(publicNodes) > 0 {
|
||||
nodeGroupItems = append(nodeGroupItems, types.NodeGroupItem{
|
||||
Id: 0,
|
||||
Name: "",
|
||||
Nodes: publicNodes,
|
||||
})
|
||||
logger.Infof("[PreviewUserNodes] adding public group: nodes=%d", len(publicNodes))
|
||||
logger.Infof("[PreviewUserNodes] skipping %d public nodes (not in user's assigned group)", len(publicNodes))
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
@@ -632,7 +632,7 @@ func (l *RecalculateGroupLogic) executeTrafficGrouping(tx *gorm.DB, historyId in
|
||||
// 1. 获取所有设置了流量区间的节点组
|
||||
var nodeGroups []group.NodeGroup
|
||||
if err := tx.Where("for_calculation = ?", true).
|
||||
Where("(min_traffic_gb > 0 OR max_traffic_gb > 0)").
|
||||
Where("max_traffic_gb > 0").
|
||||
Find(&nodeGroups).Error; err != nil {
|
||||
l.Errorw("failed to query node groups", logger.Field("error", err.Error()))
|
||||
return 0, err
|
||||
|
||||
@@ -26,7 +26,19 @@ func NewGetRegisterConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext)
|
||||
}
|
||||
|
||||
func (l *GetRegisterConfigLogic) GetRegisterConfig() (*types.RegisterConfig, error) {
|
||||
resp := &types.RegisterConfig{}
|
||||
resp := &types.RegisterConfig{
|
||||
StopRegister: l.svcCtx.Config.Register.StopRegister,
|
||||
EnableTrial: l.svcCtx.Config.Register.EnableTrial,
|
||||
EnableTrialEmailWhitelist: l.svcCtx.Config.Register.EnableTrialEmailWhitelist,
|
||||
TrialSubscribe: l.svcCtx.Config.Register.TrialSubscribe,
|
||||
TrialTime: l.svcCtx.Config.Register.TrialTime,
|
||||
TrialTimeUnit: l.svcCtx.Config.Register.TrialTimeUnit,
|
||||
TrialEmailDomainWhitelist: l.svcCtx.Config.Register.TrialEmailDomainWhitelist,
|
||||
EnableIpRegisterLimit: l.svcCtx.Config.Register.EnableIpRegisterLimit,
|
||||
IpRegisterLimit: l.svcCtx.Config.Register.IpRegisterLimit,
|
||||
IpRegisterLimitDuration: l.svcCtx.Config.Register.IpRegisterLimitDuration,
|
||||
DeviceLimit: l.svcCtx.Config.Register.DeviceLimit,
|
||||
}
|
||||
|
||||
// get register config from database
|
||||
configs, err := l.svcCtx.SystemModel.GetRegisterConfig(l.ctx)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/initialize"
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
@@ -44,8 +45,28 @@ func (l *UpdateRegisterConfigLogic) UpdateRegisterConfig(req *types.RegisterConf
|
||||
fieldName := t.Field(i).Name
|
||||
// Get the field value to string
|
||||
fieldValue := tool.ConvertValueToString(v.Field(i))
|
||||
// Update the site config
|
||||
err = db.Model(&system.System{}).Where("`category` = 'register' and `key` = ?", fieldName).Update("value", fieldValue).Error
|
||||
|
||||
var existing system.System
|
||||
queryErr := db.Where("`category` = ? and `key` = ?", "register", fieldName).First(&existing).Error
|
||||
if queryErr != nil && !errors.Is(queryErr, gorm.ErrRecordNotFound) {
|
||||
return queryErr
|
||||
}
|
||||
if errors.Is(queryErr, gorm.ErrRecordNotFound) {
|
||||
fieldValue = l.defaultRegisterFieldValue(fieldName, fieldValue)
|
||||
}
|
||||
|
||||
record := &system.System{
|
||||
Category: "register",
|
||||
Key: fieldName,
|
||||
}
|
||||
assignments := map[string]interface{}{
|
||||
"value": fieldValue,
|
||||
"type": inferRegisterSystemValueType(t.Field(i).Type.Kind()),
|
||||
"desc": fieldName,
|
||||
}
|
||||
err = db.Where("`category` = ? and `key` = ?", "register", fieldName).
|
||||
Assign(assignments).
|
||||
FirstOrCreate(record).Error
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
@@ -63,3 +84,28 @@ func (l *UpdateRegisterConfigLogic) UpdateRegisterConfig(req *types.RegisterConf
|
||||
initialize.Register(l.svcCtx)
|
||||
return nil
|
||||
}
|
||||
|
||||
func inferRegisterSystemValueType(kind reflect.Kind) string {
|
||||
switch kind {
|
||||
case reflect.Bool:
|
||||
return "bool"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return "int"
|
||||
default:
|
||||
return "string"
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateRegisterConfigLogic) defaultRegisterFieldValue(fieldName, fieldValue string) string {
|
||||
switch fieldName {
|
||||
case "EnableTrialEmailWhitelist":
|
||||
return "true"
|
||||
case "TrialEmailDomainWhitelist":
|
||||
if strings.TrimSpace(fieldValue) != "" {
|
||||
return fieldValue
|
||||
}
|
||||
return l.svcCtx.Config.Register.TrialEmailDomainWhitelist
|
||||
default:
|
||||
return fieldValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type ApproveWithdrawalLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewApproveWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApproveWithdrawalLogic {
|
||||
return &ApproveWithdrawalLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ApproveWithdrawalLogic) ApproveWithdrawal(req *types.ApproveWithdrawalRequest) error {
|
||||
return approveWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId)
|
||||
}
|
||||
@@ -2,39 +2,257 @@ package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/model/iap/apple"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/logmessage"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/internal/model/ticket"
|
||||
"github.com/perfect-panel/server/internal/model/traffic"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
pkglogger "github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DeleteUserLogic struct {
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logger.Logger
|
||||
pkglogger.Logger
|
||||
}
|
||||
|
||||
func NewDeleteUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteUserLogic {
|
||||
return &DeleteUserLogic{
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
Logger: logger.WithContext(ctx),
|
||||
Logger: pkglogger.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DeleteUserLogic) DeleteUser(req *types.GetDetailRequest) error {
|
||||
isDemo := strings.ToLower(os.Getenv("PPANEL_MODE")) == "demo"
|
||||
|
||||
if req.Id == 2 && isDemo {
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(503, "Demo mode does not allow deletion of the admin user"), "delete user failed: cannot delete admin user in demo mode")
|
||||
}
|
||||
err := l.svcCtx.UserModel.Delete(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete user error: %v", err.Error())
|
||||
|
||||
return l.purgeUser(req.Id)
|
||||
}
|
||||
|
||||
// purgeUser 硬删除用户及其所有关联数据,无孤儿数据残留。
|
||||
// 删除顺序:先删子表(引用 user_id),再删主表(user)。
|
||||
func (l *DeleteUserLogic) purgeUser(userID int64) error {
|
||||
// 1. 事务前:收集需要清缓存的数据
|
||||
userInfo, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user failed: %v", err)
|
||||
}
|
||||
|
||||
authMethods, _ := l.svcCtx.UserModel.FindUserAuthMethods(l.ctx, userID)
|
||||
subscribes, _ := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, userID)
|
||||
|
||||
// 2. 查 ticket id 列表(ticket_follow 通过 ticket_id 关联,需要先查再删)
|
||||
var ticketIDs []int64
|
||||
l.svcCtx.DB.WithContext(l.ctx).Model(&ticket.Ticket{}).
|
||||
Where("user_id = ?", userID).Pluck("id", &ticketIDs)
|
||||
|
||||
// 3. 查家庭关系(需要处理家庭解散)
|
||||
var familyMember usermodel.UserFamilyMember
|
||||
isFamilyOwner := false
|
||||
var familyID int64
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&usermodel.UserFamilyMember{}).
|
||||
Where("user_id = ?", userID).
|
||||
First(&familyMember).Error; err == nil {
|
||||
familyID = familyMember.FamilyId
|
||||
var family usermodel.UserFamily
|
||||
if err2 := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Where("id = ?", familyID).First(&family).Error; err2 == nil {
|
||||
isFamilyOwner = (family.OwnerUserId == userID)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 事务内:按顺序删除所有关联表,最后删 user
|
||||
err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 4a. 家庭处理
|
||||
if familyID > 0 {
|
||||
if isFamilyOwner {
|
||||
// 家主:解散整个家庭(删所有成员记录 + 删家庭)
|
||||
if e := tx.Unscoped().Where("family_id = ?", familyID).
|
||||
Delete(&usermodel.UserFamilyMember{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if e := tx.Unscoped().Where("id = ?", familyID).
|
||||
Delete(&usermodel.UserFamily{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
} else {
|
||||
// 成员:只删自己的成员记录
|
||||
if e := tx.Unscoped().Where("user_id = ? AND family_id = ?", userID, familyID).
|
||||
Delete(&usermodel.UserFamilyMember{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4b. 用户认证方式
|
||||
if e := tx.Unscoped().Where("user_id = ?", userID).
|
||||
Delete(&usermodel.AuthMethods{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4c. 订阅
|
||||
if e := tx.Unscoped().Where("user_id = ?", userID).
|
||||
Delete(&usermodel.Subscribe{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4d. 设备 + 设备在线记录
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&usermodel.Device{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&usermodel.DeviceOnlineRecord{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4e. 提现记录
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&usermodel.Withdrawal{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4f. 订单
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&order.Order{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4g. 流量日志
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&traffic.TrafficLog{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4h. 系统日志(object_id = userID)
|
||||
if e := tx.Where("object_id = ?", userID).
|
||||
Delete(&log.SystemLog{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4i. 工单 follow + 工单
|
||||
if len(ticketIDs) > 0 {
|
||||
if e := tx.Where("ticket_id IN ?", ticketIDs).
|
||||
Delete(&ticket.Follow{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&ticket.Ticket{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4j. Apple IAP 交易记录
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&apple.Transaction{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4k. 日志消息
|
||||
if e := tx.Where("user_id = ?", userID).
|
||||
Delete(&logmessage.LogMessage{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// 4l. 最后删除 user(Unscoped = 物理删除)
|
||||
if e := tx.Unscoped().Where("id = ?", userID).
|
||||
Delete(&usermodel.User{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "purge user %d failed: %v", userID, err)
|
||||
}
|
||||
|
||||
// 5. 事务后:清缓存 + 踢设备
|
||||
l.cleanupAfterDelete(userID, userInfo, authMethods, subscribes)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *DeleteUserLogic) cleanupAfterDelete(
|
||||
userID int64,
|
||||
userInfo *usermodel.User,
|
||||
authMethods []*usermodel.AuthMethods,
|
||||
subscribes []*usermodel.SubscribeDetails,
|
||||
) {
|
||||
// 踢设备
|
||||
var devices []usermodel.Device
|
||||
l.svcCtx.DB.WithContext(l.ctx).Where("user_id = ?", userID).Find(&devices)
|
||||
for _, d := range devices {
|
||||
l.svcCtx.DeviceManager.KickDevice(d.UserId, d.Identifier)
|
||||
}
|
||||
|
||||
// 清 session
|
||||
l.clearAllSessions(userID)
|
||||
|
||||
// 清 email 缓存
|
||||
var emailKeys []string
|
||||
for _, am := range authMethods {
|
||||
if am.AuthType == "email" && am.AuthIdentifier != "" {
|
||||
emailKeys = append(emailKeys, fmt.Sprintf("cache:user:email:%s", am.AuthIdentifier))
|
||||
}
|
||||
}
|
||||
if len(emailKeys) > 0 {
|
||||
if e := l.svcCtx.Redis.Del(l.ctx, emailKeys...).Err(); e != nil {
|
||||
l.Errorw("clear email cache failed", pkglogger.Field("user_id", userID), pkglogger.Field("error", e.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
// 清 user 缓存
|
||||
if userInfo != nil {
|
||||
if e := l.svcCtx.UserModel.ClearUserCache(l.ctx, userInfo); e != nil {
|
||||
l.Errorw("clear user cache failed", pkglogger.Field("user_id", userID), pkglogger.Field("error", e.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
// 清订阅缓存
|
||||
subModels := make([]*usermodel.Subscribe, 0, len(subscribes)+1)
|
||||
subModels = append(subModels, &usermodel.Subscribe{UserId: userID})
|
||||
for _, s := range subscribes {
|
||||
subModels = append(subModels, &usermodel.Subscribe{
|
||||
Id: s.Id, UserId: s.UserId, SubscribeId: s.SubscribeId, Token: s.Token,
|
||||
})
|
||||
}
|
||||
if e := l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, subModels...); e != nil {
|
||||
l.Errorw("clear subscribe cache failed", pkglogger.Field("user_id", userID), pkglogger.Field("error", e.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
// clearAllSessions 清理用户所有 session
|
||||
func (l *DeleteUserLogic) clearAllSessions(userID int64) {
|
||||
sessionsKey := fmt.Sprintf("%s%d", config.UserSessionsKeyPrefix, userID)
|
||||
sessions, _ := l.svcCtx.Redis.ZRange(l.ctx, sessionsKey, 0, -1).Result()
|
||||
pipe := l.svcCtx.Redis.TxPipeline()
|
||||
for _, sid := range sessions {
|
||||
pipe.Del(l.ctx, fmt.Sprintf("%s:%s", config.SessionIdKey, sid))
|
||||
pipe.Del(l.ctx, fmt.Sprintf("%s:detail:%s", config.SessionIdKey, sid))
|
||||
pipe.ZRem(l.ctx, sessionsKey, sid)
|
||||
}
|
||||
pipe.Del(l.ctx, sessionsKey)
|
||||
if _, e := pipe.Exec(l.ctx); e != nil {
|
||||
l.Errorw("clear sessions failed", pkglogger.Field("user_id", userID), pkglogger.Field("error", e.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,13 @@ func normalizeFamilyStatusInput(status string) (uint8, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func findUserIdentifiers(ctx context.Context, db *gorm.DB, userIDs []int64) (map[int64]string, error) {
|
||||
identifierMap := make(map[int64]string)
|
||||
type identifierInfo struct {
|
||||
Identifier string
|
||||
AuthType string
|
||||
}
|
||||
|
||||
func findUserIdentifiers(ctx context.Context, db *gorm.DB, userIDs []int64) (map[int64]identifierInfo, error) {
|
||||
identifierMap := make(map[int64]identifierInfo)
|
||||
if len(userIDs) == 0 {
|
||||
return identifierMap, nil
|
||||
}
|
||||
@@ -92,8 +97,31 @@ func findUserIdentifiers(ctx context.Context, db *gorm.DB, userIDs []int64) (map
|
||||
continue
|
||||
}
|
||||
selectedPriority[row.UserId] = currentPriority
|
||||
identifierMap[row.UserId] = row.AuthIdentifier
|
||||
identifierMap[row.UserId] = identifierInfo{
|
||||
Identifier: row.AuthIdentifier,
|
||||
AuthType: row.AuthType,
|
||||
}
|
||||
}
|
||||
|
||||
return identifierMap, nil
|
||||
}
|
||||
|
||||
func parseDeviceType(userAgent string) string {
|
||||
ua := strings.ToLower(userAgent)
|
||||
switch {
|
||||
case strings.Contains(ua, "iphone"):
|
||||
return "iPhone"
|
||||
case strings.Contains(ua, "ipad"):
|
||||
return "iPad"
|
||||
case strings.Contains(ua, "android"):
|
||||
return "Android"
|
||||
case strings.Contains(ua, "windows"):
|
||||
return "Windows"
|
||||
case strings.Contains(ua, "macintosh"), strings.Contains(ua, "mac os"):
|
||||
return "Mac"
|
||||
case strings.Contains(ua, "linux"):
|
||||
return "Linux"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,18 +63,22 @@ func (l *GetFamilyDetailLogic) GetFamilyDetail(req *types.GetFamilyDetailRequest
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query family member identifiers failed")
|
||||
}
|
||||
|
||||
// 查出所有成员的设备,构建 userId → deviceNo 映射
|
||||
// 查出所有成员的设备,构建 userId → deviceNo 映射 + deviceType 映射
|
||||
deviceNoMap := make(map[int64]string)
|
||||
deviceTypeMap := make(map[int64]string)
|
||||
devices, _, _ := l.svcCtx.UserModel.QueryDeviceListByUserIds(l.ctx, userIDs)
|
||||
for _, d := range devices {
|
||||
if _, exists := deviceNoMap[d.UserId]; !exists {
|
||||
deviceNoMap[d.UserId] = tool.DeviceIdToHash(d.Id)
|
||||
deviceTypeMap[d.UserId] = parseDeviceType(d.UserAgent)
|
||||
}
|
||||
}
|
||||
|
||||
memberItems := make([]types.FamilyMemberItem, 0, len(members))
|
||||
for _, member := range members {
|
||||
identifier := identifierMap[member.UserId]
|
||||
info := identifierMap[member.UserId]
|
||||
identifier := info.Identifier
|
||||
authType := info.AuthType
|
||||
if identifier == "" {
|
||||
identifier = strconv.FormatInt(member.UserId, 10)
|
||||
}
|
||||
@@ -82,7 +86,9 @@ func (l *GetFamilyDetailLogic) GetFamilyDetail(req *types.GetFamilyDetailRequest
|
||||
memberItem := types.FamilyMemberItem{
|
||||
UserId: member.UserId,
|
||||
Identifier: identifier,
|
||||
AuthType: authType,
|
||||
DeviceNo: deviceNoMap[member.UserId],
|
||||
DeviceType: deviceTypeMap[member.UserId],
|
||||
Role: member.Role,
|
||||
RoleName: mapFamilyRoleName(member.Role),
|
||||
Status: member.Status,
|
||||
@@ -96,7 +102,9 @@ func (l *GetFamilyDetailLogic) GetFamilyDetail(req *types.GetFamilyDetailRequest
|
||||
memberItems = append(memberItems, memberItem)
|
||||
}
|
||||
|
||||
ownerIdentifier := identifierMap[family.OwnerUserId]
|
||||
ownerInfo := identifierMap[family.OwnerUserId]
|
||||
ownerIdentifier := ownerInfo.Identifier
|
||||
ownerAuthType := ownerInfo.AuthType
|
||||
if ownerIdentifier == "" {
|
||||
ownerIdentifier = strconv.FormatInt(family.OwnerUserId, 10)
|
||||
}
|
||||
@@ -106,6 +114,7 @@ func (l *GetFamilyDetailLogic) GetFamilyDetail(req *types.GetFamilyDetailRequest
|
||||
FamilyId: family.Id,
|
||||
OwnerUserId: family.OwnerUserId,
|
||||
OwnerIdentifier: ownerIdentifier,
|
||||
OwnerAuthType: ownerAuthType,
|
||||
Status: mapFamilyStatus(family.Status),
|
||||
ActiveMemberCount: activeMemberCount,
|
||||
MaxMembers: family.MaxMembers,
|
||||
|
||||
@@ -123,7 +123,9 @@ func (l *GetFamilyListLogic) GetFamilyList(req *types.GetFamilyListRequest) (*ty
|
||||
|
||||
list := make([]types.FamilySummary, 0, len(families))
|
||||
for _, family := range families {
|
||||
ownerIdentifier := identifierMap[family.OwnerUserId]
|
||||
ownerInfo := identifierMap[family.OwnerUserId]
|
||||
ownerIdentifier := ownerInfo.Identifier
|
||||
ownerAuthType := ownerInfo.AuthType
|
||||
if ownerIdentifier == "" {
|
||||
ownerIdentifier = strconv.FormatInt(family.OwnerUserId, 10)
|
||||
}
|
||||
@@ -132,6 +134,7 @@ func (l *GetFamilyListLogic) GetFamilyList(req *types.GetFamilyListRequest) (*ty
|
||||
FamilyId: family.Id,
|
||||
OwnerUserId: family.OwnerUserId,
|
||||
OwnerIdentifier: ownerIdentifier,
|
||||
OwnerAuthType: ownerAuthType,
|
||||
Status: mapFamilyStatus(family.Status),
|
||||
ActiveMemberCount: countMap[family.Id],
|
||||
MaxMembers: family.MaxMembers,
|
||||
|
||||
@@ -3,9 +3,11 @@ package user
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/group"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/speedlimit"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
@@ -34,5 +36,24 @@ func (l *GetUserSubscribeByIdLogic) GetUserSubscribeById(req *types.GetUserSubsc
|
||||
}
|
||||
var subscribeDetails types.UserSubscribeDetail
|
||||
tool.DeepCopy(&subscribeDetails, sub)
|
||||
|
||||
// 填充分组名
|
||||
if sub.NodeGroupId > 0 {
|
||||
var ng group.NodeGroup
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).First(&ng, sub.NodeGroupId).Error; err == nil {
|
||||
subscribeDetails.NodeGroupName = ng.Name
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate speed limit status
|
||||
if sub.Subscribe != nil && sub.Status == 1 {
|
||||
result := speedlimit.Calculate(l.ctx, l.svcCtx.DB, sub.UserId, sub.Id, sub.Subscribe.SpeedLimit, sub.Subscribe.TrafficLimit)
|
||||
subscribeDetails.EffectiveSpeed = result.EffectiveSpeed
|
||||
subscribeDetails.IsThrottled = result.IsThrottled
|
||||
subscribeDetails.ThrottleRule = result.ThrottleRule
|
||||
subscribeDetails.ThrottleStart = result.ThrottleStart
|
||||
subscribeDetails.ThrottleEnd = result.ThrottleEnd
|
||||
}
|
||||
|
||||
return &subscribeDetails, nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package user
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/group"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -38,10 +39,33 @@ func (l *GetUserSubscribeLogic) GetUserSubscribe(req *types.GetUserSubscribeList
|
||||
Total: int64(len(data)),
|
||||
}
|
||||
|
||||
// 收集所有 node_group_id,批量查分组名
|
||||
groupIdSet := make(map[int64]struct{})
|
||||
for _, item := range data {
|
||||
if item.NodeGroupId > 0 {
|
||||
groupIdSet[item.NodeGroupId] = struct{}{}
|
||||
}
|
||||
}
|
||||
groupNames := make(map[int64]string)
|
||||
if len(groupIdSet) > 0 {
|
||||
ids := make([]int64, 0, len(groupIdSet))
|
||||
for id := range groupIdSet {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
var groups []group.NodeGroup
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).Where("id IN ?", ids).Find(&groups).Error; err == nil {
|
||||
for _, g := range groups {
|
||||
groupNames[g.Id] = g.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range data {
|
||||
var sub types.UserSubscribe
|
||||
tool.DeepCopy(&sub, item)
|
||||
sub.Short, _ = tool.FixedUniqueString(item.Token, 8, "")
|
||||
sub.NodeGroupId = item.NodeGroupId
|
||||
sub.NodeGroupName = groupNames[item.NodeGroupId]
|
||||
resp.List = append(resp.List, sub)
|
||||
}
|
||||
return
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetWithdrawalListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetWithdrawalListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWithdrawalListLogic {
|
||||
return &GetWithdrawalListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListRequest) (*types.GetWithdrawalListResponse, error) {
|
||||
page := req.Page
|
||||
size := req.Size
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if size <= 0 {
|
||||
size = 10
|
||||
}
|
||||
|
||||
query := l.svcCtx.DB.WithContext(l.ctx).Model(&usermodel.Withdrawal{})
|
||||
if req.UserId != nil {
|
||||
query = query.Where("user_id = ?", *req.UserId)
|
||||
}
|
||||
if req.Status != nil {
|
||||
query = query.Where("status = ?", *req.Status)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count withdrawals failed: %v", err)
|
||||
}
|
||||
|
||||
var rows []usermodel.Withdrawal
|
||||
if err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query withdrawals failed: %v", err)
|
||||
}
|
||||
|
||||
list := make([]types.WithdrawalLog, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
list = append(list, types.WithdrawalLog{
|
||||
Id: row.Id,
|
||||
UserId: row.UserId,
|
||||
Amount: row.Amount,
|
||||
Content: row.Content,
|
||||
Status: row.Status,
|
||||
Reason: row.Reason,
|
||||
CreatedAt: row.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: row.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.GetWithdrawalListResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type RejectWithdrawalLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewRejectWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RejectWithdrawalLogic {
|
||||
return &RejectWithdrawalLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *RejectWithdrawalLogic) RejectWithdrawal(req *types.RejectWithdrawalRequest) error {
|
||||
return rejectWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId, req.Reason)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
logicCommon "github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -100,28 +101,41 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
}
|
||||
|
||||
if req.Commission != userInfo.Commission {
|
||||
|
||||
commentLog := log.Commission{
|
||||
Type: log.CommissionTypeAdjust,
|
||||
Amount: req.Commission - userInfo.Commission,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
if isWithdrawalScene(req.Remark) {
|
||||
logWithdrawalGuard(l.Logger, userInfo.Id)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "commission overwrite is blocked in withdrawal scene")
|
||||
}
|
||||
|
||||
content, _ := commentLog.Marshal()
|
||||
err = tx.Create(&log.SystemLog{
|
||||
Type: log.TypeCommission.Uint8(),
|
||||
Date: time.Now().Format(time.DateOnly),
|
||||
ObjectID: userInfo.Id,
|
||||
Content: string(content),
|
||||
}).Error
|
||||
if err != nil {
|
||||
change := req.Commission - userInfo.Commission
|
||||
if err = l.svcCtx.UserModel.UpdateCommission(l.ctx, userInfo.Id, change, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = logicCommon.WriteCommissionLog(tx, userInfo.Id, log.CommissionTypeAdjust, change, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
userInfo.Commission = req.Commission
|
||||
}
|
||||
tool.DeepCopy(userInfo, req)
|
||||
userInfo.OnlyFirstPurchase = &req.OnlyFirstPurchase
|
||||
if req.Avatar != "" {
|
||||
userInfo.Avatar = req.Avatar
|
||||
}
|
||||
if req.ReferCode != "" {
|
||||
userInfo.ReferCode = req.ReferCode
|
||||
}
|
||||
userInfo.RefererId = req.RefererId
|
||||
if req.Enable != nil {
|
||||
userInfo.Enable = req.Enable
|
||||
}
|
||||
if req.IsAdmin != nil {
|
||||
userInfo.IsAdmin = req.IsAdmin
|
||||
}
|
||||
if req.Remark != "" {
|
||||
userInfo.Remark = req.Remark
|
||||
}
|
||||
if req.OnlyFirstPurchase != nil {
|
||||
userInfo.OnlyFirstPurchase = req.OnlyFirstPurchase
|
||||
}
|
||||
if req.ReferralPercentage != 0 {
|
||||
userInfo.ReferralPercentage = req.ReferralPercentage
|
||||
}
|
||||
|
||||
if req.Password != "" {
|
||||
if userInfo.Id == 2 && isDemo {
|
||||
|
||||
@@ -54,6 +54,7 @@ func (l *UpdateUserSubscribeLogic) UpdateUserSubscribe(req *types.UpdateUserSubs
|
||||
UUID: userSub.UUID,
|
||||
Status: userSub.Status,
|
||||
NodeGroupId: userSub.NodeGroupId,
|
||||
GroupLocked: userSub.GroupLocked,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
logicCommon "github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64) error {
|
||||
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
||||
if err != nil {
|
||||
if err.Error() == "withdrawal status invalid" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
|
||||
}
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
||||
}
|
||||
|
||||
if err := tx.Model(&usermodel.Withdrawal{}).
|
||||
Where("id = ? AND status = 0", withdrawalID).
|
||||
Updates(map[string]interface{}{
|
||||
"status": 1,
|
||||
"reason": "",
|
||||
}).Error; err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "approve withdrawal failed: %v", err)
|
||||
}
|
||||
|
||||
if err := logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdraw, withdrawal.Amount, ""); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func rejectWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64, reason string) error {
|
||||
reason = strings.TrimSpace(reason)
|
||||
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
||||
if err != nil {
|
||||
if err.Error() == "withdrawal status invalid" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
|
||||
}
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
||||
}
|
||||
|
||||
if err := tx.Model(&usermodel.Withdrawal{}).
|
||||
Where("id = ? AND status = 0", withdrawalID).
|
||||
Updates(map[string]interface{}{
|
||||
"status": 2,
|
||||
"reason": reason,
|
||||
}).Error; err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "reject withdrawal failed: %v", err)
|
||||
}
|
||||
|
||||
if err := svcCtx.UserModel.UpdateCommission(ctx, withdrawal.UserId, withdrawal.Amount, tx); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err)
|
||||
}
|
||||
|
||||
if err := logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdrawReject, withdrawal.Amount, ""); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func isWithdrawalScene(remark string) bool {
|
||||
normalized := strings.ToLower(strings.TrimSpace(remark))
|
||||
return strings.Contains(normalized, "withdraw") || strings.Contains(normalized, "提现")
|
||||
}
|
||||
|
||||
func logWithdrawalGuard(l logger.Logger, userID int64) {
|
||||
l.Errorw("blocked commission overwrite in withdrawal scene", logger.Field("user_id", userID))
|
||||
}
|
||||
@@ -64,6 +64,17 @@ func (l *AdminGenerateCaptchaLogic) AdminGenerateCaptcha() (resp *types.Generate
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
// For Turnstile, just return the site key
|
||||
resp.Id = config.TurnstileSiteKey
|
||||
} else if config.CaptchaType == "slider" {
|
||||
// For slider, generate background and block images
|
||||
sliderSvc := captcha.NewSliderService(l.svcCtx.Redis)
|
||||
id, bgImage, blockImage, err := sliderSvc.GenerateSlider(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminGenerateCaptchaLogic] Generate slider captcha error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Generate slider captcha error: %v", err.Error())
|
||||
}
|
||||
resp.Id = id
|
||||
resp.Image = bgImage
|
||||
resp.BlockImage = blockImage
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
|
||||
@@ -137,65 +137,28 @@ func (l *AdminLoginLogic) AdminLogin(req *types.UserLoginRequest) (resp *types.L
|
||||
}
|
||||
|
||||
func (l *AdminLoginLogic) verifyCaptcha(req *types.UserLoginRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminLoginLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
var cfg struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &cfg)
|
||||
|
||||
// Check if captcha is enabled for admin login
|
||||
if !config.EnableAdminLoginCaptcha {
|
||||
if !cfg.EnableAdminLoginCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
return captcha.VerifyCaptcha(l.ctx, l.svcCtx.Redis, cfg.CaptchaType, cfg.TurnstileSecret, captcha.VerifyInput{
|
||||
CaptchaId: req.CaptchaId,
|
||||
CaptchaCode: req.CaptchaCode,
|
||||
CfToken: req.CfToken,
|
||||
SliderToken: req.SliderToken,
|
||||
IP: req.IP,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminLoginLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminLoginLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -165,65 +165,28 @@ func (l *AdminResetPasswordLogic) AdminResetPassword(req *types.ResetPasswordReq
|
||||
}
|
||||
|
||||
func (l *AdminResetPasswordLogic) verifyCaptcha(req *types.ResetPasswordRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminResetPasswordLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
var cfg struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &cfg)
|
||||
|
||||
// Check if admin login captcha is enabled (use admin login captcha for reset password)
|
||||
if !config.EnableAdminLoginCaptcha {
|
||||
if !cfg.EnableAdminLoginCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
return captcha.VerifyCaptcha(l.ctx, l.svcCtx.Redis, cfg.CaptchaType, cfg.TurnstileSecret, captcha.VerifyInput{
|
||||
CaptchaId: req.CaptchaId,
|
||||
CaptchaCode: req.CaptchaCode,
|
||||
CfToken: req.CfToken,
|
||||
SliderToken: req.SliderToken,
|
||||
IP: req.IP,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminResetPasswordLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminResetPasswordLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/captcha"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type AdminSliderVerifyCaptchaLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Verify slider captcha
|
||||
func NewAdminSliderVerifyCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminSliderVerifyCaptchaLogic {
|
||||
return &AdminSliderVerifyCaptchaLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *AdminSliderVerifyCaptchaLogic) AdminSliderVerifyCaptcha(req *types.SliderVerifyCaptchaRequest) (resp *types.SliderVerifyCaptchaResponse, err error) {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminSliderVerifyCaptchaLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
if config.CaptchaType != "slider" {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "slider captcha not enabled")
|
||||
}
|
||||
|
||||
sliderSvc := captcha.NewSliderService(l.svcCtx.Redis)
|
||||
token, err := sliderSvc.VerifySlider(l.ctx, req.Id, req.X, req.Y, req.Trail)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminSliderVerifyCaptchaLogic] VerifySlider error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify slider error")
|
||||
}
|
||||
|
||||
return &types.SliderVerifyCaptchaResponse{
|
||||
Token: token,
|
||||
}, nil
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/jwt"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/uuidx"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
@@ -97,6 +96,17 @@ func (l *DeviceLoginLogic) DeviceLogin(req *types.DeviceLoginRequest) (resp *typ
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user failed: %v", err.Error())
|
||||
}
|
||||
|
||||
// Update base_payload if provided
|
||||
if req.BasePayload != "" && req.BasePayload != deviceInfo.BasePayload {
|
||||
deviceInfo.BasePayload = req.BasePayload
|
||||
if updateErr := l.svcCtx.UserModel.UpdateDevice(l.ctx, deviceInfo); updateErr != nil {
|
||||
l.Errorw("update device base_payload failed",
|
||||
logger.Field("device_id", deviceInfo.Id),
|
||||
logger.Field("error", updateErr.Error()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 注销后 device auth_method 被删除,重新登录时需要补回
|
||||
hasDeviceAuth := false
|
||||
for _, am := range userInfo.AuthMethods {
|
||||
@@ -180,7 +190,6 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
||||
)
|
||||
|
||||
var userInfo *user.User
|
||||
var trialSubscribe *user.Subscribe
|
||||
err := l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
// Create new user
|
||||
userInfo = &user.User{
|
||||
@@ -227,6 +236,7 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
||||
UserAgent: req.UserAgent,
|
||||
Identifier: req.Identifier,
|
||||
ShortCode: req.ShortCode,
|
||||
BasePayload: req.BasePayload,
|
||||
Enabled: true,
|
||||
Online: false,
|
||||
}
|
||||
@@ -239,15 +249,6 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert device failed: %v", err)
|
||||
}
|
||||
|
||||
// Activate trial if enabled
|
||||
if l.svcCtx.Config.Register.EnableTrial {
|
||||
var trialErr error
|
||||
trialSubscribe, trialErr = l.activeTrial(userInfo.Id, db)
|
||||
if trialErr != nil {
|
||||
return trialErr
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -259,25 +260,6 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Clear cache after transaction success
|
||||
if l.svcCtx.Config.Register.EnableTrial && trialSubscribe != nil {
|
||||
// Clear user subscription cache
|
||||
if err = l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, trialSubscribe); err != nil {
|
||||
l.Errorw("ClearSubscribeCache failed", logger.Field("error", err.Error()), logger.Field("userSubscribeId", trialSubscribe.Id))
|
||||
// Don't return error, just log it
|
||||
}
|
||||
// Clear subscription cache
|
||||
if err = l.svcCtx.SubscribeModel.ClearCache(l.ctx, trialSubscribe.SubscribeId); err != nil {
|
||||
l.Errorw("ClearSubscribeCache failed", logger.Field("error", err.Error()), logger.Field("subscribeId", trialSubscribe.SubscribeId))
|
||||
// Don't return error, just log it
|
||||
}
|
||||
// Clear all server cache
|
||||
if err = l.svcCtx.NodeModel.ClearServerAllCache(l.ctx); err != nil {
|
||||
l.Errorf("ClearServerAllCache error: %v", err.Error())
|
||||
// Don't return error, just log it
|
||||
}
|
||||
}
|
||||
|
||||
l.Infow("device registration completed successfully",
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("identifier", req.Identifier),
|
||||
@@ -309,51 +291,3 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
||||
|
||||
return userInfo, nil
|
||||
}
|
||||
|
||||
func (l *DeviceLoginLogic) activeTrial(userId int64, db *gorm.DB) (*user.Subscribe, error) {
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, l.svcCtx.Config.Register.TrialSubscribe)
|
||||
if err != nil {
|
||||
l.Errorw("failed to find trial subscription template",
|
||||
logger.Field("user_id", userId),
|
||||
logger.Field("trial_subscribe_id", l.svcCtx.Config.Register.TrialSubscribe),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
startTime := time.Now()
|
||||
expireTime := tool.AddTime(l.svcCtx.Config.Register.TrialTimeUnit, l.svcCtx.Config.Register.TrialTime, startTime)
|
||||
subscribeToken := uuidx.NewUUID().String()
|
||||
subscribeUUID := uuidx.NewUUID().String()
|
||||
|
||||
userSub := &user.Subscribe{
|
||||
UserId: userId,
|
||||
OrderId: 0,
|
||||
SubscribeId: sub.Id,
|
||||
StartTime: startTime,
|
||||
ExpireTime: expireTime,
|
||||
Traffic: sub.Traffic,
|
||||
Download: 0,
|
||||
Upload: 0,
|
||||
Token: subscribeToken,
|
||||
UUID: subscribeUUID,
|
||||
Status: 1,
|
||||
}
|
||||
|
||||
if err := db.Create(userSub).Error; err != nil {
|
||||
l.Errorw("failed to insert trial subscription",
|
||||
logger.Field("user_id", userId),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
l.Infow("trial subscription activated successfully",
|
||||
logger.Field("user_id", userId),
|
||||
logger.Field("subscribe_id", sub.Id),
|
||||
logger.Field("expire_time", expireTime),
|
||||
logger.Field("traffic", sub.Traffic),
|
||||
)
|
||||
|
||||
return userSub, nil
|
||||
}
|
||||
|
||||
@@ -2,13 +2,11 @@ package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
@@ -47,29 +45,6 @@ func (l *EmailLoginLogic) EmailLogin(req *types.EmailLoginRequest) (resp *types.
|
||||
req.Code = strings.TrimSpace(req.Code)
|
||||
|
||||
// Verify Code
|
||||
scenes := []string{constant.Security.String(), constant.Register.String(), "unknown"}
|
||||
var verified bool
|
||||
var cacheKeyUsed string
|
||||
var payload common.CacheKeyPayload
|
||||
for _, scene := range scenes {
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, scene, req.Email)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil || value == "" {
|
||||
continue
|
||||
}
|
||||
if err := json.Unmarshal([]byte(value), &payload); err != nil {
|
||||
continue
|
||||
}
|
||||
if payload.Code == req.Code && time.Now().Unix()-payload.LastAt <= l.svcCtx.Config.VerifyCode.VerifyCodeExpireTime {
|
||||
verified = true
|
||||
cacheKeyUsed = cacheKey
|
||||
break
|
||||
}
|
||||
}
|
||||
if !verified {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verification code error or expired")
|
||||
}
|
||||
l.svcCtx.Redis.Del(l.ctx, cacheKeyUsed)
|
||||
|
||||
// Check User
|
||||
userInfo, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
|
||||
@@ -125,7 +100,10 @@ func (l *EmailLoginLogic) EmailLogin(req *types.EmailLoginRequest) (resp *types.
|
||||
if err = db.Create(authInfo).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if l.svcCtx.Config.Register.EnableTrial {
|
||||
rc := l.svcCtx.Config.Register
|
||||
if ShouldAutoGrantTrialOnPublicEmailFlows(rc) &&
|
||||
ShouldGrantTrialForEmail(rc, req.Email) &&
|
||||
!NormalizedEmailHasTrial(l.ctx, l.svcCtx.DB, req.Email, rc.TrialSubscribe) {
|
||||
if err = l.activeTrial(userInfo.Id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -64,6 +64,17 @@ func (l *GenerateCaptchaLogic) GenerateCaptcha() (resp *types.GenerateCaptchaRes
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
// For Turnstile, just return the site key
|
||||
resp.Id = config.TurnstileSiteKey
|
||||
} else if config.CaptchaType == "slider" {
|
||||
// For slider, generate background and block images
|
||||
sliderSvc := captcha.NewSliderService(l.svcCtx.Redis)
|
||||
id, bgImage, blockImage, err := sliderSvc.GenerateSlider(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[GenerateCaptchaLogic] Generate slider captcha error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Generate slider captcha error: %v", err.Error())
|
||||
}
|
||||
resp.Id = id
|
||||
resp.Image = bgImage
|
||||
resp.BlockImage = blockImage
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
|
||||
@@ -4,9 +4,11 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
authlogic "github.com/perfect-panel/server/internal/logic/auth"
|
||||
"github.com/perfect-panel/server/internal/model/auth"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
@@ -393,10 +395,17 @@ func (l *OAuthLoginGetTokenLogic) register(email, avatar, method, openid, reques
|
||||
}
|
||||
}
|
||||
|
||||
if l.svcCtx.Config.Register.EnableTrial {
|
||||
rc := l.svcCtx.Config.Register
|
||||
shouldActivateTrial := email != "" &&
|
||||
authlogic.ShouldAutoGrantTrialOnPublicEmailFlows(rc) &&
|
||||
authlogic.ShouldGrantTrialForEmail(rc, email) &&
|
||||
!authlogic.NormalizedEmailHasTrial(l.ctx, l.svcCtx.DB, email, rc.TrialSubscribe)
|
||||
|
||||
if shouldActivateTrial {
|
||||
l.Debugw("activating trial subscription",
|
||||
logger.Field("request_id", requestID),
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("email", email),
|
||||
)
|
||||
var trialErr error
|
||||
trialSubscribe, trialErr = l.activeTrial(userInfo.Id, requestID)
|
||||
@@ -882,3 +891,22 @@ func (l *OAuthLoginGetTokenLogic) activeTrial(uid int64, requestID string) (*use
|
||||
)
|
||||
return userSub, nil
|
||||
}
|
||||
|
||||
// isEmailDomainWhitelisted checks if the email's domain is in the comma-separated whitelist.
|
||||
// Returns false if the email format is invalid.
|
||||
func (l *OAuthLoginGetTokenLogic) isEmailDomainWhitelisted(email, whitelistCSV string) bool {
|
||||
if whitelistCSV == "" {
|
||||
return false
|
||||
}
|
||||
parts := strings.SplitN(email, "@", 2)
|
||||
if len(parts) != 2 {
|
||||
return false
|
||||
}
|
||||
domain := strings.ToLower(strings.TrimSpace(parts[1]))
|
||||
for _, d := range strings.Split(whitelistCSV, ",") {
|
||||
if strings.ToLower(strings.TrimSpace(d)) == domain {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -163,66 +163,28 @@ func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (res
|
||||
}
|
||||
|
||||
func (l *ResetPasswordLogic) verifyCaptcha(req *types.ResetPasswordRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[ResetPasswordLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
var cfg struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &cfg)
|
||||
|
||||
// Check if user reset password captcha is enabled
|
||||
if !config.EnableUserResetPasswordCaptcha {
|
||||
if !cfg.EnableUserResetPasswordCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
return captcha.VerifyCaptcha(l.ctx, l.svcCtx.Redis, cfg.CaptchaType, cfg.TurnstileSecret, captcha.VerifyInput{
|
||||
CaptchaId: req.CaptchaId,
|
||||
CaptchaCode: req.CaptchaCode,
|
||||
CfToken: req.CfToken,
|
||||
SliderToken: req.SliderToken,
|
||||
IP: req.IP,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[ResetPasswordLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[ResetPasswordLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/captcha"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type SliderVerifyCaptchaLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Verify slider captcha
|
||||
func NewSliderVerifyCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SliderVerifyCaptchaLogic {
|
||||
return &SliderVerifyCaptchaLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *SliderVerifyCaptchaLogic) SliderVerifyCaptcha(req *types.SliderVerifyCaptchaRequest) (resp *types.SliderVerifyCaptchaResponse, err error) {
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
}
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
if config.CaptchaType != string(captcha.CaptchaTypeSlider) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "slider captcha not enabled")
|
||||
}
|
||||
|
||||
sliderSvc := captcha.NewSliderService(l.svcCtx.Redis)
|
||||
token, err := sliderSvc.VerifySlider(l.ctx, req.Id, req.X, req.Y, req.Trail)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "slider verify failed: %v", err.Error())
|
||||
}
|
||||
|
||||
return &types.SliderVerifyCaptchaResponse{Token: token}, nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user