Files
chanora/crates/chanora_protocol/src/lib.rs
T
Edison Jwa aa796d7395 feat: file transfer system (avatar/icon download with cacache) (#40)
* docs(architecture): add file transfer design, research, and implementation plan

* feat(cache): add chanora_cache crate with cacache-backed blob cache

- New chanora_cache crate: content-addressed blob store wrapping cacache
- BlobCache API: async put/get/remove/clear/total_size/evict
- Key validation: av_ prefix (32 hex chars), ic_ prefix (decimal digits)
- Cacache provides crash safety, SSRI integrity, content dedup
- Mtime-based eviction via cacache::list_sync + sort by timestamp
- 7 unit tests all passing
- Added to workspace members

* feat(protocol): add file download support for avatars and icons

- Add Request::DownloadFile variant with oneshot reply
- Add ProtocolClient::download_avatar(client_uid) and download_icon(icon_id)
- Track pending file downloads by FiletransferHandle
- Handle StreamItem::FileDownload: read bytes from TCP stream
- Handle StreamItem::FiletransferFailed: map to ProtocolError
- Add ProtocolError::FileTransfer(String) variant
- Add path helper tests for avatar/icon download paths
- No tsclientlib types leak across the adapter boundary

* feat(core): add blob cache wiring and avatar download orchestration

- Add chanora_cache dependency to Cargo.toml
- Add blob_cache field to ChanoraSession (Arc<Mutex<Option<BlobCache>>>)
- Add init_cache() method: creates BlobCache, runs eviction
- Add get_avatar() method: cache-first, download on miss, store in cache
- Add clear_cache() and cache_size() methods for cache management
- Add CoreError::Cache variant for BlobCacheError conversion
- Add avatar_cache integration test

* feat(bridge): add init_cache, download_avatar, and cache management functions

- Add init_cache(dir) bridge function
- Add download_avatar(avatar_hash, client_uid) bridge function
- Add clear_file_cache() and file_cache_size() bridge functions
- Map CoreError::Cache and ProtocolError::FileTransfer in BridgeError

* feat(flutter): add cache initialization wiring and avatar download shims

- Add wireCache() to app_bootstrap using getApplicationCacheDirectory()
- Call wireCache() after wireStorage() in main bootstrap flow
- Add Dart-side initCache and downloadAvatar wrapper shims in api.dart
- Update Cargo.lock for new chanora_cache dependency

* feat(core): FileTransferService with coalescing, throttling, negative cache

- New file_transfer module with FileTransferService struct
- Semaphore(2) throttles concurrent downloads
- In-flight HashMap coalesces duplicate avatar requests
- 5-min negative cache short-circuits ServerRejected misses
- ChanoraSession delegates get_avatar through the service
- connect/disconnect update shared protocol handle
- clear_cache/cache_size delegate to service
- 2 new unit tests (cached hit, negative cache)

* feat(core,bridge): add get_icon with coalescing and negative cache

- FileTransferService::get_icon() mirrors get_avatar pattern
- ChanoraSession::get_icon() delegates through FileTransferService
- Bridge download_icon() exposed for Flutter
- Dart downloadIcon() shim added
- Uses PREFIX_ICON (ic_<crc32u>) cache key format
- 1 new unit test (cached icon hit)

* fix(core,protocol): simplify store_protocol and add download size cap

- store_protocol: always write to shared Arc<Mutex<Option<ProtocolClient>>>;
  the FileTransferService holds the same Arc so it sees updates automatically
- read_download_bytes: reject downloads exceeding 10 MB to prevent
  malicious servers from causing OOM
2026-06-10 11:45:14 +09:00

123 lines
4.4 KiB
Rust

//! # `chanora_protocol`
//!
//! TeamSpeak-compatible protocol adapter. Isolates `tsclientlib`
//! behind a typed boundary so the rest of Chanora is decoupled from
//! the upstream library's types (SAD-067, SysDes-011, SysDes-029).
//!
//! ## What this crate exposes
//!
//! * [`ConnectConfig`] — typed connection parameters.
//! * [`ProtocolClient`] — async handle owning the connection task.
//! * [`ServerSnapshot`], [`ChannelInfo`], [`ClientInfo`],
//! [`ClientProfile`] — opaque
//! DTOs containing only `String`s and primitives.
//! * [`ProtocolError`] — typed error catalogue.
//!
//! ## What this crate does NOT expose
//!
//! * `tsclientlib::*` types.
//! * `tsproto::*` types.
//! * Any audio-related types — those live in `chanora_audio`.
//!
//! Promoted from `poc/tsclientlib-connect-spike` on 2026-05-14
//! as part of the Alpha build.
//!
//! ## Server address resolution (A.1)
//!
//! `chanora_resolver` owns TeamSpeak client address resolution:
//! server-name aliases, `_ts3._udp` SRV, TSDNS SRV/TCP, and DNS
//! fallback. This crate asks it for a final IP `host:port` and feeds
//! the resulting `SocketAddr` directly to `tsclientlib::Connection::build`
//! so tsclientlib's own resolver is not used.
#![forbid(unsafe_code)]
#![warn(missing_docs)]
mod adapter;
mod dto;
pub mod poke_limiter;
pub use adapter::{ConnectConfig, DisconnectReason, InboundVoice, ProtocolClient, SnapshotProbe};
pub use dto::{
ChannelId, ChannelInfo, ChatMessage, ClientId, ClientInfo, ClientProfile, MessageTarget,
PokeStrength, ProtocolDelta, ServerActivity, ServerSnapshot,
};
pub use poke_limiter::PokeLimiter;
// Re-export the upstream voice types so chanora_audio can build outbound
// voice packets without taking a direct dependency on tsclientlib /
// tsproto_packets. Per SAD-067 this is the *one* deliberate
// re-export: the audio path is performance-sensitive and a parallel
// type hierarchy would force copies for every 20 ms frame.
pub use tsproto_packets::packets::{
AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket,
};
use thiserror::Error;
/// Errors surfaced by the protocol adapter. None of these expose
/// `tsclientlib`-specific types; raw upstream errors are mapped here
/// to typed arms.
#[derive(Debug, Error)]
pub enum ProtocolError {
/// Configuration is invalid before any I/O is attempted (bad
/// hostname, missing identity, etc.).
#[error("invalid protocol configuration: {0}")]
Invalid(String),
/// Hostname resolution failed. Distinct from [`Self::Connect`]
/// so the UI can show a meaningful "Server not found" message
/// instead of a generic connection error.
#[error("dns lookup failed for '{host}': {reason}")]
DnsFailed {
/// The hostname (or `host:port`) the caller submitted.
host: String,
/// Reason from the platform resolver.
reason: String,
},
/// Failed to dial / handshake with the server.
#[error("connect failed: {0}")]
Connect(String),
/// The connection ended before becoming ready.
#[error("disconnected before ready: {0}")]
DisconnectedEarly(String),
/// Connection lost after becoming ready.
#[error("connection lost: {0}")]
Lost(String),
/// Identity parsing failed.
#[error("identity error: {0}")]
Identity(String),
/// Operation timed out.
#[error("protocol timeout")]
Timeout,
/// A server command was rejected by the TeamSpeak server with
/// a typed error code. The `code` is the raw TS3 error number
/// (see https://github.com/ReSpeak/tsdeclarations Errors.csv),
/// and `message` is the server-supplied human-readable text.
/// Distinguishing this from `Backend` lets the UI surface a
/// localised explanation (insufficient permission, wrong
/// channel password, etc.) instead of a generic failure.
#[error("server rejected (code {code}): {message}")]
ServerRejected {
/// Raw TS3 error code (e.g. 0x0a08 = `permissions_client_insufficient`).
code: u32,
/// Server-supplied message text.
message: String,
},
/// A backend error escaped the mapping. Production callers
/// should never see this; if they do, it is a mapping bug here.
#[error("protocol backend: {0}")]
Backend(String),
/// A file transfer failed while downloading protocol-owned assets.
#[error("file transfer failed: {0}")]
FileTransfer(String),
}