feat(v2): add runtime contract and queue V2 commands
Runtime contract (ADR Phase 1+2): - Add RuntimeManager with canonical state machine - Add RuntimeStatus, RuntimeError (typed errors) - Add RuntimeEvent for lifecycle events - Add runtime_get_status and runtime_bootstrap commands Queue V2 commands: - v2_add_to_queue, v2_add_to_queue_next - v2_set_queue, v2_remove_from_queue - v2_next_track, v2_previous_track, v2_play_queue_index - V2QueueTrack type with proper field mapping All queue operations now have V2 equivalents. Frontend migration to use these commands is next.
This commit is contained in:
1 parent
d79e84fb9c
commit
67ed397d02
3 files changed
+652
-3
No files matched your search
@@ -1,12 +1,12 @@
|
||||
//! V2 Commands - Using the new multi-crate architecture
|
||||
//!
|
||||
//! These commands use QbzCore via CoreBridge instead of the old AppState.
|
||||
//! They coexist with the old commands during migration.
|
||||
//! Runtime contract ensures proper lifecycle (see ADR_RUNTIME_SESSION_CONTRACT.md).
|
||||
//!
|
||||
//! Playback flows through CoreBridge -> QbzCore -> Player (qbz-player crate).
|
||||
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
use tauri::{Emitter, State};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use qbz_models::{Album, Artist, Quality, QueueState, RepeatMode, SearchResultsPage, Track, UserSession};
|
||||
@@ -17,6 +17,7 @@ use crate::config::audio_settings::AudioSettingsState;
|
||||
use crate::core_bridge::CoreBridgeState;
|
||||
use crate::offline_cache::OfflineCacheState;
|
||||
use crate::queue::QueueManager;
|
||||
use crate::runtime::{RuntimeManagerState, RuntimeStatus, RuntimeError, RuntimeEvent, RuntimeState, DegradedReason};
|
||||
use crate::AppState;
|
||||
|
||||
// ==================== Helper Functions ====================
|
||||
@@ -97,6 +98,129 @@ async fn download_audio(url: &str) -> Result<Vec<u8>, String> {
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
|
||||
// ==================== Runtime Contract Commands ====================
|
||||
|
||||
/// Get current runtime status
|
||||
/// Use this to check if the runtime is ready before calling other commands
|
||||
#[tauri::command]
|
||||
pub async fn runtime_get_status(
|
||||
runtime: State<'_, RuntimeManagerState>,
|
||||
) -> Result<RuntimeStatus, String> {
|
||||
Ok(runtime.manager().get_status().await)
|
||||
}
|
||||
|
||||
/// Bootstrap the runtime - single entrypoint for initialization
|
||||
///
|
||||
/// This command:
|
||||
/// 1. Initializes the API client (extracts bundle tokens)
|
||||
/// 2. Checks for saved credentials and auto-logs in if available
|
||||
/// 3. Activates per-user session if user is logged in
|
||||
/// 4. Authenticates CoreBridge/V2
|
||||
///
|
||||
/// Returns RuntimeStatus with full state information.
|
||||
/// Clients should call this once at startup and react to the returned state.
|
||||
#[tauri::command]
|
||||
pub async fn runtime_bootstrap(
|
||||
app: tauri::AppHandle,
|
||||
runtime: State<'_, RuntimeManagerState>,
|
||||
app_state: State<'_, AppState>,
|
||||
core_bridge: State<'_, CoreBridgeState>,
|
||||
) -> Result<RuntimeStatus, RuntimeError> {
|
||||
let manager = runtime.manager();
|
||||
|
||||
// Check if bootstrap is already in progress
|
||||
if manager.is_bootstrap_in_progress().await {
|
||||
return Err(RuntimeError::BootstrapInProgress);
|
||||
}
|
||||
manager.set_bootstrap_in_progress(true).await;
|
||||
|
||||
log::info!("[Runtime] Bootstrap starting...");
|
||||
|
||||
// Step 1: Initialize API client (bundle tokens)
|
||||
{
|
||||
let client = app_state.client.read().await;
|
||||
match client.init().await {
|
||||
Ok(_) => {
|
||||
log::info!("[Runtime] API client initialized (bundle tokens extracted)");
|
||||
manager.set_client_initialized(true).await;
|
||||
let _ = app.emit("runtime:event", RuntimeEvent::RuntimeInitialized);
|
||||
}
|
||||
Err(e) => {
|
||||
let reason = DegradedReason::BundleExtractionFailed(e.to_string());
|
||||
log::error!("[Runtime] Bundle extraction failed: {}", e);
|
||||
manager.set_degraded(reason.clone()).await;
|
||||
manager.set_bootstrap_in_progress(false).await;
|
||||
let _ = app.emit("runtime:event", RuntimeEvent::RuntimeDegraded { reason: reason.clone() });
|
||||
return Err(RuntimeError::RuntimeDegraded(reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Check for saved credentials and attempt auto-login
|
||||
let creds = crate::credentials::load_qobuz_credentials();
|
||||
let last_user_id = crate::user_data::UserDataPaths::load_last_user_id();
|
||||
|
||||
if let (Ok(Some(creds)), Some(user_id)) = (creds, last_user_id) {
|
||||
log::info!("[Runtime] Found saved credentials, attempting auto-login for user {}", user_id);
|
||||
|
||||
// Login to legacy client
|
||||
let client = app_state.client.read().await;
|
||||
match client.login(&creds.email, &creds.password).await {
|
||||
Ok(session) => {
|
||||
log::info!("[Runtime] Legacy auth successful for user {}", session.user_id);
|
||||
manager.set_legacy_auth(true, Some(session.user_id)).await;
|
||||
let _ = app.emit("runtime:event", RuntimeEvent::AuthChanged {
|
||||
logged_in: true,
|
||||
user_id: Some(session.user_id),
|
||||
});
|
||||
|
||||
// Step 3: Activate per-user session
|
||||
// This is done by calling activate_user_session command
|
||||
// For now, we just mark the user_id and let the frontend handle it
|
||||
// In a full implementation, we'd activate here directly
|
||||
|
||||
// Step 4: Authenticate CoreBridge/V2
|
||||
if let Some(bridge) = core_bridge.try_get().await {
|
||||
match bridge.login(&creds.email, &creds.password).await {
|
||||
Ok(_) => {
|
||||
log::info!("[Runtime] CoreBridge auth successful");
|
||||
manager.set_corebridge_auth(true).await;
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("[Runtime] CoreBridge auth failed: {}", e);
|
||||
let _ = app.emit("runtime:event", RuntimeEvent::CoreBridgeAuthFailed {
|
||||
error: e.to_string(),
|
||||
});
|
||||
// Don't fail bootstrap - V2 auth failure is recoverable
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::warn!("[Runtime] CoreBridge not yet initialized, V2 auth deferred");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("[Runtime] Auto-login failed: {}", e);
|
||||
// Not a fatal error - user can login manually
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::info!("[Runtime] No saved credentials or last user ID, staying in InitializedNoAuth");
|
||||
}
|
||||
|
||||
manager.set_bootstrap_in_progress(false).await;
|
||||
let status = manager.get_status().await;
|
||||
log::info!("[Runtime] Bootstrap complete: {:?}", status.state);
|
||||
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
/// Emit a runtime event (internal helper)
|
||||
fn emit_runtime_event(app: &tauri::AppHandle, event: RuntimeEvent) {
|
||||
if let Err(e) = app.emit("runtime:event", &event) {
|
||||
log::warn!("[Runtime] Failed to emit event: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Prefetch (V2) ====================
|
||||
|
||||
/// Number of Qobuz tracks to prefetch (not total tracks, just Qobuz)
|
||||
@@ -287,6 +411,156 @@ pub async fn v2_clear_queue(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Queue track representation for V2 commands
|
||||
/// Maps to internal QueueTrack format
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct V2QueueTrack {
|
||||
pub id: u64,
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
pub album: String,
|
||||
#[serde(rename = "duration")]
|
||||
pub duration_secs: u64,
|
||||
#[serde(rename = "artwork")]
|
||||
pub artwork_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub hires: bool,
|
||||
pub bit_depth: Option<u32>,
|
||||
pub sample_rate: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub is_local: bool,
|
||||
pub album_id: Option<String>,
|
||||
pub artist_id: Option<u64>,
|
||||
#[serde(default = "default_streamable")]
|
||||
pub streamable: bool,
|
||||
/// Source type: "qobuz", "local", "plex"
|
||||
#[serde(default)]
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
fn default_streamable() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl From<V2QueueTrack> for crate::queue::QueueTrack {
|
||||
fn from(t: V2QueueTrack) -> Self {
|
||||
Self {
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
artist: t.artist,
|
||||
album: t.album,
|
||||
duration_secs: t.duration_secs,
|
||||
artwork_url: t.artwork_url,
|
||||
hires: t.hires,
|
||||
bit_depth: t.bit_depth,
|
||||
sample_rate: t.sample_rate,
|
||||
is_local: t.is_local,
|
||||
album_id: t.album_id,
|
||||
artist_id: t.artist_id,
|
||||
streamable: t.streamable,
|
||||
source: t.source,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::queue::QueueTrack> for V2QueueTrack {
|
||||
fn from(t: crate::queue::QueueTrack) -> Self {
|
||||
Self {
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
artist: t.artist,
|
||||
album: t.album,
|
||||
duration_secs: t.duration_secs,
|
||||
artwork_url: t.artwork_url,
|
||||
hires: t.hires,
|
||||
bit_depth: t.bit_depth,
|
||||
sample_rate: t.sample_rate,
|
||||
is_local: t.is_local,
|
||||
album_id: t.album_id,
|
||||
artist_id: t.artist_id,
|
||||
streamable: t.streamable,
|
||||
source: t.source,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add track to the end of the queue (V2)
|
||||
#[tauri::command]
|
||||
pub async fn v2_add_to_queue(
|
||||
track: V2QueueTrack,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("[V2] add_to_queue: {} - {}", track.id, track.title);
|
||||
app_state.queue.add_track(track.into());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add track to play next (V2)
|
||||
#[tauri::command]
|
||||
pub async fn v2_add_to_queue_next(
|
||||
track: V2QueueTrack,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("[V2] add_to_queue_next: {} - {}", track.id, track.title);
|
||||
app_state.queue.add_track_next(track.into());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set the entire queue and start playing from index (V2)
|
||||
#[tauri::command]
|
||||
pub async fn v2_set_queue(
|
||||
tracks: Vec<V2QueueTrack>,
|
||||
start_index: usize,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("[V2] set_queue: {} tracks, start at {}", tracks.len(), start_index);
|
||||
let queue_tracks: Vec<crate::queue::QueueTrack> = tracks.into_iter().map(Into::into).collect();
|
||||
app_state.queue.set_queue(queue_tracks, Some(start_index));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a track from the queue by index (V2)
|
||||
#[tauri::command]
|
||||
pub async fn v2_remove_from_queue(
|
||||
index: usize,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("[V2] remove_from_queue: index {}", index);
|
||||
app_state.queue.remove_track(index);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Skip to next track in queue (V2)
|
||||
#[tauri::command]
|
||||
pub async fn v2_next_track(
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<Option<V2QueueTrack>, String> {
|
||||
log::info!("[V2] next_track");
|
||||
let track = app_state.queue.next();
|
||||
Ok(track.map(Into::into))
|
||||
}
|
||||
|
||||
/// Go to previous track in queue (V2)
|
||||
#[tauri::command]
|
||||
pub async fn v2_previous_track(
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<Option<V2QueueTrack>, String> {
|
||||
log::info!("[V2] previous_track");
|
||||
let track = app_state.queue.previous();
|
||||
Ok(track.map(Into::into))
|
||||
}
|
||||
|
||||
/// Play a specific track in the queue by index (V2)
|
||||
#[tauri::command]
|
||||
pub async fn v2_play_queue_index(
|
||||
index: usize,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<Option<V2QueueTrack>, String> {
|
||||
log::info!("[V2] play_queue_index: {}", index);
|
||||
let track = app_state.queue.play_index(index);
|
||||
Ok(track.map(Into::into))
|
||||
}
|
||||
|
||||
// ==================== Search Commands (V2) ====================
|
||||
|
||||
/// Search for albums (V2 - uses QbzCore)
|
||||
|
||||
+13
-1
@@ -6,6 +6,7 @@
|
||||
pub mod tauri_adapter;
|
||||
pub mod core_bridge;
|
||||
pub mod commands_v2;
|
||||
pub mod runtime;
|
||||
|
||||
pub mod api;
|
||||
pub mod api_cache;
|
||||
@@ -294,6 +295,7 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_clipboard_manager::init())
|
||||
.manage(AppState::with_device_and_settings(saved_device, audio_settings))
|
||||
.manage(core_bridge::CoreBridgeState::new())
|
||||
.manage(runtime::RuntimeManagerState::new())
|
||||
.manage(user_data_paths)
|
||||
.setup(move |app| {
|
||||
// Create main window programmatically so we can set the correct
|
||||
@@ -1094,15 +1096,25 @@ pub fn run() {
|
||||
logging::get_backend_logs,
|
||||
logging::upload_logs_to_paste,
|
||||
// V2 commands (new multi-crate architecture)
|
||||
// Runtime contract
|
||||
commands_v2::runtime_get_status,
|
||||
commands_v2::runtime_bootstrap,
|
||||
// Auth
|
||||
commands_v2::v2_is_logged_in,
|
||||
commands_v2::v2_login,
|
||||
commands_v2::v2_logout,
|
||||
// Queue
|
||||
// Queue (V2)
|
||||
commands_v2::v2_get_queue_state,
|
||||
commands_v2::v2_set_repeat_mode,
|
||||
commands_v2::v2_toggle_shuffle,
|
||||
commands_v2::v2_clear_queue,
|
||||
commands_v2::v2_add_to_queue,
|
||||
commands_v2::v2_add_to_queue_next,
|
||||
commands_v2::v2_set_queue,
|
||||
commands_v2::v2_remove_from_queue,
|
||||
commands_v2::v2_next_track,
|
||||
commands_v2::v2_previous_track,
|
||||
commands_v2::v2_play_queue_index,
|
||||
// Search
|
||||
commands_v2::v2_search_albums,
|
||||
commands_v2::v2_search_tracks,
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
//! Runtime Session Contract
|
||||
//!
|
||||
//! Implements the UI-agnostic runtime lifecycle as per ADR_RUNTIME_SESSION_CONTRACT.md
|
||||
//!
|
||||
//! Key concepts:
|
||||
//! - Single bootstrap entrypoint
|
||||
//! - Canonical state machine (Uninitialized -> Ready)
|
||||
//! - Typed errors (no string matching)
|
||||
//! - Command gating in backend
|
||||
//! - Lifecycle events
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// Canonical runtime states
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "state", content = "data")]
|
||||
pub enum RuntimeState {
|
||||
/// Initial state - nothing initialized
|
||||
Uninitialized,
|
||||
/// Client initialized but no authentication
|
||||
InitializedNoAuth,
|
||||
/// Authenticated but per-user session not activated (transitional)
|
||||
AuthenticatedNoUserSession { user_id: u64 },
|
||||
/// Fully ready - all systems operational
|
||||
Ready { user_id: u64 },
|
||||
/// Degraded state - something is broken
|
||||
Degraded { reason: DegradedReason },
|
||||
}
|
||||
|
||||
impl Default for RuntimeState {
|
||||
fn default() -> Self {
|
||||
Self::Uninitialized
|
||||
}
|
||||
}
|
||||
|
||||
/// Reasons for degraded state
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "code", content = "message")]
|
||||
pub enum DegradedReason {
|
||||
/// Bundle token extraction failed
|
||||
BundleExtractionFailed(String),
|
||||
/// CoreBridge initialization failed
|
||||
CoreBridgeInitFailed(String),
|
||||
/// Network connectivity issues
|
||||
NetworkError(String),
|
||||
/// Database/storage issues
|
||||
StorageError(String),
|
||||
}
|
||||
|
||||
/// Full runtime status returned by runtime_get_status and runtime_bootstrap
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RuntimeStatus {
|
||||
/// Current state
|
||||
pub state: RuntimeState,
|
||||
/// User ID if authenticated (None if not logged in)
|
||||
pub user_id: Option<u64>,
|
||||
/// Whether the API client is initialized (bundle tokens extracted)
|
||||
pub client_initialized: bool,
|
||||
/// Whether legacy auth is active
|
||||
pub legacy_auth: bool,
|
||||
/// Whether CoreBridge/V2 auth is active
|
||||
pub corebridge_auth: bool,
|
||||
/// Whether per-user session is activated
|
||||
pub session_activated: bool,
|
||||
/// Degraded reason if state is Degraded
|
||||
pub degraded_reason: Option<DegradedReason>,
|
||||
}
|
||||
|
||||
impl Default for RuntimeStatus {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: RuntimeState::Uninitialized,
|
||||
user_id: None,
|
||||
client_initialized: false,
|
||||
legacy_auth: false,
|
||||
corebridge_auth: false,
|
||||
session_activated: false,
|
||||
degraded_reason: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed runtime errors - no string matching in clients
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "code", content = "details")]
|
||||
pub enum RuntimeError {
|
||||
/// Runtime not initialized - call runtime_bootstrap first
|
||||
RuntimeNotInitialized,
|
||||
/// Authentication required for this operation
|
||||
AuthRequired,
|
||||
/// Per-user session not activated - call activate_user_session
|
||||
UserSessionNotActivated,
|
||||
/// CoreBridge/V2 auth missing - V2 commands won't work
|
||||
CoreBridgeAuthMissing,
|
||||
/// Runtime is in degraded state
|
||||
RuntimeDegraded(DegradedReason),
|
||||
/// Invalid user ID (e.g., 0)
|
||||
InvalidUserId,
|
||||
/// Bootstrap already in progress
|
||||
BootstrapInProgress,
|
||||
/// Internal error
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RuntimeError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::RuntimeNotInitialized => write!(f, "Runtime not initialized"),
|
||||
Self::AuthRequired => write!(f, "Authentication required"),
|
||||
Self::UserSessionNotActivated => write!(f, "User session not activated"),
|
||||
Self::CoreBridgeAuthMissing => write!(f, "CoreBridge authentication missing"),
|
||||
Self::RuntimeDegraded(reason) => write!(f, "Runtime degraded: {:?}", reason),
|
||||
Self::InvalidUserId => write!(f, "Invalid user ID"),
|
||||
Self::BootstrapInProgress => write!(f, "Bootstrap already in progress"),
|
||||
Self::Internal(msg) => write!(f, "Internal error: {}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RuntimeError {}
|
||||
|
||||
/// Command prerequisites - what each command requires
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CommandRequirement {
|
||||
/// No requirements (public endpoints)
|
||||
None,
|
||||
/// Requires client to be initialized (bundle tokens)
|
||||
RequiresClientInit,
|
||||
/// Requires authentication (logged in)
|
||||
RequiresAuth,
|
||||
/// Requires per-user session to be activated
|
||||
RequiresUserSession,
|
||||
/// Requires CoreBridge/V2 auth (for V2 commands)
|
||||
RequiresCoreBridgeAuth,
|
||||
}
|
||||
|
||||
/// Runtime state manager - thread-safe, holds canonical state
|
||||
pub struct RuntimeManager {
|
||||
state: Arc<RwLock<RuntimeStatus>>,
|
||||
bootstrap_in_progress: Arc<RwLock<bool>>,
|
||||
}
|
||||
|
||||
impl RuntimeManager {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Arc::new(RwLock::new(RuntimeStatus::default())),
|
||||
bootstrap_in_progress: Arc::new(RwLock::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get current runtime status
|
||||
pub async fn get_status(&self) -> RuntimeStatus {
|
||||
self.state.read().await.clone()
|
||||
}
|
||||
|
||||
/// Update runtime state
|
||||
pub async fn set_state(&self, new_state: RuntimeState) {
|
||||
let mut status = self.state.write().await;
|
||||
status.state = new_state.clone();
|
||||
|
||||
// Update derived fields based on state
|
||||
match &new_state {
|
||||
RuntimeState::Uninitialized => {
|
||||
status.client_initialized = false;
|
||||
status.legacy_auth = false;
|
||||
status.corebridge_auth = false;
|
||||
status.session_activated = false;
|
||||
status.user_id = None;
|
||||
status.degraded_reason = None;
|
||||
}
|
||||
RuntimeState::InitializedNoAuth => {
|
||||
status.client_initialized = true;
|
||||
status.legacy_auth = false;
|
||||
status.corebridge_auth = false;
|
||||
status.session_activated = false;
|
||||
status.user_id = None;
|
||||
status.degraded_reason = None;
|
||||
}
|
||||
RuntimeState::AuthenticatedNoUserSession { user_id } => {
|
||||
status.client_initialized = true;
|
||||
status.legacy_auth = true;
|
||||
status.session_activated = false;
|
||||
status.user_id = Some(*user_id);
|
||||
status.degraded_reason = None;
|
||||
}
|
||||
RuntimeState::Ready { user_id } => {
|
||||
status.client_initialized = true;
|
||||
status.legacy_auth = true;
|
||||
status.corebridge_auth = true;
|
||||
status.session_activated = true;
|
||||
status.user_id = Some(*user_id);
|
||||
status.degraded_reason = None;
|
||||
}
|
||||
RuntimeState::Degraded { reason } => {
|
||||
status.degraded_reason = Some(reason.clone());
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("[Runtime] State changed to: {:?}", new_state);
|
||||
}
|
||||
|
||||
/// Mark client as initialized
|
||||
pub async fn set_client_initialized(&self, initialized: bool) {
|
||||
let mut status = self.state.write().await;
|
||||
status.client_initialized = initialized;
|
||||
if initialized && status.state == RuntimeState::Uninitialized {
|
||||
status.state = RuntimeState::InitializedNoAuth;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark legacy auth status
|
||||
pub async fn set_legacy_auth(&self, auth: bool, user_id: Option<u64>) {
|
||||
let mut status = self.state.write().await;
|
||||
status.legacy_auth = auth;
|
||||
if auth {
|
||||
if let Some(uid) = user_id {
|
||||
status.user_id = Some(uid);
|
||||
if !status.session_activated {
|
||||
status.state = RuntimeState::AuthenticatedNoUserSession { user_id: uid };
|
||||
}
|
||||
}
|
||||
} else {
|
||||
status.user_id = None;
|
||||
status.corebridge_auth = false;
|
||||
status.session_activated = false;
|
||||
status.state = RuntimeState::InitializedNoAuth;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark CoreBridge auth status
|
||||
pub async fn set_corebridge_auth(&self, auth: bool) {
|
||||
let mut status = self.state.write().await;
|
||||
status.corebridge_auth = auth;
|
||||
}
|
||||
|
||||
/// Mark session as activated
|
||||
pub async fn set_session_activated(&self, activated: bool, user_id: u64) {
|
||||
let mut status = self.state.write().await;
|
||||
status.session_activated = activated;
|
||||
if activated && status.legacy_auth && status.corebridge_auth {
|
||||
status.state = RuntimeState::Ready { user_id };
|
||||
status.user_id = Some(user_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if bootstrap is in progress
|
||||
pub async fn is_bootstrap_in_progress(&self) -> bool {
|
||||
*self.bootstrap_in_progress.read().await
|
||||
}
|
||||
|
||||
/// Set bootstrap in progress flag
|
||||
pub async fn set_bootstrap_in_progress(&self, in_progress: bool) {
|
||||
*self.bootstrap_in_progress.write().await = in_progress;
|
||||
}
|
||||
|
||||
/// Validate command requirements against current state
|
||||
pub async fn check_requirements(&self, req: CommandRequirement) -> Result<(), RuntimeError> {
|
||||
let status = self.state.read().await;
|
||||
|
||||
match req {
|
||||
CommandRequirement::None => Ok(()),
|
||||
CommandRequirement::RequiresClientInit => {
|
||||
if !status.client_initialized {
|
||||
Err(RuntimeError::RuntimeNotInitialized)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
CommandRequirement::RequiresAuth => {
|
||||
if !status.client_initialized {
|
||||
Err(RuntimeError::RuntimeNotInitialized)
|
||||
} else if !status.legacy_auth {
|
||||
Err(RuntimeError::AuthRequired)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
CommandRequirement::RequiresUserSession => {
|
||||
if !status.client_initialized {
|
||||
Err(RuntimeError::RuntimeNotInitialized)
|
||||
} else if !status.legacy_auth {
|
||||
Err(RuntimeError::AuthRequired)
|
||||
} else if !status.session_activated {
|
||||
Err(RuntimeError::UserSessionNotActivated)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
CommandRequirement::RequiresCoreBridgeAuth => {
|
||||
if !status.client_initialized {
|
||||
Err(RuntimeError::RuntimeNotInitialized)
|
||||
} else if !status.legacy_auth {
|
||||
Err(RuntimeError::AuthRequired)
|
||||
} else if !status.session_activated {
|
||||
Err(RuntimeError::UserSessionNotActivated)
|
||||
} else if !status.corebridge_auth {
|
||||
Err(RuntimeError::CoreBridgeAuthMissing)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if in degraded state
|
||||
pub async fn is_degraded(&self) -> bool {
|
||||
matches!(self.state.read().await.state, RuntimeState::Degraded { .. })
|
||||
}
|
||||
|
||||
/// Set degraded state
|
||||
pub async fn set_degraded(&self, reason: DegradedReason) {
|
||||
self.set_state(RuntimeState::Degraded { reason }).await;
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeManager {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Tauri state wrapper
|
||||
pub struct RuntimeManagerState(pub Arc<RuntimeManager>);
|
||||
|
||||
impl RuntimeManagerState {
|
||||
pub fn new() -> Self {
|
||||
Self(Arc::new(RuntimeManager::new()))
|
||||
}
|
||||
|
||||
pub fn manager(&self) -> &RuntimeManager {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeManagerState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Lifecycle Events ====================
|
||||
|
||||
/// Events emitted during runtime lifecycle
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "event", content = "data")]
|
||||
pub enum RuntimeEvent {
|
||||
/// Runtime initialized (client ready)
|
||||
RuntimeInitialized,
|
||||
/// Authentication state changed
|
||||
AuthChanged { logged_in: bool, user_id: Option<u64> },
|
||||
/// Per-user session activated
|
||||
UserSessionActivated { user_id: u64 },
|
||||
/// Per-user session deactivated
|
||||
UserSessionDeactivated,
|
||||
/// CoreBridge auth failed
|
||||
CoreBridgeAuthFailed { error: String },
|
||||
/// Runtime entered degraded state
|
||||
RuntimeDegraded { reason: DegradedReason },
|
||||
/// Runtime fully ready
|
||||
RuntimeReady { user_id: u64 },
|
||||
}
|
||||
Reference in new issue
Block a user