pub struct Updater {
pub client: Client,
pub owner: String,
pub name: String,
pub version: String,
pub latest_version: Option<String>,
pub download_url: Option<String>,
/* private fields */
}Expand description
Manages the complete application update process from version checking to binary replacement.
The Updater encapsulates all state and behavior needed for safe, reliable application updates. It handles GitHub API communication, platform detection, download management, and atomic binary replacement with backup and rollback capabilities.
§State Management
The Updater maintains several pieces of state throughout the update process:
- Version Information: Current and latest version tracking
- Download State: URLs and file paths for update assets
- Configuration: API endpoints and platform identification
- Check Throttling: Timestamps for rate-limited update checks
§Thread Safety
The Updater is designed for single-threaded use during update operations. While individual methods are safe to call, the update process itself should not be parallelized to avoid file system conflicts during binary replacement.
Fields§
§client: ClientHTTP client for making API requests to GitHub.
Configured with appropriate headers and timeouts for reliable communication with GitHub’s API endpoints.
owner: StringGitHub repository owner (organization or user account).
Extracted from build-time metadata to identify the source repository for release information and asset downloads.
name: StringApplication/repository name for GitHub API requests.
Combined with owner to form complete repository identification for API endpoint construction and asset discovery.
version: StringCurrent version of the running application.
Embedded at compile time to enable comparison with latest available versions from GitHub releases. Used for determining update necessity.
latest_version: Option<String>Latest version available from GitHub (if newer than current).
Populated after successful version check if a newer version is found. Used for user notifications and update confirmation messages.
download_url: Option<String>Download URL for the latest release asset matching current platform.
Determined through platform detection and asset filtering. Used for downloading the appropriate binary for the current system configuration.
Implementations§
Source§impl Updater
impl Updater
Sourcepub fn new() -> Result<Self>
pub fn new() -> Result<Self>
Creates a new Updater instance with configuration from build-time metadata.
This constructor initializes the updater with all necessary configuration for communicating with GitHub’s API and managing the update process. It uses compile-time metadata to automatically configure repository information.
§Configuration Sources
The constructor uses several sources for configuration:
- Build Metadata: Repository owner, name, and current version
- GitHub API: Standard endpoints for releases and asset discovery
- Data Storage: Platform-appropriate paths for cache and state files
- Network Configuration: HTTP client with reasonable defaults
§File System Setup
The constructor creates necessary file system entries:
- Check Cache File: For storing last update check timestamp
- Data Directory: Platform-specific application data location
- Permissions: Appropriate read/write permissions for update operations
§Returns
Returns a configured Updater instance ready for version checking and update operations, or an error if initialization fails.
§Errors
- Data Storage: Cannot determine or create application data directory
- File System: Permission issues with cache file creation
- Configuration: Invalid repository information in build metadata
§Examples
use kasl::libs::update::Updater;
let updater = Updater::new()?;
println!("Updater configured for {} v{}", updater.name, updater.version);Sourcepub async fn show_update_notification()
pub async fn show_update_notification()
Displays a notification if a new version is available, with throttled checking.
This method provides a user-friendly way to check for updates without being intrusive. It implements intelligent throttling to avoid excessive API calls while ensuring users are notified of important updates in a timely manner.
§Throttling Logic
The method implements several levels of throttling:
- Time-Based: Respects the daily check interval configuration
- Graceful Failure: Silently handles initialization or network errors
- Non-Blocking: Returns immediately if checks aren’t due
- Background Operation: Doesn’t interrupt normal application flow
§User Experience
- Non-Intrusive: Only shows notifications when updates are available
- Informative: Provides clear version information in notifications
- Actionable: Suggests how users can install available updates
- Reliable: Handles network errors gracefully without user impact
§Implementation Strategy
The method uses a fail-fast approach:
- Returns immediately if updater initialization fails
- Skips check if not enough time has passed since last check
- Only displays notification if newer version is confirmed available
- Handles all errors silently to avoid disrupting user workflow
§Examples
use kasl::libs::update::Updater;
// Call during application startup
Updater::show_update_notification().await;
// User sees notification only if update is available and check is due§Background Behavior
This method is designed to be called during application startup:
- Startup Integration: Called automatically during main application init
- Non-Blocking: Doesn’t delay application startup or user operations
- Error Resilience: Network or API failures don’t affect application functionality
- Rate Limiting: Respects GitHub API limits through intelligent throttling
Sourcepub async fn perform_update(&self) -> Result<()>
pub async fn perform_update(&self) -> Result<()>
Performs the complete update process: download, verification, and installation.
This method orchestrates the entire update workflow, from downloading the latest release to safely replacing the current executable. It implements multiple safety mechanisms to ensure the update process is reliable and recoverable in case of failures.
§Update Process Flow
The method follows a carefully designed sequence:
- Pre-flight Validation: Verifies that download URL is available
- Asset Download: Retrieves the release archive from GitHub
- Local Storage: Saves archive to temporary location for processing
- Binary Extraction: Extracts and validates the new executable
- Backup Creation: Creates backup of current executable
- Atomic Replacement: Replaces current executable with new version
- Cleanup: Removes temporary files and completes the process
§Safety Mechanisms
§Backup and Recovery
- Current Executable Backup: Automatically created before replacement
- Rollback Capability: Failed updates can be reverted using backup
- Atomic Operations: Binary replacement is performed atomically
- Error Recovery: Partial failures are cleaned up automatically
§Validation and Verification
- Download Validation: Ensures complete archive download
- Archive Integrity: Validates archive format and structure
- Binary Verification: Confirms executable is present in archive
- Platform Compatibility: Verifies binary matches current platform
§Error Handling
The method implements comprehensive error handling:
- Network Errors: Download failures are reported with clear messages
- File System Errors: Permission and disk space issues are handled
- Archive Errors: Corrupted or invalid archives are detected
- Backup Failures: Issues with backup creation abort the process
§Preconditions
This method requires that check_for_latest_release() has been called
successfully and that self.download_url contains a valid URL.
§Returns
Returns Ok(()) on successful update completion, or an error describing
the specific failure that occurred during the update process.
§Examples
use kasl::libs::update::Updater;
let mut updater = Updater::new()?;
if updater.check_for_latest_release().await? {
updater.perform_update().await?;
println!("Update completed successfully");
}§Error Scenarios
- No Download URL:
check_for_latest_release()hasn’t been called successfully - Network Failure: Unable to download release archive from GitHub
- Disk Space: Insufficient space for temporary files or backup
- Permissions: Cannot write to application directory or create backup
- Archive Corruption: Downloaded archive is corrupted or invalid format
- Missing Binary: Archive doesn’t contain expected executable file
Sourcepub async fn check_for_latest_release(&mut self) -> Result<bool>
pub async fn check_for_latest_release(&mut self) -> Result<bool>
Checks GitHub for the latest release and determines if an update is available.
This method communicates with GitHub’s releases API to fetch information about the latest available version. It compares version strings to determine if the current application version is outdated and populates the updater’s state with download information if an update is needed.
§Version Comparison Logic
The method uses string comparison for version precedence:
- Version Normalization: Strips ‘v’ prefix from GitHub tags if present
- String Comparison: Uses lexicographic comparison for version ordering
- Update Detection: Identifies when remote version is greater than current
- State Population: Stores version and download information for later use
§API Communication
§Request Configuration
- User Agent: Identifies requests with application name
- Rate Limiting: Respects GitHub’s API rate limits
- Error Handling: Gracefully handles API errors and timeouts
- JSON Parsing: Deserializes GitHub’s release response format
§Response Processing
- Version Extraction: Parses tag_name from release information
- Asset Discovery: Finds platform-appropriate download assets
- URL Resolution: Determines correct download URL for current platform
- Cache Update: Records check timestamp for throttling
§State Updates
When a newer version is found, the method updates:
- latest_version: Stores the newer version string for display
- download_url: Sets the URL for downloading the platform-specific binary
- Check Timestamp: Records when this check was performed for throttling
§Returns
Returns true if a newer version is available and download URL is found,
false if the current version is up-to-date or no compatible asset exists.
§Errors
- Network Errors: API request failures, timeouts, or connectivity issues
- API Errors: GitHub API rate limiting or service unavailability
- Parsing Errors: Invalid JSON response format from GitHub
- File System Errors: Cannot update check timestamp cache file
§Examples
use kasl::libs::update::Updater;
let mut updater = Updater::new()?;
if updater.check_for_latest_release().await? {
println!("Update available: {} -> {}",
updater.version,
updater.latest_version.unwrap());
}