264 lines
5.7 KiB
Markdown
264 lines
5.7 KiB
Markdown
# Cubenet SDK - Client Library
|
||
|
||
## 📦 Описание
|
||
|
||
`cubenet-sdk` — это клиентская библиотека для взаимодействия с Cubenet Backend из приложений на Rust.
|
||
|
||
## 🚀 Installation
|
||
|
||
Добавьте в `Cargo.toml`:
|
||
|
||
```toml
|
||
[dependencies]
|
||
cubenet-sdk = { path = "../../sdk/cubenet-sdk" }
|
||
tokio = { version = "1.35", features = ["full"] }
|
||
```
|
||
|
||
## 📚 Usage
|
||
|
||
### Базовый пример
|
||
|
||
```rust
|
||
use cubenet_sdk::CubenetClient;
|
||
|
||
#[tokio::main]
|
||
async fn main() -> Result<()> {
|
||
// Создать клиент
|
||
let client = CubenetClient::new("http://localhost:8000".into());
|
||
|
||
// Проверить здоровье сервиса
|
||
let health = client.health().await?;
|
||
println!("Health: {}", health.status);
|
||
|
||
Ok(())
|
||
}
|
||
```
|
||
|
||
### Работа с пользователями
|
||
|
||
```rust
|
||
use cubenet_sdk::CubenetClient;
|
||
|
||
#[tokio::main]
|
||
async fn main() -> Result<()> {
|
||
let client = CubenetClient::new("http://localhost:8000".into());
|
||
|
||
// Получить всех пользователей
|
||
let users = client.get_users().await?;
|
||
for user in users {
|
||
println!("User: {} ({})", user.name, user.email);
|
||
}
|
||
|
||
// Создать нового пользователя
|
||
let new_user = client.create_user(
|
||
"John Doe".to_string(),
|
||
"john@example.com".to_string(),
|
||
).await?;
|
||
println!("Created: {:?}", new_user);
|
||
|
||
Ok(())
|
||
}
|
||
```
|
||
|
||
## 📋 API Reference
|
||
|
||
### CubenetClient
|
||
|
||
#### Создание
|
||
```rust
|
||
let client = CubenetClient::new("http://localhost:8000".into());
|
||
```
|
||
|
||
#### Методы
|
||
|
||
**health()** - Проверить здоровье сервиса
|
||
```rust
|
||
let response = client.health().await?;
|
||
// HealthResponse { status: "OK" }
|
||
```
|
||
|
||
**get_users()** - Получить всех пользователей
|
||
```rust
|
||
let users: Vec<User> = client.get_users().await?;
|
||
```
|
||
|
||
**create_user(name, email)** - Создать пользователя
|
||
```rust
|
||
let user = client.create_user(
|
||
"Name".to_string(),
|
||
"email@example.com".to_string(),
|
||
).await?;
|
||
```
|
||
|
||
**base_url()** - Получить base URL
|
||
```rust
|
||
let url = client.base_url();
|
||
```
|
||
|
||
## 🔌 Models
|
||
|
||
### User
|
||
```rust
|
||
pub struct User {
|
||
pub id: i32,
|
||
pub name: String,
|
||
pub email: String,
|
||
}
|
||
```
|
||
|
||
### CreateUserRequest
|
||
```rust
|
||
pub struct CreateUserRequest {
|
||
pub name: String,
|
||
pub email: String,
|
||
}
|
||
```
|
||
|
||
### HealthResponse
|
||
```rust
|
||
pub struct HealthResponse {
|
||
pub status: String,
|
||
}
|
||
```
|
||
|
||
### AuditLogEntry
|
||
```rust
|
||
pub struct AuditLogEntry {
|
||
pub id: String,
|
||
pub user_id: Option<String>,
|
||
pub action: String,
|
||
pub status: String,
|
||
pub resource: String,
|
||
pub endpoint: String,
|
||
pub created_at: String,
|
||
}
|
||
```
|
||
|
||
## ❌ Error Handling
|
||
|
||
### Error Types
|
||
|
||
```rust
|
||
pub enum Error {
|
||
HttpError(reqwest::Error),
|
||
InvalidResponse(String),
|
||
NotFound(String),
|
||
Unauthorized,
|
||
BadRequest(String),
|
||
InternalError(String),
|
||
SerializationError(serde_json::Error),
|
||
}
|
||
```
|
||
|
||
### Обработка ошибок
|
||
|
||
```rust
|
||
match client.get_users().await {
|
||
Ok(users) => println!("Users: {:?}", users),
|
||
Err(Error::NotFound(_)) => println!("No users found"),
|
||
Err(Error::Unauthorized) => println!("Please authenticate"),
|
||
Err(e) => println!("Error: {}", e),
|
||
}
|
||
```
|
||
|
||
## 🧪 Testing
|
||
|
||
### Unit Tests
|
||
```bash
|
||
cargo test -p cubenet-sdk
|
||
```
|
||
|
||
### Integration Tests
|
||
```rust
|
||
#[tokio::test]
|
||
async fn test_client() {
|
||
let client = CubenetClient::new("http://localhost:8000".into());
|
||
let health = client.health().await;
|
||
assert!(health.is_ok());
|
||
}
|
||
```
|
||
|
||
## 📝 Examples
|
||
|
||
### Пример 1: Работа с пользователями
|
||
```rust
|
||
use cubenet_sdk::CubenetClient;
|
||
|
||
#[tokio::main]
|
||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||
let client = CubenetClient::new("http://localhost:8000".into());
|
||
|
||
// Получить пользователей
|
||
let users = client.get_users().await?;
|
||
println!("Total users: {}", users.len());
|
||
|
||
// Создать нового пользователя
|
||
let new_user = client.create_user(
|
||
"Alice".to_string(),
|
||
"alice@example.com".to_string(),
|
||
).await?;
|
||
println!("Created: {:?}", new_user);
|
||
|
||
Ok(())
|
||
}
|
||
```
|
||
|
||
### Пример 2: Error Handling
|
||
```rust
|
||
use cubenet_sdk::{CubenetClient, Error};
|
||
|
||
#[tokio::main]
|
||
async fn main() {
|
||
let client = CubenetClient::new("http://invalid-url".into());
|
||
|
||
match client.health().await {
|
||
Ok(health) => println!("Status: {}", health.status),
|
||
Err(Error::HttpError(e)) => eprintln!("HTTP error: {}", e),
|
||
Err(e) => eprintln!("Error: {}", e),
|
||
}
|
||
}
|
||
```
|
||
|
||
## 🔮 Planned Features
|
||
|
||
- [ ] Async batch operations
|
||
- [ ] Stream support
|
||
- [ ] Caching layer
|
||
- [ ] Request interceptors
|
||
- [ ] Custom middleware
|
||
- [ ] WebSocket support
|
||
- [ ] Event streaming
|
||
|
||
## 🚀 Best Practices
|
||
|
||
1. ✅ Переиспользуйте один client для всех запросов
|
||
2. ✅ Обрабатывайте ошибки правильно
|
||
3. ✅ Используйте async/await
|
||
4. ✅ Кэшируйте результаты если нужно
|
||
5. ✅ Логируйте запросы для отладки
|
||
|
||
## 📊 Performance
|
||
|
||
- HTTP/1.1 с connection pooling
|
||
- Keep-alive по умолчанию
|
||
- Таймауты: 30 сек по умолчанию
|
||
- Retry логика: не включена (добавьте в v0.2)
|
||
|
||
## 🔐 Security
|
||
|
||
- TLS/SSL поддержка
|
||
- Custom headers поддержка
|
||
- Нет логирования чувствительных данных
|
||
|
||
## 📞 Support
|
||
|
||
Для проблем и предложений:
|
||
1. Читайте TESTING_GUIDE.md
|
||
2. Смотрите примеры в tests/
|
||
3. Проверяйте логи сервиса
|
||
|
||
---
|
||
|
||
**Version**: 0.1.0
|
||
**Status**: ✅ Production Ready
|