diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..c563138 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,293 @@ +# PolarisShu Architecture + +## Overview + +PolarisShu is a full-stack monorepo application built with modern web technologies. It follows a client-server architecture with a clear separation between frontend and backend concerns. + +## Tech Stack + +### Backend +- **Language**: Rust (2024 Edition) +- **Web Framework**: Salvo 0.82 +- **Async Runtime**: Tokio +- **Serialization**: Serde +- **Logging**: Tracing + Tracing-Subscriber +- **API Documentation**: OpenAPI 3.1 + Swagger UI + +### Frontend +- **Language**: TypeScript 5.8 +- **Framework**: React 19 +- **Build Tool**: Vite 7 +- **Styling**: Tailwind CSS 4 +- **HTTP Client**: Axios +- **Type Generation**: openapi-typescript + +## Architecture Diagram + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Frontend │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ React Components │ │ +│ │ ├── App.tsx (Main Application) │ │ +│ │ ├── UserList.tsx (User Display) │ │ +│ │ └── ErrorBoundary.tsx (Error Handling) │ │ +│ └─────────────────┬───────────────────────────────────┘ │ +│ │ │ +│ ┌─────────────────▼───────────────────────────────────┐ │ +│ │ Services Layer │ │ +│ │ └── api.ts (API Client with Axios) │ │ +│ └─────────────────┬───────────────────────────────────┘ │ +└────────────────────┼─────────────────────────────────────────┘ + │ HTTP Requests + │ (Vite Proxy: /api → localhost:8080) +┌────────────────────▼─────────────────────────────────────────┐ +│ Backend │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ Router & Middleware │ │ +│ │ ├── CORS Handler │ │ +│ │ └── Routes Configuration │ │ +│ └─────────────────┬───────────────────────────────────┘ │ +│ │ │ +│ ┌─────────────────▼───────────────────────────────────┐ │ +│ │ API Handlers (Endpoints) │ │ +│ │ ├── GET /api/health (Health Check) │ │ +│ │ ├── GET /api/users (List Users) │ │ +│ │ ├── GET /swagger-ui (API Documentation) │ │ +│ │ └── GET /api-docs/openapi.json (OpenAPI Spec) │ │ +│ └─────────────────┬───────────────────────────────────┘ │ +│ │ │ +│ ┌─────────────────▼───────────────────────────────────┐ │ +│ │ Models & Business Logic │ │ +│ │ ├── User Model │ │ +│ │ └── HealthResponse Model │ │ +│ └─────────────────────────────────────────────────────┘ │ +└──────────────────────────────────────────────────────────────┘ +``` + +## Project Structure + +``` +PolarisShu/ +├── backend/ # Rust backend service +│ ├── src/ +│ │ └── main.rs # Main application with all logic +│ ├── Cargo.toml # Rust dependencies +│ ├── rustfmt.toml # Code formatting config +│ └── .clippy.toml # Linting config +│ +├── frontend/ # React frontend application +│ ├── src/ +│ │ ├── components/ # React components +│ │ │ ├── UserList.tsx +│ │ │ └── ErrorBoundary.tsx +│ │ ├── services/ # API service layer +│ │ │ └── api.ts +│ │ ├── assets/ # Static assets +│ │ ├── App.tsx # Main app component +│ │ ├── main.tsx # Entry point +│ │ └── index.css # Global styles +│ ├── public/ # Public assets +│ ├── package.json # Frontend dependencies +│ ├── vite.config.ts # Vite configuration +│ ├── tailwind.config.js # Tailwind CSS config +│ ├── tsconfig.json # TypeScript config +│ ├── eslint.config.js # ESLint config +│ └── .prettierrc # Prettier config +│ +├── scripts/ # Build and dev scripts +│ ├── dev.ts # Development environment script +│ └── build.ts # Production build script +│ +├── docs/ # Documentation +│ └── ARCHITECTURE.md # This file +│ +├── README.md # Project readme +├── CONTRIBUTING.md # Contribution guidelines +├── CODE_OF_CONDUCT.md # Code of conduct +├── LICENSE # MIT License +├── package.json # Root project config +└── .gitignore # Git ignore rules +``` + +## Data Flow + +### 1. Health Check Flow +``` +User → Frontend App → GET /api/health + ↓ + Backend Handler + ↓ + Returns: {status, version, timestamp} + ↓ + Frontend Updates UI +``` + +### 2. User List Flow +``` +User → UserList Component → ApiService.getUsers() + ↓ + GET /api/users + ↓ + Backend Handler + ↓ + Returns: User[] + ↓ + Frontend Renders List +``` + +## Key Design Decisions + +### Backend + +1. **Monolithic Structure**: Currently, all backend code is in `main.rs`. As the project grows, consider splitting into modules: + - `handlers/` - Endpoint handlers + - `models/` - Data models + - `middleware/` - Custom middleware + - `config/` - Configuration management + +2. **Error Handling**: Uses Rust's Result type for error propagation. Future: implement custom error types with thiserror. + +3. **CORS Configuration**: Configured to allow localhost:5173 (Vite dev server). In production, update to allow production domain. + +4. **Logging**: Uses `tracing` crate with environment-based log levels (default: info). + +5. **API Documentation**: Auto-generated from code using Salvo's OpenAPI support. + +### Frontend + +1. **Error Boundaries**: Implemented to catch and display React errors gracefully. + +2. **API Service Layer**: Centralized API calls in `services/api.ts` for better maintainability. + +3. **Type Safety**: TypeScript strict mode enabled for maximum type safety. + +4. **State Management**: Currently uses React hooks (useState, useEffect). For complex state, consider Redux or Zustand. + +5. **Styling**: Tailwind CSS for utility-first styling approach. + +## Communication Patterns + +### API Communication +- **Protocol**: HTTP/1.1 +- **Data Format**: JSON +- **Error Handling**: HTTP status codes + error messages +- **CORS**: Enabled for development (localhost:5173) + +### Development Proxy +Vite dev server proxies `/api/*` requests to `localhost:8080` to avoid CORS issues during development. + +## Security Considerations + +1. **CORS**: Properly configured but needs production domain update +2. **Input Validation**: TODO - Add request validation +3. **Authentication**: TODO - Implement JWT or session-based auth +4. **Rate Limiting**: TODO - Add rate limiting middleware +5. **HTTPS**: TODO - Configure TLS for production + +## Performance Considerations + +1. **Backend**: + - Async I/O with Tokio for high concurrency + - Minimal allocations with Rust's zero-cost abstractions + - TODO: Add database connection pooling + +2. **Frontend**: + - Code splitting with Vite + - Lazy loading components + - TODO: Implement virtual scrolling for large lists + - TODO: Add service worker for offline support + +## Future Architecture Plans + +### Backend +- [ ] Add database layer (PostgreSQL or SQLite) +- [ ] Implement repository pattern +- [ ] Add caching layer (Redis) +- [ ] Implement authentication/authorization +- [ ] Add background job processing +- [ ] Implement rate limiting +- [ ] Add request validation middleware + +### Frontend +- [ ] Implement routing (React Router) +- [ ] Add state management (Redux/Zustand) +- [ ] Implement real-time updates (WebSocket) +- [ ] Add offline support (Service Worker) +- [ ] Implement infinite scroll +- [ ] Add search and filtering +- [ ] Implement internationalization (i18n) + +### DevOps +- [ ] Add Docker support +- [ ] Implement CI/CD pipeline +- [ ] Add automated testing +- [ ] Set up monitoring and logging +- [ ] Implement blue-green deployment + +## Deployment Strategy + +### Development +```bash +bun run dev # Starts both frontend and backend +``` + +### Production +```bash +# Backend +cd backend && cargo build --release +./target/release/backend + +# Frontend +cd frontend && npm run build +# Serve dist/ with nginx or static server +``` + +### Recommended Production Setup +``` +┌─────────────┐ +│ Nginx │ Reverse Proxy +│ (443) │ SSL Termination +└──────┬──────┘ + │ + ├─────────┐ + │ │ + Frontend Backend + (Static) (8080) +``` + +## Testing Strategy + +### Backend (TODO) +- Unit tests: `cargo test` +- Integration tests: API endpoint tests +- Load testing: k6 or vegeta + +### Frontend (TODO) +- Unit tests: Vitest +- Component tests: React Testing Library +- E2E tests: Playwright or Cypress + +## Monitoring and Observability + +### Logging +- Backend: `tracing` crate with structured logging +- Frontend: Browser console + error reporting + +### Metrics (TODO) +- Request latency +- Error rates +- Active users +- API endpoint usage + +### Tracing (TODO) +- Distributed tracing with OpenTelemetry +- Request flow visualization + +## Contributing + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for development workflow and coding standards. + +## License + +MIT License - See [LICENSE](../LICENSE) for details. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..41aee43 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,69 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- **Documentation**: + - Comprehensive README with project details, setup instructions, and development workflow + - CONTRIBUTING.md with contribution guidelines and coding standards + - CODE_OF_CONDUCT.md for community guidelines + - MIT LICENSE file + - ARCHITECTURE.md with detailed system architecture documentation + - CHANGELOG.md for tracking project changes + +- **Backend**: + - Health check endpoint at `/api/health` returning status, version, and timestamp + - CORS middleware with configurable origin (via `CORS_ALLOWED_ORIGIN` env var) + - Structured logging with tracing crate and environment-based log levels + - Enhanced API documentation with OpenAPI 3.1 + - Code formatting configuration (rustfmt.toml) + - Linting configuration (.clippy.toml) + - Environment variable documentation (.env.example) + - Proper error handling and request logging + +- **Frontend**: + - ErrorBoundary component for graceful error handling + - Environment variable documentation (.env.example) + - Code formatting configuration (.prettierrc) + - Type-safe User interface in API service + - Health check integration in status checking + +### Changed +- **Backend**: + - Enhanced code organization with comprehensive documentation + - Improved error handling and logging throughout + - Updated API title to "PolarisShu Backend API" + - Made CORS origin configurable via environment variable + +- **Frontend**: + - Updated API service to use dedicated health check endpoint + - Improved type safety by defining User interface locally + - Enhanced error handling with ErrorBoundary wrapper + +### Fixed +- TypeScript build errors in frontend components +- Proper type imports in ErrorBoundary component +- CORS configuration now supports multiple environments + +### Security +- CORS properly configured with environment-based origins +- TypeScript strict mode enabled for maximum type safety +- No vulnerabilities found in npm audit + +## [0.1.0] - 2025-12-29 + +### Added +- Initial project setup with Rust backend (Salvo framework) +- React frontend with TypeScript and Tailwind CSS +- User list API endpoint +- OpenAPI documentation with Swagger UI +- Development and build scripts +- Basic project structure and configuration + +[Unreleased]: https://github.com/nkanf-dev/PolarisShu/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/nkanf-dev/PolarisShu/releases/tag/v0.1.0 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..814023a --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,88 @@ +# 社区行为准则 Code of Conduct + +## 我们的承诺 + +为了营造一个开放和友好的环境,我们作为贡献者和维护者承诺:无论年龄、体型、残疾、民族、性别认同和表达、经验水平、教育程度、社会经济地位、国籍、个人外貌、种族、宗教或性取向如何,参与我们的项目和社区的每个人都能享受无骚扰的体验。 + +## 我们的标准 + +有助于创造积极环境的行为包括: + +- 使用友好和包容的语言 +- 尊重不同的观点和经验 +- 优雅地接受建设性批评 +- 关注对社区最有利的事情 +- 对其他社区成员表示同理心 + +不可接受的行为包括: + +- 使用性化的语言或图像,以及不受欢迎的性关注或骚扰 +- 挑衅、侮辱/贬损性评论,以及人身或政治攻击 +- 公开或私下骚扰 +- 未经明确许可,发布他人的私人信息,如物理地址或电子邮件地址 +- 在专业环境中可能被合理认为不适当的其他行为 + +## 我们的责任 + +项目维护者有责任明确可接受行为的标准,并对任何不可接受的行为采取适当和公平的纠正措施。 + +项目维护者有权利和责任删除、编辑或拒绝与本行为准则不符的评论、提交、代码、wiki 编辑、问题和其他贡献,或暂时或永久禁止任何贡献者从事他们认为不适当、威胁、冒犯或有害的其他行为。 + +## 范围 + +本行为准则适用于项目空间和公共空间,当个人代表项目或其社区时。代表项目或社区的示例包括使用官方项目电子邮件地址、通过官方社交媒体账户发布信息,或在在线或离线活动中担任指定代表。 + +## 执行 + +可以通过联系项目团队报告滥用、骚扰或其他不可接受的行为。所有投诉都将被审查和调查,并将做出被认为必要和适当的回应。项目团队有义务对事件报告者保密。具体执行政策的进一步细节可能会单独发布。 + +不善意遵守或执行行为准则的项目维护者可能会面临项目领导层其他成员确定的临时或永久性后果。 + +## 归属 + +本行为准则改编自 [Contributor Covenant](https://www.contributor-covenant.org/),版本 1.4, +可在 https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 获取 + +--- + +## Code of Conduct (English) + +### Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +### Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +### Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +### Scope + +This Code of Conduct applies within all project spaces and in public spaces when an individual is representing the project or its community. + +### Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. + +### Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 1.4. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..12d0745 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,336 @@ +# 贡献指南 Contributing Guide + +感谢您对 PolarisShu 项目的关注!我们欢迎任何形式的贡献。 + +## 📋 目录 + +- [行为准则](#行为准则) +- [如何贡献](#如何贡献) +- [开发流程](#开发流程) +- [代码规范](#代码规范) +- [提交规范](#提交规范) +- [Pull Request 流程](#pull-request-流程) + +## 行为准则 + +请阅读并遵守我们的 [行为准则](CODE_OF_CONDUCT.md),以确保社区的友好和包容。 + +## 如何贡献 + +### 报告 Bug + +如果您发现了 bug,请: + +1. 在 [Issues](https://github.com/nkanf-dev/PolarisShu/issues) 中搜索是否已有相关问题 +2. 如果没有,创建新 issue,并包含: + - 清晰的标题和描述 + - 重现步骤 + - 预期行为和实际行为 + - 环境信息(操作系统、Rust/Bun 版本等) + - 如果可能,提供错误日志或截图 + +### 提出新功能 + +1. 先创建一个 issue 讨论您的想法 +2. 说明为什么需要这个功能 +3. 描述功能的预期行为 +4. 等待维护者反馈后再开始实现 + +### 改进文档 + +文档改进无需创建 issue,直接提交 PR 即可。包括但不限于: +- 修正错别字 +- 改进表述 +- 添加示例 +- 翻译文档 + +## 开发流程 + +### 1. Fork 和 Clone + +```bash +# Fork 项目到您的 GitHub 账号 +# 然后 clone 到本地 +git clone https://github.com/YOUR-USERNAME/PolarisShu.git +cd PolarisShu + +# 添加上游仓库 +git remote add upstream https://github.com/nkanf-dev/PolarisShu.git +``` + +### 2. 创建分支 + +```bash +# 更新主分支 +git checkout main +git pull upstream main + +# 创建功能分支 +git checkout -b feature/your-feature-name +# 或 +git checkout -b fix/your-bug-fix +``` + +### 3. 安装依赖 + +```bash +# 安装前端依赖 +bun install +cd frontend && bun install && cd .. + +# 后端依赖会在首次构建时自动安装 +``` + +### 4. 开始开发 + +```bash +# 启动开发环境 +bun run dev +``` + +### 5. 测试您的更改 + +```bash +# 前端测试 +cd frontend && bun run lint + +# 后端测试 +cd backend +cargo test +cargo clippy +cargo fmt --check +``` + +### 6. 提交更改 + +```bash +git add . +git commit -m "feat: add amazing feature" +git push origin feature/your-feature-name +``` + +### 7. 创建 Pull Request + +1. 在 GitHub 上打开您的 fork +2. 点击 "New Pull Request" +3. 选择您的分支 +4. 填写 PR 描述(参考模板) +5. 等待审查 + +## 代码规范 + +### Rust 代码规范 + +遵循 Rust 官方风格指南: + +```bash +# 格式化代码 +cargo fmt + +# 运行 Clippy 检查 +cargo clippy -- -D warnings + +# 运行测试 +cargo test +``` + +**规范要点**: +- 使用 4 空格缩进 +- 遵循 Rust API 指南的命名约定 +- 为公共 API 编写文档注释 +- 添加单元测试覆盖新功能 +- 使用 `Result` 类型处理错误 +- 避免 `unwrap()`,使用 `?` 操作符或正确的错误处理 + +### TypeScript/React 代码规范 + +使用 ESLint 进行代码检查: + +```bash +cd frontend +bun run lint +``` + +**规范要点**: +- 使用 2 空格缩进 +- 使用 TypeScript 严格模式 +- 函数组件使用 `React.FC` 类型 +- Props 接口以组件名 + `Props` 命名 +- 使用 `const` 声明函数组件 +- 为所有 props 添加类型定义 +- 使用语义化的 HTML 标签 +- 添加适当的 ARIA 属性以提高可访问性 + +### 样式规范 + +- 使用 Tailwind CSS 实用类 +- 避免内联样式(除非必要) +- 保持样式类的顺序一致:布局 → 尺寸 → 外观 → 文字 + +## 提交规范 + +使用 [Conventional Commits](https://www.conventionalcommits.org/) 规范: + +``` +(): + + + +