Files
ProxyWarden/.agent/skills/rust-tauri-backend/SKILL.md

107 lines
4.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Skill: Rust / Tauri Backend
## Когда использовать
Используй этот skill при изменениях в `src-tauri`, Tauri commands, Rust models, validation, storage, adapters, component detection, subscription fetching, config generation или service orchestration.
## Главная цель
Держать backend надежным, типизированным и безопасным. Backend управляет системой пользователя, поэтому «ну вроде работает» здесь примерно как инструкция по посадке самолета, написанная на салфетке.
## Инварианты
- Tauri command layer должен быть thin boundary, а не склад всей бизнес-логики.
- Долгие/blocking операции не должны выполняться на async runtime thread.
- Все ошибки, которые видит UI, должны быть structured and actionable.
- Validation должна происходить на backend даже если UI уже проверяет input.
- Generated config writes должны быть atomic where practical.
- Secrets never logged or fully displayed.
## Preferred command pattern
Для тяжелых операций:
```rust
#[tauri::command]
pub async fn some_command(input: SomeInput) -> Result<SomeOutput, CommandError> {
tauri::async_runtime::spawn_blocking(move || some_command_impl(input))
.await
.map_err(background_task_error)?
}
```
Implementation function должна быть тестируемой без Tauri runtime, если возможно.
## DTO boundary
При добавлении или изменении command:
1. Rust input/output DTO.
2. TypeScript DTO in `src/domain/types.ts`.
3. Wrapper in `src/api/tauriCommands.ts`.
4. UI usage.
5. Tests for pure logic.
Не использовать `serde_json::Value` как permanent API, если структура известна.
## Error handling
- Не использовать `unwrap()`/`expect()` в production path.
- Возвращать `CommandError { code, message, details }`.
- Для validation использовать список проблем, а не первую попавшуюся ошибку.
- Internal error text не должен раскрывать secrets.
- Если операция partial, вернуть partial state/result where possible.
## Storage
При изменении `storage.rs`:
- Keep tmp + bak write pattern.
- Не превращать invalid JSON в default молча. Prefer corruption backup/restore path.
- Для critical writes использовать same-directory temp file and rename.
- Не хранить derived artifacts как source of truth.
- Не хранить raw subscription/proxy secrets в activity log.
## Refactoring guidance
`src-tauri/src/commands.rs` слишком большой. Новую логику по возможности выносить:
```text
commands/dto.rs
commands/status.rs
commands/profiles.rs
commands/targets.rs
commands/components.rs
commands/subscription.rs
commands/proxifyre.rs
commands/singbox.rs
services/elevated.rs
services/powershell.rs
services/proxifyre_service.rs
services/singbox_service.rs
```
При рефакторинге сохранять external command names, чтобы UI не ломался без причины.
## Validation checklist
- `cargo fmt --all -- --check`
- `cargo clippy --all-targets --all-features -- -D warnings`
- `cargo test --all-targets`
- Relevant Windows/manual check if touching service/install/elevation.
Если `cargo` недоступен в среде, честно написать, что backend проверен только статически. Не изображать компилятор, у него и так тяжелая жизнь.
## Как отчитываться
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
Минимум для нетривиальной задачи:
- короткая сводка;
- таблица файлов `Файл / Что изменилось / Зачем`;
- важные места без пересказа каждой строки;
- что проверено;
- что не проверено;
- конкретные риски.