Initial commit: React client + Rust server full-stack project

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
cc 2026-06-17 20:49:17 +08:00
commit 2205408252
40 changed files with 5270 additions and 0 deletions

28
.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# --- Client ---
node_modules
dist
dist-ssr
*.local
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# --- Server ---
Server/target

2
Client/.env Normal file
View File

@ -0,0 +1,2 @@
# 后端基址(前端直连,跨源由后端 CORS 放行)。
VITE_API_BASE=http://localhost:8080

2
Client/.env.production Normal file
View File

@ -0,0 +1,2 @@
# 生产:前端由 Rust 同源托管API 用相对路径(留空即相对当前源)。
VITE_API_BASE=

24
Client/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
Client/README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

22
Client/eslint.config.js Normal file
View File

@ -0,0 +1,22 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])

13
Client/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sign in</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3180
Client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

35
Client/package.json Normal file
View File

@ -0,0 +1,35 @@
{
"name": "client",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@fontsource-variable/fraunces": "^5.2.9",
"@fontsource/hanken-grotesk": "^5.2.8",
"framer-motion": "^12.40.0",
"react": "^19.2.6",
"react-dom": "^19.2.6"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@tailwindcss/vite": "^4.3.1",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0",
"tailwindcss": "^4.3.1",
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

24
Client/public/icons.svg Normal file
View File

@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

13
Client/src/App.tsx Normal file
View File

@ -0,0 +1,13 @@
import { CursorFollower } from './components/CursorFollower'
import { LoginPage } from './components/LoginPage'
function App() {
return (
<>
<CursorFollower />
<LoginPage />
</>
)
}
export default App

BIN
Client/src/assets/hero.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@ -0,0 +1,37 @@
import { motion } from 'framer-motion'
interface AnnouncementBarProps {
text: string
/** 后端在线时显示脉冲指示点 */
online?: boolean
}
// 顶部细 bar居中文本 + 在线指示点,入场下滑。
export function AnnouncementBar({ text, online = false }: AnnouncementBarProps) {
return (
<motion.div
initial={{ y: '-100%', opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ duration: 0.7, ease: [0.22, 1, 0.36, 1] }}
className="relative z-20 border-b border-line/70 bg-surface/60 backdrop-blur-sm"
>
<div className="flex items-center justify-center gap-2.5 py-2.5">
{/* 状态点:在线脉冲,离线暗淡 */}
<span className="relative flex h-1.5 w-1.5" aria-hidden>
{online && (
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-accent opacity-60 motion-reduce:hidden" />
)}
<span
className={
'relative inline-flex h-1.5 w-1.5 rounded-full ' +
(online ? 'bg-accent' : 'bg-muted/40')
}
/>
</span>
<p className="text-center font-mono text-[11px] font-medium uppercase tracking-[0.22em] text-muted">
{text}
</p>
</div>
</motion.div>
)
}

View File

@ -0,0 +1,45 @@
import { motion } from 'framer-motion'
import { fadeUp, stagger } from './motion'
// 左侧氛围面板:动态渐变 mesh + 颗粒噪点 + 大号斜体 signature 标题
export function AtmospherePanel() {
return (
<div className="grain relative flex min-h-[280px] flex-col overflow-hidden bg-surface p-10 lg:p-14">
{/* 缓慢漂移的渐变 mesh */}
<div className="mesh" aria-hidden />
<motion.div
variants={stagger(0.3, 0.12)}
initial="hidden"
animate="show"
className="relative z-10 flex h-full flex-1 flex-col justify-between gap-12"
>
<motion.span
variants={fadeUp}
className="text-xs font-medium uppercase tracking-[0.3em] text-accent"
>
Members area
</motion.span>
{/* Signature括号 + 闪烁下划线游标 */}
<motion.h1
variants={fadeUp}
className="font-display text-5xl italic leading-[1.05] text-text sm:text-6xl lg:text-7xl"
>
Welcome{' '}
<span className="text-muted">(</span>
back
<span className="text-muted">)</span>
<span className="cursor-bar ml-1 inline-block not-italic text-accent">_</span>
</motion.h1>
<motion.p
variants={fadeUp}
className="max-w-sm text-sm leading-relaxed text-muted"
>
Pick up where you left off. Your space, your work exactly as you left it.
</motion.p>
</motion.div>
</div>
)
}

View File

@ -0,0 +1,65 @@
import { useEffect, useState } from 'react'
import { motion, useMotionValue, useSpring } from 'framer-motion'
// 跟随鼠标的小圆环(仿 Few & Far
// 仅在精确指针设备启用;触摸设备与 reduced-motion 下不挂载。
export function CursorFollower() {
const x = useMotionValue(-100)
const y = useMotionValue(-100)
const springX = useSpring(x, { stiffness: 350, damping: 28, mass: 0.4 })
const springY = useSpring(y, { stiffness: 350, damping: 28, mass: 0.4 })
const [enabled, setEnabled] = useState(false)
const [hovering, setHovering] = useState(false)
const [visible, setVisible] = useState(false)
useEffect(() => {
const fine = window.matchMedia('(pointer: fine)')
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)')
if (!fine.matches || reduce.matches) return
setEnabled(true)
document.body.classList.add('has-custom-cursor')
const handleMove = (e: MouseEvent) => {
x.set(e.clientX)
y.set(e.clientY)
setVisible(true)
const target = e.target as Element | null
setHovering(
!!target?.closest('a, button, input, textarea, select, label, [data-cursor]'),
)
}
const handleLeave = () => setVisible(false)
window.addEventListener('mousemove', handleMove)
document.addEventListener('mouseleave', handleLeave)
return () => {
window.removeEventListener('mousemove', handleMove)
document.removeEventListener('mouseleave', handleLeave)
document.body.classList.remove('has-custom-cursor')
}
}, [x, y])
if (!enabled) return null
return (
<motion.div
aria-hidden
className="pointer-events-none fixed left-0 top-0 z-[100]"
style={{ x: springX, y: springY }}
>
<motion.span
className="block rounded-full border border-accent"
style={{ translateX: '-50%', translateY: '-50%', mixBlendMode: 'difference' }}
animate={{
width: hovering ? 54 : 24,
height: hovering ? 54 : 24,
opacity: visible ? 1 : 0,
backgroundColor: hovering ? 'rgba(201, 154, 91, 0.22)' : 'rgba(201, 154, 91, 0)',
}}
transition={{ type: 'spring', stiffness: 260, damping: 20 }}
/>
</motion.div>
)
}

View File

@ -0,0 +1,72 @@
import type { FormEvent } from 'react'
import { motion } from 'framer-motion'
import { fadeUp, stagger } from './motion'
import { TextField } from './ui/TextField'
import { Button } from './ui/Button'
// 右侧登录表单:纯 UI暂无后端逻辑。
export function LoginForm() {
const handleSubmit = (e: FormEvent) => {
e.preventDefault()
// TODO: 接入 Rust 后端鉴权
}
return (
<motion.div
variants={stagger(0.5, 0.1)}
initial="hidden"
animate="show"
className="flex w-full max-w-md flex-col justify-center px-8 py-14 sm:px-12 lg:px-16"
>
<motion.div variants={fadeUp} className="mb-10">
<h2 className="font-display text-3xl font-medium text-text">Sign in</h2>
<p className="mt-2 text-sm text-muted">Enter your details to continue.</p>
</motion.div>
<form onSubmit={handleSubmit} className="flex flex-col gap-7">
<motion.div variants={fadeUp}>
<TextField label="Email" type="email" name="email" autoComplete="email" />
</motion.div>
<motion.div variants={fadeUp}>
<TextField
label="Password"
type="password"
name="password"
autoComplete="current-password"
/>
</motion.div>
<motion.div
variants={fadeUp}
className="flex items-center justify-between text-sm"
>
<label className="flex cursor-pointer items-center gap-2 text-muted">
<input
type="checkbox"
className="h-4 w-4 accent-[var(--color-accent)]"
/>
Remember me
</label>
<a
href="#"
className="text-muted underline-offset-4 transition-colors hover:text-accent hover:underline"
>
Forgot password?
</a>
</motion.div>
<motion.div variants={fadeUp} className="mt-2">
<Button type="submit">Sign in</Button>
</motion.div>
</form>
<motion.p variants={fadeUp} className="mt-8 text-center text-sm text-muted">
New here?{' '}
<a href="#" className="text-accent underline-offset-4 hover:underline">
Create an account
</a>
</motion.p>
</motion.div>
)
}

View File

@ -0,0 +1,22 @@
import { useSystemStats } from '../hooks/useSystemStats'
import { AnnouncementBar } from './AnnouncementBar'
import { AtmospherePanel } from './AtmospherePanel'
import { LoginForm } from './LoginForm'
export function LoginPage() {
// 每秒轮询后端系统状态,展示在顶部栏。
const stats = useSystemStats()
return (
<div className="flex min-h-svh flex-col bg-bg">
<AnnouncementBar text={stats.text} online={stats.online} />
<main className="grid flex-1 grid-cols-1 lg:grid-cols-[1.4fr_1fr]">
<AtmospherePanel />
<div className="flex items-center justify-center bg-bg">
<LoginForm />
</div>
</main>
</div>
)
}

View File

@ -0,0 +1,22 @@
import type { Variants } from 'framer-motion'
// 缓动自然的减速曲线ease-out expo 风格)
const EASE = [0.22, 1, 0.36, 1] as const
// 单元素淡入上浮
export const fadeUp: Variants = {
hidden: { opacity: 0, y: 22 },
show: {
opacity: 1,
y: 0,
transition: { duration: 0.7, ease: EASE },
},
}
// 容器:编排子元素依次入场
export const stagger = (delayChildren = 0.2, staggerChildren = 0.1): Variants => ({
hidden: {},
show: {
transition: { delayChildren, staggerChildren },
},
})

View File

@ -0,0 +1,27 @@
import { motion } from 'framer-motion'
import type { ComponentPropsWithoutRef } from 'react'
// 与 framer-motion 冲突的原生事件处理器从类型中剔除
type ButtonProps = Omit<
ComponentPropsWithoutRef<'button'>,
'onAnimationStart' | 'onAnimationEnd' | 'onDragStart' | 'onDragEnd' | 'onDrag'
>
export function Button({ children, className = '', ...props }: ButtonProps) {
return (
<motion.button
whileHover={{ scale: 1.015 }}
whileTap={{ scale: 0.985 }}
transition={{ type: 'spring', stiffness: 400, damping: 28 }}
className={
'group relative w-full overflow-hidden rounded-full bg-accent px-6 py-3.5 ' +
'text-sm font-medium uppercase tracking-[0.18em] text-bg ' +
'transition-colors hover:bg-accent-soft ' +
className
}
{...props}
>
<span className="relative z-10">{children}</span>
</motion.button>
)
}

View File

@ -0,0 +1,68 @@
import { useId, useState } from 'react'
import type { ChangeEvent, ComponentPropsWithoutRef, FocusEvent } from 'react'
type TextFieldProps = ComponentPropsWithoutRef<'input'> & { label: string }
export function TextField({
label,
id,
className = '',
onFocus,
onBlur,
onChange,
...props
}: TextFieldProps) {
const generatedId = useId()
const fieldId = id ?? generatedId
const [focused, setFocused] = useState(false)
const [hasValue, setHasValue] = useState(false)
const floated = focused || hasValue
const handleFocus = (e: FocusEvent<HTMLInputElement>) => {
setFocused(true)
onFocus?.(e)
}
const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
setFocused(false)
setHasValue(e.target.value.length > 0)
onBlur?.(e)
}
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setHasValue(e.target.value.length > 0)
onChange?.(e)
}
return (
<div className="relative">
<input
id={fieldId}
placeholder={label}
onFocus={handleFocus}
onBlur={handleBlur}
onChange={handleChange}
className={
'peer w-full border-0 border-b border-line bg-transparent px-0 pb-2 pt-6 ' +
'text-base text-text placeholder:text-transparent outline-none ' +
className
}
{...props}
/>
<label
htmlFor={fieldId}
className={
'pointer-events-none absolute left-0 origin-left transition-all duration-200 ' +
(floated ? 'top-0 text-xs tracking-wide text-accent' : 'top-6 text-base text-muted')
}
>
{label}
</label>
{/* 聚焦时底部线条展开 */}
<span
className={
'absolute bottom-0 left-0 h-px bg-accent transition-all duration-300 ' +
(focused ? 'w-full' : 'w-0')
}
/>
</div>
)
}

View File

@ -0,0 +1,47 @@
import { useEffect, useState } from 'react'
// 后端基址:默认本机 8080可用 VITE_API_BASE 覆盖。
const API_BASE =
(import.meta.env.VITE_API_BASE as string | undefined) ?? 'http://localhost:8080'
// 后端不可达时的回退文案(即顶部栏的默认测试文本)。
const FALLBACK = 'Now in private beta — building something better.'
export interface SystemStats {
/** 顶部栏要展示的字符串 */
text: string
/** 后端是否可达 */
online: boolean
}
/**
* `intervalMs`
* 退线
*/
export function useSystemStats(intervalMs = 1000): SystemStats {
const [stats, setStats] = useState<SystemStats>({ text: FALLBACK, online: false })
useEffect(() => {
let cancelled = false
const poll = async () => {
try {
const res = await fetch(`${API_BASE}/api/web/stats`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = (await res.json()) as { text: string }
if (!cancelled) setStats({ text: data.text, online: true })
} catch {
if (!cancelled) setStats({ text: FALLBACK, online: false })
}
}
poll() // 立即拉一次,避免首秒空白
const id = setInterval(poll, intervalMs)
return () => {
cancelled = true
clearInterval(id)
}
}, [intervalMs])
return stats
}

108
Client/src/index.css Normal file
View File

@ -0,0 +1,108 @@
/* ── Fonts (本地打包,离线/WSL 可用) ───────────────────────── */
@import '@fontsource-variable/fraunces/opsz.css';
@import '@fontsource-variable/fraunces/opsz-italic.css';
@import '@fontsource/hanken-grotesk/300.css';
@import '@fontsource/hanken-grotesk/400.css';
@import '@fontsource/hanken-grotesk/500.css';
@import '@fontsource/hanken-grotesk/600.css';
@import 'tailwindcss';
/* ── Design tokens暖调暗色编辑风──────────────────────────── */
@theme {
--color-bg: #17130f;
--color-surface: #221c16;
--color-text: #eae2d4;
--color-muted: #9b8f7e;
--color-accent: #c99a5b;
--color-accent-soft: #e0bd8a;
--color-line: #3a3027;
--font-display: 'Fraunces Variable', ui-serif, Georgia, serif;
--font-sans: 'Hanken Grotesk', system-ui, -apple-system, sans-serif;
}
/* ── Base ────────────────────────────────────────────────── */
html {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
body {
margin: 0;
min-height: 100svh;
background-color: var(--color-bg);
color: var(--color-text);
font-family: var(--font-sans);
font-weight: 400;
/* 隐藏系统光标,由 CursorFollower 接管(仅精确指针设备)*/
}
@media (pointer: fine) {
body.has-custom-cursor,
body.has-custom-cursor * {
cursor: none;
}
}
/* 选中文本配色 */
::selection {
background: var(--color-accent);
color: var(--color-bg);
}
/* 可见键盘焦点环 */
:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 2px;
}
/* ── 颗粒噪点(叠加在氛围面板上)─────────────────────────────── */
.grain::before {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0.06;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
mix-blend-mode: overlay;
}
/* ── 动态渐变 mesh缓慢漂移───────────────────────────────── */
@keyframes drift {
0% { transform: translate3d(-6%, -4%, 0) scale(1.15) rotate(0deg); }
50% { transform: translate3d(6%, 4%, 0) scale(1.25) rotate(8deg); }
100% { transform: translate3d(-6%, -4%, 0) scale(1.15) rotate(0deg); }
}
.mesh {
position: absolute;
inset: -25%;
background:
radial-gradient(40% 45% at 25% 30%, rgba(201, 154, 91, 0.45), transparent 70%),
radial-gradient(35% 40% at 75% 65%, rgba(140, 96, 64, 0.40), transparent 70%),
radial-gradient(45% 50% at 60% 20%, rgba(90, 70, 52, 0.40), transparent 70%);
filter: blur(40px);
animation: drift 26s ease-in-out infinite;
will-change: transform;
}
/* ── 标题下划线闪烁游标 ──────────────────────────────────────── */
@keyframes blink {
0%, 45% { opacity: 1; }
50%, 95% { opacity: 0; }
100% { opacity: 1; }
}
.cursor-bar {
animation: blink 1.15s steps(1, end) infinite;
}
/* ── reduced-motion 降级 ────────────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
.mesh,
.cursor-bar {
animation: none;
}
}

10
Client/src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

25
Client/tsconfig.app.json Normal file
View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

7
Client/tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

24
Client/tsconfig.node.json Normal file
View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

11
Client/vite.config.ts Normal file
View File

@ -0,0 +1,11 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
host: true, // 监听所有地址,便于 WSL/局域网访问
},
})

1
Server/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

866
Server/Cargo.lock generated Normal file
View File

@ -0,0 +1,866 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "bitflags"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
[[package]]
name = "bytes"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-channel"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-sink"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "http"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "http-body"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"pin-project-lite",
]
[[package]]
name = "http-range-header"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"
dependencies = [
"atomic-waker",
"bytes",
"futures-channel",
"futures-core",
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
]
[[package]]
name = "hyper-util"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"bytes",
"http",
"http-body",
"hyper",
"pin-project-lite",
"tokio",
"tower-service",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a"
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "mio"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "ntapi"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
dependencies = [
"winapi",
]
[[package]]
name = "objc2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags",
"dispatch2",
"objc2",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "objc2-io-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
dependencies = [
"libc",
"objc2-core-foundation",
]
[[package]]
name = "objc2-open-directory"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb82bed227edf5201dfedf072bba4015a33d3d4a98519837295a90f0a23f676d"
dependencies = [
"objc2",
"objc2-core-foundation",
"objc2-foundation",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
"itoa",
"serde",
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "server"
version = "0.1.0"
dependencies = [
"axum",
"serde",
"serde_json",
"sysinfo",
"tokio",
"tower-http",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
name = "socket2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "syn"
version = "2.0.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]]
name = "sysinfo"
version = "0.39.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21d0d938c10fcda3e897e28aaddf4ab462375d411f4378cd63b1c945f69aba96"
dependencies = [
"libc",
"memchr",
"ntapi",
"objc2-core-foundation",
"objc2-io-kit",
"objc2-open-directory",
"windows",
]
[[package]]
name = "tokio"
version = "1.52.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
dependencies = [
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-util"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tokio",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower-http"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b11f75e912b0c2be01b63d8cf8057b8c3f97cf34abb3d431a3a4c8675498e233"
dependencies = [
"bitflags",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
"http-range-header",
"httpdate",
"mime",
"mime_guess",
"percent-encoding",
"pin-project-lite",
"tokio",
"tokio-util",
"tower-layer",
"tower-service",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"log",
"pin-project-lite",
"tracing-core",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"

12
Server/Cargo.toml Normal file
View File

@ -0,0 +1,12 @@
[package]
name = "server"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8.9"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.150"
sysinfo = "0.39.3"
tokio = { version = "1.52.3", features = ["full"] }
tower-http = { version = "0.7.0", features = ["cors", "fs"] }

159
Server/README.md Normal file
View File

@ -0,0 +1,159 @@
# InternetProject 后端Rust
系统监控后端:每秒采集 CPU 使用率、内存使用率、内存总量与可用内存,
格式化成字符串,通过 HTTP 接口提供给 **React 前端**(顶部栏每秒刷新展示)。
接口按使用方分区,并为未来的 **.NET 客户端**预留了独立区域。
技术栈:`axum` 0.8 + `tokio` + `sysinfo` + `serde` + `tower-http`(cors)。
---
## 1. 整体架构与数据流
```
┌──────────────────────────────┐
每秒采样 │ 后台任务 run_sampler (tokio) │
┌────────────┐ write │ sysinfo::System 刷新指标 │
│ sysinfo │───────►│ → Stats → 写入共享快照 │
└────────────┘ └──────────────┬───────────────┘
│ Arc<RwLock<Stats>>
▼ read
浏览器(React) GET /api/web/stats ┌─────────────┐
localhost:5173 ───────────────────►│ axum 路由 │ CORS 放行前端源
◄─── JSON(Stats) ────│ 0.0.0.0:8080│
└─────────────┘
.NET 客户端 GET /api/client/* ───► 同一服务,不同接口区(无 CORS
```
**关键设计**:采样(写)与请求(读)解耦。后台任务持有 `sysinfo::System`
每秒刷新一次并写入一个 `RwLock` 保护的快照HTTP handler 只读快照、
立即返回,不会因为采集系统指标而阻塞请求。
---
## 2. 逐文件说明(`src/`
| 文件 | 职责 |
|------|------|
| `main.rs` | 入口。建 `AppState``tokio::spawn` 采样任务 → 构建路由 → 绑定 `0.0.0.0:8080``axum::serve`。 |
| `monitor.rs` | `Stats` 数据结构、格式化、后台采样循环 `run_sampler`。 |
| `state.rs` | `AppState`:被 `Arc<RwLock<…>>` 包裹的共享快照,可廉价 clone。 |
| `routes/mod.rs` | 组装并合并 `web` / `client` 两个子路由。 |
| `routes/web.rs` | 前端接口 `GET /api/web/stats`**挂 CORS**。 |
| `routes/client.rs` | 未来 .NET 客户端接口区,目前 `GET /api/client/health` 占位,**不挂 CORS**。 |
### `monitor.rs` 要点
- **`Stats`**`#[serde(rename_all = "camelCase")]`,序列化为
`text` / `cpu` / `memUsedPct` / `memTotalBytes` / `memAvailableBytes`
`text` 是给 UI 直接展示的字符串,其余原始字段留给后续可视化。
- **CPU 使用率需要两次刷新**`sysinfo` 的 CPU 占用率是两次刷新之间的差值。
所以 `run_sampler``refresh_cpu_usage()` 预热一次,等待
`MINIMUM_CPU_UPDATE_INTERVAL`,之后再进入「每秒刷新」循环,读数才准确。
- **内存单位**`sysinfo` 返回**字节**。`used = total - available`
百分比 = `used / total * 100`,展示时换算 GB。
### `state.rs` 要点
- `Arc` 让状态在「采样任务」和「每个请求」之间共享;
`RwLock` 允许多读单写(这里是单写者 + 偶发读者)。
- handler 里 `state.snapshot.read().await.clone()` 取一份快照副本后立刻释放锁。
---
## 3. CORS为什么前端要、客户端不要
**CORS跨源资源共享是浏览器的安全机制**,由浏览器强制执行:
- React 前端运行在浏览器里,页面源是 `http://localhost:5173`
而后端是 `http://localhost:8080` —— **协议/host/port 任一不同即为「跨源」**
浏览器默认禁止 JS 读取跨源响应,除非后端在响应里带上
`Access-Control-Allow-Origin` 等头声明「我允许这个源」。
所以 `web.rs``tower-http``CorsLayer` 放行前端源:
```rust
let cors = CorsLayer::new()
.allow_origin(AllowOrigin::list([
"http://localhost:5173".parse().unwrap(),
"http://127.0.0.1:5173".parse().unwrap(),
]))
.allow_methods([Method::GET]);
```
- **.NET 客户端不是浏览器**(用 `HttpClient` 直接发请求),
不存在「同源策略」,也不会发 CORS 预检、不校验响应头。
因此 `client.rs` **不挂 CORS** —— 加了也无意义。
> 一句话CORS 只拦浏览器。给前端配,给客户端不用配。
部署到生产、前端由后端托管成同源时CORS 也不会碍事;若前端换了域名,
只需在 `allow_origin` 列表里加上新源。
---
## 4. 接口分区(前端 vs 客户端不共用接口)
两类调用方走**不同的路径前缀**,在代码里也是不同的子路由模块,便于各自演进、
施加不同中间件(如 CORS、认证
| 区域 | 前缀 | 使用方 | CORS |
|------|------|--------|------|
| Web | `/api/web/*` | React 前端(浏览器) | ✅ 放行前端源 |
| Client | `/api/client/*` | 未来 .NET 客户端 | ❌ 不需要 |
---
## 5. API 参考
### `GET /api/web/stats` (前端)
```json
{
"text": "CPU 4.4% · MEM 48.3% · 15.2/31.4 GB · Free 16.2 GB",
"cpu": 4.39,
"memUsedPct": 48.35,
"memTotalBytes": 33664409600,
"memAvailableBytes": 17387958272
}
```
### `GET /api/client/health` (客户端占位)
```json
{ "status": "ok" }
```
---
## 6. 运行
```bash
# 拉依赖若慢,先给 cargo 设代理:
# export http_proxy=http://127.0.0.1:7890 https_proxy=http://127.0.0.1:7890
cd Server
cargo run # 监听 http://0.0.0.0:8080
```
快速自测:
```bash
curl http://localhost:8080/api/web/stats
curl http://localhost:8080/api/client/health
# 验证 CORS 头:
curl -i -H "Origin: http://localhost:5173" http://localhost:8080/api/web/stats | grep -i access-control
```
前端:`cd Client && npm run dev`,浏览器开 `http://localhost:5173`
顶部栏会每秒刷新系统状态字符串(后端没开时回退到默认文案、状态点变暗)。
---
## 7. 未来 .NET 客户端如何连接
客户端走 `/api/client/*`,不受 CORS 影响,直接请求即可:
```csharp
using var http = new HttpClient { BaseAddress = new Uri("http://<server-host>:8080") };
var resp = await http.GetStringAsync("/api/client/health");
// => {"status":"ok"}
```
后续把客户端要的功能加到 `routes/client.rs` 即可,与前端接口互不影响。

29
Server/src/main.rs Normal file
View File

@ -0,0 +1,29 @@
//! InternetProject 后端入口。
//!
//! 启动一个后台采样任务持续刷新系统指标,并对外提供 HTTP 接口:
//! - `GET /api/web/stats` 给 React 前端(挂 CORS
//! - `GET /api/client/health` 给未来 .NET 客户端(不挂 CORS
mod monitor;
mod routes;
mod state;
use state::AppState;
#[tokio::main]
async fn main() {
let state = AppState::new();
// 后台每秒采样系统指标,写入共享快照。
tokio::spawn(monitor::run_sampler(state.clone()));
let app = routes::build_router(state);
let addr = "0.0.0.0:8080";
let listener = tokio::net::TcpListener::bind(addr)
.await
.expect("无法绑定 0.0.0.0:8080");
println!("backend listening on http://{addr}");
axum::serve(listener, app).await.expect("server error");
}

98
Server/src/monitor.rs Normal file
View File

@ -0,0 +1,98 @@
//! 系统指标采集与格式化。
//!
//! 后台任务持有一个 `sysinfo::System`,每秒刷新一次并把结果写入共享快照。
//! HTTP handler 只读快照,不直接碰 `sysinfo`,避免阻塞请求。
use std::time::Duration;
use serde::Serialize;
use sysinfo::System;
use tokio::time::sleep;
use crate::state::AppState;
/// 一次采样的结果。`text` 是给 UI 顶部栏直接展示的字符串,
/// 其余原始字段保留给后续可视化(图表等)。
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Stats {
/// 预格式化的展示字符串
pub text: String,
/// CPU 使用率百分比0100
pub cpu: f32,
/// 内存使用率百分比0100
pub mem_used_pct: f32,
/// 内存总量(字节)
pub mem_total_bytes: u64,
/// 可用内存(字节)
pub mem_available_bytes: u64,
}
impl Default for Stats {
fn default() -> Self {
Self {
text: "Connecting…".to_string(),
cpu: 0.0,
mem_used_pct: 0.0,
mem_total_bytes: 0,
mem_available_bytes: 0,
}
}
}
fn bytes_to_gb(bytes: u64) -> f64 {
bytes as f64 / 1024.0 / 1024.0 / 1024.0
}
impl Stats {
/// 从已刷新的 `System` 读出指标并格式化。
fn from_system(sys: &System) -> Self {
let cpu = sys.global_cpu_usage();
let total = sys.total_memory();
let available = sys.available_memory();
let used = total.saturating_sub(available);
let mem_used_pct = if total > 0 {
used as f32 / total as f32 * 100.0
} else {
0.0
};
let text = format!(
"CPU {:.1}% · MEM {:.1}% · {:.1}/{:.1} GB · Free {:.1} GB",
cpu,
mem_used_pct,
bytes_to_gb(used),
bytes_to_gb(total),
bytes_to_gb(available),
);
Self {
text,
cpu,
mem_used_pct,
mem_total_bytes: total,
mem_available_bytes: available,
}
}
}
/// 后台采样循环:每秒刷新并写回共享快照。
///
/// CPU 使用率是两次刷新之间的差值,所以先预热一次(间隔
/// `MINIMUM_CPU_UPDATE_INTERVAL`),之后循环里的读数才准确。
pub async fn run_sampler(state: AppState) {
let mut sys = System::new();
sys.refresh_cpu_usage();
sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL).await;
loop {
sys.refresh_cpu_usage();
sys.refresh_memory();
let stats = Stats::from_system(&sys);
*state.snapshot.write().await = stats;
sleep(Duration::from_secs(1)).await;
}
}

View File

@ -0,0 +1,15 @@
//! 未来 .NET 客户端专用接口区。
//!
//! 与前端**不共用接口**。这里不挂 CORS——.NET 的 HttpClient 不是浏览器,
//! 不会发起/校验 CORS 预检,加了也没意义。后续客户端功能在此扩展。
use axum::{Json, Router, routing::get};
use serde_json::{Value, json};
pub fn router() -> Router {
Router::new().route("/api/client/health", get(health))
}
async fn health() -> Json<Value> {
Json(json!({ "status": "ok" }))
}

30
Server/src/routes/mod.rs Normal file
View File

@ -0,0 +1,30 @@
//! 路由组装。
//!
//! 接口按使用方分区:
//! - `web` —— 给浏览器里的 React 前端,**挂 CORS**。
//! - `client` —— 给未来的 .NET 客户端,**不挂 CORS**(非浏览器不受 CORS 约束)。
//!
//! 另外把构建好的前端静态资源作为兜底服务SPA未命中的路径回退到
//! `index.html`),让单个二进制同时托管前端 + API。静态目录默认 `static`
//! 可用环境变量 `STATIC_DIR` 覆盖。
mod client;
mod web;
use axum::Router;
use tower_http::services::{ServeDir, ServeFile};
use crate::state::AppState;
pub fn build_router(state: AppState) -> Router {
let static_dir = std::env::var("STATIC_DIR").unwrap_or_else(|_| "static".to_string());
let index_file = format!("{static_dir}/index.html");
// SPA目录里找不到的请求回退到 index.html
let serve_frontend = ServeDir::new(&static_dir).fallback(ServeFile::new(index_file));
Router::new()
.merge(web::router(state))
.merge(client::router())
// API 之外的路径交给前端静态资源
.fallback_service(serve_frontend)
}

27
Server/src/routes/web.rs Normal file
View File

@ -0,0 +1,27 @@
//! 前端React专用接口。挂 CORS仅放行前端开发源。
use axum::{Json, Router, extract::State, http::Method, routing::get};
use tower_http::cors::{AllowOrigin, CorsLayer};
use crate::{monitor::Stats, state::AppState};
pub fn router(state: AppState) -> Router {
// CORS只有浏览器会校验。放行前端开发源 + GET 方法即可。
let cors = CorsLayer::new()
.allow_origin(AllowOrigin::list([
"http://localhost:5173".parse().unwrap(),
"http://127.0.0.1:5173".parse().unwrap(),
]))
.allow_methods([Method::GET]);
Router::new()
.route("/api/web/stats", get(stats))
.layer(cors)
.with_state(state)
}
/// 返回最新系统状态快照。
async fn stats(State(state): State<AppState>) -> Json<Stats> {
let snapshot = state.snapshot.read().await.clone();
Json(snapshot)
}

24
Server/src/state.rs Normal file
View File

@ -0,0 +1,24 @@
//! 共享应用状态。
//!
//! 采样任务(写)与 HTTP handler通过一个被 `RwLock` 保护的
//! `Stats` 快照通信。`AppState` 可廉价 `clone`(内部是 `Arc`)。
use std::sync::Arc;
use tokio::sync::RwLock;
use crate::monitor::Stats;
#[derive(Clone)]
pub struct AppState {
/// 最新一次采样快照。
pub snapshot: Arc<RwLock<Stats>>,
}
impl AppState {
pub fn new() -> Self {
Self {
snapshot: Arc::new(RwLock::new(Stats::default())),
}
}
}