refactor(qconnect): share delegation lifecycle
Move authority fences, preflight, rejoin watchdogs, LAN projection, and physical runtime teardown into qconnect-app for both Qt and qbzd. cx
This commit is contained in:
19 files changed
+1839
-1897
No files matched your search
Generated
+1
@@ -4729,6 +4729,7 @@ dependencies = [
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"uuid 1.26.0",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+160
-101
@@ -116,27 +116,60 @@ fn observe_owner_action() -> OwnerActionObservation {
|
||||
token: OwnerActionToken::Qconnect(token),
|
||||
})
|
||||
}
|
||||
qconnect_app::OwnerAuthorityObservation::Delegated => {
|
||||
OwnerActionObservation::Delegated
|
||||
}
|
||||
qconnect_app::OwnerAuthorityObservation::Delegated => OwnerActionObservation::Delegated,
|
||||
qconnect_app::OwnerAuthorityObservation::Fenced => OwnerActionObservation::Fenced,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
enum OwnerScopedSnapshot<T> {
|
||||
Captured {
|
||||
owner_action: Option<OwnerActionLease>,
|
||||
snapshot: T,
|
||||
},
|
||||
Fenced,
|
||||
}
|
||||
|
||||
/// Freeze the authority observation before reading a local playback snapshot.
|
||||
/// A fallible transition fence does not consume the snapshot at all; delegated
|
||||
/// playback may still be read for UI/reporting but carries no owner permit.
|
||||
fn capture_owner_scoped_snapshot<T>(
|
||||
observe: impl FnOnce() -> OwnerActionObservation,
|
||||
read: impl FnOnce() -> T,
|
||||
) -> OwnerScopedSnapshot<T> {
|
||||
match observe() {
|
||||
OwnerActionObservation::Owner(owner_action) => OwnerScopedSnapshot::Captured {
|
||||
owner_action: Some(owner_action),
|
||||
snapshot: read(),
|
||||
},
|
||||
OwnerActionObservation::Delegated => OwnerScopedSnapshot::Captured {
|
||||
owner_action: None,
|
||||
snapshot: read(),
|
||||
},
|
||||
OwnerActionObservation::Fenced => OwnerScopedSnapshot::Fenced,
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_generation_changed(
|
||||
observed: Option<OwnerActionToken>,
|
||||
previous: Option<OwnerActionToken>,
|
||||
) -> bool {
|
||||
observed.is_some() && observed != previous
|
||||
}
|
||||
|
||||
/// Re-admit a queued continuation only for the authority generation that read
|
||||
/// its input. This is deliberately different from [`begin_owner_action`]: a
|
||||
/// guest -> owner promotion must not legitimize work derived from guest state.
|
||||
pub(crate) async fn begin_owner_action_exact(
|
||||
token: OwnerActionToken,
|
||||
) -> Option<OwnerActionLease> {
|
||||
pub(crate) async fn begin_owner_action_exact(token: OwnerActionToken) -> Option<OwnerActionLease> {
|
||||
match token {
|
||||
OwnerActionToken::BeforeService => crate::qconnect_qt::service()
|
||||
.is_none()
|
||||
.then_some(OwnerActionLease {
|
||||
_permit: None,
|
||||
token,
|
||||
}),
|
||||
OwnerActionToken::BeforeService => {
|
||||
crate::qconnect_qt::service()
|
||||
.is_none()
|
||||
.then_some(OwnerActionLease {
|
||||
_permit: None,
|
||||
token,
|
||||
})
|
||||
}
|
||||
OwnerActionToken::Qconnect(token) => crate::qconnect_qt::service()?
|
||||
.wait_for_exact_owner_action_permit(token)
|
||||
.await
|
||||
@@ -278,9 +311,7 @@ where
|
||||
let generation = owner_playback_task_generation();
|
||||
let (start_tx, start_rx) = tokio::sync::oneshot::channel();
|
||||
let task = tokio::spawn(async move {
|
||||
if start_rx.await.is_err()
|
||||
|| owner_playback_task_generation() != generation
|
||||
{
|
||||
if start_rx.await.is_err() || owner_playback_task_generation() != generation {
|
||||
return;
|
||||
}
|
||||
future.await;
|
||||
@@ -319,7 +350,10 @@ pub(crate) fn cancel_owner_playback_tasks() {
|
||||
let mut tasks = owner_playback_tasks()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
tasks.drain(..).map(|(_, handle)| handle).collect::<Vec<_>>()
|
||||
tasks
|
||||
.drain(..)
|
||||
.map(|(_, handle)| handle)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for handle in handles {
|
||||
handle.abort();
|
||||
@@ -1312,7 +1346,9 @@ pub(crate) async fn restore_owner_playback(
|
||||
match qbz_source::registry().claim(&raw) {
|
||||
Ok(item) => Some(item),
|
||||
Err(error) if track.is_local => {
|
||||
return Err(format!("owner source restore could not claim its row: {error}"));
|
||||
return Err(format!(
|
||||
"owner source restore could not claim its row: {error}"
|
||||
));
|
||||
}
|
||||
// Legacy Qobuz queue snapshots may predate the explicit `source`
|
||||
// field. Preserve their catalog fallback when `is_local` is false.
|
||||
@@ -3714,15 +3750,20 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
|
||||
// The error slot is itself a playback snapshot. Admit before
|
||||
// draining it so a guest error cannot be applied to an owner
|
||||
// row after a guest -> owner promotion.
|
||||
let error_owner_snapshot = match observe_owner_action() {
|
||||
OwnerActionObservation::Owner(owner_action) => Some(owner_action),
|
||||
OwnerActionObservation::Delegated => None,
|
||||
// Do not drain an owner error or perturb playback edge
|
||||
// bookkeeping merely because a candidate is still inside
|
||||
// its fallible, pre-commit fence.
|
||||
OwnerActionObservation::Fenced => continue,
|
||||
};
|
||||
if let Some(msg) = runtime.core().player().state.take_stream_error_message() {
|
||||
let (error_owner_snapshot, stream_error) =
|
||||
match capture_owner_scoped_snapshot(observe_owner_action, || {
|
||||
runtime.core().player().state.take_stream_error_message()
|
||||
}) {
|
||||
OwnerScopedSnapshot::Captured {
|
||||
owner_action,
|
||||
snapshot,
|
||||
} => (owner_action, snapshot),
|
||||
// Do not drain an owner error or perturb playback edge
|
||||
// bookkeeping merely because a candidate is still inside
|
||||
// its fallible, pre-commit fence.
|
||||
OwnerScopedSnapshot::Fenced => continue,
|
||||
};
|
||||
if let Some(msg) = stream_error {
|
||||
log::error!("[qbz-qt] audio output error: {msg}");
|
||||
let sandboxed = !matches!(
|
||||
qbz_audio::health::detect_sandbox(),
|
||||
@@ -3948,15 +3989,19 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
|
||||
// snapshot. `None` is a valid delegated observation: UI/QConnect
|
||||
// reporting remain live, but owner-only consumers must use this
|
||||
// exact result and may not obtain a fresh permit later in the tick.
|
||||
let owner_snapshot = match observe_owner_action() {
|
||||
OwnerActionObservation::Owner(owner_action) => Some(owner_action),
|
||||
OwnerActionObservation::Delegated => None,
|
||||
// Preserve last_track_id / last_owner_token and every owner
|
||||
// integration across a candidate that may still fail. Only an
|
||||
// actually installed guest is an authority edge.
|
||||
OwnerActionObservation::Fenced => continue,
|
||||
};
|
||||
let event = runtime.core().player().get_playback_event();
|
||||
let (owner_snapshot, event) =
|
||||
match capture_owner_scoped_snapshot(observe_owner_action, || {
|
||||
runtime.core().player().get_playback_event()
|
||||
}) {
|
||||
OwnerScopedSnapshot::Captured {
|
||||
owner_action,
|
||||
snapshot,
|
||||
} => (owner_action, snapshot),
|
||||
// Preserve last_track_id / last_owner_token and every owner
|
||||
// integration across a candidate that may still fail. Only an
|
||||
// actually installed guest is an authority edge.
|
||||
OwnerScopedSnapshot::Fenced => continue,
|
||||
};
|
||||
let track_id = event.track_id;
|
||||
let position = event.position;
|
||||
let duration = event.duration;
|
||||
@@ -4003,9 +4048,8 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
|
||||
// numeric track id nor the sampled Option-ness changed. The old
|
||||
// delayed integrations were invalidated by that authority cycle,
|
||||
// so this fresh snapshot must re-arm their edge work.
|
||||
let owner_generation_changed = observed_owner_token.is_some()
|
||||
&& observed_owner_token != last_owner_token;
|
||||
if track_id != 0 && (track_id != last_track_id || owner_generation_changed) {
|
||||
let owner_changed = owner_generation_changed(observed_owner_token, last_owner_token);
|
||||
if track_id != 0 && (track_id != last_track_id || owner_changed) {
|
||||
if owner_snapshot.is_some() {
|
||||
// A cold OWNER start that reached audio is no longer
|
||||
// pending. Guest playback must not consume this latch.
|
||||
@@ -4382,18 +4426,17 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
|
||||
let explicit_recovery_edge = event.engine_empty_generation
|
||||
!= seen_engine_empty_generation
|
||||
|| event.source_failure_generation != seen_source_failure_generation;
|
||||
let queue_track_id = if owner_snapshot.is_some()
|
||||
&& (explicit_recovery_edge || sampled_track_end)
|
||||
{
|
||||
runtime
|
||||
.core()
|
||||
.current_track()
|
||||
.await
|
||||
.map(|t| t.id)
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let queue_track_id =
|
||||
if owner_snapshot.is_some() && (explicit_recovery_edge || sampled_track_end) {
|
||||
runtime
|
||||
.core()
|
||||
.current_track()
|
||||
.await
|
||||
.map(|t| t.id)
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let recovery_cause = playback_recovery_cause(
|
||||
&event,
|
||||
queue_track_id,
|
||||
@@ -4559,20 +4602,23 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests (pure functions only — no Qt, no engine, no session)
|
||||
// Tests (no Qt, engine, audio device or session)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
filter_queue_with, gapless_edge_matches, playback_recovery_cause, prefetch_track_ids,
|
||||
quality_badge_from, reconcile_device_cap, should_stream_gapless_successor,
|
||||
stream_error_text, xorshift_shuffle_seeded, PlaybackRecoveryCause, PrefetchCandidate,
|
||||
PrefetchTrackEdge,
|
||||
cancel_owner_playback_tasks, capture_owner_scoped_snapshot, filter_queue_with,
|
||||
gapless_edge_matches, owner_generation_changed, playback_recovery_cause,
|
||||
prefetch_track_ids, quality_badge_from, reconcile_device_cap,
|
||||
should_stream_gapless_successor, spawn_owner_playback_task, stream_error_text,
|
||||
xorshift_shuffle_seeded, OwnerActionObservation, OwnerActionToken, OwnerScopedSnapshot,
|
||||
PlaybackRecoveryCause, PrefetchCandidate, PrefetchTrackEdge,
|
||||
};
|
||||
use qbz_models::{Quality, QualityLimit, QueueTrack};
|
||||
use qbz_player::PlaybackEvent;
|
||||
use qbz_source::QualityHint;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn remote(id: u64) -> PrefetchCandidate {
|
||||
PrefetchCandidate {
|
||||
@@ -4612,58 +4658,71 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poll_freezes_owner_authority_before_its_playback_snapshot() {
|
||||
let source = include_str!("playback_qt.rs");
|
||||
let poll = source
|
||||
.split_once("pub fn start_poll_loop")
|
||||
.expect("poll loop source")
|
||||
.1
|
||||
.split_once("// Tests (pure functions only")
|
||||
.expect("poll loop terminator")
|
||||
.0;
|
||||
let lease = poll
|
||||
.find("let owner_snapshot = match observe_owner_action()")
|
||||
.expect("owner snapshot admission");
|
||||
let event = poll
|
||||
.find("let event = runtime.core().player().get_playback_event();")
|
||||
.expect("playback event read");
|
||||
assert!(lease < event, "owner admission must precede PlaybackEvent");
|
||||
assert!(
|
||||
poll[lease..event].contains("OwnerActionObservation::Fenced => continue"),
|
||||
"a fallible candidate fence must preserve the prior owner snapshot"
|
||||
);
|
||||
fn owner_observation_precedes_snapshot_and_fence_does_not_consume_it() {
|
||||
use std::cell::RefCell;
|
||||
|
||||
let after_event = &poll[event..];
|
||||
assert!(
|
||||
!after_event.contains("let Some(_owner_action) = begin_owner_action()"),
|
||||
"a fresh owner permit must not promote work derived from this snapshot"
|
||||
let order = RefCell::new(Vec::new());
|
||||
let captured = capture_owner_scoped_snapshot(
|
||||
|| {
|
||||
order.borrow_mut().push("observe");
|
||||
OwnerActionObservation::Delegated
|
||||
},
|
||||
|| {
|
||||
order.borrow_mut().push("read");
|
||||
41_u64
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
after_event.contains("begin_owner_action_exact(owner_token).await"),
|
||||
"spawned continuations must re-admit the exact observed owner"
|
||||
);
|
||||
assert!(
|
||||
after_event.contains("observed_owner_token != last_owner_token"),
|
||||
"same-track owner generation changes must re-arm owner-only edges"
|
||||
assert!(matches!(
|
||||
captured,
|
||||
OwnerScopedSnapshot::Captured {
|
||||
owner_action: None,
|
||||
snapshot: 41
|
||||
}
|
||||
));
|
||||
assert_eq!(*order.borrow(), ["observe", "read"]);
|
||||
|
||||
order.borrow_mut().clear();
|
||||
let fenced = capture_owner_scoped_snapshot(
|
||||
|| {
|
||||
order.borrow_mut().push("observe");
|
||||
OwnerActionObservation::Fenced
|
||||
},
|
||||
|| {
|
||||
order.borrow_mut().push("read");
|
||||
99_u64
|
||||
},
|
||||
);
|
||||
assert!(matches!(fenced, OwnerScopedSnapshot::Fenced));
|
||||
assert_eq!(*order.borrow(), ["observe"]);
|
||||
|
||||
let first = OwnerActionToken::BeforeService;
|
||||
assert!(owner_generation_changed(Some(first), None));
|
||||
assert!(!owner_generation_changed(Some(first), Some(first)));
|
||||
assert!(!owner_generation_changed(None, Some(first)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_background_task_is_registered_before_it_can_start_io() {
|
||||
let source = include_str!("playback_qt.rs");
|
||||
let body = source
|
||||
.split_once("fn spawn_owner_playback_task")
|
||||
.expect("owner playback task registry")
|
||||
.1
|
||||
.split_once("pub(crate) fn cancel_owner_playback_tasks")
|
||||
.expect("owner playback cancellation boundary")
|
||||
.0;
|
||||
let register = body
|
||||
.find("tasks.push((generation, abort.clone()))")
|
||||
.expect("abort handle registration");
|
||||
let start = body.find("start_tx.send(())").expect("task start gate");
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn owner_background_task_is_cancelable_before_it_can_start_io() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
assert!(register < start);
|
||||
cancel_owner_playback_tasks();
|
||||
let ran = Arc::new(AtomicBool::new(false));
|
||||
let observed = Arc::clone(&ran);
|
||||
let task = spawn_owner_playback_task(async move {
|
||||
observed.store(true, Ordering::Release);
|
||||
});
|
||||
cancel_owner_playback_tasks();
|
||||
let _ = task.await;
|
||||
assert!(!ran.load(Ordering::Acquire));
|
||||
|
||||
let completed = Arc::new(AtomicBool::new(false));
|
||||
let observed = Arc::clone(&completed);
|
||||
spawn_owner_playback_task(async move {
|
||||
observed.store(true, Ordering::Release);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(completed.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,9 +4,16 @@
|
||||
//! installed runtime remains authoritative. The synchronous commit methods do
|
||||
//! only a short stamped runtime swap; teardown, queue restoration and cloud
|
||||
//! bootstrap happen afterwards.
|
||||
//!
|
||||
//! Race-sensitive policy is deliberately shared by `qconnect-app`: authority
|
||||
//! fences and deferred release, QWS preflight/join/rejoin, LAN projection and
|
||||
//! physical LAN lifecycle. The code left here is an adapter boundary for Qt's
|
||||
//! playback-task registry, UI projection and Cast ownership lane. Do not mirror
|
||||
//! new policy into the qbzd adapter; extract it with behavioral tests in
|
||||
//! `qconnect-app`.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Mutex as StdMutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -15,19 +22,18 @@ use qbz_app::shell::AppRuntime;
|
||||
use qbz_core::{LoggingAdapter, QueueAuthoritySnapshot};
|
||||
use qbz_models::Quality;
|
||||
use qbz_qobuz::{DelegatedApiConfig, DelegatedApiEndpoint, DelegatedQobuzClient, QobuzClient};
|
||||
use qconnect_app::renderer::PLAYING_STATE_STOPPED;
|
||||
use qconnect_app::{
|
||||
AuthorityCell, AuthorityOrigin, AuthorityStamp, CommitRejected, DelegationCancellation,
|
||||
DelegationCoordinator, DelegationErrorCode, DelegationHost, QconnectApp, QconnectAppEvent,
|
||||
QconnectEventSink, QconnectLifecycleState, QconnectRemoteSyncState, QconnectSessionState,
|
||||
RendererBufferState, RendererReport, RendererReportType, RestoreReason, SessionLoopHost,
|
||||
JOIN_SESSION_REASON_CONTROLLER_REQUEST,
|
||||
acquire_transition_guard_and_fence, max_audio_quality_from_quality, AuthorityCell,
|
||||
AuthorityOrigin, AuthorityStamp, CommitRejected, DeferredActivationRelease,
|
||||
DelegatedRejoinWatchdog, DelegatedRuntimeEventDirective, DelegatedRuntimeEventState,
|
||||
DelegationCancellation, DelegationCoordinator, DelegationErrorCode, DelegationHost,
|
||||
DelegationPreflight, OwnerActionFence, QconnectApp, QconnectAppEvent, QconnectEventSink,
|
||||
QconnectLifecycleState, QconnectRemoteSyncState, QconnectSessionState, RestoreReason,
|
||||
SessionLoopHost,
|
||||
};
|
||||
use qconnect_lan::{HandoffCandidate, LanProjection};
|
||||
use qconnect_protocol::RendererCommandType;
|
||||
use qconnect_transport_ws::{NativeWsTransport, TransportEvent, WsTransportConfig};
|
||||
use tokio::sync::{broadcast, oneshot, watch, Mutex as AsyncMutex, OwnedMutexGuard};
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::qconnect_engine_qt::QtRendererEngine;
|
||||
@@ -44,92 +50,9 @@ use crate::qconnect_transport_qt::{
|
||||
type Runtime = Arc<AppRuntime<LoggingAdapter>>;
|
||||
pub type QtDelegationCoordinator = DelegationCoordinator<QtDelegationHost>;
|
||||
|
||||
const PREFLIGHT_BUFFER_EVENTS: usize = 256;
|
||||
const PREFLIGHT_BUFFER_BYTES: usize = 256 * 1024;
|
||||
const DELEGATED_REJOIN_SESSION_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const SHUTDOWN_RESTORE_OWNER: u8 = 0;
|
||||
const SHUTDOWN_DISCARD_OWNER: u8 = 1;
|
||||
|
||||
#[derive(Default)]
|
||||
struct RejoinWatchdogGeneration(AtomicU64);
|
||||
|
||||
impl RejoinWatchdogGeneration {
|
||||
fn advance(&self) -> u64 {
|
||||
self.0.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
|
||||
}
|
||||
|
||||
/// Claims an armed generation exactly once. A reconnect, successful
|
||||
/// establishment, runtime drop, or replacement arm advances the epoch and
|
||||
/// makes the stale deadline harmless.
|
||||
fn claim(&self, expected: u64) -> bool {
|
||||
self.0
|
||||
.compare_exchange(
|
||||
expected,
|
||||
expected.wrapping_add(1),
|
||||
Ordering::AcqRel,
|
||||
Ordering::Acquire,
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
struct DelegatedRejoinWatchdog {
|
||||
generation: Arc<RejoinWatchdogGeneration>,
|
||||
task: Option<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl DelegatedRejoinWatchdog {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
generation: Arc::new(RejoinWatchdogGeneration::default()),
|
||||
task: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn arm(
|
||||
&mut self,
|
||||
authority: Arc<AuthorityCell>,
|
||||
stamp: AuthorityStamp,
|
||||
delegation_generation: u64,
|
||||
coordinator: Option<QtDelegationCoordinator>,
|
||||
) {
|
||||
// Advance before aborting so even a task already waking at the
|
||||
// deadline loses its compare-exchange against this newer rejoin.
|
||||
let watchdog_generation = self.generation.advance();
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
let generation = Arc::clone(&self.generation);
|
||||
self.task = Some(tokio::spawn(async move {
|
||||
tokio::time::sleep(DELEGATED_REJOIN_SESSION_TIMEOUT).await;
|
||||
if !generation.claim(watchdog_generation)
|
||||
|| stamp.origin()
|
||||
!= (AuthorityOrigin::Delegated {
|
||||
generation: delegation_generation,
|
||||
})
|
||||
|| !authority.is_current(stamp)
|
||||
{
|
||||
return;
|
||||
}
|
||||
request_restore(coordinator.as_ref(), delegation_generation).await;
|
||||
}));
|
||||
}
|
||||
|
||||
fn cancel(&mut self) {
|
||||
// Invalidate first: abort is cooperative and may race a waking task.
|
||||
self.generation.advance();
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DelegatedRejoinWatchdog {
|
||||
fn drop(&mut self) {
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct OwnerSnapshot {
|
||||
queue: QueueAuthoritySnapshot,
|
||||
@@ -145,48 +68,18 @@ struct OwnerPlaybackSnapshot {
|
||||
had_loaded_audio: bool,
|
||||
}
|
||||
|
||||
struct OwnerActionFence {
|
||||
authority: Arc<AuthorityCell>,
|
||||
}
|
||||
|
||||
impl OwnerActionFence {
|
||||
fn acquire(authority: Arc<AuthorityCell>) -> Self {
|
||||
authority.suspend_owner_actions();
|
||||
Self { authority }
|
||||
}
|
||||
|
||||
async fn acquire_drained(authority: Arc<AuthorityCell>) -> Self {
|
||||
// Close admission before cancellation: a task registered concurrently
|
||||
// is then either in playback_qt's abort registry or can only wait on
|
||||
// this fence without acquiring a drain-visible permit.
|
||||
let fence = Self::acquire(authority);
|
||||
crate::playback_qt::cancel_owner_playback_tasks();
|
||||
fence.authority.wait_for_actions_drained().await;
|
||||
fence
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OwnerActionFence {
|
||||
fn drop(&mut self) {
|
||||
self.authority.resume_owner_actions();
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapter payload only: the shared preparation/activation policy lives in
|
||||
/// `qconnect-app`; these concrete Qt app/sink handles cannot cross the crate
|
||||
/// boundary without coupling the shared layer back to the frontend.
|
||||
struct PreparedCommon {
|
||||
app: Arc<QtQconnectApp>,
|
||||
sink: Arc<QtQconnectEventSink>,
|
||||
config: WsTransportConfig,
|
||||
sync_state: Arc<AsyncMutex<QconnectRemoteSyncState>>,
|
||||
receiver: broadcast::Receiver<TransportEvent>,
|
||||
buffered: VecDeque<TransportEvent>,
|
||||
buffered_bytes: usize,
|
||||
preflight: DelegationPreflight,
|
||||
stamp: AuthorityStamp,
|
||||
expected_current: AuthorityStamp,
|
||||
custom_name: Option<String>,
|
||||
/// Captured from owner SESSION_STATE during preparation. `prepare_owner`
|
||||
/// cannot return until the matching SessionEstablished signal also arrives,
|
||||
/// and this value stays private until `commit_owner` installs that runtime.
|
||||
confirmed_owner_session_id: Option<Zeroizing<String>>,
|
||||
}
|
||||
|
||||
pub struct PreparedDelegation {
|
||||
@@ -226,56 +119,6 @@ struct PendingActivation {
|
||||
owner_restore_task: Arc<StdMutex<Option<OwnerRestoreTask>>>,
|
||||
}
|
||||
|
||||
/// Final edge of an installed transition.
|
||||
///
|
||||
/// Owner rollback moves this guard into the tracked restore task. Its `Drop`
|
||||
/// implementation is the cancellation boundary: even if coordinator cleanup,
|
||||
/// shutdown, or the restore task itself is cancelled, the installed runtime is
|
||||
/// woken and both the owner-action fence and host transition gate are released.
|
||||
struct DeferredActivationRelease {
|
||||
start: Option<oneshot::Sender<()>>,
|
||||
transition_fence: Option<OwnerActionFence>,
|
||||
transition_guard: Option<OwnedMutexGuard<()>>,
|
||||
}
|
||||
|
||||
impl DeferredActivationRelease {
|
||||
fn new(
|
||||
start: Option<oneshot::Sender<()>>,
|
||||
transition_fence: Option<OwnerActionFence>,
|
||||
transition_guard: Option<OwnedMutexGuard<()>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
start,
|
||||
transition_fence,
|
||||
transition_guard,
|
||||
}
|
||||
}
|
||||
|
||||
fn wake_runtime(&mut self) {
|
||||
// Admission opens before the prepared loop wakes so every buffered
|
||||
// command is retained and can obtain its normal stamped action permit.
|
||||
self.transition_fence.take();
|
||||
if let Some(start) = self.start.take() {
|
||||
let _ = start.send(());
|
||||
}
|
||||
}
|
||||
|
||||
fn unlock_transition(&mut self) {
|
||||
self.transition_guard.take();
|
||||
}
|
||||
|
||||
fn release(&mut self) {
|
||||
self.wake_runtime();
|
||||
self.unlock_transition();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DeferredActivationRelease {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
}
|
||||
}
|
||||
|
||||
/// A restore remains owned by the host until it publishes a terminal result.
|
||||
/// Waiters clone only the watch receiver, so cancelling or timing out a waiter
|
||||
/// never drops (and therefore never detaches) the underlying `JoinHandle`.
|
||||
@@ -290,6 +133,12 @@ impl OwnerRestoreTask {
|
||||
}
|
||||
}
|
||||
|
||||
fn observe_owner_restore(
|
||||
slot: &StdMutex<Option<OwnerRestoreTask>>,
|
||||
) -> Option<watch::Receiver<Option<Result<(), &'static str>>>> {
|
||||
recover_lock(slot).as_ref().map(|task| task.result.clone())
|
||||
}
|
||||
|
||||
impl Drop for OwnerRestoreTask {
|
||||
fn drop(&mut self) {
|
||||
// Host destruction or explicit replacement must not leave a restore
|
||||
@@ -426,9 +275,7 @@ impl QtDelegationHost {
|
||||
// Clone only the result channel. The host keeps owning the JoinHandle,
|
||||
// so cancellation of this future or expiry of this wait cannot detach
|
||||
// a rollback that still owns the transition gate/fence.
|
||||
let result = recover_lock(&self.owner_restore_task)
|
||||
.as_ref()
|
||||
.map(|task| task.result.clone());
|
||||
let result = observe_owner_restore(&self.owner_restore_task);
|
||||
let Some(result) = result else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -613,13 +460,10 @@ impl DelegationHost for QtDelegationHost {
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered: VecDeque::new(),
|
||||
buffered_bytes: 0,
|
||||
preflight: DelegationPreflight::new(receiver),
|
||||
stamp,
|
||||
expected_current,
|
||||
custom_name,
|
||||
confirmed_owner_session_id: None,
|
||||
};
|
||||
let api_validation = async {
|
||||
delegated_client
|
||||
@@ -629,7 +473,7 @@ impl DelegationHost for QtDelegationHost {
|
||||
};
|
||||
tokio::try_join!(
|
||||
api_validation,
|
||||
wait_for_qws_ready(&mut common, cancellation)
|
||||
common.preflight.wait_for_qws_ready(cancellation)
|
||||
)?;
|
||||
|
||||
Ok(PreparedDelegation {
|
||||
@@ -655,15 +499,15 @@ impl DelegationHost for QtDelegationHost {
|
||||
// The host gate carries this critical section through commit, retirement
|
||||
// and any owner playback rollback. A candidate therefore waits for a
|
||||
// valid prior rollback instead of cancelling it.
|
||||
prepared.transition_guard = Some(Arc::clone(&self.transition_gate).lock_owned().await);
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
prepared.transition_fence =
|
||||
Some(OwnerActionFence::acquire_drained(Arc::clone(&self.authority)).await);
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
let (transition_guard, transition_fence) = acquire_transition_guard_and_fence(
|
||||
Arc::clone(&self.transition_gate),
|
||||
Arc::clone(&self.authority),
|
||||
prepared.common.expected_current,
|
||||
crate::playback_qt::cancel_owner_playback_tasks,
|
||||
)
|
||||
.await?;
|
||||
prepared.transition_guard = Some(transition_guard);
|
||||
prepared.transition_fence = Some(transition_fence);
|
||||
if prepared.common.expected_current.origin() == AuthorityOrigin::Owner {
|
||||
let queue = self.runtime.core().capture_authority_snapshot().await;
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
@@ -701,7 +545,11 @@ impl DelegationHost for QtDelegationHost {
|
||||
effective_delegated_quality(),
|
||||
)
|
||||
.await?;
|
||||
wait_for_activation(&mut prepared.common, cancellation).await?;
|
||||
prepared
|
||||
.common
|
||||
.preflight
|
||||
.wait_for_activation(cancellation)
|
||||
.await?;
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
@@ -824,28 +672,31 @@ impl DelegationHost for QtDelegationHost {
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered: VecDeque::new(),
|
||||
buffered_bytes: 0,
|
||||
preflight: DelegationPreflight::new(receiver),
|
||||
stamp,
|
||||
expected_current,
|
||||
custom_name,
|
||||
confirmed_owner_session_id: None,
|
||||
};
|
||||
wait_for_qws_ready(&mut common, cancellation.clone())
|
||||
common
|
||||
.preflight
|
||||
.wait_for_qws_ready(cancellation.clone())
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::OwnerRestoreFailed)?;
|
||||
bootstrap_prepared_owner_presence(&common.app, common.custom_name.clone())
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::OwnerRestoreFailed)?;
|
||||
wait_for_owner_session(&mut common, cancellation)
|
||||
common
|
||||
.preflight
|
||||
.wait_for_owner_session(cancellation)
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::OwnerRestoreFailed)?;
|
||||
let transition_guard = Arc::clone(&self.transition_gate).lock_owned().await;
|
||||
let transition_fence = OwnerActionFence::acquire_drained(Arc::clone(&self.authority)).await;
|
||||
if !self.authority.is_current(expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
let (transition_guard, transition_fence) = acquire_transition_guard_and_fence(
|
||||
Arc::clone(&self.transition_gate),
|
||||
Arc::clone(&self.authority),
|
||||
expected_current,
|
||||
crate::playback_qt::cancel_owner_playback_tasks,
|
||||
)
|
||||
.await?;
|
||||
Ok(PreparedOwner {
|
||||
common,
|
||||
transition_guard,
|
||||
@@ -869,7 +720,12 @@ impl DelegationHost for QtDelegationHost {
|
||||
));
|
||||
}
|
||||
let stamp = prepared.common.stamp;
|
||||
let Some(owner_session_id) = prepared.common.confirmed_owner_session_id.clone() else {
|
||||
let Some(owner_session_id) = prepared
|
||||
.common
|
||||
.preflight
|
||||
.confirmed_owner_session_id()
|
||||
.map(|session_id| Zeroizing::new(session_id.to_string()))
|
||||
else {
|
||||
return Err(CommitRejected::new(
|
||||
prepared,
|
||||
DelegationErrorCode::CommitRejected,
|
||||
@@ -971,7 +827,11 @@ impl DelegationHost for QtDelegationHost {
|
||||
// because disable/logout arrived: its queue snapshot was already
|
||||
// consumed at commit and cannot be reconstructed after cancellation.
|
||||
let transition_guard = Arc::clone(&self.transition_gate).lock_owned().await;
|
||||
let shutdown_fence = OwnerActionFence::acquire_drained(Arc::clone(&self.authority)).await;
|
||||
let shutdown_fence = OwnerActionFence::acquire_drained(
|
||||
Arc::clone(&self.authority),
|
||||
crate::playback_qt::cancel_owner_playback_tasks,
|
||||
)
|
||||
.await;
|
||||
let previous = self.projection.clear_authority(&self.authority);
|
||||
let was_delegated = previous
|
||||
.is_some_and(|stamp| matches!(stamp.origin(), AuthorityOrigin::Delegated { .. }));
|
||||
@@ -1235,163 +1095,6 @@ fn effective_delegated_quality() -> Quality {
|
||||
crate::playback_qt::local_playback_quality().0
|
||||
}
|
||||
|
||||
fn quality_wire(quality: Quality) -> i32 {
|
||||
match quality {
|
||||
Quality::Mp3 => 1,
|
||||
Quality::Lossless => 2,
|
||||
Quality::HiRes => 3,
|
||||
Quality::UltraHiRes => 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn retained_event_bytes(event: &TransportEvent) -> usize {
|
||||
match event {
|
||||
TransportEvent::InboundPayloadBytes { payload, .. } => payload.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn should_retain(event: &TransportEvent) -> bool {
|
||||
matches!(
|
||||
event,
|
||||
TransportEvent::Connected
|
||||
| TransportEvent::Disconnected
|
||||
| TransportEvent::SessionEstablished
|
||||
| TransportEvent::InboundPayloadBytes { .. }
|
||||
| TransportEvent::InboundQueueServerEvent(_)
|
||||
| TransportEvent::InboundRendererServerCommand(_)
|
||||
| TransportEvent::InboundReceived(_)
|
||||
)
|
||||
}
|
||||
|
||||
fn retain_event(
|
||||
common: &mut PreparedCommon,
|
||||
event: TransportEvent,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
if !should_retain(&event) {
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = retained_event_bytes(&event);
|
||||
if common.buffered.len() >= PREFLIGHT_BUFFER_EVENTS
|
||||
|| common.buffered_bytes.saturating_add(bytes) > PREFLIGHT_BUFFER_BYTES
|
||||
{
|
||||
return Err(DelegationErrorCode::Internal);
|
||||
}
|
||||
common.buffered_bytes = common.buffered_bytes.saturating_add(bytes);
|
||||
common.buffered.push_back(event);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn next_preflight_event(
|
||||
common: &mut PreparedCommon,
|
||||
mut cancellation: DelegationCancellation,
|
||||
) -> Result<TransportEvent, DelegationErrorCode> {
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => Err(DelegationErrorCode::CandidateCancelled),
|
||||
event = common.receiver.recv() => match event {
|
||||
Ok(event) => Ok(event),
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => Err(DelegationErrorCode::Internal),
|
||||
Err(broadcast::error::RecvError::Closed) => Err(DelegationErrorCode::QwsRejected),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_qws_ready(
|
||||
common: &mut PreparedCommon,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut authenticated = false;
|
||||
let mut subscribed = false;
|
||||
while !(authenticated && subscribed) {
|
||||
let event = next_preflight_event(common, cancellation.clone()).await?;
|
||||
match &event {
|
||||
TransportEvent::Authenticated => authenticated = true,
|
||||
TransportEvent::Subscribed => subscribed = true,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. } => {
|
||||
return Err(DelegationErrorCode::QwsRejected)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
retain_event(common, event)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait_for_activation(
|
||||
common: &mut PreparedCommon,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
loop {
|
||||
let event = next_preflight_event(common, cancellation.clone()).await?;
|
||||
let accepted = matches!(
|
||||
&event,
|
||||
TransportEvent::InboundRendererServerCommand(command)
|
||||
if command.command_type == RendererCommandType::SrvrRndrSetActive
|
||||
&& command.payload.get("active").and_then(serde_json::Value::as_bool)
|
||||
== Some(true)
|
||||
);
|
||||
if matches!(
|
||||
&event,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. }
|
||||
) {
|
||||
return Err(DelegationErrorCode::ActivationRejected);
|
||||
}
|
||||
retain_event(common, event)?;
|
||||
if accepted {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owner preparation is complete only after the cloud has accepted the
|
||||
/// controller-side join and emitted the same establishment signal consumed by
|
||||
/// a live session loop. Authentication/subscription and a successful socket
|
||||
/// send are necessary but not sufficient to publish `OwnerReady`.
|
||||
async fn wait_for_owner_session(
|
||||
common: &mut PreparedCommon,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut established = false;
|
||||
loop {
|
||||
let event = next_preflight_event(common, cancellation.clone()).await?;
|
||||
if let Some(session_id) = owner_session_id_from_event(&event).map(str::to_string) {
|
||||
common.confirmed_owner_session_id = Some(Zeroizing::new(session_id));
|
||||
}
|
||||
established |= matches!(&event, TransportEvent::SessionEstablished);
|
||||
if matches!(
|
||||
&event,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. }
|
||||
) {
|
||||
return Err(DelegationErrorCode::OwnerRestoreFailed);
|
||||
}
|
||||
retain_event(common, event)?;
|
||||
if established && common.confirmed_owner_session_id.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_session_id_from_event(event: &TransportEvent) -> Option<&str> {
|
||||
match event {
|
||||
TransportEvent::InboundQueueServerEvent(event)
|
||||
if event.message_type() == "MESSAGE_TYPE_SRVR_CTRL_SESSION_STATE" =>
|
||||
{
|
||||
event
|
||||
.payload
|
||||
.get("session_uuid")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|session_id| !session_id.is_empty())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_delegated_join(
|
||||
app: &Arc<QtQconnectApp>,
|
||||
session_id: &str,
|
||||
@@ -1401,33 +1104,15 @@ async fn send_delegated_join(
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut device_info = default_qconnect_device_info_with_name(custom_name);
|
||||
if let Some(capabilities) = device_info.capabilities.as_mut() {
|
||||
capabilities.max_audio_quality = Some(quality_wire(quality));
|
||||
capabilities.max_audio_quality = Some(max_audio_quality_from_quality(quality));
|
||||
}
|
||||
let queue_version = app.queue_state_snapshot().await.version;
|
||||
let report = RendererReport::new(
|
||||
RendererReportType::RndrSrvrJoinSession,
|
||||
Uuid::new_v4().to_string(),
|
||||
queue_version,
|
||||
serde_json::json!({
|
||||
"session_uuid": session_id,
|
||||
"device_info": serde_json::to_value(device_info).unwrap_or_default(),
|
||||
"is_active": become_active,
|
||||
"reason": JOIN_SESSION_REASON_CONTROLLER_REQUEST,
|
||||
"initial_state": {
|
||||
"playing_state": PLAYING_STATE_STOPPED,
|
||||
"buffer_state": RendererBufferState::Ok.as_i32(),
|
||||
"current_position": 0,
|
||||
"duration": 0,
|
||||
"queue_version": {
|
||||
"major": queue_version.major,
|
||||
"minor": queue_version.minor,
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
app.send_renderer_report_command(report)
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::ActivationRejected)
|
||||
app.send_delegated_join(
|
||||
session_id,
|
||||
become_active,
|
||||
serde_json::to_value(device_info).unwrap_or_default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::ActivationRejected)
|
||||
}
|
||||
|
||||
/// Apply a delegated-runtime lifecycle edge only while the exact stamped Qt
|
||||
@@ -1473,12 +1158,12 @@ fn spawn_delegated_runtime(
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered,
|
||||
preflight,
|
||||
stamp,
|
||||
custom_name,
|
||||
..
|
||||
} = common;
|
||||
let (receiver, buffered) = preflight.into_session_events();
|
||||
let (start, started) = oneshot::channel();
|
||||
let loop_app = Arc::clone(&app);
|
||||
let loop_sink = Arc::clone(&sink);
|
||||
@@ -1531,11 +1216,11 @@ fn spawn_owner_runtime(
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered,
|
||||
preflight,
|
||||
stamp,
|
||||
..
|
||||
} = common;
|
||||
let (receiver, buffered) = preflight.into_session_events();
|
||||
let idle_retry_active = config.reconnect_idle_retry_ms > 0;
|
||||
let host: Arc<dyn SessionLoopHost> = Arc::new(QtSessionLoopHost {
|
||||
app: Arc::clone(&app),
|
||||
@@ -1585,7 +1270,7 @@ async fn run_delegated_loop(
|
||||
coordinator: Option<QtDelegationCoordinator>,
|
||||
custom_name: Option<String>,
|
||||
) {
|
||||
let mut disconnected = false;
|
||||
let mut reconnect_state = DelegatedRuntimeEventState::default();
|
||||
let mut rejoin_watchdog = DelegatedRejoinWatchdog::new();
|
||||
for event in buffered {
|
||||
if !handle_delegated_event(
|
||||
@@ -1599,7 +1284,7 @@ async fn run_delegated_loop(
|
||||
stamp,
|
||||
coordinator.as_ref(),
|
||||
custom_name.as_deref(),
|
||||
&mut disconnected,
|
||||
&mut reconnect_state,
|
||||
&mut rejoin_watchdog,
|
||||
)
|
||||
.await
|
||||
@@ -1630,7 +1315,7 @@ async fn run_delegated_loop(
|
||||
stamp,
|
||||
coordinator.as_ref(),
|
||||
custom_name.as_deref(),
|
||||
&mut disconnected,
|
||||
&mut reconnect_state,
|
||||
&mut rejoin_watchdog,
|
||||
)
|
||||
.await
|
||||
@@ -1652,15 +1337,14 @@ async fn handle_delegated_event(
|
||||
stamp: AuthorityStamp,
|
||||
coordinator: Option<&QtDelegationCoordinator>,
|
||||
custom_name: Option<&str>,
|
||||
disconnected: &mut bool,
|
||||
reconnect_state: &mut DelegatedRuntimeEventState,
|
||||
rejoin_watchdog: &mut DelegatedRejoinWatchdog,
|
||||
) -> bool {
|
||||
if !authority.is_current(stamp) {
|
||||
return false;
|
||||
}
|
||||
match &event {
|
||||
TransportEvent::Disconnected => {
|
||||
*disconnected = true;
|
||||
match reconnect_state.observe(&event) {
|
||||
DelegatedRuntimeEventDirective::Reconnecting => {
|
||||
rejoin_watchdog.cancel();
|
||||
update_lifecycle_state_if_running(
|
||||
inner,
|
||||
@@ -1671,7 +1355,7 @@ async fn handle_delegated_event(
|
||||
)
|
||||
.await;
|
||||
}
|
||||
TransportEvent::Subscribed if *disconnected => {
|
||||
DelegatedRuntimeEventDirective::Rejoin => {
|
||||
if send_delegated_join(
|
||||
app,
|
||||
session_id,
|
||||
@@ -1685,15 +1369,12 @@ async fn handle_delegated_event(
|
||||
request_restore(coordinator, generation).await;
|
||||
return false;
|
||||
}
|
||||
rejoin_watchdog.arm(
|
||||
Arc::clone(authority),
|
||||
stamp,
|
||||
generation,
|
||||
coordinator.cloned(),
|
||||
);
|
||||
let coordinator = coordinator.cloned();
|
||||
rejoin_watchdog.arm(Arc::clone(authority), stamp, generation, move |generation| {
|
||||
async move { request_restore(coordinator.as_ref(), generation).await }
|
||||
});
|
||||
}
|
||||
TransportEvent::SessionEstablished => {
|
||||
*disconnected = false;
|
||||
DelegatedRuntimeEventDirective::Connected => {
|
||||
rejoin_watchdog.cancel();
|
||||
update_lifecycle_state_if_running(
|
||||
inner,
|
||||
@@ -1704,11 +1385,11 @@ async fn handle_delegated_event(
|
||||
)
|
||||
.await;
|
||||
}
|
||||
TransportEvent::CloudError { .. } | TransportEvent::MaxReconnectAttemptsExceeded { .. } => {
|
||||
DelegatedRuntimeEventDirective::RestoreOwner => {
|
||||
request_restore(coordinator, generation).await;
|
||||
return false;
|
||||
}
|
||||
_ => {}
|
||||
DelegatedRuntimeEventDirective::Forward => {}
|
||||
}
|
||||
if !authority.is_current(stamp) {
|
||||
return false;
|
||||
@@ -1735,114 +1416,16 @@ async fn request_restore(coordinator: Option<&QtDelegationCoordinator>, generati
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn quality_mapping_never_exceeds_the_configured_cap() {
|
||||
assert_eq!(quality_wire(Quality::Mp3), 1);
|
||||
assert_eq!(quality_wire(Quality::Lossless), 2);
|
||||
assert_eq!(quality_wire(Quality::HiRes), 3);
|
||||
assert_eq!(quality_wire(Quality::UltraHiRes), 4);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn restore_observer_leaves_the_tracked_worker_owned_by_its_slot() {
|
||||
let (_result_sender, result) = watch::channel(None);
|
||||
let handle = tokio::spawn(std::future::pending::<()>());
|
||||
let slot = StdMutex::new(Some(OwnerRestoreTask { handle, result }));
|
||||
|
||||
#[test]
|
||||
fn preflight_retains_only_events_needed_after_commit() {
|
||||
assert!(!should_retain(&TransportEvent::Authenticated));
|
||||
assert!(!should_retain(&TransportEvent::KeepalivePingSent));
|
||||
assert!(should_retain(&TransportEvent::Disconnected));
|
||||
assert!(should_retain(&TransportEvent::SessionEstablished));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_watchdog_generation_is_claimed_once() {
|
||||
let generation = RejoinWatchdogGeneration::default();
|
||||
let armed = generation.advance();
|
||||
|
||||
assert!(generation.claim(armed));
|
||||
assert!(!generation.claim(armed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_watchdog_ignores_cancelled_and_replaced_generations() {
|
||||
let generation = RejoinWatchdogGeneration::default();
|
||||
let cancelled = generation.advance();
|
||||
generation.advance();
|
||||
let replacement = generation.advance();
|
||||
|
||||
assert!(!generation.claim(cancelled));
|
||||
assert!(generation.claim(replacement));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transition_fence_precedes_playback_task_cancel_and_drain() {
|
||||
let source = include_str!("qconnect_delegation_qt.rs");
|
||||
let body = source
|
||||
.split_once("async fn acquire_drained")
|
||||
.expect("owner fence helper")
|
||||
.1
|
||||
.split_once("impl Drop for OwnerActionFence")
|
||||
.expect("owner fence helper terminator")
|
||||
.0;
|
||||
let fence = body.find("Self::acquire(authority)").expect("fence close");
|
||||
let cancel = body
|
||||
.find("cancel_owner_playback_tasks()")
|
||||
.expect("playback task cancellation");
|
||||
let drain = body
|
||||
.find("wait_for_actions_drained().await")
|
||||
.expect("authority drain");
|
||||
assert!(fence < cancel && cancel < drain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_activation_waits_for_prior_restore_instead_of_cancelling_it() {
|
||||
let source = include_str!("qconnect_delegation_qt.rs");
|
||||
let body = source
|
||||
.split_once("async fn activate_delegation")
|
||||
.expect("delegation activation")
|
||||
.1
|
||||
.split_once("fn commit_delegation")
|
||||
.expect("delegation commit boundary")
|
||||
.0;
|
||||
let gate = body
|
||||
.find("lock_owned().await")
|
||||
.expect("host transition gate");
|
||||
let fence = body
|
||||
.find("OwnerActionFence::acquire_drained")
|
||||
.expect("owner-action fence");
|
||||
|
||||
assert!(gate < fence);
|
||||
assert!(!body.contains("cancel_owner_playback_restore"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_waiter_does_not_consume_the_tracked_join_handle() {
|
||||
let source = include_str!("qconnect_delegation_qt.rs");
|
||||
let body = source
|
||||
.split_once("pub async fn await_owner_playback_restore")
|
||||
.expect("restore waiter")
|
||||
.1
|
||||
.split_once("pub fn owner_restore_pending")
|
||||
.expect("restore waiter boundary")
|
||||
.0;
|
||||
|
||||
assert!(body.contains("task.result.clone()"));
|
||||
assert!(!body.contains("owner_restore_task).take()"));
|
||||
assert!(!body.contains("task.handle"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restored_owner_loop_wakes_only_after_the_fence_opens() {
|
||||
let source = include_str!("qconnect_delegation_qt.rs");
|
||||
let body = source
|
||||
.split_once("fn wake_runtime")
|
||||
.expect("deferred activation release")
|
||||
.1
|
||||
.split_once("fn unlock_transition")
|
||||
.expect("deferred activation boundary")
|
||||
.0;
|
||||
let fence = body
|
||||
.find("transition_fence.take()")
|
||||
.expect("owner admission reopen");
|
||||
let start = body.find("start.send(())").expect("owner loop wake");
|
||||
|
||||
assert!(fence < start);
|
||||
let observer = observe_owner_restore(&slot).expect("restore observation");
|
||||
drop(observer);
|
||||
assert!(recover_lock(&slot)
|
||||
.as_ref()
|
||||
.is_some_and(OwnerRestoreTask::is_pending));
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,12 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::sync::{Arc, Mutex as StdMutex};
|
||||
use std::sync::Arc;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
use qbz_models::Quality;
|
||||
use qconnect_app::{AuthorityCell, AuthorityOrigin, AuthorityStamp};
|
||||
use qconnect_app::LanProjectionSlot;
|
||||
use qconnect_lan::{
|
||||
ConnectInfo, DeviceType, DisplayInfo, EndpointPolicy, HandoffCandidate, LanError,
|
||||
LanProjection, LanService, LanServiceConfig, MaxAudioQuality,
|
||||
@@ -25,178 +25,7 @@ const ADMISSION_WAIT: Duration = Duration::from_secs(60);
|
||||
const QT_MODEL: &str = "QBZ Desktop";
|
||||
const ADMISSION_THREAD_NAME: &str = "qbz-qt-qconnect-lan-admission";
|
||||
|
||||
/// Stamp-aware bridge between runtime authority and the synchronous LAN
|
||||
/// projection read by the HTTP worker.
|
||||
///
|
||||
/// Every Qt authority install/clear is serialized through this short-held
|
||||
/// mutex. An old runtime event can therefore never overwrite the session of a
|
||||
/// replacement runtime, and a prepared candidate is not exposed until the
|
||||
/// same critical section that installs its authority.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct QtLanProjectionSlot {
|
||||
inner: Arc<StdMutex<ProjectionSlotState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProjectionSlotState {
|
||||
projection: Option<LanProjection>,
|
||||
installed: Option<InstalledSessionProjection>,
|
||||
}
|
||||
|
||||
struct InstalledSessionProjection {
|
||||
stamp: AuthorityStamp,
|
||||
session_id: Option<String>,
|
||||
}
|
||||
|
||||
impl QtLanProjectionSlot {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, ProjectionSlotState> {
|
||||
self.inner.lock().unwrap_or_else(|poisoned| {
|
||||
log::error!("[QConnect LAN] projection slot recovered from a poisoned lock");
|
||||
let guard = poisoned.into_inner();
|
||||
self.inner.clear_poison();
|
||||
guard
|
||||
})
|
||||
}
|
||||
|
||||
fn write_projection(state: &ProjectionSlotState, session_id: Option<String>) {
|
||||
if let Some(projection) = state.projection.as_ref() {
|
||||
projection.set_current_session_id(session_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Install a runtime and its already-confirmed public session atomically
|
||||
/// with respect to every projection update. `session_id` is `None` for a
|
||||
/// fresh owner until its first cloud SESSION_STATE arrives.
|
||||
pub(crate) fn install_authority(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
session_id: Option<&str>,
|
||||
) -> bool {
|
||||
let mut state = self.lock();
|
||||
|
||||
// Fail closed during the tiny install boundary: the old session may no
|
||||
// longer be current, while exposing the candidate before install would
|
||||
// violate the handoff transaction.
|
||||
Self::write_projection(&state, None);
|
||||
if !authority.install(stamp) {
|
||||
let current = authority.current();
|
||||
let restore = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| Some(installed.stamp) == current)
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
if current != state.installed.as_ref().map(|installed| installed.stamp) {
|
||||
state.installed = None;
|
||||
}
|
||||
Self::write_projection(&state, restore);
|
||||
return false;
|
||||
}
|
||||
|
||||
let session_id = session_id.map(str::to_string);
|
||||
state.installed = Some(InstalledSessionProjection {
|
||||
stamp,
|
||||
session_id: session_id.clone(),
|
||||
});
|
||||
Self::write_projection(&state, session_id);
|
||||
true
|
||||
}
|
||||
|
||||
/// Publish a cloud-confirmed owner session from an event belonging to the
|
||||
/// exact installed runtime. Delegated session ids enter only through
|
||||
/// `install_authority` after their transactional commit.
|
||||
pub(crate) fn confirm_owner_session(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
session_id: &str,
|
||||
) -> bool {
|
||||
if stamp.origin() != AuthorityOrigin::Owner || session_id.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut state = self.lock();
|
||||
if !authority.is_current(stamp)
|
||||
|| state.installed.as_ref().map(|installed| installed.stamp) != Some(stamp)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let session_id = session_id.to_string();
|
||||
if let Some(installed) = state.installed.as_mut() {
|
||||
installed.session_id = Some(session_id.clone());
|
||||
}
|
||||
Self::write_projection(&state, Some(session_id));
|
||||
true
|
||||
}
|
||||
|
||||
/// Snapshot the exact installed session for listener construction. This
|
||||
/// seeds GET connect-info before the HTTP worker can accept its first call.
|
||||
pub(crate) fn current_session_id(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
expected: AuthorityStamp,
|
||||
) -> Option<String> {
|
||||
let state = self.lock();
|
||||
if !authority.is_current(expected) {
|
||||
return None;
|
||||
}
|
||||
state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| installed.stamp == expected)
|
||||
.and_then(|installed| installed.session_id.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn attach(&self, authority: &AuthorityCell, projection: LanProjection) {
|
||||
let mut state = self.lock();
|
||||
let current = authority.current();
|
||||
let session_id = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| Some(installed.stamp) == current)
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
projection.set_current_session_id(session_id);
|
||||
state.projection = Some(projection);
|
||||
}
|
||||
|
||||
pub(crate) fn detach(&self) {
|
||||
self.lock().projection.take();
|
||||
}
|
||||
|
||||
pub(crate) fn clear_authority(&self, authority: &AuthorityCell) -> Option<AuthorityStamp> {
|
||||
let mut state = self.lock();
|
||||
Self::write_projection(&state, None);
|
||||
let previous = authority.clear();
|
||||
state.installed = None;
|
||||
previous
|
||||
}
|
||||
|
||||
pub(crate) fn clear_if_current(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
expected: AuthorityStamp,
|
||||
) -> bool {
|
||||
let mut state = self.lock();
|
||||
if !authority.is_current(expected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Self::write_projection(&state, None);
|
||||
if authority.clear_if_current(expected) {
|
||||
state.installed = None;
|
||||
true
|
||||
} else {
|
||||
let restore = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| authority.is_current(installed.stamp))
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
Self::write_projection(&state, restore);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) type QtLanProjectionSlot = LanProjectionSlot;
|
||||
|
||||
/// Map the effective local playback ceiling to the exact official LAN enum.
|
||||
/// The same `local_playback_quality` source is used by stream resolution and
|
||||
@@ -472,79 +301,4 @@ mod tests {
|
||||
projection.set_current_session_id(None);
|
||||
assert_eq!(projection.connect_info().current_session_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamped_projection_publishes_only_installed_authority() {
|
||||
let authority = AuthorityCell::new();
|
||||
let slot = QtLanProjectionSlot::default();
|
||||
let projection = build_projection(
|
||||
&fixture_identity(),
|
||||
"app-id".to_string(),
|
||||
MaxAudioQuality::UpToCd,
|
||||
None,
|
||||
);
|
||||
slot.attach(&authority, projection.clone());
|
||||
|
||||
let owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, owner, None));
|
||||
assert!(slot.confirm_owner_session(&authority, owner, "owner-session"));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session")
|
||||
);
|
||||
|
||||
// Merely reserving/preparing a guest cannot expose its candidate id.
|
||||
let guest = authority.reserve(AuthorityOrigin::Delegated { generation: 7 });
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session")
|
||||
);
|
||||
|
||||
assert!(slot.install_authority(&authority, guest, Some("guest-session")));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("guest-session")
|
||||
);
|
||||
|
||||
// A late event from the retired owner cannot overwrite the guest.
|
||||
assert!(!slot.confirm_owner_session(&authority, owner, "stale-owner-session"));
|
||||
// Delegated events never replace the handoff id either; only their
|
||||
// stamped install is allowed to publish it.
|
||||
assert!(!slot.confirm_owner_session(&authority, guest, "delegated-event-session"));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("guest-session")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_session_events_update_and_stale_clear_cannot_win() {
|
||||
let authority = AuthorityCell::new();
|
||||
let slot = QtLanProjectionSlot::default();
|
||||
let projection = build_projection(
|
||||
&fixture_identity(),
|
||||
"app-id".to_string(),
|
||||
MaxAudioQuality::UpToCd,
|
||||
None,
|
||||
);
|
||||
slot.attach(&authority, projection.clone());
|
||||
|
||||
let first_owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, first_owner, None));
|
||||
assert!(slot.confirm_owner_session(&authority, first_owner, "owner-session-a"));
|
||||
assert!(slot.confirm_owner_session(&authority, first_owner, "owner-session-b"));
|
||||
assert_eq!(
|
||||
slot.current_session_id(&authority, first_owner).as_deref(),
|
||||
Some("owner-session-b")
|
||||
);
|
||||
|
||||
let next_owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, next_owner, Some("owner-session-c")));
|
||||
assert!(!slot.install_authority(&authority, first_owner, Some("stale-owner-session")));
|
||||
assert!(!slot.clear_if_current(&authority, first_owner));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session-c")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -56,14 +56,14 @@ use qconnect_app::renderer::{PLAYING_STATE_PAUSED, PLAYING_STATE_PLAYING, PLAYIN
|
||||
use qconnect_app::{
|
||||
build_effective_renderer_snapshot, build_renderer_playback_report,
|
||||
ensure_session_renderer_state, is_local_renderer_active, is_peer_renderer_active,
|
||||
queue_item_snapshot_for_cursor, renderer_allows_remote_volume, AuthorityActionPermit,
|
||||
AuthorityCell, AuthorityOrigin, AuthorityStamp, DelegationCoordinatorConfig, DelegationHost,
|
||||
OwnerAuthorityObservation, OwnerAuthorityToken, QConnectQueueState, QConnectRendererState,
|
||||
QconnectApp, QconnectAppEvent, QconnectDisabledToken, QconnectEnableIntent,
|
||||
QconnectEnableToken, QconnectEventSink, QconnectFileAudioQualitySnapshot,
|
||||
QconnectLifecycleState, QconnectRemoteSyncState, QconnectSessionState, QueueCommandType,
|
||||
RendererBufferState, RendererPlaybackSnapshot, RendererReport, RendererReportType,
|
||||
SessionLoopHost,
|
||||
lan_callback_is_current, queue_item_snapshot_for_cursor, renderer_allows_remote_volume,
|
||||
AuthorityActionPermit, AuthorityCell, AuthorityOrigin, AuthorityStamp,
|
||||
DelegationCoordinatorConfig, DelegationHost, LanRuntimeLifecycle, OwnerAuthorityObservation,
|
||||
OwnerAuthorityToken, QConnectQueueState, QConnectRendererState, QconnectApp, QconnectAppEvent,
|
||||
QconnectDisabledToken, QconnectEnableIntent, QconnectEnableToken, QconnectEventSink,
|
||||
QconnectFileAudioQualitySnapshot, QconnectLifecycleState, QconnectRemoteSyncState,
|
||||
QconnectSessionState, QueueCommandType, RendererBufferState, RendererPlaybackSnapshot,
|
||||
RendererReport, RendererReportType, SessionLoopHost,
|
||||
};
|
||||
use qconnect_lan::EndpointPolicy;
|
||||
use qconnect_transport_ws::{NativeWsTransport, WsTransportConfig};
|
||||
@@ -85,26 +85,9 @@ use crate::qconnect_transport_qt::{
|
||||
|
||||
const QCONNECT_PLAY_TRACK_HANDOFF_WAIT_MS: u64 = 1_500;
|
||||
const QCONNECT_PLAY_TRACK_HANDOFF_POLL_MS: u64 = 50;
|
||||
const QCONNECT_LAN_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const QCONNECT_LAN_START_CLEANUP_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const QCONNECT_COORDINATOR_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const QCONNECT_AUTHORITY_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
async fn shutdown_lan_runtime(mut runtime: QtLanRuntime) -> Result<(), String> {
|
||||
let mut shutdown = tokio::task::spawn_blocking(move || runtime.shutdown_blocking());
|
||||
match tokio::time::timeout(QCONNECT_LAN_SHUTDOWN_TIMEOUT, &mut shutdown).await {
|
||||
Ok(Ok(())) => Ok(()),
|
||||
Ok(Err(_)) => Err("qconnect-lan-shutdown-task-failed".to_string()),
|
||||
Err(_) => {
|
||||
// A running spawn_blocking task cannot be preempted safely. Drop
|
||||
// its handle and let the runtime finish its idempotent teardown;
|
||||
// the service slot and projection have already been detached.
|
||||
drop(shutdown);
|
||||
Err("qconnect-lan-shutdown-timed-out".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wall-clock now in ms (mirrors the Tauri `qconnect_now_ms`, which is
|
||||
/// Tauri-local; reimplemented inline here per the controller-port spec).
|
||||
fn qconnect_now_ms() -> u64 {
|
||||
@@ -482,14 +465,6 @@ pub(crate) fn lock_inner(inner: &StdMutex<QtQconnectInner>) -> StdMutexGuard<'_,
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn lan_callback_is_current(
|
||||
enable_intent: &QconnectEnableIntent,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
) -> bool {
|
||||
enable_intent.current_token().is_some() && authority.is_current(stamp)
|
||||
}
|
||||
|
||||
/// Dedup + gate a lifecycle transition: only emit while a runtime is alive and
|
||||
/// the state actually changes. Mirrors the Tauri `update_lifecycle_state_if_running`.
|
||||
async fn update_lifecycle_state_if_running(
|
||||
@@ -527,15 +502,7 @@ pub struct QtQconnectService {
|
||||
delegation_host: Arc<QtDelegationHost>,
|
||||
coordinator: QtDelegationCoordinator,
|
||||
lan: Mutex<Option<QtLanRuntime>>,
|
||||
/// `QtLanRuntime::start` runs on the blocking pool and cannot be aborted
|
||||
/// after it begins. Keep that physical work visible after enabled intent
|
||||
/// is cancelled so teardown cannot report success while a late listener
|
||||
/// is still capable of appearing.
|
||||
lan_start_pending: Arc<AtomicBool>,
|
||||
/// A LAN worker that could not be joined or physically shut down is a
|
||||
/// process-lifetime fail-closed fence. Logical slot removal is not enough
|
||||
/// to admit another QConnect authority in that state.
|
||||
lan_teardown_unsafe: Arc<AtomicBool>,
|
||||
lan_lifecycle: LanRuntimeLifecycle<QtLanRuntime>,
|
||||
lifecycle_gate: Mutex<()>,
|
||||
/// Controller-mode mirror of the local queue's manual block (#442 "Play
|
||||
/// later"): steers `insert_after` for play-later routing. See the struct
|
||||
@@ -937,8 +904,9 @@ impl QtQconnectService {
|
||||
delegation_host,
|
||||
coordinator,
|
||||
lan: Mutex::new(None),
|
||||
lan_start_pending: Arc::new(AtomicBool::new(false)),
|
||||
lan_teardown_unsafe: Arc::new(AtomicBool::new(false)),
|
||||
lan_lifecycle: LanRuntimeLifecycle::new(|runtime: &mut QtLanRuntime| {
|
||||
runtime.shutdown_blocking()
|
||||
}),
|
||||
lifecycle_gate: Mutex::new(()),
|
||||
controller_manual: Mutex::new(ControllerManualBlock::default()),
|
||||
teardown_incomplete: AtomicBool::new(false),
|
||||
@@ -1111,7 +1079,7 @@ impl QtQconnectService {
|
||||
stamp: AuthorityStamp,
|
||||
qws_endpoint: &str,
|
||||
) -> Result<(), String> {
|
||||
if self.lan_teardown_unsafe.load(Ordering::Acquire) {
|
||||
if !self.lan_lifecycle.teardown_safe() {
|
||||
return Err("qconnect-lan-physical-teardown-unsafe".to_string());
|
||||
}
|
||||
if !self.enable_intent.is_current(enable_token) {
|
||||
@@ -1156,95 +1124,48 @@ impl QtQconnectService {
|
||||
let runtime_handle = tokio::runtime::Handle::current();
|
||||
let bridge_handle = runtime_handle.clone();
|
||||
|
||||
if self.lan_start_pending.swap(true, Ordering::AcqRel) {
|
||||
return Err("qconnect-lan-start-already-pending".to_string());
|
||||
}
|
||||
let mut start_task = tokio::task::spawn_blocking(move || {
|
||||
QtLanRuntime::start(
|
||||
bridge_handle,
|
||||
endpoint_policy,
|
||||
app_id,
|
||||
max_audio_quality,
|
||||
Some(current_session_id),
|
||||
move |candidate| {
|
||||
let coordinator = coordinator.clone();
|
||||
let callback_intent = Arc::clone(&callback_intent);
|
||||
let callback_authority = Arc::clone(&callback_authority);
|
||||
async move {
|
||||
// The listener belongs to the installed authority, not
|
||||
// to the one-shot connect epoch that installed it. A
|
||||
// fresh manual intent may reuse that runtime; disable
|
||||
// or authority replacement still closes admission.
|
||||
if !lan_callback_is_current(
|
||||
callback_intent.as_ref(),
|
||||
callback_authority.as_ref(),
|
||||
stamp,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
match coordinator.admit(candidate).await {
|
||||
Ok(generation) => log::info!(
|
||||
"[QConnect LAN] handoff admitted generation={generation}"
|
||||
),
|
||||
Err(error) => {
|
||||
log::warn!("[QConnect LAN] handoff admission rejected: {error}")
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
});
|
||||
let start_result = tokio::select! {
|
||||
biased;
|
||||
_ = self.enable_intent.cancelled(enable_token) => {
|
||||
// `spawn_blocking` cannot be aborted once running. Keep its
|
||||
// result owned and withdraw any listener it manages to create.
|
||||
// The pending bit remains raised until that physical cleanup
|
||||
// finishes, so the disconnect path must fail closed meanwhile.
|
||||
let pending = Arc::clone(&self.lan_start_pending);
|
||||
let unsafe_latch = Arc::clone(&self.lan_teardown_unsafe);
|
||||
tokio::spawn(async move {
|
||||
let cleanup_safe = match start_task.await {
|
||||
Ok(Ok(runtime)) => match shutdown_lan_runtime(runtime).await {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"[QConnect LAN] cancelled listener cleanup failed: {error}"
|
||||
);
|
||||
false
|
||||
let started = self
|
||||
.lan_lifecycle
|
||||
.start(
|
||||
move || {
|
||||
QtLanRuntime::start(
|
||||
bridge_handle,
|
||||
endpoint_policy,
|
||||
app_id,
|
||||
max_audio_quality,
|
||||
Some(current_session_id),
|
||||
move |candidate| {
|
||||
let coordinator = coordinator.clone();
|
||||
let callback_intent = Arc::clone(&callback_intent);
|
||||
let callback_authority = Arc::clone(&callback_authority);
|
||||
async move {
|
||||
if !lan_callback_is_current(
|
||||
callback_intent.as_ref(),
|
||||
callback_authority.as_ref(),
|
||||
stamp,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
match coordinator.admit(candidate).await {
|
||||
Ok(generation) => log::info!(
|
||||
"[QConnect LAN] handoff admitted generation={generation}"
|
||||
),
|
||||
Err(error) => log::warn!(
|
||||
"[QConnect LAN] handoff admission rejected: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
},
|
||||
Ok(Err(_)) => true,
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"[QConnect LAN] cancelled listener start worker failed: {error}"
|
||||
);
|
||||
false
|
||||
}
|
||||
};
|
||||
if !cleanup_safe {
|
||||
unsafe_latch.store(true, Ordering::Release);
|
||||
}
|
||||
pending.store(false, Ordering::Release);
|
||||
});
|
||||
return Err("qconnect-lan-disabled".to_string());
|
||||
}
|
||||
result = &mut start_task => result,
|
||||
};
|
||||
self.lan_start_pending.store(false, Ordering::Release);
|
||||
let started = match start_result {
|
||||
Ok(Ok(runtime)) => runtime,
|
||||
Ok(Err(_)) => return Err("qconnect-lan-bind-failed".to_string()),
|
||||
Err(_) => {
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
return Err("qconnect-lan-start-task-failed".to_string());
|
||||
}
|
||||
};
|
||||
)
|
||||
},
|
||||
self.enable_intent.cancelled(enable_token),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
|
||||
if !self.enable_intent.is_current(enable_token) || !self.authority.is_current(stamp) {
|
||||
if let Err(error) = shutdown_lan_runtime(started).await {
|
||||
if let Err(error) = self.lan_lifecycle.shutdown(started).await {
|
||||
log::warn!("[QConnect LAN] stale listener teardown failed: {error}");
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
}
|
||||
return Err("qconnect-lan-owner-superseded".to_string());
|
||||
}
|
||||
@@ -1277,9 +1198,8 @@ impl QtQconnectService {
|
||||
}
|
||||
|
||||
if let Some(stale) = pending {
|
||||
if let Err(error) = shutdown_lan_runtime(stale).await {
|
||||
if let Err(error) = self.lan_lifecycle.shutdown(stale).await {
|
||||
log::warn!("[QConnect LAN] rejected listener teardown failed: {error}");
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
Err("qconnect-lan-disabled-or-owner-superseded".to_string())
|
||||
@@ -1289,26 +1209,15 @@ impl QtQconnectService {
|
||||
self.delegation_host.detach_projection();
|
||||
let runtime = self.lan.lock().await.take();
|
||||
if let Some(runtime) = runtime {
|
||||
if let Err(error) = shutdown_lan_runtime(runtime).await {
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
return Err(error);
|
||||
}
|
||||
self.lan_lifecycle
|
||||
.shutdown(runtime)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
if self.lan_start_pending.load(Ordering::Acquire) {
|
||||
let settled = tokio::time::timeout(QCONNECT_LAN_START_CLEANUP_TIMEOUT, async {
|
||||
while self.lan_start_pending.load(Ordering::Acquire) {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
self.lan_lifecycle
|
||||
.settle()
|
||||
.await
|
||||
.is_ok();
|
||||
if !settled {
|
||||
return Err("qconnect-lan-start-cleanup-timed-out".to_string());
|
||||
}
|
||||
}
|
||||
if self.lan_teardown_unsafe.load(Ordering::Acquire) {
|
||||
return Err("qconnect-lan-physical-teardown-unsafe".to_string());
|
||||
}
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1419,8 +1328,8 @@ impl QtQconnectService {
|
||||
let inner = lock_inner(&self.inner);
|
||||
inner.runtime.is_some()
|
||||
|| inner.connecting_token.is_some()
|
||||
|| self.lan_start_pending.load(Ordering::Acquire)
|
||||
|| self.lan_teardown_unsafe.load(Ordering::Acquire)
|
||||
|| self.lan_lifecycle.start_pending()
|
||||
|| !self.lan_lifecycle.teardown_safe()
|
||||
|| self.teardown_incomplete.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
@@ -2069,8 +1978,7 @@ impl QtQconnectService {
|
||||
log::warn!("[QConnect] LAN teardown failed: {error}");
|
||||
false
|
||||
} else {
|
||||
!self.lan_start_pending.load(Ordering::Acquire)
|
||||
&& !self.lan_teardown_unsafe.load(Ordering::Acquire)
|
||||
!self.lan_lifecycle.start_pending() && self.lan_lifecycle.teardown_safe()
|
||||
};
|
||||
// A restore scheduled by the preceding delegated -> owner transition
|
||||
// still owns the delegation transition gate. Let that tracked task
|
||||
@@ -3498,14 +3406,13 @@ impl QtQconnectService {
|
||||
///
|
||||
/// WS-AUTHORITATIVE (load-bearing): QBZ sends ONLY `{shuffle_mode,
|
||||
/// shuffle_seed, shuffle_pivot_queue_item_id}` — never a local order. The
|
||||
/// cloud generates the order and echoes it; QBZ applies ONLY that echoed
|
||||
/// order (inbound SetShuffleMode is flag-only + materialize applies the
|
||||
/// cloud's `shuffled_track_indexes`). The local `playback::toggle_shuffle`
|
||||
/// path (which DOES invent a local random order — the documented failure
|
||||
/// mode) is reachable ONLY when NOT connected (this returns `Ok(false)` then,
|
||||
/// so the caller runs it offline). The previous peer-only gate let that local
|
||||
/// path run while connected-as-renderer, which both did nothing visible AND
|
||||
/// risked the divergent-order bug.
|
||||
/// server-authorized seed/pivot or `shuffled_track_indexes` is the sole
|
||||
/// input to the deterministic playback order applied by every client.
|
||||
/// Inbound `SetShuffleMode` alone cannot mutate the local queue. The local
|
||||
/// `playback::toggle_shuffle` path (which invents local entropy) is reachable
|
||||
/// ONLY when NOT connected (this returns `Ok(false)` then, so the caller runs
|
||||
/// it offline). The previous peer-only gate let that local path run while
|
||||
/// connected-as-renderer, producing the documented divergent-order bug.
|
||||
pub async fn toggle_shuffle_if_remote(&self) -> Result<bool, String> {
|
||||
let Some(_runtime_action) = self.begin_runtime_action_if_running()? else {
|
||||
return Ok(false);
|
||||
@@ -3529,9 +3436,10 @@ impl QtQconnectService {
|
||||
// never populates for a peer.
|
||||
let next_shuffle = !queue.shuffle_mode;
|
||||
|
||||
// The cloud REQUIRES a `shuffle_seed` when enabling ("shuffleSeed is
|
||||
// undefined" otherwise) and uses it to GENERATE the order — QBZ supplies
|
||||
// only the seed + pivot, never an order. No `rand` crate here (unlike
|
||||
// The server REQUIRES a `shuffle_seed` when enabling ("shuffleSeed is
|
||||
// undefined" otherwise). QBZ originates one only while acting as the
|
||||
// controller that requested this toggle; renderers consume the echoed
|
||||
// WS seed/pivot and never generate another. No `rand` crate here (unlike
|
||||
// Tauri); seed from the wall clock, masked to i32::MAX for the wire
|
||||
// `fixed32`. Pivot keeps the current track at the front. Mirrors the
|
||||
// Tauri `apply_qconnect_shuffle_mode` payload.
|
||||
@@ -4527,9 +4435,8 @@ async fn deferred_renderer_join(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{is_qconnect_queue_track, lan_callback_is_current};
|
||||
use super::is_qconnect_queue_track;
|
||||
use qbz_models::QueueTrack;
|
||||
use qconnect_app::{AuthorityCell, AuthorityOrigin, QconnectEnableIntent};
|
||||
|
||||
fn track(source: Option<&str>, is_local: bool) -> QueueTrack {
|
||||
QueueTrack {
|
||||
@@ -4587,44 +4494,6 @@ mod tests {
|
||||
assert!(!is_qconnect_queue_track(&row));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_lan_callback_survives_enabled_epoch_refresh_only() {
|
||||
let intent = QconnectEnableIntent::new(true);
|
||||
let original = intent.current_token().expect("initial enabled intent");
|
||||
let authority = AuthorityCell::new();
|
||||
let stamp = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(authority.install(stamp));
|
||||
assert!(lan_callback_is_current(&intent, &authority, stamp));
|
||||
|
||||
let refreshed = intent.enable_new_intent();
|
||||
assert!(!intent.is_current(original));
|
||||
assert!(intent.is_current(refreshed));
|
||||
assert!(lan_callback_is_current(&intent, &authority, stamp));
|
||||
|
||||
let disabled = intent.disable();
|
||||
assert!(!lan_callback_is_current(&intent, &authority, stamp));
|
||||
assert!(intent.enable_if_disabled(disabled).is_some());
|
||||
assert!(lan_callback_is_current(&intent, &authority, stamp));
|
||||
|
||||
authority.clear();
|
||||
assert!(!lan_callback_is_current(&intent, &authority, stamp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lan_candidate_callback_uses_live_intent_and_exact_authority() {
|
||||
let source = include_str!("qconnect_qt.rs");
|
||||
let body = source
|
||||
.split_once("move |candidate|")
|
||||
.expect("LAN candidate callback")
|
||||
.1
|
||||
.split_once("match coordinator.admit(candidate).await")
|
||||
.expect("LAN candidate admission")
|
||||
.0;
|
||||
|
||||
assert!(body.contains("lan_callback_is_current("));
|
||||
assert!(!body.contains("is_current(enable_token)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cast_teardown_replaces_only_the_exact_enabled_intent() {
|
||||
let source = include_str!("qconnect_qt.rs");
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
//! installed runtime remains authoritative. The synchronous commit methods do
|
||||
//! only a short stamped runtime swap; teardown, queue restoration and cloud
|
||||
//! bootstrap happen afterwards.
|
||||
//!
|
||||
//! Race-sensitive policy is deliberately shared by `qconnect-app`: authority
|
||||
//! fences and deferred release, QWS preflight/join/rejoin, LAN projection and
|
||||
//! physical LAN lifecycle. The code left here is an adapter boundary for
|
||||
//! qbzd's shared state, volume modes and abortable task registry. Do not mirror
|
||||
//! new policy into the Qt adapter; extract it with behavioral tests in
|
||||
//! `qconnect-app`.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::future::Future;
|
||||
@@ -16,18 +23,17 @@ use qbz_app::shell::AppRuntime;
|
||||
use qbz_core::QueueAuthoritySnapshot;
|
||||
use qbz_models::{CoreEvent, Quality};
|
||||
use qbz_qobuz::{DelegatedApiConfig, DelegatedApiEndpoint, DelegatedQobuzClient, QobuzClient};
|
||||
use qconnect_app::renderer::PLAYING_STATE_STOPPED;
|
||||
use qconnect_app::{
|
||||
CommitRejected, DelegationCancellation, DelegationCoordinator, DelegationErrorCode,
|
||||
DelegationHost, QconnectApp, QconnectAppEvent, QconnectEventSink, QconnectLifecycleState,
|
||||
QconnectRemoteSyncState, QconnectSessionState, RendererBufferState, RendererReport,
|
||||
RendererReportType, RestoreReason, SessionLoopHost, JOIN_SESSION_REASON_CONTROLLER_REQUEST,
|
||||
acquire_transition_guard_and_fence, max_audio_quality_from_quality, CommitRejected,
|
||||
DeferredActivationRelease, DelegatedRejoinWatchdog, DelegatedRuntimeEventDirective,
|
||||
DelegatedRuntimeEventState, DelegationCancellation, DelegationCoordinator, DelegationErrorCode,
|
||||
DelegationHost, DelegationPreflight, OwnerActionFence, QconnectApp, QconnectAppEvent,
|
||||
QconnectEventSink, QconnectLifecycleState, QconnectRemoteSyncState, QconnectSessionState,
|
||||
RestoreReason, SessionLoopHost,
|
||||
};
|
||||
use qconnect_lan::{HandoffCandidate, LanProjection};
|
||||
use qconnect_protocol::RendererCommandType;
|
||||
use qconnect_transport_ws::{NativeWsTransport, TransportEvent, WsTransportConfig};
|
||||
use tokio::sync::{broadcast, oneshot, watch, Mutex as AsyncMutex, OwnedMutexGuard};
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::adapter::DaemonAdapter;
|
||||
@@ -48,9 +54,6 @@ type SharedState = Arc<StdMutex<DaemonShared>>;
|
||||
type OwnerRestoreResult = Result<(), &'static str>;
|
||||
pub type DaemonDelegationCoordinator = DelegationCoordinator<DaemonDelegationHost>;
|
||||
|
||||
const PREFLIGHT_BUFFER_EVENTS: usize = 256;
|
||||
const PREFLIGHT_BUFFER_BYTES: usize = 256 * 1024;
|
||||
const DELEGATED_REJOIN_SESSION_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const SHUTDOWN_RESTORE_OWNER: u8 = 0;
|
||||
const SHUTDOWN_DISCARD_OWNER: u8 = 1;
|
||||
static NEXT_OWNER_RESTORE_TASK_ID: AtomicU64 = AtomicU64::new(1);
|
||||
@@ -69,86 +72,6 @@ impl OwnerRestoreTask {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RejoinWatchdogGeneration(AtomicU64);
|
||||
|
||||
impl RejoinWatchdogGeneration {
|
||||
fn advance(&self) -> u64 {
|
||||
self.0.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
|
||||
}
|
||||
|
||||
/// Claims an armed generation exactly once. A reconnect, successful
|
||||
/// establishment, runtime drop, or replacement arm advances the epoch and
|
||||
/// makes the stale deadline harmless.
|
||||
fn claim(&self, expected: u64) -> bool {
|
||||
self.0
|
||||
.compare_exchange(
|
||||
expected,
|
||||
expected.wrapping_add(1),
|
||||
Ordering::AcqRel,
|
||||
Ordering::Acquire,
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
struct DelegatedRejoinWatchdog {
|
||||
generation: Arc<RejoinWatchdogGeneration>,
|
||||
task: Option<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl DelegatedRejoinWatchdog {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
generation: Arc::new(RejoinWatchdogGeneration::default()),
|
||||
task: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn arm(
|
||||
&mut self,
|
||||
authority: Arc<AuthorityCell>,
|
||||
stamp: AuthorityStamp,
|
||||
delegation_generation: u64,
|
||||
coordinator: Option<DaemonDelegationCoordinator>,
|
||||
) {
|
||||
// Advance before aborting so even a task already waking at the
|
||||
// deadline loses its compare-exchange against this newer rejoin.
|
||||
let watchdog_generation = self.generation.advance();
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
let generation = Arc::clone(&self.generation);
|
||||
self.task = Some(tokio::spawn(async move {
|
||||
tokio::time::sleep(DELEGATED_REJOIN_SESSION_TIMEOUT).await;
|
||||
if !generation.claim(watchdog_generation)
|
||||
|| stamp.origin()
|
||||
!= (AuthorityOrigin::Delegated {
|
||||
generation: delegation_generation,
|
||||
})
|
||||
|| !authority.is_current(stamp)
|
||||
{
|
||||
return;
|
||||
}
|
||||
request_restore(coordinator.as_ref(), delegation_generation).await;
|
||||
}));
|
||||
}
|
||||
|
||||
fn cancel(&mut self) {
|
||||
// Invalidate first: abort is cooperative and may race a waking task.
|
||||
self.generation.advance();
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DelegatedRejoinWatchdog {
|
||||
fn drop(&mut self) {
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct OwnerSnapshot {
|
||||
queue: QueueAuthoritySnapshot,
|
||||
@@ -164,39 +87,19 @@ struct OwnerPlaybackSnapshot {
|
||||
had_loaded_audio: bool,
|
||||
}
|
||||
|
||||
struct OwnerActionFence {
|
||||
authority: Arc<AuthorityCell>,
|
||||
}
|
||||
|
||||
impl OwnerActionFence {
|
||||
fn acquire(authority: Arc<AuthorityCell>) -> Self {
|
||||
authority.suspend_owner_actions();
|
||||
Self { authority }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OwnerActionFence {
|
||||
fn drop(&mut self) {
|
||||
self.authority.resume_owner_actions();
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapter payload only: the shared preparation/activation policy lives in
|
||||
/// `qconnect-app`; these concrete daemon app/sink handles and `VolumeMode`
|
||||
/// cannot cross the crate boundary without coupling the shared layer to qbzd.
|
||||
struct PreparedCommon {
|
||||
app: Arc<DaemonQconnectApp>,
|
||||
sink: Arc<DaemonEventSink>,
|
||||
config: WsTransportConfig,
|
||||
sync_state: Arc<AsyncMutex<QconnectRemoteSyncState>>,
|
||||
receiver: broadcast::Receiver<TransportEvent>,
|
||||
buffered: VecDeque<TransportEvent>,
|
||||
buffered_bytes: usize,
|
||||
preflight: DelegationPreflight,
|
||||
stamp: AuthorityStamp,
|
||||
expected_current: AuthorityStamp,
|
||||
volume_mode: VolumeMode,
|
||||
custom_name: Option<String>,
|
||||
/// Captured from owner SESSION_STATE during preparation. `prepare_owner`
|
||||
/// cannot return until the matching SessionEstablished signal also arrives,
|
||||
/// and this value stays private until `commit_owner` installs that runtime.
|
||||
confirmed_owner_session_id: Option<Zeroizing<String>>,
|
||||
}
|
||||
|
||||
pub struct PreparedDelegation {
|
||||
@@ -237,49 +140,6 @@ struct PendingActivation {
|
||||
owner_quality: Quality,
|
||||
}
|
||||
|
||||
/// The final release edge of an installed authority transition.
|
||||
///
|
||||
/// Owner rollback moves this guard into its tracked playback-restoration task,
|
||||
/// keeping both ordinary owner actions and the next authority transition out
|
||||
/// until the restored stream is stable. `Drop` is deliberately sufficient: a
|
||||
/// coordinator cleanup timeout or task abort still wakes the installed event
|
||||
/// loop and releases both gates.
|
||||
struct DeferredActivationRelease {
|
||||
start: Option<oneshot::Sender<()>>,
|
||||
transition_fence: Option<OwnerActionFence>,
|
||||
transition_guard: Option<OwnedMutexGuard<()>>,
|
||||
}
|
||||
|
||||
impl DeferredActivationRelease {
|
||||
fn new(
|
||||
start: Option<oneshot::Sender<()>>,
|
||||
transition_fence: Option<OwnerActionFence>,
|
||||
transition_guard: Option<OwnedMutexGuard<()>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
start,
|
||||
transition_fence,
|
||||
transition_guard,
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&mut self) {
|
||||
// Admission opens before the prepared loop wakes so buffered commands
|
||||
// cannot observe the transition fence and disappear as rejected work.
|
||||
self.transition_fence.take();
|
||||
if let Some(start) = self.start.take() {
|
||||
let _ = start.send(());
|
||||
}
|
||||
self.transition_guard.take();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DeferredActivationRelease {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
}
|
||||
}
|
||||
|
||||
impl PendingActivation {
|
||||
fn release(&mut self) {
|
||||
let Some(start) = self.start.take() else {
|
||||
@@ -639,14 +499,11 @@ impl DelegationHost for DaemonDelegationHost {
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered: VecDeque::new(),
|
||||
buffered_bytes: 0,
|
||||
preflight: DelegationPreflight::new(receiver),
|
||||
stamp,
|
||||
expected_current,
|
||||
volume_mode,
|
||||
custom_name,
|
||||
confirmed_owner_session_id: None,
|
||||
};
|
||||
let api_validation = async {
|
||||
delegated_client
|
||||
@@ -656,7 +513,7 @@ impl DelegationHost for DaemonDelegationHost {
|
||||
};
|
||||
tokio::try_join!(
|
||||
api_validation,
|
||||
wait_for_qws_ready(&mut common, cancellation)
|
||||
common.preflight.wait_for_qws_ready(cancellation)
|
||||
)?;
|
||||
|
||||
Ok(PreparedDelegation {
|
||||
@@ -675,26 +532,20 @@ impl DelegationHost for DaemonDelegationHost {
|
||||
prepared: &mut PreparedDelegation,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
// Serialize the fallible activation/commit/retirement tail before
|
||||
// closing ordinary action admission. The guard remains in `prepared`
|
||||
// through commit and moves into `PendingActivation`; owner rollback
|
||||
// keeps it until playback is restored. A second fence is not a mutex,
|
||||
// so this explicit gate is what prevents overlapping transitions.
|
||||
prepared.transition_guard = Some(Arc::clone(&self.transition_gate).lock_owned().await);
|
||||
|
||||
// Fence every installed authority, including delegated -> delegated:
|
||||
// runtime action permits can span catalog/stream awaits and must drain
|
||||
// before cloud activation. Join is deliberately the final I/O before
|
||||
// the stamped swap; once SET_ACTIVE=true arrives, commit stays short.
|
||||
// Only the owner additionally needs a queue snapshot for restore.
|
||||
prepared.transition_fence = Some(OwnerActionFence::acquire(Arc::clone(&self.authority)));
|
||||
self.authority.wait_for_actions_drained().await;
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
let (transition_guard, transition_fence) = acquire_transition_guard_and_fence(
|
||||
Arc::clone(&self.transition_gate),
|
||||
Arc::clone(&self.authority),
|
||||
prepared.common.expected_current,
|
||||
|| {},
|
||||
)
|
||||
.await?;
|
||||
prepared.transition_guard = Some(transition_guard);
|
||||
prepared.transition_fence = Some(transition_fence);
|
||||
if prepared.common.expected_current.origin() == AuthorityOrigin::Owner {
|
||||
let queue = self.runtime.core().capture_authority_snapshot().await;
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
@@ -732,7 +583,11 @@ impl DelegationHost for DaemonDelegationHost {
|
||||
current_quality(&self.quality_cap),
|
||||
)
|
||||
.await?;
|
||||
wait_for_activation(&mut prepared.common, cancellation).await?;
|
||||
prepared
|
||||
.common
|
||||
.preflight
|
||||
.wait_for_activation(cancellation)
|
||||
.await?;
|
||||
if !self.authority.is_current(prepared.common.expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
@@ -860,30 +715,32 @@ impl DelegationHost for DaemonDelegationHost {
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered: VecDeque::new(),
|
||||
buffered_bytes: 0,
|
||||
preflight: DelegationPreflight::new(receiver),
|
||||
stamp,
|
||||
expected_current,
|
||||
volume_mode,
|
||||
custom_name,
|
||||
confirmed_owner_session_id: None,
|
||||
};
|
||||
wait_for_qws_ready(&mut common, cancellation.clone())
|
||||
common
|
||||
.preflight
|
||||
.wait_for_qws_ready(cancellation.clone())
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::OwnerRestoreFailed)?;
|
||||
bootstrap_prepared_owner_presence(&common.app, common.custom_name.clone())
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::OwnerRestoreFailed)?;
|
||||
wait_for_owner_session(&mut common, cancellation)
|
||||
common
|
||||
.preflight
|
||||
.wait_for_owner_session(cancellation)
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::OwnerRestoreFailed)?;
|
||||
let transition_guard = Arc::clone(&self.transition_gate).lock_owned().await;
|
||||
let transition_fence = OwnerActionFence::acquire(Arc::clone(&self.authority));
|
||||
self.authority.wait_for_actions_drained().await;
|
||||
if !self.authority.is_current(expected_current) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
let (transition_guard, transition_fence) = acquire_transition_guard_and_fence(
|
||||
Arc::clone(&self.transition_gate),
|
||||
Arc::clone(&self.authority),
|
||||
expected_current,
|
||||
|| {},
|
||||
)
|
||||
.await?;
|
||||
Ok(PreparedOwner {
|
||||
common,
|
||||
transition_guard,
|
||||
@@ -907,7 +764,12 @@ impl DelegationHost for DaemonDelegationHost {
|
||||
));
|
||||
}
|
||||
let stamp = prepared.common.stamp;
|
||||
let Some(owner_session_id) = prepared.common.confirmed_owner_session_id.clone() else {
|
||||
let Some(owner_session_id) = prepared
|
||||
.common
|
||||
.preflight
|
||||
.confirmed_owner_session_id()
|
||||
.map(|session_id| Zeroizing::new(session_id.to_string()))
|
||||
else {
|
||||
return Err(CommitRejected::new(
|
||||
prepared,
|
||||
DelegationErrorCode::CommitRejected,
|
||||
@@ -1013,8 +875,8 @@ impl DelegationHost for DaemonDelegationHost {
|
||||
// intentional: cancelling that valid restore would lose the original
|
||||
// owner stream just because a later candidate/shutdown arrived.
|
||||
let transition_guard = Arc::clone(&self.transition_gate).lock_owned().await;
|
||||
let shutdown_fence = OwnerActionFence::acquire(Arc::clone(&self.authority));
|
||||
self.authority.wait_for_actions_drained().await;
|
||||
let shutdown_fence =
|
||||
OwnerActionFence::acquire_drained(Arc::clone(&self.authority), || {}).await;
|
||||
let previous = self.projection.clear_authority(&self.authority);
|
||||
let was_delegated = previous
|
||||
.is_some_and(|stamp| matches!(stamp.origin(), AuthorityOrigin::Delegated { .. }));
|
||||
@@ -1312,163 +1174,6 @@ fn current_quality(quality: &StdMutex<Quality>) -> Quality {
|
||||
*recover_lock(quality)
|
||||
}
|
||||
|
||||
fn quality_wire(quality: Quality) -> i32 {
|
||||
match quality {
|
||||
Quality::Mp3 => 1,
|
||||
Quality::Lossless => 2,
|
||||
Quality::HiRes => 3,
|
||||
Quality::UltraHiRes => 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn retained_event_bytes(event: &TransportEvent) -> usize {
|
||||
match event {
|
||||
TransportEvent::InboundPayloadBytes { payload, .. } => payload.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn should_retain(event: &TransportEvent) -> bool {
|
||||
matches!(
|
||||
event,
|
||||
TransportEvent::Connected
|
||||
| TransportEvent::Disconnected
|
||||
| TransportEvent::SessionEstablished
|
||||
| TransportEvent::InboundPayloadBytes { .. }
|
||||
| TransportEvent::InboundQueueServerEvent(_)
|
||||
| TransportEvent::InboundRendererServerCommand(_)
|
||||
| TransportEvent::InboundReceived(_)
|
||||
)
|
||||
}
|
||||
|
||||
fn retain_event(
|
||||
common: &mut PreparedCommon,
|
||||
event: TransportEvent,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
if !should_retain(&event) {
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = retained_event_bytes(&event);
|
||||
if common.buffered.len() >= PREFLIGHT_BUFFER_EVENTS
|
||||
|| common.buffered_bytes.saturating_add(bytes) > PREFLIGHT_BUFFER_BYTES
|
||||
{
|
||||
return Err(DelegationErrorCode::Internal);
|
||||
}
|
||||
common.buffered_bytes = common.buffered_bytes.saturating_add(bytes);
|
||||
common.buffered.push_back(event);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn next_preflight_event(
|
||||
common: &mut PreparedCommon,
|
||||
mut cancellation: DelegationCancellation,
|
||||
) -> Result<TransportEvent, DelegationErrorCode> {
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => Err(DelegationErrorCode::CandidateCancelled),
|
||||
event = common.receiver.recv() => match event {
|
||||
Ok(event) => Ok(event),
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => Err(DelegationErrorCode::Internal),
|
||||
Err(broadcast::error::RecvError::Closed) => Err(DelegationErrorCode::QwsRejected),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_qws_ready(
|
||||
common: &mut PreparedCommon,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut authenticated = false;
|
||||
let mut subscribed = false;
|
||||
while !(authenticated && subscribed) {
|
||||
let event = next_preflight_event(common, cancellation.clone()).await?;
|
||||
match &event {
|
||||
TransportEvent::Authenticated => authenticated = true,
|
||||
TransportEvent::Subscribed => subscribed = true,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. } => {
|
||||
return Err(DelegationErrorCode::QwsRejected)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
retain_event(common, event)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait_for_activation(
|
||||
common: &mut PreparedCommon,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
loop {
|
||||
let event = next_preflight_event(common, cancellation.clone()).await?;
|
||||
let accepted = matches!(
|
||||
&event,
|
||||
TransportEvent::InboundRendererServerCommand(command)
|
||||
if command.command_type == RendererCommandType::SrvrRndrSetActive
|
||||
&& command.payload.get("active").and_then(serde_json::Value::as_bool)
|
||||
== Some(true)
|
||||
);
|
||||
if matches!(
|
||||
&event,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. }
|
||||
) {
|
||||
return Err(DelegationErrorCode::ActivationRejected);
|
||||
}
|
||||
retain_event(common, event)?;
|
||||
if accepted {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owner preparation is complete only after the cloud has accepted the
|
||||
/// controller-side join and emitted the same establishment signal consumed by
|
||||
/// a live session loop. Authentication/subscription and a successful socket
|
||||
/// send are necessary but not sufficient to publish `OwnerReady`.
|
||||
async fn wait_for_owner_session(
|
||||
common: &mut PreparedCommon,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut established = false;
|
||||
loop {
|
||||
let event = next_preflight_event(common, cancellation.clone()).await?;
|
||||
if let Some(session_id) = owner_session_id_from_event(&event).map(str::to_string) {
|
||||
common.confirmed_owner_session_id = Some(Zeroizing::new(session_id));
|
||||
}
|
||||
established |= matches!(&event, TransportEvent::SessionEstablished);
|
||||
if matches!(
|
||||
&event,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. }
|
||||
) {
|
||||
return Err(DelegationErrorCode::OwnerRestoreFailed);
|
||||
}
|
||||
retain_event(common, event)?;
|
||||
if established && common.confirmed_owner_session_id.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_session_id_from_event(event: &TransportEvent) -> Option<&str> {
|
||||
match event {
|
||||
TransportEvent::InboundQueueServerEvent(event)
|
||||
if event.message_type() == "MESSAGE_TYPE_SRVR_CTRL_SESSION_STATE" =>
|
||||
{
|
||||
event
|
||||
.payload
|
||||
.get("session_uuid")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|session_id| !session_id.is_empty())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_delegated_join(
|
||||
app: &Arc<DaemonQconnectApp>,
|
||||
session_id: &str,
|
||||
@@ -1478,33 +1183,15 @@ async fn send_delegated_join(
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut device_info = default_qconnect_device_info_with_name(custom_name);
|
||||
if let Some(capabilities) = device_info.capabilities.as_mut() {
|
||||
capabilities.max_audio_quality = Some(quality_wire(quality));
|
||||
capabilities.max_audio_quality = Some(max_audio_quality_from_quality(quality));
|
||||
}
|
||||
let queue_version = app.queue_state_snapshot().await.version;
|
||||
let report = RendererReport::new(
|
||||
RendererReportType::RndrSrvrJoinSession,
|
||||
Uuid::new_v4().to_string(),
|
||||
queue_version,
|
||||
serde_json::json!({
|
||||
"session_uuid": session_id,
|
||||
"device_info": serde_json::to_value(device_info).unwrap_or_default(),
|
||||
"is_active": become_active,
|
||||
"reason": JOIN_SESSION_REASON_CONTROLLER_REQUEST,
|
||||
"initial_state": {
|
||||
"playing_state": PLAYING_STATE_STOPPED,
|
||||
"buffer_state": RendererBufferState::Ok.as_i32(),
|
||||
"current_position": 0,
|
||||
"duration": 0,
|
||||
"queue_version": {
|
||||
"major": queue_version.major,
|
||||
"minor": queue_version.minor,
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
app.send_renderer_report_command(report)
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::ActivationRejected)
|
||||
app.send_delegated_join(
|
||||
session_id,
|
||||
become_active,
|
||||
serde_json::to_value(device_info).unwrap_or_default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| DelegationErrorCode::ActivationRejected)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -1523,12 +1210,12 @@ fn spawn_delegated_runtime(
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered,
|
||||
preflight,
|
||||
stamp,
|
||||
custom_name,
|
||||
..
|
||||
} = common;
|
||||
let (receiver, buffered) = preflight.into_session_events();
|
||||
let (start, started) = oneshot::channel();
|
||||
let loop_app = Arc::clone(&app);
|
||||
let loop_sink = Arc::clone(&sink);
|
||||
@@ -1584,12 +1271,12 @@ fn spawn_owner_runtime(
|
||||
sink,
|
||||
config,
|
||||
sync_state,
|
||||
receiver,
|
||||
buffered,
|
||||
preflight,
|
||||
stamp,
|
||||
volume_mode,
|
||||
..
|
||||
} = common;
|
||||
let (receiver, buffered) = preflight.into_session_events();
|
||||
let idle_retry_active = config.reconnect_idle_retry_ms > 0;
|
||||
let host: Arc<dyn SessionLoopHost> = Arc::new(DaemonSessionLoopHost {
|
||||
app: Arc::clone(&app),
|
||||
@@ -1643,7 +1330,7 @@ async fn run_delegated_loop(
|
||||
custom_name: Option<String>,
|
||||
quality: Quality,
|
||||
) {
|
||||
let mut disconnected = false;
|
||||
let mut reconnect_state = DelegatedRuntimeEventState::default();
|
||||
let mut rejoin_watchdog = DelegatedRejoinWatchdog::new();
|
||||
for event in buffered {
|
||||
if !handle_delegated_event(
|
||||
@@ -1659,7 +1346,7 @@ async fn run_delegated_loop(
|
||||
coordinator.as_ref(),
|
||||
custom_name.as_deref(),
|
||||
quality,
|
||||
&mut disconnected,
|
||||
&mut reconnect_state,
|
||||
&mut rejoin_watchdog,
|
||||
)
|
||||
.await
|
||||
@@ -1692,7 +1379,7 @@ async fn run_delegated_loop(
|
||||
coordinator.as_ref(),
|
||||
custom_name.as_deref(),
|
||||
quality,
|
||||
&mut disconnected,
|
||||
&mut reconnect_state,
|
||||
&mut rejoin_watchdog,
|
||||
)
|
||||
.await
|
||||
@@ -1716,15 +1403,14 @@ async fn handle_delegated_event(
|
||||
coordinator: Option<&DaemonDelegationCoordinator>,
|
||||
custom_name: Option<&str>,
|
||||
quality: Quality,
|
||||
disconnected: &mut bool,
|
||||
reconnect_state: &mut DelegatedRuntimeEventState,
|
||||
rejoin_watchdog: &mut DelegatedRejoinWatchdog,
|
||||
) -> bool {
|
||||
if !authority.is_current(stamp) {
|
||||
return false;
|
||||
}
|
||||
match &event {
|
||||
TransportEvent::Disconnected => {
|
||||
*disconnected = true;
|
||||
match reconnect_state.observe(&event) {
|
||||
DelegatedRuntimeEventDirective::Reconnecting => {
|
||||
rejoin_watchdog.cancel();
|
||||
update_lifecycle_state_if_running(
|
||||
inner,
|
||||
@@ -1736,7 +1422,7 @@ async fn handle_delegated_event(
|
||||
)
|
||||
.await;
|
||||
}
|
||||
TransportEvent::Subscribed if *disconnected => {
|
||||
DelegatedRuntimeEventDirective::Rejoin => {
|
||||
if send_delegated_join(app, session_id, true, custom_name, quality)
|
||||
.await
|
||||
.is_err()
|
||||
@@ -1744,15 +1430,12 @@ async fn handle_delegated_event(
|
||||
request_restore(coordinator, generation).await;
|
||||
return false;
|
||||
}
|
||||
rejoin_watchdog.arm(
|
||||
Arc::clone(authority),
|
||||
stamp,
|
||||
generation,
|
||||
coordinator.cloned(),
|
||||
);
|
||||
let coordinator = coordinator.cloned();
|
||||
rejoin_watchdog.arm(Arc::clone(authority), stamp, generation, move |generation| {
|
||||
async move { request_restore(coordinator.as_ref(), generation).await }
|
||||
});
|
||||
}
|
||||
TransportEvent::SessionEstablished => {
|
||||
*disconnected = false;
|
||||
DelegatedRuntimeEventDirective::Connected => {
|
||||
rejoin_watchdog.cancel();
|
||||
update_lifecycle_state_if_running(
|
||||
inner,
|
||||
@@ -1764,11 +1447,11 @@ async fn handle_delegated_event(
|
||||
)
|
||||
.await;
|
||||
}
|
||||
TransportEvent::CloudError { .. } | TransportEvent::MaxReconnectAttemptsExceeded { .. } => {
|
||||
DelegatedRuntimeEventDirective::RestoreOwner => {
|
||||
request_restore(coordinator, generation).await;
|
||||
return false;
|
||||
}
|
||||
_ => {}
|
||||
DelegatedRuntimeEventDirective::Forward => {}
|
||||
}
|
||||
if !authority.is_current(stamp) {
|
||||
return false;
|
||||
@@ -1790,44 +1473,3 @@ async fn request_restore(coordinator: Option<&DaemonDelegationCoordinator>, gene
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn quality_mapping_never_exceeds_the_configured_cap() {
|
||||
assert_eq!(quality_wire(Quality::Mp3), 1);
|
||||
assert_eq!(quality_wire(Quality::Lossless), 2);
|
||||
assert_eq!(quality_wire(Quality::HiRes), 3);
|
||||
assert_eq!(quality_wire(Quality::UltraHiRes), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_retains_only_events_needed_after_commit() {
|
||||
assert!(!should_retain(&TransportEvent::Authenticated));
|
||||
assert!(!should_retain(&TransportEvent::KeepalivePingSent));
|
||||
assert!(should_retain(&TransportEvent::Disconnected));
|
||||
assert!(should_retain(&TransportEvent::SessionEstablished));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_watchdog_generation_is_claimed_once() {
|
||||
let generation = RejoinWatchdogGeneration::default();
|
||||
let armed = generation.advance();
|
||||
|
||||
assert!(generation.claim(armed));
|
||||
assert!(!generation.claim(armed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_watchdog_ignores_cancelled_and_replaced_generations() {
|
||||
let generation = RejoinWatchdogGeneration::default();
|
||||
let cancelled = generation.advance();
|
||||
generation.advance();
|
||||
let replacement = generation.advance();
|
||||
|
||||
assert!(!generation.claim(cancelled));
|
||||
assert!(generation.claim(replacement));
|
||||
}
|
||||
}
|
||||
@@ -7,17 +7,17 @@
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::sync::{Arc, Mutex as StdMutex};
|
||||
use std::sync::Arc;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
use qbz_models::Quality;
|
||||
use qconnect_app::LanProjectionSlot;
|
||||
use qconnect_lan::{
|
||||
ConnectInfo, DeviceType, DisplayInfo, EndpointPolicy, HandoffCandidate, LanError,
|
||||
LanProjection, LanService, LanServiceConfig, MaxAudioQuality,
|
||||
};
|
||||
|
||||
use super::authority::{AuthorityCell, AuthorityOrigin, AuthorityStamp};
|
||||
use super::transport::default_qconnect_device_info;
|
||||
|
||||
const ADMISSION_WAIT: Duration = Duration::from_secs(60);
|
||||
@@ -27,174 +27,7 @@ const ADMISSION_THREAD_NAME: &str = "qbzd-qconnect-lan-admission";
|
||||
|
||||
pub type HandoffCallback = Arc<dyn Fn(HandoffCandidate) + Send + Sync + 'static>;
|
||||
|
||||
/// Stamp-aware bridge between runtime authority and the synchronous LAN
|
||||
/// projection read by the HTTP worker.
|
||||
///
|
||||
/// Every qbzd authority install/clear is serialized through this short-held
|
||||
/// mutex. An old runtime event can therefore never overwrite the session of a
|
||||
/// replacement runtime, and a prepared candidate is not exposed until the same
|
||||
/// critical section that installs its authority.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct DaemonLanProjectionSlot {
|
||||
inner: Arc<StdMutex<ProjectionSlotState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProjectionSlotState {
|
||||
projection: Option<LanProjection>,
|
||||
installed: Option<InstalledSessionProjection>,
|
||||
}
|
||||
|
||||
struct InstalledSessionProjection {
|
||||
stamp: AuthorityStamp,
|
||||
session_id: Option<String>,
|
||||
}
|
||||
|
||||
impl DaemonLanProjectionSlot {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, ProjectionSlotState> {
|
||||
self.inner.lock().unwrap_or_else(|poisoned| {
|
||||
log::error!("[QConnect LAN] projection slot recovered from a poisoned lock");
|
||||
let guard = poisoned.into_inner();
|
||||
self.inner.clear_poison();
|
||||
guard
|
||||
})
|
||||
}
|
||||
|
||||
fn write_projection(state: &ProjectionSlotState, session_id: Option<String>) {
|
||||
if let Some(projection) = state.projection.as_ref() {
|
||||
projection.set_current_session_id(session_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Install a runtime and its already-confirmed public session atomically
|
||||
/// with respect to every projection update. `session_id` is `None` for a
|
||||
/// fresh owner until its first cloud SESSION_STATE arrives.
|
||||
pub fn install_authority(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
session_id: Option<&str>,
|
||||
) -> bool {
|
||||
let mut state = self.lock();
|
||||
|
||||
// Fail closed during the tiny install boundary: the old session may no
|
||||
// longer be current, while exposing the candidate before install would
|
||||
// violate the handoff transaction.
|
||||
Self::write_projection(&state, None);
|
||||
if !authority.install(stamp) {
|
||||
let current = authority.current();
|
||||
let restore = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| Some(installed.stamp) == current)
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
if current != state.installed.as_ref().map(|installed| installed.stamp) {
|
||||
state.installed = None;
|
||||
}
|
||||
Self::write_projection(&state, restore);
|
||||
return false;
|
||||
}
|
||||
|
||||
let session_id = session_id.map(str::to_string);
|
||||
state.installed = Some(InstalledSessionProjection {
|
||||
stamp,
|
||||
session_id: session_id.clone(),
|
||||
});
|
||||
Self::write_projection(&state, session_id);
|
||||
true
|
||||
}
|
||||
|
||||
/// Publish a cloud-confirmed owner session from an event belonging to the
|
||||
/// exact installed runtime. Delegated session ids enter only through
|
||||
/// `install_authority` after their transactional commit.
|
||||
pub fn confirm_owner_session(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
session_id: &str,
|
||||
) -> bool {
|
||||
if stamp.origin() != AuthorityOrigin::Owner || session_id.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut state = self.lock();
|
||||
if !authority.is_current(stamp)
|
||||
|| state.installed.as_ref().map(|installed| installed.stamp) != Some(stamp)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let session_id = session_id.to_string();
|
||||
if let Some(installed) = state.installed.as_mut() {
|
||||
installed.session_id = Some(session_id.clone());
|
||||
}
|
||||
Self::write_projection(&state, Some(session_id));
|
||||
true
|
||||
}
|
||||
|
||||
/// Snapshot the exact installed session for listener construction. This
|
||||
/// seeds GET connect-info before the HTTP worker can accept its first call.
|
||||
pub fn current_session_id(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
expected: AuthorityStamp,
|
||||
) -> Option<String> {
|
||||
let state = self.lock();
|
||||
if !authority.is_current(expected) {
|
||||
return None;
|
||||
}
|
||||
state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| installed.stamp == expected)
|
||||
.and_then(|installed| installed.session_id.clone())
|
||||
}
|
||||
|
||||
pub fn attach(&self, authority: &AuthorityCell, projection: LanProjection) {
|
||||
let mut state = self.lock();
|
||||
let current = authority.current();
|
||||
let session_id = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| Some(installed.stamp) == current)
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
projection.set_current_session_id(session_id);
|
||||
state.projection = Some(projection);
|
||||
}
|
||||
|
||||
pub fn detach(&self) {
|
||||
self.lock().projection.take();
|
||||
}
|
||||
|
||||
pub fn clear_authority(&self, authority: &AuthorityCell) -> Option<AuthorityStamp> {
|
||||
let mut state = self.lock();
|
||||
Self::write_projection(&state, None);
|
||||
let previous = authority.clear();
|
||||
state.installed = None;
|
||||
previous
|
||||
}
|
||||
|
||||
pub fn clear_if_current(&self, authority: &AuthorityCell, expected: AuthorityStamp) -> bool {
|
||||
let mut state = self.lock();
|
||||
if !authority.is_current(expected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Self::write_projection(&state, None);
|
||||
if authority.clear_if_current(expected) {
|
||||
state.installed = None;
|
||||
true
|
||||
} else {
|
||||
let restore = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| authority.is_current(installed.stamp))
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
Self::write_projection(&state, restore);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) type DaemonLanProjectionSlot = LanProjectionSlot;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum DaemonLanError {
|
||||
@@ -452,75 +285,4 @@ mod tests {
|
||||
projection.set_current_session_id(None);
|
||||
assert_eq!(projection.connect_info().current_session_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamped_projection_publishes_only_installed_authority() {
|
||||
let authority = AuthorityCell::new();
|
||||
let slot = DaemonLanProjectionSlot::default();
|
||||
let projection = build_projection(
|
||||
&fixture_identity(),
|
||||
"app-id".to_string(),
|
||||
Quality::Lossless,
|
||||
None,
|
||||
);
|
||||
slot.attach(&authority, projection.clone());
|
||||
|
||||
let owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, owner, None));
|
||||
assert!(slot.confirm_owner_session(&authority, owner, "owner-session"));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session")
|
||||
);
|
||||
|
||||
// Merely reserving/preparing a guest cannot expose its candidate id.
|
||||
let guest = authority.reserve(AuthorityOrigin::Delegated { generation: 7 });
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session")
|
||||
);
|
||||
|
||||
assert!(slot.install_authority(&authority, guest, Some("guest-session")));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("guest-session")
|
||||
);
|
||||
|
||||
// A late event from the retired owner cannot overwrite the guest.
|
||||
assert!(!slot.confirm_owner_session(&authority, owner, "stale-owner-session"));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("guest-session")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_session_events_update_and_stale_clear_cannot_win() {
|
||||
let authority = AuthorityCell::new();
|
||||
let slot = DaemonLanProjectionSlot::default();
|
||||
let projection = build_projection(
|
||||
&fixture_identity(),
|
||||
"app-id".to_string(),
|
||||
Quality::Lossless,
|
||||
None,
|
||||
);
|
||||
slot.attach(&authority, projection.clone());
|
||||
|
||||
let first_owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, first_owner, None));
|
||||
assert!(slot.confirm_owner_session(&authority, first_owner, "owner-session-a"));
|
||||
assert!(slot.confirm_owner_session(&authority, first_owner, "owner-session-b"));
|
||||
assert_eq!(
|
||||
slot.current_session_id(&authority, first_owner).as_deref(),
|
||||
Some("owner-session-b")
|
||||
);
|
||||
|
||||
let next_owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, next_owner, Some("owner-session-c")));
|
||||
assert!(!slot.clear_if_current(&authority, first_owner));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session-c")
|
||||
);
|
||||
}
|
||||
}
|
||||
+53
-121
@@ -37,10 +37,11 @@ use std::time::Duration;
|
||||
use qbz_app::shell::AppRuntime;
|
||||
use qbz_models::CoreEvent;
|
||||
use qconnect_app::{
|
||||
compute_effective_startup, CredentialOrigin, DelegationCoordinator,
|
||||
compute_effective_startup, lan_callback_is_current, CredentialOrigin, DelegationCoordinator,
|
||||
DelegationCoordinatorConfig, DelegationErrorCode, DelegationHost, DelegationPhase,
|
||||
DelegationSnapshot, QconnectApp, QconnectAppEvent, QconnectEnableIntent, QconnectEnableToken,
|
||||
QconnectEventSink, QconnectLifecycleState, QconnectRemoteSyncState, SessionLoopHost,
|
||||
DelegationSnapshot, LanRuntimeLifecycle, QconnectApp, QconnectAppEvent, QconnectEnableIntent,
|
||||
QconnectEnableToken, QconnectEventSink, QconnectLifecycleState, QconnectRemoteSyncState,
|
||||
SessionLoopHost,
|
||||
};
|
||||
use qconnect_lan::EndpointPolicy;
|
||||
use qconnect_transport_ws::{NativeWsTransport, WsTransportConfig};
|
||||
@@ -61,25 +62,9 @@ use self::sink::{DaemonEventSink, DaemonQconnectApp};
|
||||
type Runtime = Arc<AppRuntime<DaemonAdapter>>;
|
||||
type SharedState = Arc<std::sync::Mutex<DaemonShared>>;
|
||||
|
||||
const QCONNECT_LAN_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const QCONNECT_LAN_START_CLEANUP_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const QCONNECT_COORDINATOR_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const QCONNECT_AUTHORITY_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
async fn shutdown_lan_runtime(mut runtime: DaemonLanRuntime) -> Result<(), String> {
|
||||
let mut shutdown = tokio::task::spawn_blocking(move || runtime.shutdown());
|
||||
match tokio::time::timeout(QCONNECT_LAN_SHUTDOWN_TIMEOUT, &mut shutdown).await {
|
||||
Ok(Ok(())) => Ok(()),
|
||||
Ok(Err(_)) => Err("qconnect-lan-shutdown-task-failed".to_string()),
|
||||
Err(_) => {
|
||||
// The detached blocking worker continues the idempotent shutdown;
|
||||
// the daemon slot and projection have already been withdrawn.
|
||||
drop(shutdown);
|
||||
Err("qconnect-lan-shutdown-timed-out".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The live QConnect runtime for one connected session (app + its config + the
|
||||
/// spawned event loop + the shared sync accumulator).
|
||||
pub(crate) struct DaemonQconnectRuntime {
|
||||
@@ -209,12 +194,7 @@ pub struct DaemonQconnectService {
|
||||
delegation_host: Arc<DaemonDelegationHost>,
|
||||
coordinator: DaemonDelegationCoordinator,
|
||||
lan: AsyncMutex<Option<DaemonLanRuntime>>,
|
||||
/// A cancelled blocking start remains physically live until its result is
|
||||
/// joined and any listener it created is shut down.
|
||||
lan_start_pending: Arc<AtomicBool>,
|
||||
/// Permanent fail-closed fence for a LAN worker whose physical teardown
|
||||
/// could not be confirmed.
|
||||
lan_teardown_unsafe: Arc<AtomicBool>,
|
||||
lan_lifecycle: LanRuntimeLifecycle<DaemonLanRuntime>,
|
||||
lifecycle_gate: AsyncMutex<()>,
|
||||
teardown_incomplete: AtomicBool,
|
||||
}
|
||||
@@ -284,7 +264,7 @@ impl DaemonQconnectService {
|
||||
stamp: AuthorityStamp,
|
||||
qws_endpoint: &str,
|
||||
) -> Result<(), String> {
|
||||
if self.lan_teardown_unsafe.load(Ordering::Acquire) {
|
||||
if !self.lan_lifecycle.teardown_safe() {
|
||||
return Err("qconnect-lan-physical-teardown-unsafe".to_string());
|
||||
}
|
||||
if !self.enable_intent.is_current(enable_token) {
|
||||
@@ -330,9 +310,14 @@ impl DaemonQconnectService {
|
||||
}
|
||||
let coordinator = self.coordinator.clone();
|
||||
let callback_intent = Arc::clone(&self.enable_intent);
|
||||
let callback_authority = Arc::clone(&self.authority);
|
||||
let runtime_handle = tokio::runtime::Handle::current();
|
||||
let callback = Arc::new(move |candidate| {
|
||||
if !callback_intent.is_current(enable_token) {
|
||||
if !lan_callback_is_current(
|
||||
callback_intent.as_ref(),
|
||||
callback_authority.as_ref(),
|
||||
stamp,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let result = runtime_handle.block_on(coordinator.admit(candidate));
|
||||
@@ -346,65 +331,26 @@ impl DaemonQconnectService {
|
||||
}
|
||||
});
|
||||
|
||||
if self.lan_start_pending.swap(true, Ordering::AcqRel) {
|
||||
return Err("qconnect-lan-start-already-pending".to_string());
|
||||
}
|
||||
let mut start_task = tokio::task::spawn_blocking(move || {
|
||||
DaemonLanRuntime::start(
|
||||
endpoint_policy,
|
||||
app_id,
|
||||
quality,
|
||||
Some(current_session_id),
|
||||
callback,
|
||||
let started = self
|
||||
.lan_lifecycle
|
||||
.start(
|
||||
move || {
|
||||
DaemonLanRuntime::start(
|
||||
endpoint_policy,
|
||||
app_id,
|
||||
quality,
|
||||
Some(current_session_id),
|
||||
callback,
|
||||
)
|
||||
},
|
||||
self.enable_intent.cancelled(enable_token),
|
||||
)
|
||||
});
|
||||
let start_result = tokio::select! {
|
||||
biased;
|
||||
_ = self.enable_intent.cancelled(enable_token) => {
|
||||
let pending = Arc::clone(&self.lan_start_pending);
|
||||
let unsafe_latch = Arc::clone(&self.lan_teardown_unsafe);
|
||||
tokio::spawn(async move {
|
||||
let cleanup_safe = match start_task.await {
|
||||
Ok(Ok(runtime)) => match shutdown_lan_runtime(runtime).await {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"[QConnect LAN] cancelled listener cleanup failed: {error}"
|
||||
);
|
||||
false
|
||||
}
|
||||
},
|
||||
Ok(Err(_)) => true,
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"[QConnect LAN] cancelled listener start worker failed: {error}"
|
||||
);
|
||||
false
|
||||
}
|
||||
};
|
||||
if !cleanup_safe {
|
||||
unsafe_latch.store(true, Ordering::Release);
|
||||
}
|
||||
pending.store(false, Ordering::Release);
|
||||
});
|
||||
return Err("qconnect-lan-disabled".to_string());
|
||||
}
|
||||
result = &mut start_task => result,
|
||||
};
|
||||
self.lan_start_pending.store(false, Ordering::Release);
|
||||
let started = match start_result {
|
||||
Ok(Ok(runtime)) => runtime,
|
||||
Ok(Err(_)) => return Err("qconnect-lan-bind-failed".to_string()),
|
||||
Err(_) => {
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
return Err("qconnect-lan-start-task-failed".to_string());
|
||||
}
|
||||
};
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
|
||||
if !self.enable_intent.is_current(enable_token) || !self.authority.is_current(stamp) {
|
||||
if let Err(error) = shutdown_lan_runtime(started).await {
|
||||
if let Err(error) = self.lan_lifecycle.shutdown(started).await {
|
||||
log::warn!("[QConnect LAN] stale listener teardown failed: {error}");
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
}
|
||||
return Err("qconnect-lan-owner-superseded".to_string());
|
||||
}
|
||||
@@ -431,9 +377,8 @@ impl DaemonQconnectService {
|
||||
}
|
||||
|
||||
if let Some(stale) = pending {
|
||||
if let Err(error) = shutdown_lan_runtime(stale).await {
|
||||
if let Err(error) = self.lan_lifecycle.shutdown(stale).await {
|
||||
log::warn!("[QConnect LAN] rejected listener teardown failed: {error}");
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
Err("qconnect-lan-disabled-or-owner-superseded".to_string())
|
||||
@@ -444,26 +389,15 @@ impl DaemonQconnectService {
|
||||
self.delegation_host.detach_projection();
|
||||
let runtime = self.lan.lock().await.take();
|
||||
if let Some(runtime) = runtime {
|
||||
if let Err(error) = shutdown_lan_runtime(runtime).await {
|
||||
self.lan_teardown_unsafe.store(true, Ordering::Release);
|
||||
return Err(error);
|
||||
}
|
||||
self.lan_lifecycle
|
||||
.shutdown(runtime)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
if self.lan_start_pending.load(Ordering::Acquire) {
|
||||
let settled = tokio::time::timeout(QCONNECT_LAN_START_CLEANUP_TIMEOUT, async {
|
||||
while self.lan_start_pending.load(Ordering::Acquire) {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
self.lan_lifecycle
|
||||
.settle()
|
||||
.await
|
||||
.is_ok();
|
||||
if !settled {
|
||||
return Err("qconnect-lan-start-cleanup-timed-out".to_string());
|
||||
}
|
||||
}
|
||||
if self.lan_teardown_unsafe.load(Ordering::Acquire) {
|
||||
return Err("qconnect-lan-physical-teardown-unsafe".to_string());
|
||||
}
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -606,7 +540,8 @@ impl DaemonQconnectService {
|
||||
if self.enable_intent.current_token().is_some() {
|
||||
return Err("qconnect-disable-superseded-by-enable".to_string());
|
||||
}
|
||||
self.disconnect_with_owner_policy_locked(restore_owner).await
|
||||
self.disconnect_with_owner_policy_locked(restore_owner)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn disconnect_with_owner_policy_locked(
|
||||
@@ -627,17 +562,13 @@ impl DaemonQconnectService {
|
||||
log::warn!("[QConnect] LAN teardown failed: {error}");
|
||||
false
|
||||
} else {
|
||||
!self.lan_start_pending.load(Ordering::Acquire)
|
||||
&& !self.lan_teardown_unsafe.load(Ordering::Acquire)
|
||||
!self.lan_lifecycle.start_pending() && self.lan_lifecycle.teardown_safe()
|
||||
};
|
||||
// A tracked restore from the previous authority transition owns the
|
||||
// same gate coordinator shutdown needs. Observe its bounded result
|
||||
// first so the shorter shutdown timeout cannot detach a late owner
|
||||
// runtime that starts after enabled intent was cleared.
|
||||
let prior_owner_restore = self
|
||||
.delegation_host
|
||||
.await_owner_playback_restore()
|
||||
.await;
|
||||
let prior_owner_restore = self.delegation_host.await_owner_playback_restore().await;
|
||||
self.delegation_host
|
||||
.set_shutdown_restore_owner(restore_owner);
|
||||
let coordinator_stopped = if tokio::time::timeout(
|
||||
@@ -676,10 +607,7 @@ impl DaemonQconnectService {
|
||||
true
|
||||
};
|
||||
|
||||
let shutdown_owner_restore = self
|
||||
.delegation_host
|
||||
.await_owner_playback_restore()
|
||||
.await;
|
||||
let shutdown_owner_restore = self.delegation_host.await_owner_playback_restore().await;
|
||||
let owner_restored = prior_owner_restore.is_ok()
|
||||
&& shutdown_owner_restore.is_ok()
|
||||
&& !self.delegation_host.owner_restore_pending();
|
||||
@@ -694,11 +622,11 @@ impl DaemonQconnectService {
|
||||
|
||||
if authority_safe {
|
||||
if let Ok(mut shared) = self.shared.lock() {
|
||||
shared.qconnect.state = "off".to_string();
|
||||
shared.qconnect.session_active = false;
|
||||
shared.qconnect.credential_origin = "owner".to_string();
|
||||
shared.qconnect.candidate_generation = None;
|
||||
shared.emit_qconnect_session_changed();
|
||||
shared.qconnect.state = "off".to_string();
|
||||
shared.qconnect.session_active = false;
|
||||
shared.qconnect.credential_origin = "owner".to_string();
|
||||
shared.qconnect.candidate_generation = None;
|
||||
shared.emit_qconnect_session_changed();
|
||||
}
|
||||
}
|
||||
let outcome = QconnectDisconnectOutcome {
|
||||
@@ -775,7 +703,10 @@ impl DaemonQconnectService {
|
||||
});
|
||||
|
||||
let config = match self
|
||||
.await_while_enabled(enable_token, transport::resolve_transport_config(&self.runtime))
|
||||
.await_while_enabled(
|
||||
enable_token,
|
||||
transport::resolve_transport_config(&self.runtime),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(config)) => config,
|
||||
@@ -1339,8 +1270,9 @@ pub fn start(
|
||||
delegation_host,
|
||||
coordinator,
|
||||
lan: AsyncMutex::new(None),
|
||||
lan_start_pending: Arc::new(AtomicBool::new(false)),
|
||||
lan_teardown_unsafe: Arc::new(AtomicBool::new(false)),
|
||||
lan_lifecycle: LanRuntimeLifecycle::new(|runtime: &mut DaemonLanRuntime| {
|
||||
runtime.shutdown()
|
||||
}),
|
||||
lifecycle_gate: AsyncMutex::new(()),
|
||||
teardown_incomplete: AtomicBool::new(false),
|
||||
});
|
||||
|
||||
@@ -602,7 +602,10 @@ fn normalize_opt_string(value: Option<String>) -> Option<String> {
|
||||
}
|
||||
|
||||
pub fn parse_subscribe_channels(items: Vec<String>) -> Result<Vec<Vec<u8>>, String> {
|
||||
items.into_iter().map(|item| decode_hex_channel(&item)).collect()
|
||||
items
|
||||
.into_iter()
|
||||
.map(|item| decode_hex_channel(&item))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn decode_hex_channel(raw: &str) -> Result<Vec<u8>, String> {
|
||||
@@ -657,10 +660,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn kv_helpers_round_trip_against_a_temp_daemon_db() {
|
||||
let tmp = std::env::temp_dir().join(format!(
|
||||
"qbzd_qconnect_kv_test_{}.db",
|
||||
std::process::id()
|
||||
));
|
||||
let tmp =
|
||||
std::env::temp_dir().join(format!("qbzd_qconnect_kv_test_{}.db", std::process::id()));
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
|
||||
// Unset -> defaults / None.
|
||||
|
||||
@@ -23,6 +23,7 @@ serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
zeroize = "1"
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Shared release ordering for QConnect authority transitions.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{oneshot, Mutex, OwnedMutexGuard};
|
||||
|
||||
use crate::{AuthorityCell, AuthorityStamp, DelegationErrorCode};
|
||||
|
||||
/// RAII fence that suspends owner actions until the transition releases it.
|
||||
pub struct OwnerActionFence {
|
||||
authority: Arc<AuthorityCell>,
|
||||
}
|
||||
|
||||
impl OwnerActionFence {
|
||||
pub fn acquire(authority: Arc<AuthorityCell>) -> Self {
|
||||
authority.suspend_owner_actions();
|
||||
Self { authority }
|
||||
}
|
||||
|
||||
/// Close admission, perform adapter-specific cancellation, then wait for
|
||||
/// all action permits admitted before the fence to drain.
|
||||
pub async fn acquire_drained(
|
||||
authority: Arc<AuthorityCell>,
|
||||
after_fence: impl FnOnce(),
|
||||
) -> Self {
|
||||
let fence = Self::acquire(authority);
|
||||
after_fence();
|
||||
fence.authority.wait_for_actions_drained().await;
|
||||
fence
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OwnerActionFence {
|
||||
fn drop(&mut self) {
|
||||
self.authority.resume_owner_actions();
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire the host transition lane before closing ordinary action admission,
|
||||
/// then revalidate the exact authority on both sides of the drain. This order
|
||||
/// is shared because a stale waiter must not briefly fence its replacement.
|
||||
pub async fn acquire_transition_guard_and_fence(
|
||||
transition_gate: Arc<Mutex<()>>,
|
||||
authority: Arc<AuthorityCell>,
|
||||
expected: AuthorityStamp,
|
||||
after_fence: impl FnOnce(),
|
||||
) -> Result<(OwnedMutexGuard<()>, OwnerActionFence), DelegationErrorCode> {
|
||||
let guard = transition_gate.lock_owned().await;
|
||||
if !authority.is_current(expected) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
let fence = OwnerActionFence::acquire_drained(Arc::clone(&authority), after_fence).await;
|
||||
if !authority.is_current(expected) {
|
||||
return Err(DelegationErrorCode::CandidateCancelled);
|
||||
}
|
||||
Ok((guard, fence))
|
||||
}
|
||||
|
||||
/// Cancellation-safe final release edge for an installed authority.
|
||||
///
|
||||
/// Admission always opens before the prepared loop wakes, and the transition
|
||||
/// lane unlocks last. `Drop` preserves the same order after cancellation.
|
||||
pub struct DeferredActivationRelease {
|
||||
start: Option<oneshot::Sender<()>>,
|
||||
transition_fence: Option<OwnerActionFence>,
|
||||
transition_guard: Option<OwnedMutexGuard<()>>,
|
||||
}
|
||||
|
||||
impl DeferredActivationRelease {
|
||||
pub fn new(
|
||||
start: Option<oneshot::Sender<()>>,
|
||||
transition_fence: Option<OwnerActionFence>,
|
||||
transition_guard: Option<OwnedMutexGuard<()>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
start,
|
||||
transition_fence,
|
||||
transition_guard,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wake_runtime(&mut self) {
|
||||
self.transition_fence.take();
|
||||
if let Some(start) = self.start.take() {
|
||||
let _ = start.send(());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unlock_transition(&mut self) {
|
||||
self.transition_guard.take();
|
||||
}
|
||||
|
||||
pub fn release(&mut self) {
|
||||
self.wake_runtime();
|
||||
self.unlock_transition();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DeferredActivationRelease {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use super::*;
|
||||
use crate::AuthorityOrigin;
|
||||
|
||||
#[tokio::test]
|
||||
async fn fence_closes_before_adapter_cancellation_and_waits_for_live_actions() {
|
||||
let authority = Arc::new(AuthorityCell::new());
|
||||
let permit = Arc::clone(&authority).try_owner_action_permit().unwrap();
|
||||
let cancellation_saw_closed = Arc::new(AtomicBool::new(false));
|
||||
let observed = Arc::clone(&cancellation_saw_closed);
|
||||
let task_authority = Arc::clone(&authority);
|
||||
let fence_task = tokio::spawn(async move {
|
||||
OwnerActionFence::acquire_drained(Arc::clone(&task_authority), || {
|
||||
observed.store(!task_authority.owner_actions_allowed(), Ordering::Release);
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
assert!(cancellation_saw_closed.load(Ordering::Acquire));
|
||||
assert!(!fence_task.is_finished());
|
||||
drop(permit);
|
||||
let fence = fence_task.await.unwrap();
|
||||
assert!(!authority.owner_actions_allowed());
|
||||
drop(fence);
|
||||
assert!(authority.owner_actions_allowed());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_wakes_only_after_owner_admission_reopens() {
|
||||
let authority = Arc::new(AuthorityCell::new());
|
||||
let fence = OwnerActionFence::acquire(Arc::clone(&authority));
|
||||
let (start, started) = oneshot::channel();
|
||||
let mut release = DeferredActivationRelease::new(Some(start), Some(fence), None);
|
||||
|
||||
release.wake_runtime();
|
||||
started.await.unwrap();
|
||||
assert!(authority.owner_actions_allowed());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transition_gate_precedes_fence_and_stale_waiter_never_closes_admission() {
|
||||
let authority = Arc::new(AuthorityCell::new());
|
||||
let stamp = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(authority.install(stamp));
|
||||
let gate = Arc::new(Mutex::new(()));
|
||||
let held_gate = Arc::clone(&gate).lock_owned().await;
|
||||
let task_gate = Arc::clone(&gate);
|
||||
let task_authority = Arc::clone(&authority);
|
||||
let task = tokio::spawn(async move {
|
||||
acquire_transition_guard_and_fence(task_gate, task_authority, stamp, || {}).await
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
assert!(authority.owner_actions_allowed());
|
||||
assert!(!task.is_finished());
|
||||
|
||||
drop(held_gate);
|
||||
let (guard, fence) = task.await.unwrap().unwrap();
|
||||
assert!(!authority.owner_actions_allowed());
|
||||
drop(fence);
|
||||
drop(guard);
|
||||
assert!(authority.owner_actions_allowed());
|
||||
|
||||
let stale = stamp;
|
||||
let replacement = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(authority.install(replacement));
|
||||
let callback_ran = Arc::new(AtomicBool::new(false));
|
||||
let callback_observer = Arc::clone(&callback_ran);
|
||||
assert!(matches!(
|
||||
acquire_transition_guard_and_fence(gate, Arc::clone(&authority), stale, move || {
|
||||
callback_observer.store(true, Ordering::Release)
|
||||
},)
|
||||
.await,
|
||||
Err(DelegationErrorCode::CandidateCancelled)
|
||||
));
|
||||
assert!(!callback_ran.load(Ordering::Acquire));
|
||||
assert!(authority.owner_actions_allowed());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
//! Shared reconnect watchdog for an installed delegated QConnect runtime.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use qconnect_transport_ws::TransportEvent;
|
||||
|
||||
use crate::{AuthorityCell, AuthorityOrigin, AuthorityStamp};
|
||||
|
||||
const DELEGATED_REJOIN_SESSION_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DelegatedRuntimeEventDirective {
|
||||
Forward,
|
||||
Reconnecting,
|
||||
Rejoin,
|
||||
Connected,
|
||||
RestoreOwner,
|
||||
}
|
||||
|
||||
/// Minimal shared reconnect reducer. Adapters execute their concrete lifecycle
|
||||
/// projection and report I/O, then forward non-fatal events to their app.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DelegatedRuntimeEventState {
|
||||
disconnected: bool,
|
||||
}
|
||||
|
||||
impl DelegatedRuntimeEventState {
|
||||
pub fn observe(&mut self, event: &TransportEvent) -> DelegatedRuntimeEventDirective {
|
||||
match event {
|
||||
TransportEvent::Disconnected => {
|
||||
self.disconnected = true;
|
||||
DelegatedRuntimeEventDirective::Reconnecting
|
||||
}
|
||||
TransportEvent::Subscribed if self.disconnected => {
|
||||
DelegatedRuntimeEventDirective::Rejoin
|
||||
}
|
||||
TransportEvent::SessionEstablished => {
|
||||
self.disconnected = false;
|
||||
DelegatedRuntimeEventDirective::Connected
|
||||
}
|
||||
TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. } => {
|
||||
DelegatedRuntimeEventDirective::RestoreOwner
|
||||
}
|
||||
_ => DelegatedRuntimeEventDirective::Forward,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RejoinWatchdogGeneration(AtomicU64);
|
||||
|
||||
impl RejoinWatchdogGeneration {
|
||||
fn advance(&self) -> u64 {
|
||||
self.0.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
|
||||
}
|
||||
|
||||
fn claim(&self, expected: u64) -> bool {
|
||||
self.0
|
||||
.compare_exchange(
|
||||
expected,
|
||||
expected.wrapping_add(1),
|
||||
Ordering::AcqRel,
|
||||
Ordering::Acquire,
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores owner authority if a delegated runtime fails to re-establish its
|
||||
/// session within the official receiver budget. Re-arm, cancellation, runtime
|
||||
/// replacement and drop all invalidate the prior deadline before aborting it.
|
||||
pub struct DelegatedRejoinWatchdog {
|
||||
generation: Arc<RejoinWatchdogGeneration>,
|
||||
task: Option<tokio::task::JoinHandle<()>>,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl DelegatedRejoinWatchdog {
|
||||
pub fn new() -> Self {
|
||||
Self::with_timeout(DELEGATED_REJOIN_SESSION_TIMEOUT)
|
||||
}
|
||||
|
||||
fn with_timeout(timeout: Duration) -> Self {
|
||||
Self {
|
||||
generation: Arc::new(RejoinWatchdogGeneration::default()),
|
||||
task: None,
|
||||
timeout,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn arm<F, Fut>(
|
||||
&mut self,
|
||||
authority: Arc<AuthorityCell>,
|
||||
stamp: AuthorityStamp,
|
||||
delegation_generation: u64,
|
||||
restore: F,
|
||||
) where
|
||||
F: FnOnce(u64) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
// Advance before aborting so even a task already waking at the
|
||||
// deadline loses its compare-exchange against this newer rejoin.
|
||||
let watchdog_generation = self.generation.advance();
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
let generation = Arc::clone(&self.generation);
|
||||
let timeout = self.timeout;
|
||||
self.task = Some(tokio::spawn(async move {
|
||||
tokio::time::sleep(timeout).await;
|
||||
if !generation.claim(watchdog_generation)
|
||||
|| stamp.origin()
|
||||
!= (AuthorityOrigin::Delegated {
|
||||
generation: delegation_generation,
|
||||
})
|
||||
|| !authority.is_current(stamp)
|
||||
{
|
||||
return;
|
||||
}
|
||||
restore(delegation_generation).await;
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn cancel(&mut self) {
|
||||
// Invalidate first: abort is cooperative and may race a waking task.
|
||||
self.generation.advance();
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DelegatedRejoinWatchdog {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DelegatedRejoinWatchdog {
|
||||
fn drop(&mut self) {
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn runtime_event_state_rejoins_only_after_disconnect_and_fails_closed_on_fatal() {
|
||||
let mut state = DelegatedRuntimeEventState::default();
|
||||
assert_eq!(
|
||||
state.observe(&TransportEvent::Subscribed),
|
||||
DelegatedRuntimeEventDirective::Forward
|
||||
);
|
||||
assert_eq!(
|
||||
state.observe(&TransportEvent::Disconnected),
|
||||
DelegatedRuntimeEventDirective::Reconnecting
|
||||
);
|
||||
assert_eq!(
|
||||
state.observe(&TransportEvent::Subscribed),
|
||||
DelegatedRuntimeEventDirective::Rejoin
|
||||
);
|
||||
assert_eq!(
|
||||
state.observe(&TransportEvent::SessionEstablished),
|
||||
DelegatedRuntimeEventDirective::Connected
|
||||
);
|
||||
assert_eq!(
|
||||
state.observe(&TransportEvent::Subscribed),
|
||||
DelegatedRuntimeEventDirective::Forward
|
||||
);
|
||||
assert_eq!(
|
||||
state.observe(&TransportEvent::MaxReconnectAttemptsExceeded {
|
||||
attempts: 3,
|
||||
last_reason: "sanitized".to_string(),
|
||||
}),
|
||||
DelegatedRuntimeEventDirective::RestoreOwner
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_is_claimed_once_and_replacement_invalidates_prior_arm() {
|
||||
let generation = RejoinWatchdogGeneration::default();
|
||||
let first = generation.advance();
|
||||
assert!(generation.claim(first));
|
||||
assert!(!generation.claim(first));
|
||||
|
||||
let cancelled = generation.advance();
|
||||
generation.advance();
|
||||
let replacement = generation.advance();
|
||||
assert!(!generation.claim(cancelled));
|
||||
assert!(generation.claim(replacement));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn fires_once_only_for_the_exact_installed_delegation() {
|
||||
let authority = Arc::new(AuthorityCell::new());
|
||||
let stamp = authority.reserve(AuthorityOrigin::Delegated { generation: 7 });
|
||||
assert!(authority.install(stamp));
|
||||
let restores = Arc::new(AtomicUsize::new(0));
|
||||
let observed = Arc::clone(&restores);
|
||||
let mut watchdog = DelegatedRejoinWatchdog::with_timeout(Duration::from_secs(1));
|
||||
watchdog.arm(Arc::clone(&authority), stamp, 7, move |_| async move {
|
||||
observed.fetch_add(1, Ordering::AcqRel);
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(restores.load(Ordering::Acquire), 1);
|
||||
|
||||
let stale_observed = Arc::clone(&restores);
|
||||
watchdog.arm(Arc::clone(&authority), stamp, 7, move |_| async move {
|
||||
stale_observed.fetch_add(1, Ordering::AcqRel);
|
||||
});
|
||||
let replacement = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(authority.install(replacement));
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(restores.load(Ordering::Acquire), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cancel_invalidates_a_ready_deadline_before_aborting() {
|
||||
let authority = Arc::new(AuthorityCell::new());
|
||||
let stamp = authority.reserve(AuthorityOrigin::Delegated { generation: 9 });
|
||||
assert!(authority.install(stamp));
|
||||
let restores = Arc::new(AtomicUsize::new(0));
|
||||
let observed = Arc::clone(&restores);
|
||||
let mut watchdog = DelegatedRejoinWatchdog::with_timeout(Duration::from_secs(1));
|
||||
watchdog.arm(authority, stamp, 9, move |_| async move {
|
||||
observed.fetch_add(1, Ordering::AcqRel);
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
watchdog.cancel();
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(restores.load(Ordering::Acquire), 0);
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,11 @@ pub struct DelegationCancellation {
|
||||
}
|
||||
|
||||
impl DelegationCancellation {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_receiver(receiver: watch::Receiver<bool>) -> Self {
|
||||
Self { receiver }
|
||||
}
|
||||
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
*self.receiver.borrow()
|
||||
}
|
||||
@@ -1120,11 +1125,9 @@ fn recover_std_lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_,
|
||||
/// nominal two-second shutdown budget into two seconds per generation.
|
||||
async fn await_all_or_abort(tasks: Vec<JoinHandle<()>>, timeout: Duration) {
|
||||
let mut tasks = tasks.into_iter().collect::<FuturesUnordered<_>>();
|
||||
let timed_out = tokio::time::timeout(timeout, async {
|
||||
while tasks.next().await.is_some() {}
|
||||
})
|
||||
.await
|
||||
.is_err();
|
||||
let timed_out = tokio::time::timeout(timeout, async { while tasks.next().await.is_some() {} })
|
||||
.await
|
||||
.is_err();
|
||||
if !timed_out {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
//! Shared QWS preflight state machine used by every QBZ runtime adapter.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use qconnect_protocol::RendererCommandType;
|
||||
use qconnect_transport_ws::TransportEvent;
|
||||
use tokio::sync::broadcast;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{DelegationCancellation, DelegationErrorCode};
|
||||
|
||||
const PREFLIGHT_BUFFER_EVENTS: usize = 256;
|
||||
const PREFLIGHT_BUFFER_BYTES: usize = 256 * 1024;
|
||||
|
||||
/// Owns the pre-commit receiver and the bounded replay buffer accumulated
|
||||
/// while a candidate proves QWS readiness and session acceptance.
|
||||
pub struct DelegationPreflight {
|
||||
receiver: broadcast::Receiver<TransportEvent>,
|
||||
buffered: VecDeque<TransportEvent>,
|
||||
buffered_bytes: usize,
|
||||
confirmed_owner_session_id: Option<Zeroizing<String>>,
|
||||
}
|
||||
|
||||
impl DelegationPreflight {
|
||||
pub fn new(receiver: broadcast::Receiver<TransportEvent>) -> Self {
|
||||
Self {
|
||||
receiver,
|
||||
buffered: VecDeque::new(),
|
||||
buffered_bytes: 0,
|
||||
confirmed_owner_session_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn confirmed_owner_session_id(&self) -> Option<&str> {
|
||||
self.confirmed_owner_session_id
|
||||
.as_deref()
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
/// Transfer the live receiver and replay-worthy events into the installed
|
||||
/// runtime after the authority commit succeeds.
|
||||
pub fn into_session_events(
|
||||
self,
|
||||
) -> (
|
||||
broadcast::Receiver<TransportEvent>,
|
||||
VecDeque<TransportEvent>,
|
||||
) {
|
||||
(self.receiver, self.buffered)
|
||||
}
|
||||
|
||||
pub async fn wait_for_qws_ready(
|
||||
&mut self,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut authenticated = false;
|
||||
let mut subscribed = false;
|
||||
while !(authenticated && subscribed) {
|
||||
let event = self.next_event(cancellation.clone()).await?;
|
||||
match &event {
|
||||
TransportEvent::Authenticated => authenticated = true,
|
||||
TransportEvent::Subscribed => subscribed = true,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. } => {
|
||||
return Err(DelegationErrorCode::QwsRejected)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.retain(event)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn wait_for_activation(
|
||||
&mut self,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
loop {
|
||||
let event = self.next_event(cancellation.clone()).await?;
|
||||
let accepted = matches!(
|
||||
&event,
|
||||
TransportEvent::InboundRendererServerCommand(command)
|
||||
if command.command_type == RendererCommandType::SrvrRndrSetActive
|
||||
&& command.payload.get("active").and_then(serde_json::Value::as_bool)
|
||||
== Some(true)
|
||||
);
|
||||
if matches!(
|
||||
&event,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. }
|
||||
) {
|
||||
return Err(DelegationErrorCode::ActivationRejected);
|
||||
}
|
||||
self.retain(event)?;
|
||||
if accepted {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owner preparation completes only after the cloud emits both the
|
||||
/// controller session id and the establishment proof used by live loops.
|
||||
pub async fn wait_for_owner_session(
|
||||
&mut self,
|
||||
cancellation: DelegationCancellation,
|
||||
) -> Result<(), DelegationErrorCode> {
|
||||
let mut established = false;
|
||||
loop {
|
||||
let event = self.next_event(cancellation.clone()).await?;
|
||||
if let Some(session_id) = owner_session_id_from_event(&event).map(str::to_string) {
|
||||
self.confirmed_owner_session_id = Some(Zeroizing::new(session_id));
|
||||
}
|
||||
established |= matches!(&event, TransportEvent::SessionEstablished);
|
||||
if matches!(
|
||||
&event,
|
||||
TransportEvent::Disconnected
|
||||
| TransportEvent::CloudError { .. }
|
||||
| TransportEvent::MaxReconnectAttemptsExceeded { .. }
|
||||
) {
|
||||
return Err(DelegationErrorCode::OwnerRestoreFailed);
|
||||
}
|
||||
self.retain(event)?;
|
||||
if established && self.confirmed_owner_session_id.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn next_event(
|
||||
&mut self,
|
||||
mut cancellation: DelegationCancellation,
|
||||
) -> Result<TransportEvent, DelegationErrorCode> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => Err(DelegationErrorCode::CandidateCancelled),
|
||||
event = self.receiver.recv() => match event {
|
||||
Ok(event) => Ok(event),
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => Err(DelegationErrorCode::Internal),
|
||||
Err(broadcast::error::RecvError::Closed) => Err(DelegationErrorCode::QwsRejected),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn retain(&mut self, event: TransportEvent) -> Result<(), DelegationErrorCode> {
|
||||
if !should_retain(&event) {
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = retained_event_bytes(&event);
|
||||
if self.buffered.len() >= PREFLIGHT_BUFFER_EVENTS
|
||||
|| self.buffered_bytes.saturating_add(bytes) > PREFLIGHT_BUFFER_BYTES
|
||||
{
|
||||
return Err(DelegationErrorCode::Internal);
|
||||
}
|
||||
self.buffered_bytes = self.buffered_bytes.saturating_add(bytes);
|
||||
self.buffered.push_back(event);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn retained_event_bytes(event: &TransportEvent) -> usize {
|
||||
match event {
|
||||
TransportEvent::InboundPayloadBytes { payload, .. } => payload.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn should_retain(event: &TransportEvent) -> bool {
|
||||
matches!(
|
||||
event,
|
||||
TransportEvent::Connected
|
||||
| TransportEvent::Disconnected
|
||||
| TransportEvent::SessionEstablished
|
||||
| TransportEvent::InboundPayloadBytes { .. }
|
||||
| TransportEvent::InboundQueueServerEvent(_)
|
||||
| TransportEvent::InboundRendererServerCommand(_)
|
||||
| TransportEvent::InboundReceived(_)
|
||||
)
|
||||
}
|
||||
|
||||
fn owner_session_id_from_event(event: &TransportEvent) -> Option<&str> {
|
||||
match event {
|
||||
TransportEvent::InboundQueueServerEvent(event)
|
||||
if event.message_type() == "MESSAGE_TYPE_SRVR_CTRL_SESSION_STATE" =>
|
||||
{
|
||||
event
|
||||
.payload
|
||||
.get("session_uuid")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|session_id| !session_id.is_empty())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use qconnect_protocol::{
|
||||
QueueEventType, QueueServerEvent, RendererCommandType, RendererServerCommand,
|
||||
};
|
||||
use tokio::sync::watch;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn cancellation(cancelled: bool) -> (watch::Sender<bool>, DelegationCancellation) {
|
||||
let (sender, receiver) = watch::channel(cancelled);
|
||||
(sender, DelegationCancellation::from_receiver(receiver))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readiness_accepts_either_order_and_replays_only_runtime_events() {
|
||||
let (sender, receiver) = broadcast::channel(8);
|
||||
let mut preflight = DelegationPreflight::new(receiver);
|
||||
sender.send(TransportEvent::Subscribed).unwrap();
|
||||
sender.send(TransportEvent::Connected).unwrap();
|
||||
sender.send(TransportEvent::Authenticated).unwrap();
|
||||
|
||||
let (_cancel_guard, cancellation) = cancellation(false);
|
||||
preflight.wait_for_qws_ready(cancellation).await.unwrap();
|
||||
let (_, buffered) = preflight.into_session_events();
|
||||
assert!(matches!(buffered.front(), Some(TransportEvent::Connected)));
|
||||
assert_eq!(buffered.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn activation_requires_active_true_and_retains_commands_in_order() {
|
||||
let (sender, receiver) = broadcast::channel(8);
|
||||
let mut preflight = DelegationPreflight::new(receiver);
|
||||
for active in [false, true] {
|
||||
sender
|
||||
.send(TransportEvent::InboundRendererServerCommand(
|
||||
RendererServerCommand {
|
||||
command_type: RendererCommandType::SrvrRndrSetActive,
|
||||
payload: serde_json::json!({ "active": active }),
|
||||
},
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let (_cancel_guard, cancellation) = cancellation(false);
|
||||
preflight.wait_for_activation(cancellation).await.unwrap();
|
||||
let (_, buffered) = preflight.into_session_events();
|
||||
assert_eq!(buffered.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owner_requires_session_state_and_establishment_in_any_order() {
|
||||
let (sender, receiver) = broadcast::channel(8);
|
||||
let mut preflight = DelegationPreflight::new(receiver);
|
||||
sender.send(TransportEvent::SessionEstablished).unwrap();
|
||||
sender
|
||||
.send(TransportEvent::InboundQueueServerEvent(QueueServerEvent {
|
||||
event_type: QueueEventType::SrvrCtrlSessionState,
|
||||
action_uuid: None,
|
||||
queue_version: None,
|
||||
payload: serde_json::json!({ "session_uuid": "owner-session" }),
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let (_cancel_guard, cancellation) = cancellation(false);
|
||||
preflight
|
||||
.wait_for_owner_session(cancellation)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
preflight.confirmed_owner_session_id(),
|
||||
Some("owner-session")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_wins_without_waiting_for_transport() {
|
||||
let (_sender, receiver) = broadcast::channel(1);
|
||||
let mut preflight = DelegationPreflight::new(receiver);
|
||||
let (_cancel_guard, cancellation) = cancellation(true);
|
||||
assert_eq!(
|
||||
preflight.wait_for_qws_ready(cancellation).await,
|
||||
Err(DelegationErrorCode::CandidateCancelled)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_wins_when_a_transport_event_is_already_ready() {
|
||||
let (sender, receiver) = broadcast::channel(1);
|
||||
let mut preflight = DelegationPreflight::new(receiver);
|
||||
sender.send(TransportEvent::Authenticated).unwrap();
|
||||
let (_cancel_guard, cancellation) = cancellation(true);
|
||||
|
||||
assert_eq!(
|
||||
preflight.wait_for_qws_ready(cancellation).await,
|
||||
Err(DelegationErrorCode::CandidateCancelled)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_buffer_is_bounded_by_count_and_payload_bytes() {
|
||||
let (_sender, receiver) = broadcast::channel(1);
|
||||
let mut preflight = DelegationPreflight::new(receiver);
|
||||
for _ in 0..PREFLIGHT_BUFFER_EVENTS {
|
||||
preflight.retain(TransportEvent::Connected).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
preflight.retain(TransportEvent::Connected),
|
||||
Err(DelegationErrorCode::Internal)
|
||||
);
|
||||
|
||||
let (_sender, receiver) = broadcast::channel(1);
|
||||
let mut preflight = DelegationPreflight::new(receiver);
|
||||
assert_eq!(
|
||||
preflight.retain(TransportEvent::InboundPayloadBytes {
|
||||
cloud_message_type: 6,
|
||||
payload: vec![0; PREFLIGHT_BUFFER_BYTES + 1],
|
||||
}),
|
||||
Err(DelegationErrorCode::Internal)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -48,13 +48,19 @@ pub enum QconnectAppEvent {
|
||||
payload: Value,
|
||||
},
|
||||
/// Active peer renderer went silent >=12s while PLAYING (liveness watchdog).
|
||||
RendererUnreachable { renderer_id: i32 },
|
||||
RendererUnreachable {
|
||||
renderer_id: i32,
|
||||
},
|
||||
/// Active peer renderer left gracefully (status == ACTIVE_DISCONNECTED).
|
||||
RendererDisconnected { renderer_id: i32 },
|
||||
RendererDisconnected {
|
||||
renderer_id: i32,
|
||||
},
|
||||
/// Post-reconnect resync has been issued (safe-to-replay advisory).
|
||||
ResyncComplete,
|
||||
/// Granular connection lifecycle changed (Connecting/Reconnecting/Connected/Exhausted/Off).
|
||||
LifecycleChanged { state: QconnectLifecycleState },
|
||||
LifecycleChanged {
|
||||
state: QconnectLifecycleState,
|
||||
},
|
||||
/// Pass-through diagnostic (inbound-event preview, cloud error, max-reconnect, ...).
|
||||
/// `channel` is the legacy Tauri channel suffix so the mapper is mechanical.
|
||||
Diagnostic {
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Shared, stamp-aware projection of QConnect authority into the LAN wire.
|
||||
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
use qconnect_lan::LanProjection;
|
||||
|
||||
use crate::{AuthorityCell, AuthorityOrigin, AuthorityStamp};
|
||||
|
||||
/// Serializes runtime authority changes with the synchronous LAN projection.
|
||||
///
|
||||
/// A stale runtime can therefore neither overwrite the public session of its
|
||||
/// replacement nor clear that replacement after an asynchronous task returns.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct LanProjectionSlot {
|
||||
inner: Arc<Mutex<ProjectionSlotState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProjectionSlotState {
|
||||
projection: Option<LanProjection>,
|
||||
installed: Option<InstalledSessionProjection>,
|
||||
}
|
||||
|
||||
struct InstalledSessionProjection {
|
||||
stamp: AuthorityStamp,
|
||||
session_id: Option<String>,
|
||||
}
|
||||
|
||||
impl LanProjectionSlot {
|
||||
fn lock(&self) -> MutexGuard<'_, ProjectionSlotState> {
|
||||
self.inner.lock().unwrap_or_else(|poisoned| {
|
||||
log::error!("[QConnect LAN] projection slot recovered from a poisoned lock");
|
||||
let guard = poisoned.into_inner();
|
||||
self.inner.clear_poison();
|
||||
guard
|
||||
})
|
||||
}
|
||||
|
||||
fn write_projection(state: &ProjectionSlotState, session_id: Option<String>) {
|
||||
if let Some(projection) = state.projection.as_ref() {
|
||||
projection.set_current_session_id(session_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Install a runtime and its already-confirmed public session atomically.
|
||||
/// `session_id` is `None` for an owner awaiting its first SESSION_STATE.
|
||||
pub fn install_authority(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
session_id: Option<&str>,
|
||||
) -> bool {
|
||||
let mut state = self.lock();
|
||||
|
||||
// Fail closed during the tiny install boundary: the old session may no
|
||||
// longer be current, while exposing the candidate before install would
|
||||
// violate the handoff transaction.
|
||||
Self::write_projection(&state, None);
|
||||
if !authority.install(stamp) {
|
||||
let current = authority.current();
|
||||
let restore = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| Some(installed.stamp) == current)
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
if current != state.installed.as_ref().map(|installed| installed.stamp) {
|
||||
state.installed = None;
|
||||
}
|
||||
Self::write_projection(&state, restore);
|
||||
return false;
|
||||
}
|
||||
|
||||
let session_id = session_id.map(str::to_string);
|
||||
state.installed = Some(InstalledSessionProjection {
|
||||
stamp,
|
||||
session_id: session_id.clone(),
|
||||
});
|
||||
Self::write_projection(&state, session_id);
|
||||
true
|
||||
}
|
||||
|
||||
/// Publish a cloud-confirmed owner session from the exact installed
|
||||
/// runtime. Delegated session ids enter only through `install_authority`.
|
||||
pub fn confirm_owner_session(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
session_id: &str,
|
||||
) -> bool {
|
||||
if stamp.origin() != AuthorityOrigin::Owner || session_id.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut state = self.lock();
|
||||
if !authority.is_current(stamp)
|
||||
|| state.installed.as_ref().map(|installed| installed.stamp) != Some(stamp)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let session_id = session_id.to_string();
|
||||
if let Some(installed) = state.installed.as_mut() {
|
||||
installed.session_id = Some(session_id.clone());
|
||||
}
|
||||
Self::write_projection(&state, Some(session_id));
|
||||
true
|
||||
}
|
||||
|
||||
/// Snapshot the installed session for listener construction.
|
||||
pub fn current_session_id(
|
||||
&self,
|
||||
authority: &AuthorityCell,
|
||||
expected: AuthorityStamp,
|
||||
) -> Option<String> {
|
||||
let state = self.lock();
|
||||
if !authority.is_current(expected) {
|
||||
return None;
|
||||
}
|
||||
state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| installed.stamp == expected)
|
||||
.and_then(|installed| installed.session_id.clone())
|
||||
}
|
||||
|
||||
pub fn attach(&self, authority: &AuthorityCell, projection: LanProjection) {
|
||||
let mut state = self.lock();
|
||||
let current = authority.current();
|
||||
let session_id = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| Some(installed.stamp) == current)
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
projection.set_current_session_id(session_id);
|
||||
state.projection = Some(projection);
|
||||
}
|
||||
|
||||
pub fn detach(&self) {
|
||||
self.lock().projection.take();
|
||||
}
|
||||
|
||||
pub fn clear_authority(&self, authority: &AuthorityCell) -> Option<AuthorityStamp> {
|
||||
let mut state = self.lock();
|
||||
Self::write_projection(&state, None);
|
||||
let previous = authority.clear();
|
||||
state.installed = None;
|
||||
previous
|
||||
}
|
||||
|
||||
pub fn clear_if_current(&self, authority: &AuthorityCell, expected: AuthorityStamp) -> bool {
|
||||
let mut state = self.lock();
|
||||
if !authority.is_current(expected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Self::write_projection(&state, None);
|
||||
if authority.clear_if_current(expected) {
|
||||
state.installed = None;
|
||||
true
|
||||
} else {
|
||||
let restore = state
|
||||
.installed
|
||||
.as_ref()
|
||||
.filter(|installed| authority.is_current(installed.stamp))
|
||||
.and_then(|installed| installed.session_id.clone());
|
||||
Self::write_projection(&state, restore);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use qconnect_lan::{ConnectInfo, DeviceType, DisplayInfo, LanProjection, MaxAudioQuality};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn projection() -> LanProjection {
|
||||
LanProjection::new(
|
||||
DisplayInfo {
|
||||
friendly_name: "QBZ".to_string(),
|
||||
serial_number: "device-id".to_string(),
|
||||
brand_display_name: "QBZ".to_string(),
|
||||
model_display_name: "QBZ Desktop".to_string(),
|
||||
max_audio_quality: MaxAudioQuality::UpToCd,
|
||||
device_type: DeviceType::Computer,
|
||||
software_version: "qbz/test".to_string(),
|
||||
},
|
||||
ConnectInfo {
|
||||
app_id: "app-id".to_string(),
|
||||
current_session_id: None,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishes_only_the_exact_installed_authority() {
|
||||
let authority = AuthorityCell::new();
|
||||
let slot = LanProjectionSlot::default();
|
||||
let projection = projection();
|
||||
slot.attach(&authority, projection.clone());
|
||||
|
||||
let owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, owner, None));
|
||||
assert!(slot.confirm_owner_session(&authority, owner, "owner-session"));
|
||||
|
||||
let guest = authority.reserve(AuthorityOrigin::Delegated { generation: 7 });
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session")
|
||||
);
|
||||
assert!(slot.install_authority(&authority, guest, Some("guest-session")));
|
||||
|
||||
assert!(!slot.confirm_owner_session(&authority, owner, "stale-owner"));
|
||||
assert!(!slot.confirm_owner_session(&authority, guest, "guest-event"));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("guest-session")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_install_and_clear_preserve_the_replacement_projection() {
|
||||
let authority = AuthorityCell::new();
|
||||
let slot = LanProjectionSlot::default();
|
||||
let projection = projection();
|
||||
slot.attach(&authority, projection.clone());
|
||||
|
||||
let first = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, first, Some("first")));
|
||||
let replacement = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, replacement, Some("replacement")));
|
||||
|
||||
assert!(!slot.install_authority(&authority, first, Some("stale")));
|
||||
assert!(!slot.clear_if_current(&authority, first));
|
||||
assert_eq!(
|
||||
slot.current_session_id(&authority, replacement).as_deref(),
|
||||
Some("replacement")
|
||||
);
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("replacement")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_seeds_current_session_and_detach_stops_projection_writes() {
|
||||
let authority = AuthorityCell::new();
|
||||
let slot = LanProjectionSlot::default();
|
||||
let owner = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(slot.install_authority(&authority, owner, Some("owner-session")));
|
||||
|
||||
let projection = projection();
|
||||
slot.attach(&authority, projection.clone());
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session")
|
||||
);
|
||||
|
||||
slot.detach();
|
||||
assert_eq!(slot.clear_authority(&authority), Some(owner));
|
||||
assert_eq!(
|
||||
projection.connect_info().current_session_id.as_deref(),
|
||||
Some("owner-session")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Shared physical lifecycle for the blocking QConnect LAN receiver adapters.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::{AuthorityCell, AuthorityStamp, QconnectEnableIntent};
|
||||
|
||||
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const START_CLEANUP_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// A listener outlives the one-shot enable epoch that created it, but never
|
||||
/// the current enabled intent or the exact authority runtime it projects.
|
||||
pub fn lan_callback_is_current(
|
||||
enable_intent: &QconnectEnableIntent,
|
||||
authority: &AuthorityCell,
|
||||
stamp: AuthorityStamp,
|
||||
) -> bool {
|
||||
enable_intent.current_token().is_some() && authority.is_current(stamp)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum LanRuntimeError {
|
||||
#[error("qconnect-lan-physical-teardown-unsafe")]
|
||||
PhysicalTeardownUnsafe,
|
||||
#[error("qconnect-lan-start-already-pending")]
|
||||
StartAlreadyPending,
|
||||
#[error("qconnect-lan-disabled")]
|
||||
Cancelled,
|
||||
#[error("qconnect-lan-bind-failed")]
|
||||
BindFailed,
|
||||
#[error("qconnect-lan-start-task-failed")]
|
||||
StartTaskFailed,
|
||||
#[error("qconnect-lan-shutdown-task-failed")]
|
||||
ShutdownTaskFailed,
|
||||
#[error("qconnect-lan-shutdown-timed-out")]
|
||||
ShutdownTimedOut,
|
||||
#[error("qconnect-lan-start-cleanup-timed-out")]
|
||||
StartCleanupTimedOut,
|
||||
}
|
||||
|
||||
/// Owns the pending-start fence and the irreversible unsafe-teardown latch.
|
||||
///
|
||||
/// Qt and qbzd supply only their runtime constructor and blocking shutdown
|
||||
/// primitive. Cancellation cleanup, worker joining, timeouts and fail-closed
|
||||
/// latching are identical and remain tested in this shared implementation.
|
||||
pub struct LanRuntimeLifecycle<R> {
|
||||
start_pending: Arc<AtomicBool>,
|
||||
teardown_unsafe: Arc<AtomicBool>,
|
||||
shutdown: Arc<dyn Fn(&mut R) + Send + Sync + 'static>,
|
||||
}
|
||||
|
||||
impl<R> Clone for LanRuntimeLifecycle<R> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
start_pending: Arc::clone(&self.start_pending),
|
||||
teardown_unsafe: Arc::clone(&self.teardown_unsafe),
|
||||
shutdown: Arc::clone(&self.shutdown),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R> LanRuntimeLifecycle<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
pub fn new(shutdown: impl Fn(&mut R) + Send + Sync + 'static) -> Self {
|
||||
Self {
|
||||
start_pending: Arc::new(AtomicBool::new(false)),
|
||||
teardown_unsafe: Arc::new(AtomicBool::new(false)),
|
||||
shutdown: Arc::new(shutdown),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_pending(&self) -> bool {
|
||||
self.start_pending.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn teardown_safe(&self) -> bool {
|
||||
!self.teardown_unsafe.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub async fn start<E, S, C>(&self, start: S, cancellation: C) -> Result<R, LanRuntimeError>
|
||||
where
|
||||
E: Send + 'static,
|
||||
S: FnOnce() -> Result<R, E> + Send + 'static,
|
||||
C: Future<Output = ()>,
|
||||
{
|
||||
if !self.teardown_safe() {
|
||||
return Err(LanRuntimeError::PhysicalTeardownUnsafe);
|
||||
}
|
||||
if self.start_pending.swap(true, Ordering::AcqRel) {
|
||||
return Err(LanRuntimeError::StartAlreadyPending);
|
||||
}
|
||||
|
||||
let mut start_task = tokio::task::spawn_blocking(start);
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation => {
|
||||
// A running blocking task cannot be aborted. Its supervisor
|
||||
// retains ownership until any resulting listener is withdrawn.
|
||||
let lifecycle = self.clone();
|
||||
tokio::spawn(async move {
|
||||
match start_task.await {
|
||||
Ok(Ok(runtime)) => {
|
||||
if let Err(error) = lifecycle.shutdown(runtime).await {
|
||||
log::warn!(
|
||||
"[QConnect LAN] cancelled listener cleanup failed: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(Err(_)) => {}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"[QConnect LAN] cancelled listener start worker failed: {error}"
|
||||
);
|
||||
lifecycle.teardown_unsafe.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
lifecycle.start_pending.store(false, Ordering::Release);
|
||||
});
|
||||
return Err(LanRuntimeError::Cancelled);
|
||||
}
|
||||
result = &mut start_task => result,
|
||||
};
|
||||
self.start_pending.store(false, Ordering::Release);
|
||||
|
||||
match result {
|
||||
Ok(Ok(runtime)) => Ok(runtime),
|
||||
Ok(Err(_)) => Err(LanRuntimeError::BindFailed),
|
||||
Err(_) => {
|
||||
self.teardown_unsafe.store(true, Ordering::Release);
|
||||
Err(LanRuntimeError::StartTaskFailed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run physical teardown on the blocking pool. Any lost worker or timeout
|
||||
/// latches the lifecycle unsafe so logout/disable cannot claim success.
|
||||
pub async fn shutdown(&self, mut runtime: R) -> Result<(), LanRuntimeError> {
|
||||
let shutdown_fn = Arc::clone(&self.shutdown);
|
||||
let mut shutdown = tokio::task::spawn_blocking(move || shutdown_fn(&mut runtime));
|
||||
let result = match tokio::time::timeout(SHUTDOWN_TIMEOUT, &mut shutdown).await {
|
||||
Ok(Ok(())) => Ok(()),
|
||||
Ok(Err(_)) => Err(LanRuntimeError::ShutdownTaskFailed),
|
||||
Err(_) => {
|
||||
// The detached worker keeps owning the runtime and may finish
|
||||
// its idempotent shutdown, but the process can no longer prove
|
||||
// that the listener and mDNS publication are gone.
|
||||
drop(shutdown);
|
||||
Err(LanRuntimeError::ShutdownTimedOut)
|
||||
}
|
||||
};
|
||||
if result.is_err() {
|
||||
self.teardown_unsafe.store(true, Ordering::Release);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Wait for cancellation cleanup to take ownership and finish, then prove
|
||||
/// that no physical listener is left in an unknown state.
|
||||
pub async fn settle(&self) -> Result<(), LanRuntimeError> {
|
||||
if self.start_pending() {
|
||||
let settled = tokio::time::timeout(START_CLEANUP_TIMEOUT, async {
|
||||
while self.start_pending() {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.is_ok();
|
||||
if !settled {
|
||||
return Err(LanRuntimeError::StartCleanupTimedOut);
|
||||
}
|
||||
}
|
||||
if !self.teardown_safe() {
|
||||
return Err(LanRuntimeError::PhysicalTeardownUnsafe);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use super::*;
|
||||
use crate::AuthorityOrigin;
|
||||
|
||||
#[test]
|
||||
fn callback_survives_intent_refresh_but_not_disable_or_authority_change() {
|
||||
let intent = QconnectEnableIntent::new(true);
|
||||
let original = intent.current_token().unwrap();
|
||||
let authority = AuthorityCell::new();
|
||||
let stamp = authority.reserve(AuthorityOrigin::Owner);
|
||||
assert!(authority.install(stamp));
|
||||
assert!(lan_callback_is_current(&intent, &authority, stamp));
|
||||
|
||||
let refreshed = intent.enable_new_intent();
|
||||
assert!(!intent.is_current(original));
|
||||
assert!(intent.is_current(refreshed));
|
||||
assert!(lan_callback_is_current(&intent, &authority, stamp));
|
||||
|
||||
let disabled = intent.disable();
|
||||
assert!(!lan_callback_is_current(&intent, &authority, stamp));
|
||||
assert!(intent.enable_if_disabled(disabled).is_some());
|
||||
assert!(lan_callback_is_current(&intent, &authority, stamp));
|
||||
|
||||
authority.clear();
|
||||
assert!(!lan_callback_is_current(&intent, &authority, stamp));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn successful_start_and_shutdown_share_one_physical_owner() {
|
||||
let shutdowns = Arc::new(AtomicUsize::new(0));
|
||||
let observed = Arc::clone(&shutdowns);
|
||||
let lifecycle = LanRuntimeLifecycle::new(move |_runtime: &mut u8| {
|
||||
observed.fetch_add(1, Ordering::AcqRel);
|
||||
});
|
||||
|
||||
let runtime = lifecycle
|
||||
.start(|| Ok::<_, ()>(7), std::future::pending())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(runtime, 7);
|
||||
assert!(!lifecycle.start_pending());
|
||||
lifecycle.shutdown(runtime).await.unwrap();
|
||||
assert_eq!(shutdowns.load(Ordering::Acquire), 1);
|
||||
assert!(lifecycle.teardown_safe());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_supervisor_withdraws_late_listener_before_settling() {
|
||||
let shutdowns = Arc::new(AtomicUsize::new(0));
|
||||
let observed = Arc::clone(&shutdowns);
|
||||
let lifecycle = LanRuntimeLifecycle::new(move |_runtime: &mut u8| {
|
||||
observed.fetch_add(1, Ordering::AcqRel);
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
lifecycle
|
||||
.start(
|
||||
|| {
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
Ok::<_, ()>(1)
|
||||
},
|
||||
std::future::ready(()),
|
||||
)
|
||||
.await,
|
||||
Err(LanRuntimeError::Cancelled)
|
||||
);
|
||||
assert!(lifecycle.start_pending());
|
||||
lifecycle.settle().await.unwrap();
|
||||
assert_eq!(shutdowns.load(Ordering::Acquire), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn panicked_shutdown_latches_fail_closed() {
|
||||
let lifecycle = LanRuntimeLifecycle::new(|_runtime: &mut u8| panic!("shutdown failed"));
|
||||
assert_eq!(
|
||||
lifecycle.shutdown(1).await,
|
||||
Err(LanRuntimeError::ShutdownTaskFailed)
|
||||
);
|
||||
assert!(!lifecycle.teardown_safe());
|
||||
assert_eq!(
|
||||
lifecycle.settle().await,
|
||||
Err(LanRuntimeError::PhysicalTeardownUnsafe)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,15 @@
|
||||
|
||||
mod app;
|
||||
mod authority;
|
||||
mod authority_transition;
|
||||
mod delegation;
|
||||
mod delegation_preflight;
|
||||
mod delegated_rejoin;
|
||||
mod error;
|
||||
mod events;
|
||||
mod feature_flags;
|
||||
mod lan_projection;
|
||||
mod lan_runtime;
|
||||
pub mod queue_resolution;
|
||||
pub mod renderer;
|
||||
mod renderer_engine;
|
||||
@@ -26,17 +31,26 @@ pub use authority::{
|
||||
ExactOwnerAuthorityObservation, OwnerAuthorityObservation, OwnerAuthorityToken,
|
||||
QconnectDisabledToken, QconnectEnableIntent, QconnectEnableToken,
|
||||
};
|
||||
pub use authority_transition::{
|
||||
acquire_transition_guard_and_fence, DeferredActivationRelease, OwnerActionFence,
|
||||
};
|
||||
pub use delegation::{
|
||||
CommitRejected, CredentialOrigin, DelegationCancellation, DelegationCandidate,
|
||||
DelegationCoordinator, DelegationCoordinatorConfig, DelegationCoordinatorError,
|
||||
DelegationErrorCode, DelegationHost, DelegationPhase, DelegationSnapshot, RestoreReason,
|
||||
};
|
||||
pub use delegation_preflight::DelegationPreflight;
|
||||
pub use delegated_rejoin::{
|
||||
DelegatedRejoinWatchdog, DelegatedRuntimeEventDirective, DelegatedRuntimeEventState,
|
||||
};
|
||||
pub use error::{QconnectAppError, QconnectOwnerFailure};
|
||||
pub use events::{NoOpEventSink, QconnectAppEvent, QconnectEventSink};
|
||||
pub use feature_flags::{
|
||||
QBZ_QCONNECT_PANEL_SWITCH, QBZ_QCONNECT_QUEUE_MODEL, QBZ_QCONNECT_STRICT_DOMAIN_ISOLATION,
|
||||
QBZ_QCONNECT_TRANSPORT,
|
||||
};
|
||||
pub use lan_projection::LanProjectionSlot;
|
||||
pub use lan_runtime::{lan_callback_is_current, LanRuntimeError, LanRuntimeLifecycle};
|
||||
pub use qconnect_core::{
|
||||
evaluate_remote_queue_admission, resolve_handoff_intent, validate_track_origins_for_admission,
|
||||
AdmissionDecision, HandoffIntent, QConnectQueueState, QConnectRendererState, QueueVersion,
|
||||
@@ -48,17 +62,18 @@ pub use qconnect_protocol::{
|
||||
pub use renderer_engine::QconnectRendererEngine;
|
||||
pub use reporting::{
|
||||
build_renderer_playback_report, qconnect_report_track_id, renderer_buffer_state,
|
||||
RendererPlaybackSnapshot,
|
||||
renderer_playing_state, RendererPlaybackSnapshot,
|
||||
};
|
||||
pub use session::{
|
||||
build_effective_renderer_snapshot, build_session_renderer_snapshot, compute_connection_state,
|
||||
deferred_join_reason, find_unique_renderer_id, is_local_renderer_active,
|
||||
is_peer_renderer_active, normalize_active_renderer_id, qconnect_millis_from_secs,
|
||||
quality_from_max_audio_quality, queue_item_snapshot_for_cursor, refresh_local_renderer_id,
|
||||
renderer_allows_remote_volume, should_arm_renderer_watchdog, should_reask_queue_state,
|
||||
ConnectionDecision, LocalIdentity, QconnectFileAudioQualitySnapshot, QconnectLifecycleState,
|
||||
QconnectRendererInfo, QconnectSessionRendererState, QconnectSessionState, RendererStatus,
|
||||
ServerActiveState, JOIN_SESSION_REASON_CONTROLLER_REQUEST, JOIN_SESSION_REASON_RECONNECTION,
|
||||
is_peer_renderer_active, max_audio_quality_from_quality, normalize_active_renderer_id,
|
||||
qconnect_millis_from_secs, quality_from_max_audio_quality, queue_item_snapshot_for_cursor,
|
||||
refresh_local_renderer_id, renderer_allows_remote_volume, should_arm_renderer_watchdog,
|
||||
should_reask_queue_state, ConnectionDecision, LocalIdentity,
|
||||
QconnectFileAudioQualitySnapshot, QconnectLifecycleState, QconnectRendererInfo,
|
||||
QconnectSessionRendererState, QconnectSessionState, RendererStatus, ServerActiveState,
|
||||
JOIN_SESSION_REASON_CONTROLLER_REQUEST, JOIN_SESSION_REASON_RECONNECTION,
|
||||
QCONNECT_RENDERER_LOST_TIMEOUT_MS,
|
||||
};
|
||||
pub use startup::{compute_effective_startup, QconnectStartupMode};
|
||||
|
||||
@@ -210,6 +210,17 @@ pub fn quality_from_max_audio_quality(level: Option<i32>) -> Quality {
|
||||
}
|
||||
}
|
||||
|
||||
/// Map the local quality cap to the exact QConnect `max_audio_quality` wire
|
||||
/// level. Join reports from every host adapter must use this one mapping.
|
||||
pub const fn max_audio_quality_from_quality(quality: Quality) -> i32 {
|
||||
match quality {
|
||||
Quality::Mp3 => 1,
|
||||
Quality::Lossless => 2,
|
||||
Quality::HiRes => 3,
|
||||
Quality::UltraHiRes => 4,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Session topology types (relocated from the Tauri adapter — slice 2+4).
|
||||
//
|
||||
@@ -574,7 +585,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn renderer_status_from_wire_collapses_unknown_and_missing_to_inactive() {
|
||||
assert_eq!(RendererStatus::from_wire(Some(99)), RendererStatus::Inactive); // UNRECOGNIZED
|
||||
assert_eq!(
|
||||
RendererStatus::from_wire(Some(99)),
|
||||
RendererStatus::Inactive
|
||||
); // UNRECOGNIZED
|
||||
assert_eq!(RendererStatus::from_wire(None), RendererStatus::Inactive); // absent field
|
||||
}
|
||||
|
||||
@@ -620,6 +634,17 @@ mod tests {
|
||||
assert_eq!(quality_from_max_audio_quality(Some(4)), Quality::UltraHiRes);
|
||||
assert_eq!(quality_from_max_audio_quality(Some(5)), Quality::UltraHiRes);
|
||||
assert_eq!(quality_from_max_audio_quality(None), Quality::UltraHiRes);
|
||||
assert_eq!(quality_from_max_audio_quality(Some(99)), Quality::UltraHiRes);
|
||||
assert_eq!(
|
||||
quality_from_max_audio_quality(Some(99)),
|
||||
Quality::UltraHiRes
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_quality_maps_to_exact_qconnect_wire_levels() {
|
||||
assert_eq!(max_audio_quality_from_quality(Quality::Mp3), 1);
|
||||
assert_eq!(max_audio_quality_from_quality(Quality::Lossless), 2);
|
||||
assert_eq!(max_audio_quality_from_quality(Quality::HiRes), 3);
|
||||
assert_eq!(max_audio_quality_from_quality(Quality::UltraHiRes), 4);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user