diff --git a/ci/allow/forks/plex.txt b/ci/allow/forks/plex.txt index 00a5ca7ee..232dcca53 100644 --- a/ci/allow/forks/plex.txt +++ b/ci/allow/forks/plex.txt @@ -1,4 +1,4 @@ -# count: 31 +# count: 12 # Test/production forks (docs/sans-io.md), area `plex`: one line per production-visible `#[cfg(..)]` / `cfg!(..)` whose predicate reads `test` or `feature = "test-support"` # (`not(test)`, `not(any(test, feature = "test-support"))`, ...) in every machine crate (data/, plex/, media/, session/, screens/, ui/, appkit/ and machine/), keyed `::` (an attribute on an item), `::` (a statement or an inline `cfg!`) or `::` (a field). # Logic is one thing in production and tests deliver it events: there is no cfg(test) fork. Spec: ci/check-deps.sh `forks`. @@ -10,27 +10,8 @@ rust-modules/plex/src/plex/origin.rs::store_policy_forced rust-modules/plex/src/plex/servers.rs::register_captured_origin_with_connection rust-modules/plex/src/plex/session.rs::auth_paths rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::clear_for_erase rust-modules/plex/src/plex/session.rs::publish rust-modules/plex/src/plex/session.rs::read_into_cache_locked -rust-modules/plex/src/plex/session.rs::read_into_cache_locked -rust-modules/plex/src/plex/session/install_preferences.rs::candidates rust-modules/plex/src/plex/session/install_preferences.rs::candidates rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::cleanup_after_confirmed_clear rust-modules/plex/src/plex/session/persistence.rs::cleanup_after_confirmed_clear -rust-modules/plex/src/plex/session/persistence.rs::cleanup_temporaries -rust-modules/plex/src/plex/session/persistence.rs::cleanup_temporaries -rust-modules/plex/src/plex/session/persistence.rs::commit_cleared -rust-modules/plex/src/plex/session/persistence.rs::commit_cleared -rust-modules/plex/src/plex/session/persistence.rs::commit_data -rust-modules/plex/src/plex/session/persistence.rs::commit_data -rust-modules/plex/src/plex/session/persistence.rs::load -rust-modules/plex/src/plex/session/persistence.rs::load -rust-modules/plex/src/plex/session/persistence.rs::migrate_session -rust-modules/plex/src/plex/session/persistence.rs::migrate_session -rust-modules/plex/src/plex/session/persistence.rs::write_session -rust-modules/plex/src/plex/session/persistence.rs::write_session diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 49fe3eb59..e37e44a58 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -458,9 +458,11 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N `load_login_client_id`, `:4336-4349`), reusing one process-local id when storage is unavailable. `install_preferences::Saved` is `deny_unknown_fields`, version 1 (`:28-38`): it cannot carry the id without a new version. - - The authority is chosen by `target_arch = "arm"`, not by a platform value (`session/persistence.rs:1400-1425`, + - The authority was chosen by `target_arch = "arm"`, not by a platform value (`session/persistence.rs:1400-1425`, `commit_data` `:288-308`); a Tizen ARM build would select the DB8 arm with no helper behind it (F12). The - `MemoryOnly` gate sits above that selection, and W8a re-keys it. + `MemoryOnly` gate sits above that selection. W8a re-keyed plex's 21 sites to `tv::authority::authority()`: + `persistence.rs`'s dispatchers take the authority and the helper's transport, so a host test drives the helper + arm with a fake one; telemetry's sites follow in its own PR. ### Evidence from the second reviews: F40-F46 (each citation checked in the tree) @@ -502,9 +504,11 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N - `CompletionOutcome` (`plex/src/plex/session/async_persistence.rs:112`) and `LiveWrite` are matched in `session.rs`, `session/{persistence,async_persistence,prefs/profile_prefs}.rs`, `session/src/auth/owner.rs`, `telemetry/src/telemetry/incident.rs:592-600`, `src/app/adapters/session.rs` and three test files. - - `install_preferences::candidates` (`:40`) and `clear_for_erase` (`session.rs:5341`) key on the ARM cfg, so - Tizen ARM reads `native = true`; `load` accepts `version == 1` only (`:59`) and `Saved` is - `deny_unknown_fields`. The ARM canonical write is cfg'd out of host tests (`session/persistence.rs:1400-1425`). + - `install_preferences::candidates` (`:40`) and `clear_for_erase` (`session.rs:5341`) keyed on the ARM cfg, so + Tizen ARM read `native = true` (W8a re-keyed them to `tv::authority::authority()`); `load` accepts + `version == 1` only (`:59`) and `Saved` is `deny_unknown_fields`. The ARM canonical write was cfg'd out of + host tests (`session/persistence.rs:1400-1425`); it is now the `Helper` arm of `persistence::*_via`, which every + host runs over a fake transport. - `ci/check-deps.sh`: `plex/` is in `FORK_SCOPE`, `session.rs` in `MACHINES` (`:1406-1408`): a new `cfg(test)` branch there is a `forks` line, a new static a `statics` line. `platform/` is not in `FORK_SCOPE`, and only `platform/src/tv/plane.rs` is in `MACHINES` (`:1406-1408`; the scan `find` at `:1439` lists it too). The @@ -850,9 +854,12 @@ split by who reads it (critic M4): - `system { go_home, poll_home, deliver_toast }`; - `storage { authority }` (W8a): `Authority::Helper` (webOS: the LS2/DB8 storage helper is the canonical store of the session, the install's preferences and the consent record; the app's own files there are the legacy - migration inputs and the marked fallback of a helper outage) or `Authority::Files` (desktop, Tizen, a host + migration inputs, the marked fallback of a helper outage and the install-preferences file a sign-out writes + when the helper's clear is not durable) or `Authority::Files` (desktop, Tizen, a host test: the app's own record files are the store), read through - `tv::authority::authority()`. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence + `tv::authority::authority()`. `secure::mode()` decides the session record ahead of it: under `MemoryOnly` + (where Tizen starts, W9) the session lives in memory and no credential store is read or written, whatever the + authority says; only the install's own preference file persists. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence layers chose their store by; the helper's wake-up (`storage::client::install_activator`) joins it after W7b; - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), named for what they are (critic M3). Every hook is required (Decision 2, C): a platform states each field, diff --git a/rust-modules/base/src/paths.rs b/rust-modules/base/src/paths.rs index b38fd88eb..8c93833ab 100644 --- a/rust-modules/base/src/paths.rs +++ b/rust-modules/base/src/paths.rs @@ -1336,8 +1336,11 @@ mod tests { } } -/// Legacy JSON/host-simulator persistence root. The canonical ARM adapter uses helper-owned DB8; -/// this path exists for old-record migration and for host tests that must never touch the checkout. +/// Legacy JSON/host-simulator persistence root. Where the platform states the storage helper as the +/// canonical store (a webOS television, `plx_os::tv::authority`) the canonical record is +/// helper-owned DB8; where it states plain files (the desktop simulator) the canonical record files +/// are kept here. This path also exists for old-record migration and for host tests that must never +/// touch the checkout. /// /// **Test builds never resolve this to the machine-wide runtime dir by accident.** A test that /// calls [`redirect_persistent_state_root_for_test`] gets the directory it asked for; a test that diff --git a/rust-modules/os/src/tv/authority.rs b/rust-modules/os/src/tv/authority.rs index 629a19410..7d865f24d 100644 --- a/rust-modules/os/src/tv/authority.rs +++ b/rust-modules/os/src/tv/authority.rs @@ -6,10 +6,20 @@ //! state root ([`Authority::Files`]): the desktop simulator, a host test, and a platform with no //! helper at all (Tizen). //! -//! Under `Helper` the app's own files are not the store. They are the legacy migration inputs an -//! older build left, and the marked fallback the session layer writes when a commit to the helper is -//! not durable (a helper outage): while the helper cannot answer, that file is served as transient -//! state, and it never replaces the helper's record. +//! The authority is not the whole answer for the session record: the platform's persistence mode +//! ([`secure::mode()`](super::secure::mode)) decides it first. Under `StoreMode::MemoryOnly`, where +//! Tizen starts (W9), the session lives in memory and no credential store is read or written, +//! whatever the authority says; only the install's own preference file (client id, language and +//! Interface resolution) persists. +//! +//! Under `Helper` the app's own files are not the store. Three kinds remain: +//! - the legacy migration inputs an older build left; +//! - the marked fallback the session layer writes when a commit to the helper is not durable (a +//! helper outage): while the helper cannot answer, that file is served as transient state, and it +//! never replaces the helper's record; +//! - the install-preferences file a sign-out writes when the helper's clear is not durable +//! (`install_preferences::save`): an unmarked `….language.json` file beside a session candidate, which +//! `install_preferences::load` reads back into the `Locked` and `Cleared` states. //! //! The platform states the value once, as the `authority` of its [`StorageHooks`](super::StorageHooks), //! and [`authority`] reads it. A process that installed no platform (a host test) reads @@ -30,10 +40,12 @@ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Authority { /// The platform's storage helper (webOS: the LS2/DB8 service) is the canonical store. The app's - /// own files are only the legacy migration inputs and the session layer's marked fallback, which - /// is written during a helper outage and is never the record. + /// own files are only the legacy migration inputs, the session layer's marked fallback (written + /// during a helper outage, never the record) and the install-preferences file a sign-out writes + /// when the helper's clear is not durable. Helper, - /// The app's own record files under its persistent state root are the canonical store. + /// The app's own record files under its persistent state root are the canonical store. A process + /// in `StoreMode::MemoryOnly` still keeps the session record in memory (see the module doc). #[default] Files, } diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index 58e41e386..a5f97c54d 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -627,6 +627,25 @@ a dead source is **absent** from Home and states itself in its own library secti struct, and a new field follows the omit rule. 6. **The Settings row** (labels, i18n, picker) is a screens edit, and `Choice` gains a variant (T-settings). +- **Which store holds the session is the platform's statement, `plx_os::tv::authority::authority()`** + (`Helper`: the LS2/DB8 storage helper, webOS; `Files`: the 0600 record files, the desktop, a host test and + any platform with no helper), never the build's CPU or OS. `session/persistence.rs` reads it once per + public call (`load`, `commit_data`, `commit_cleared`, `write_session`, `migrate_session`, `bootstrap`, + `cleanup_after_confirmed_clear`, `cleanup_temporaries`) and hands it to the `*_via(authority, helper, ..)` + form, so a test passes the authority it grades and, for `Helper`, a transport of its own (an in-memory + `Backend` or a closure); the real `NativeTransport` is named by those public forms and by two helpers + with no `_via` seam (`reset_cleared_language()`, which `clear_for_erase` calls under `Helper` and which is + device-only, and `helper_commit`, which has no caller here), because on a Linux host it waits out a 12 s + start deadline with no helper behind it. There is no process-global override. + Under `Helper` the dispatchers never answer for a helper that cannot answer (a blocked read stays blocked, + and a legacy file is neither imported nor retired on its word); the files a television does keep beside DB8 + are `session.rs`'s own: the marked fallback `save_legacy_fallback_locked` writes when a commit is not + durable, which `read_legacy_filtered_locked` serves as transient state, the legacy migration inputs, and the + install-preferences file (`install_preferences::save`, an unmarked `….language.json` beside a session + candidate) that `clear_for_erase` writes when a sign-out's helper clear is not durable. `secure::mode()`'s + `MemoryOnly` is read before the authority: it holds the session in memory and touches no credential store. + `clear_for_erase`, `read_into_cache_locked` and `install_preferences::keeps_language_file` read the same + value; the telemetry sweep after a durable clear runs only under `Helper`. - **The DB8 document may not pass `MAX_LOGICAL_BYTES` (256 KiB), and per-profile memory is what grows it.** Past the cap EVERY write fails (`LogicalTooLarge`, reported as `InvalidSchema`), so `persistence::commit_session_with` measures the projected document (the os layer's own @@ -688,7 +707,7 @@ a dead source is **absent** from Home and states itself in its own library secti copy** (`session/memory_only.rs`): reads, guarded edits, revocation and clear all resolve against it, and no credential is committed anywhere, canonical store, sealed or plaintext fallback or revocation marker. The gate sits in `read_live_locked`, `save_locked_with_authority` - and `clear_for_erase`, above every `TEST_FILE` and `target_arch` branch, so nothing behind them + and `clear_for_erase`, above every `TEST_FILE` and storage-authority branch, so nothing behind them is reachable. A write answers `PersistOutcome::Memory`, which classifies as `CompletionOutcome::Ephemeral`: signed in for this run, so the auth owner goes on to Home, but never a saved-login claim and never a warning. `drop_cache_locked` must not run in this mode diff --git a/rust-modules/plex/src/plex/session.rs b/rust-modules/plex/src/plex/session.rs index 320bfdbc2..109c42182 100644 --- a/rust-modules/plex/src/plex/session.rs +++ b/rust-modules/plex/src/plex/session.rs @@ -65,6 +65,7 @@ pub use prefs::{IntroSkipPref, CreditsSkipPref, DolbyVisionModePref, InstantDpad ProfilePrefsRecord, ProfileSetting, ProfileWrite, QualityPref, Row, Setting, SkipIntervalPref, SubtitlePositionPref, SubtitleSizePref, SubtitleTonePref, TrailerAutoplayPref, HudEndTimePref, UiResolutionPref, UnderPostersPref}; use prefs::ProfileMemory; +use plx_os::tv::authority::{authority as storage_authority, Authority}; use serde::de::DeserializeOwned; use serde::{Deserialize, Deserializer, Serialize}; use std::sync::Mutex; @@ -3225,8 +3226,9 @@ fn read_into_cache_locked(expected: Option) -> (std::sync::Arc, let state = std::sync::Arc::new(CACHE_READ_FOR_TEST.with(|read| { read.get().unwrap_or(read_live_locked)() })); - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - plx_base::eventlog::log("session: authority read reason=miss"); + if storage_authority() == Authority::Helper { + plx_base::eventlog::log("session: authority read reason=miss"); + } if !replace_cache(cached_arm(state.clone()), expected, false) { return (state, false); } if let ReadState::Ready { session, .. } = &*state { publish_identities(session); } (state, true) @@ -5331,7 +5333,7 @@ fn clear_cleanup_outcome(outcome: persistence::ClearCleanupOutcome) -> ClearOutc /// load. The old-path copy goes too, or the migration fallback would resurrect the stale session. /// **And commits an explicit Cleared record to the canonical authority** — the legacy-file sweep /// below only ever touches pre-DB8 candidates; on a build where `persistence::load`/`write_session` -/// actually read/write the canonical store (DB8 or its host/ARM equivalent), that store is a +/// actually read/write the canonical store (DB8 or its host equivalent), that store is a /// SEPARATE copy of the account token and roster, and clearing only the legacy files would leave a /// clean-looking sign-out that the canonical authority still hands back on the next boot. /// @@ -5367,7 +5369,7 @@ pub fn clear_for_erase(all_local: bool, retry: Option) -> Erasure { return memory_only::clear_locked(all_local, retry); } let kept = retry.unwrap_or_else(|| Retained::of(&session_from_read(&read_live_locked()))); - let native = cfg!(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))); + let native = storage_authority() == Authority::Helper; // File backends need a credential-free resource before the credential file disappears. let mut preference_failures = Vec::new(); if !all_local && !native && !install_preferences::save(kept) { @@ -5419,22 +5421,20 @@ pub fn clear_for_erase(all_local: bool, retry: Option) -> Erasure { // `auth_paths()` above only ever covered `paths::session_candidates()` — the legacy // sign-in file and its pre-relocation predecessor. The recognized migration source set // is bigger (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON - // wrapper on ARM), and a candidate this sweep never visits is a live account token left + // wrapper where the helper is canonical), and a candidate this sweep never visits is a live account token left // on a rooted, world-readable install prefix after a sign-out that otherwise looked // clean. `cleanup_after_confirmed_clear` re-reads the authority to confirm it really is // Cleared before retiring anything, so this can only ever remove residue, never data a // concurrent re-login just wrote. - #[allow(unused_mut)] // only mutated on the ARM cfg arm below let mut outcome = clear_cleanup_outcome(persistence::cleanup_after_confirmed_clear()); // Telemetry/consent's own legacy files are a SEPARATE candidate set from the session // auth-token sweep above (`persistence::cleanup_after_confirmed_clear` never touches // them — see `paths::telemetry_candidates` vs `paths::session_migration_candidates`). - // On ARM, `telemetry::persistence::forget_at` defers their removal to exactly this - // moment, once this canonical commit is confirmed durable (Copilot review on PR #105, - // finding 7; ported from `release/v0.6`'s `telemetry::cleanup_after_account_clear`, - // called here in that release). - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - if !ACCOUNT_CLEAR_CLEANUP.get().is_none_or(|sweep| sweep()) { + // Where the storage helper is canonical, `telemetry::persistence::forget_at` defers their + // removal to exactly this moment, once this canonical commit is confirmed durable + // (Copilot review on PR #105, finding 7; ported from `release/v0.6`'s + // `telemetry::cleanup_after_account_clear`, called here in that release). + if native && !ACCOUNT_CLEAR_CLEANUP.get().is_none_or(|sweep| sweep()) { plx_base::eventlog::log( "session: canonical clear is durable but a telemetry/consent legacy \ candidate could not be retired — it remains on disk and will be swept \ diff --git a/rust-modules/plex/src/plex/session/install_preferences.rs b/rust-modules/plex/src/plex/session/install_preferences.rs index 6cc21def1..4d62f22c6 100644 --- a/rust-modules/plex/src/plex/session/install_preferences.rs +++ b/rust-modules/plex/src/plex/session/install_preferences.rs @@ -1,11 +1,13 @@ //! Credential-free install-wide choices (the UI language and the Interface resolution) retained by -//! host stores and explicitly supported file fallbacks. -//! Native DB8 remains authoritative whenever it answers; these files cannot authorize login. +//! file stores and explicitly supported file fallbacks. +//! The storage helper (DB8) remains authoritative whenever the platform states one +//! ([`Authority::Helper`]) and it answers; these files cannot authorize login. //! //! On a [`StoreMode::MemoryOnly`] platform this file is also where the install's own client id //! lives (version 2): the one thing a launch must know before anyone signs in and that no credential //! store is there to keep. The id is an install label, not a secret, and cannot authorize a login. use super::*; +use plx_os::tv::authority::{authority, Authority}; use plx_os::tv::secure::{mode, StoreMode}; use std::path::PathBuf; @@ -59,6 +61,13 @@ impl Saved { } } +/// Whether the install's own state root holds a `language.json`. webOS keeps these choices in DB8 +/// and never in this root; a memory-only platform has no DB8, so its root is where they live. A +/// redirected test fixture names its own files instead. +fn keeps_language_file(authority: Authority, mode: StoreMode, redirected: bool) -> bool { + (authority == Authority::Files || mode == StoreMode::MemoryOnly) && !redirected +} + fn candidates() -> Vec { #[cfg(any(test, feature = "test-support"))] let redirected = TEST_FILE.lock().unwrap_or_else(|e| e.into_inner()).is_some() @@ -66,9 +75,7 @@ fn candidates() -> Vec { #[cfg(not(any(test, feature = "test-support")))] let redirected = false; let mut paths = Vec::new(); - // webOS keeps these choices in DB8 and never in this root; a memory-only platform has no DB8. - if (!cfg!(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))) - || mode() == StoreMode::MemoryOnly) && !redirected { + if keeps_language_file(authority(), mode(), redirected) { paths.push(plx_base::paths::persistent_state_root().join("language.json")); } paths.extend(auth_paths().into_iter().map(|path| path.with_extension("language.json"))); @@ -131,3 +138,24 @@ pub(super) fn erase() -> Vec { .err().map(|error| format!("{}: {error}", path.display())) }).collect() } + +#[cfg(test)] +mod authority_tests { + use super::*; + + /// The install's own `language.json` is where a file platform keeps its choices and where a + /// memory-only platform keeps the only thing that outlives the process. A television whose + /// storage helper holds them has none, and a redirected fixture names its own files. + #[test] + fn the_language_file_is_kept_unless_the_helper_holds_the_choices() { + use Authority::{Files, Helper}; + use StoreMode::{Durable, MemoryOnly}; + assert!(keeps_language_file(Files, Durable, false), "the desktop and Tizen keep the file"); + assert!(keeps_language_file(Files, MemoryOnly, false)); + assert!(!keeps_language_file(Helper, Durable, false), "webOS keeps these choices in DB8, never in this root"); + assert!(keeps_language_file(Helper, MemoryOnly, false), "a memory-only platform has no DB8 to hold them"); + for (authority, mode) in [(Files, Durable), (Files, MemoryOnly), (Helper, MemoryOnly)] { + assert!(!keeps_language_file(authority, mode, true), "a redirected fixture never reaches the real root"); + } + } +} diff --git a/rust-modules/plex/src/plex/session/migration_tests.rs b/rust-modules/plex/src/plex/session/migration_tests.rs index 14e856f63..1c61a7f7a 100644 --- a/rust-modules/plex/src/plex/session/migration_tests.rs +++ b/rust-modules/plex/src/plex/session/migration_tests.rs @@ -1,6 +1,7 @@ //! Canonical schema and the shipping client/coordinator path, using synthetic helper transport. use super::*; use plx_os::storage::{client, state, wire::*}; +use plx_os::tv::authority::Authority; use persistence::CanonicalRead; fn fixture() -> Session { @@ -1389,3 +1390,107 @@ fn pending_revocation_prevents_missing_canonical_from_importing_a_marked_snapsho assert_eq!(store.commits, 0); assert!(source.path.exists()); } + +// Which store is canonical is the platform's statement (`plx_os::tv::authority`). The dispatchers +// take the authority and the helper's transport, so every host runs the helper arm over a +// transport of its own, and the files arm over one that fails the test if it is reached. + +/// The transport the files arm must never reach. +fn no_helper(_: Request) -> Result { + panic!("a files authority never talks to the storage helper") +} + +/// The helper arm over the production backend, which holds the record the way DB8 does: the app's +/// own state root stays empty. +#[test] +fn a_helper_authority_reads_and_clears_through_the_helper_and_keeps_no_file() { + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-helper"); + let mut backend = plx_os::storage::backend::Backend::new( + Db8::default(), state::Flavor::Stable, "com.beb.plxnative.storage".into()); + let mut transport = |request: Request| Ok(backend.dispatch(request)); + assert!(matches!(persistence::load_via(Authority::Helper, &mut transport), CanonicalRead::Missing)); + commit_fresh(&fixture(), &mut transport); + let CanonicalRead::Opened { session, .. } = persistence::load_via(Authority::Helper, &mut transport) else { + panic!("the helper holds the session") + }; + assert_eq!(session.account_token, "synthetic-account"); + assert!(matches!(persistence::commit_cleared_via(Authority::Helper, &mut transport), + persistence::CanonicalCommit::Durable { .. })); + assert!(matches!(persistence::load_via(Authority::Helper, &mut transport), CanonicalRead::Cleared { .. })); + assert_eq!( + with_io_for_test(|| persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut transport, Vec::new())), + persistence::ClearCleanupOutcome::Confirmed); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "the helper arm leaves no record file under the state root"); +} + +/// The files arm for a platform with no helper (the desktop, a host test, Tizen): the record is the +/// 0600 file under the state root, and the helper is never asked. +#[test] +fn a_files_authority_keeps_the_record_in_files_and_never_asks_the_helper() { + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-files"); + let session = fixture(); + let payload = serde_json::to_string(&session).unwrap(); + assert!(matches!(persistence::load_via(Authority::Files, &mut no_helper), CanonicalRead::Missing)); + assert!(matches!(persistence::commit_data_via(Authority::Files, &mut no_helper, payload), + persistence::CanonicalCommit::Durable { revision: 1, .. })); + assert!(matches!( + persistence::write_session_via(Authority::Files, &mut no_helper, &session, SaveAuthority::Routine), + persistence::CanonicalCommit::Durable { revision: 2, .. })); + assert!(matches!(persistence::migrate_session_via(Authority::Files, &mut no_helper, &session), + persistence::CanonicalCommit::Durable { revision: 3, .. })); + let CanonicalRead::Data { revision: 3, payload: stored } = persistence::load_via(Authority::Files, &mut no_helper) else { + panic!("the files hold the session") + }; + assert_eq!(serde_json::from_str::(&stored).unwrap().account_token, "synthetic-account"); + assert!(state.dir.join("session.json").exists()); + assert!(matches!(persistence::commit_cleared_via(Authority::Files, &mut no_helper), + persistence::CanonicalCommit::Durable { revision: 4, .. })); + assert!(matches!(persistence::load_via(Authority::Files, &mut no_helper), CanonicalRead::Cleared { revision: 4, .. })); + assert_eq!( + with_io_for_test(|| persistence::cleanup_after_confirmed_clear_via(Authority::Files, &mut no_helper, Vec::new())), + persistence::ClearCleanupOutcome::Confirmed); + let boot = persistence::bootstrap_via(Authority::Files, &mut no_helper, &mut opener(), Vec::new()); + assert!(matches!(boot.state, CanonicalRead::Cleared { revision: 4, .. }), "the record the files hold is read as it is"); +} + +/// At this layer a helper that cannot answer is a blocked canonical store: no read, write or +/// migration is answered from the record files, and a legacy file is neither imported nor retired. +/// (The session layer above writes its own marked fallback after a non-durable commit; that file is +/// not the record and is not exercised here.) +#[test] +fn a_helper_authority_never_answers_from_the_record_files_when_the_helper_cannot_answer() { + use plx_os::storage::StoreError; + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-helper-down"); + let legacy = LegacyFile::new("authority-helper-down", &serde_json::to_value(fixture()).unwrap()); + let session = fixture(); + let requests = std::cell::Cell::new(0usize); + let mut down = |_: Request| { + requests.set(requests.get() + 1); + Err(client::ClientError::Unavailable) + }; + let unavailable = persistence::CanonicalCommit::Failed(StoreError::HelperUnavailable); + assert!(matches!(persistence::load_via(Authority::Helper, &mut down), + CanonicalRead::Blocked(StoreError::HelperUnavailable))); + assert_eq!(persistence::commit_data_via(Authority::Helper, &mut down, serde_json::to_string(&session).unwrap()), + unavailable); + assert_eq!(requests.get(), 2); + assert_eq!(persistence::commit_data_via(Authority::Helper, &mut down, "not a session".into()), + persistence::CanonicalCommit::Failed(StoreError::InvalidSchema), + "a payload the helper cannot take is refused before it is sent"); + assert_eq!(requests.get(), 2); + assert_eq!(persistence::write_session_via(Authority::Helper, &mut down, &session, SaveAuthority::Routine), unavailable); + assert_eq!(persistence::migrate_session_via(Authority::Helper, &mut down, &session), unavailable); + assert_eq!(persistence::commit_cleared_via(Authority::Helper, &mut down), unavailable); + assert_eq!(requests.get(), 5, "each of those asked the helper, and only the helper"); + let boot = persistence::bootstrap_via(Authority::Helper, &mut down, &mut opener(), vec![legacy.path.clone()]); + assert!(matches!(boot.state, CanonicalRead::Blocked(StoreError::HelperUnavailable))); + assert!(boot.migration.is_none(), "a helper that is down authorizes no import"); + assert_eq!( + persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut down, vec![legacy.path.clone()]), + persistence::ClearCleanupOutcome::AuthorityNotConfirmed); + assert!(legacy.path.exists(), "an unconfirmed clear retires nothing"); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "no record file was created under the state root"); +} diff --git a/rust-modules/plex/src/plex/session/persistence.rs b/rust-modules/plex/src/plex/session/persistence.rs index 4cfb5d968..249a105b5 100644 --- a/rust-modules/plex/src/plex/session/persistence.rs +++ b/rust-modules/plex/src/plex/session/persistence.rs @@ -3,6 +3,16 @@ //! This module owns the distinction between the versioned canonical record and the legacy //! filename candidates. Canonical helper loads, typed migration, and exact readback share this //! adapter; no unavailable helper response authorizes a file-backend fallback. +//! +//! **Which store is canonical is the platform's statement**, [`plx_os::tv::authority::authority`]: +//! the storage helper ([`Authority::Helper`], webOS) or the 0600 record files ([`Authority::Files`], +//! the desktop, a host test and a platform with no helper). Every dispatcher here reads it once per +//! call, in its public form, and hands it to a `*_via(authority, helper, ..)` form that takes the +//! authority and the helper's transport as parameters, so a host test grades the helper arm with a +//! fake transport and the files arm with a transport that fails the test if it is touched. The +//! helper's real transport (`NativeTransport`) is named by the dispatchers' public forms and by +//! two helpers that have no `_via` seam: `reset_cleared_language()`, which `clear_for_erase` calls +//! under `Helper` (device-only), and `helper_commit`, which has no caller in this crate. use plx_os::storage::{ CommitReceipt, CommitStage, Record, RecordKey, RecordState, RecordStore, StoreError, @@ -15,6 +25,7 @@ use plx_os::storage::{ state::{self, Generation, MigrationProgress, Status}, wire::{AuthLoad, CommitStatus, MigrationMutation, Response, WireMutation}, }; +use plx_os::tv::authority::{authority as storage_authority, Authority}; pub enum CanonicalRead { Missing, @@ -84,26 +95,16 @@ pub fn path() -> PathBuf { } pub fn cleanup_temporaries() -> Result<(), StoreError> { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { + cleanup_temporaries_for(storage_authority()) +} + +fn cleanup_temporaries_for(authority: Authority) -> Result<(), StoreError> { + match authority { // DB8 has no app-owned rename temporaries. Legacy paths are retired explicitly after the // helper has verified the committed destination; absence of the old app/state directory // is normal on a fresh install and must not turn sign-out into a cleanup failure. - Ok(()) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - store()?.cleanup(RecordKey::Session) + Authority::Helper => Ok(()), + Authority::Files => store()?.cleanup(RecordKey::Session), } } @@ -158,45 +159,44 @@ std::thread_local! { const { std::cell::Cell::new(None) }; } +/// The canonical record from the platform's store. pub fn load() -> CanonicalRead { + load_via(storage_authority(), &mut client::NativeTransport) +} + +/// [`load`] with the authority and the helper's transport as parameters. The transport is touched +/// only by [`Authority::Helper`]. +pub(super) fn load_via(authority: Authority, helper: &mut dyn client::Transport) -> CanonicalRead { + match authority { + Authority::Helper => load_helper_with(helper), + Authority::Files => load_file(), + } +} + +/// The record files' read. A test may substitute it (`READ_FOR_TEST`), which only ever stands in +/// for this store: the helper arm is read through its transport. +fn load_file() -> CanonicalRead { #[cfg(any(test, feature = "test-support"))] if let Some(read) = READ_FOR_TEST.with(|hook| hook.get()) { return read(); } - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - return load_helper(); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let store = match store() { - Ok(store) => store, - Err(error) => return CanonicalRead::Blocked(error), - }; - match store.load(RecordKey::Session) { - Ok(None) => CanonicalRead::Missing, - Ok(Some(record)) => match record.state { - RecordState::Data { payload } => CanonicalRead::Data { - revision: record.revision, - payload, - }, - RecordState::Cleared => CanonicalRead::Cleared { - revision: record.revision, - kept: super::install_preferences::load().unwrap_or_default(), - }, + let store = match store() { + Ok(store) => store, + Err(error) => return CanonicalRead::Blocked(error), + }; + match store.load(RecordKey::Session) { + Ok(None) => CanonicalRead::Missing, + Ok(Some(record)) => match record.state { + RecordState::Data { payload } => CanonicalRead::Data { + revision: record.revision, + payload, }, - Err(error) => CanonicalRead::Blocked(error), - } + RecordState::Cleared => CanonicalRead::Cleared { + revision: record.revision, + kept: super::install_preferences::load().unwrap_or_default(), + }, + }, + Err(error) => CanonicalRead::Blocked(error), } } @@ -221,10 +221,6 @@ fn helper_rejection(code: plx_os::storage::wire::ErrorCode) -> StoreError { } } -fn load_helper() -> CanonicalRead { - load_helper_with(&mut client::NativeTransport) -} - pub fn load_helper_with(transport: &mut dyn client::Transport) -> CanonicalRead { match client::load_with(transport) { Ok(HelperLoad::Missing) => CanonicalRead::Missing, @@ -286,75 +282,81 @@ fn commit(record: Record) -> CanonicalCommit { } pub fn commit_data(payload: String) -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - let session = match serde_json::from_str::(&payload) { - Ok(session) => session, - Err(_) => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }; - return commit_session(&session, false, super::SaveAuthority::Routine); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let revision = match load() { - CanonicalRead::Data { revision, .. } - | CanonicalRead::Opened { revision, .. } - | CanonicalRead::Cleared { revision, .. } - | CanonicalRead::Locked { revision, .. } - | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { - Some(revision) => revision, - None => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }, - CanonicalRead::Missing => 1, - CanonicalRead::Blocked(error) => return CanonicalCommit::Failed(error), - }; - commit(Record::data(revision, payload)) + commit_data_via(storage_authority(), &mut client::NativeTransport, payload) +} + +/// [`commit_data`] with the authority and the helper's transport as parameters. The helper takes +/// the decoded session as a routine write; the files take the payload as it is. +pub(super) fn commit_data_via( + authority: Authority, + helper: &mut dyn client::Transport, + payload: String, +) -> CanonicalCommit { + match authority { + Authority::Helper => { + let session = match serde_json::from_str::(&payload) { + Ok(session) => session, + Err(_) => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }; + commit_session_with( + &session, + false, + super::SaveAuthority::Routine, + plx_os::tv::device::info().major, + helper, + ) + } + Authority::Files => commit_data_file(payload), } } +fn commit_data_file(payload: String) -> CanonicalCommit { + let revision = match load_file() { + CanonicalRead::Data { revision, .. } + | CanonicalRead::Opened { revision, .. } + | CanonicalRead::Cleared { revision, .. } + | CanonicalRead::Locked { revision, .. } + | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { + Some(revision) => revision, + None => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }, + CanonicalRead::Missing => 1, + CanonicalRead::Blocked(error) => return CanonicalCommit::Failed(error), + }; + commit(Record::data(revision, payload)) +} + pub fn commit_cleared() -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - return commit_clear(); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let revision = match load() { - CanonicalRead::Data { revision, .. } - | CanonicalRead::Opened { revision, .. } - | CanonicalRead::Cleared { revision, .. } - | CanonicalRead::Locked { revision, .. } - | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { - Some(revision) => revision, - None => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }, - CanonicalRead::Missing => 1, - CanonicalRead::Blocked(_) => 1, - }; - commit(Record::cleared(revision)) + commit_cleared_via(storage_authority(), &mut client::NativeTransport) +} + +/// [`commit_cleared`] with the authority and the helper's transport as parameters. +pub(super) fn commit_cleared_via( + authority: Authority, + helper: &mut dyn client::Transport, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_clear_with(helper), + Authority::Files => commit_cleared_file(), } } +fn commit_cleared_file() -> CanonicalCommit { + let revision = match load_file() { + CanonicalRead::Data { revision, .. } + | CanonicalRead::Opened { revision, .. } + | CanonicalRead::Cleared { revision, .. } + | CanonicalRead::Locked { revision, .. } + | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { + Some(revision) => revision, + None => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }, + CanonicalRead::Missing => 1, + CanonicalRead::Blocked(_) => 1, + }; + commit(Record::cleared(revision)) +} + /// Exact-payload migration. The caller owns keymanager semantics and legacy cleanup; this helper /// only commits the bytes and reports whether cleanup may proceed. pub fn migrate_exact(source: &Path, payload: &[u8]) -> (CanonicalCommit, PathBuf) { @@ -372,13 +374,25 @@ pub fn migrate_exact(source: &Path, payload: &[u8]) -> (CanonicalCommit, PathBuf /// Import an already decoded migration input through the same backend used by bootstrap. pub fn migrate_session(session: &super::Session) -> CanonicalCommit { - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - { - commit_session(session, true, super::SaveAuthority::Routine) - } - #[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] - { - write_session(session, super::SaveAuthority::Routine) + migrate_session_via(storage_authority(), &mut client::NativeTransport, session) +} + +/// [`migrate_session`] with the authority and the helper's transport as parameters. Only the helper +/// distinguishes a migration from a routine write (it advances the migration ledger). +pub(super) fn migrate_session_via( + authority: Authority, + helper: &mut dyn client::Transport, + session: &super::Session, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_session_with( + session, + true, + super::SaveAuthority::Routine, + plx_os::tv::device::info().major, + helper, + ), + Authority::Files => write_session_file(session), } } @@ -754,20 +768,6 @@ fn expected(snapshot: &client::Snapshot) -> Option<(&str, state::Expected)> { Some((&snapshot.db_rev, snapshot.state.expected())) } -fn commit_session( - session: &super::Session, - migration: bool, - authority: super::SaveAuthority, -) -> CanonicalCommit { - commit_session_with( - session, - migration, - authority, - plx_os::tv::device::info().major, - &mut client::NativeTransport, - ) -} - pub fn commit_session_with( session: &super::Session, migration: bool, @@ -901,17 +901,6 @@ pub fn commit_session_with( helper_commit_for_app_with(transport, expectation, operation, mutation) } -pub fn commit_session_with_authority( - session: &super::Session, - authority: super::SaveAuthority, -) -> CanonicalCommit { - commit_session(session, false, authority) -} - -fn commit_clear() -> CanonicalCommit { - commit_clear_with(&mut client::NativeTransport) -} - pub(super) fn commit_clear_with(transport: &mut dyn client::Transport) -> CanonicalCommit { let loaded = match client::load_with(transport) { Ok(loaded) => loaded, @@ -1184,22 +1173,38 @@ mod db8_policy_tests { let _ = std::fs::remove_dir_all(root); } + /// A television's helper keeps no app-owned rename temporaries, so there is nothing to sweep and + /// the root is left as it is; a files platform sweeps the abandoned ones its own commits left. + #[test] + fn the_helper_keeps_no_app_temporaries_and_the_files_sweep_theirs() { + let _serial = plx_base::testlock::serial(); + let root = TempPersistenceRoot::new("cleanup-temporaries"); + plx_base::paths::ensure_persistent_state_root().expect("a writable state root"); + let abandoned = root.dir.join(".session.json.new-0123456789abcdef0123456789abcdef"); + std::fs::write(&abandoned, b"temporary").unwrap(); + std::fs::set_permissions(&abandoned, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(cleanup_temporaries_for(Authority::Helper), Ok(())); + assert!(abandoned.exists(), "the helper arm sweeps nothing in the app's root"); + assert_eq!(cleanup_temporaries_for(Authority::Files), Ok(())); + assert!(!abandoned.exists(), "the files arm removes the abandoned temporary"); + } + /// `bootstrap()` and `cleanup_after_confirmed_clear()` must search and sweep the pre-DB8 - /// canonical JSON wrapper identically on ARM, so both funnel through this one helper rather - /// than each carrying its own `insert(0, path())`. This is callable unconditionally (it is - /// pure path arithmetic), so a host test can prove the shared assembly directly instead of - /// only trusting that the two ARM-gated call sites still agree. + /// canonical JSON wrapper identically where the helper is canonical, so both funnel through + /// this one helper rather than each carrying its own `insert(0, path())`. It is pure path + /// arithmetic, so a host test proves the shared assembly directly for either authority. Under + /// `Files` the wrapper is the store itself, so it is no migration source. #[test] - fn arm_candidate_assembly_puts_the_canonical_wrapper_first() { + fn the_candidates_a_platform_searches_follow_its_authority() { // `path()` reads the process-global persistent state root, which every redirecting test in // this binary moves under the lock. Two unlocked reads can straddle one of those moves, so // this takes the same lock: both reads then see one root. let _serial = plx_base::testlock::serial(); - let mut candidates = vec![PathBuf::from("/some/legacy/auth.json")]; - insert_arm_canonical_wrapper(&mut candidates); - assert_eq!(candidates[0], path()); - assert_eq!(candidates.len(), 2); - assert_eq!(candidates[1], PathBuf::from("/some/legacy/auth.json")); + let legacy = vec![PathBuf::from("/some/legacy/auth.json")]; + let helper = migration_candidates(Authority::Helper, legacy.clone()); + assert_eq!(helper, vec![path(), PathBuf::from("/some/legacy/auth.json")]); + let files = migration_candidates(Authority::Files, legacy.clone()); + assert_eq!(files, legacy, "the files platform's own store is never one of its migration sources"); } /// Point the canonical persistence root at a directory of this test's own; restore the @@ -1397,32 +1402,39 @@ pub fn write_session_timed( commit } -/// The authority-selected write used by the shared worker. ARM has exactly one authority: DB8. +/// The authority-selected write used by the shared worker. The platform has exactly one canonical +/// store at a time: the storage helper where it states one, the record files everywhere else. pub fn write_session( session: &super::Session, authority: super::SaveAuthority, ) -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - commit_session_with_authority(session, authority) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let _ = authority; - match serde_json::to_string(session) { - Ok(payload) => commit_data(payload), - Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), - } + write_session_via(storage_authority(), &mut client::NativeTransport, session, authority) +} + +/// [`write_session`] with the storage authority and the helper's transport as parameters. `save` is +/// how the caller may write ([`super::SaveAuthority`]); only the helper's protection rules read it. +pub(super) fn write_session_via( + authority: Authority, + helper: &mut dyn client::Transport, + session: &super::Session, + save: super::SaveAuthority, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_session_with( + session, + false, + save, + plx_os::tv::device::info().major, + helper, + ), + Authority::Files => write_session_file(session), + } +} + +fn write_session_file(session: &super::Session) -> CanonicalCommit { + match serde_json::to_string(session) { + Ok(payload) => commit_data_file(payload), + Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), } } @@ -1580,16 +1592,13 @@ impl MigrationStore for HelperMigration<'_> { struct FileMigration; impl MigrationStore for FileMigration { fn load(&mut self) -> CanonicalRead { - load() + load_file() } fn import(&mut self, session: &super::Session) -> CanonicalCommit { - match serde_json::to_string(session) { - Ok(payload) => commit_data(payload), - Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), - } + write_session_file(session) } fn clear(&mut self) -> CanonicalCommit { - commit_cleared() + commit_cleared_file() } } @@ -1722,13 +1731,17 @@ fn retire_exact_candidate(path: &Path, expected: &[u8]) -> bool { .is_some_and(|directory| directory.sync_all().is_ok()) } -/// The previous canonical JSON wrapper (`path()`, the pre-DB8 `session.json`) outranks older -/// bare candidates on ARM: it is a recognized migration source in its own right and must be -/// searched (on boot) and swept (on sign-out) ahead of the plain legacy files. Both call sites -/// that assemble an ARM candidate list must go through this one function so the two lists -/// cannot drift apart again. -fn insert_arm_canonical_wrapper(candidates: &mut Vec) { - candidates.insert(0, path()); +/// The migration sources a platform searches (on boot) and sweeps (on sign-out), given the legacy +/// files `base` names. Where the storage helper is canonical, the previous canonical JSON wrapper +/// (`path()`, the pre-DB8 `session.json`) outranks the older bare candidates: it is a recognized +/// migration source in its own right. Where the files are canonical it IS the store, never a +/// source. Both call sites that assemble a candidate list go through this one function so the two +/// lists cannot drift apart again. +fn migration_candidates(authority: Authority, mut base: Vec) -> Vec { + if authority == Authority::Helper { + base.insert(0, path()); + } + base } pub fn bootstrap(opener: &mut dyn LegacyOpener) -> Bootstrap { @@ -1736,32 +1749,25 @@ pub fn bootstrap(opener: &mut dyn LegacyOpener) -> Bootstrap { let candidates = plx_base::paths::session_migration_candidates(); #[cfg(any(test, feature = "test-support"))] let candidates = super::auth_paths(); - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - let mut candidates = candidates; - insert_arm_canonical_wrapper(&mut candidates); - bootstrap_with( - &mut HelperMigration { - transport: &mut client::NativeTransport, - major: plx_os::tv::device::info().major, - }, + bootstrap_via(storage_authority(), &mut client::NativeTransport, opener, candidates) +} + +/// [`bootstrap`] with the authority, the helper's transport and the legacy files `base` as +/// parameters. The canonical store is chosen here, before the loop, and never by a failed read. +pub(super) fn bootstrap_via( + authority: Authority, + helper: &mut dyn client::Transport, + opener: &mut dyn LegacyOpener, + base: Vec, +) -> Bootstrap { + let candidates = migration_candidates(authority, base); + match authority { + Authority::Helper => bootstrap_with( + &mut HelperMigration { transport: helper, major: plx_os::tv::device::info().major }, opener, &candidates, - ) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - bootstrap_with(&mut FileMigration, opener, &candidates) + ), + Authority::Files => bootstrap_with(&mut FileMigration, opener, &candidates), } } @@ -1793,24 +1799,28 @@ pub enum ClearCleanupOutcome { /// residues. Failed retirement remains visible: canonical Cleared shadows a residue only while /// the authority can answer, so a marked fallback must also be removed or neutralized. pub fn cleanup_after_confirmed_clear() -> ClearCleanupOutcome { - if !matches!(load(), CanonicalRead::Cleared { .. }) { - return ClearCleanupOutcome::AuthorityNotConfirmed; - } #[cfg(not(any(test, feature = "test-support")))] let candidates = plx_base::paths::session_migration_candidates(); #[cfg(any(test, feature = "test-support"))] let candidates = super::auth_paths(); - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - let candidates = { - let mut candidates = candidates; - insert_arm_canonical_wrapper(&mut candidates); - candidates - }; + cleanup_after_confirmed_clear_via( + storage_authority(), + &mut client::NativeTransport, + candidates, + ) +} + +/// [`cleanup_after_confirmed_clear`] with the authority, the helper's transport and the legacy +/// files `base` as parameters. +pub(super) fn cleanup_after_confirmed_clear_via( + authority: Authority, + helper: &mut dyn client::Transport, + base: Vec, +) -> ClearCleanupOutcome { + if !matches!(load_via(authority, helper), CanonicalRead::Cleared { .. }) { + return ClearCleanupOutcome::AuthorityNotConfirmed; + } + let candidates = migration_candidates(authority, base); let mut complete = super::retry_pending_retirements_locked(); for candidate in candidates { match plx_os::storage::read_owned_bytes(&candidate) { diff --git a/rust-modules/plex/src/plex/session_persistence_tests.rs b/rust-modules/plex/src/plex/session_persistence_tests.rs index 779cfbcc6..d6925e12b 100644 --- a/rust-modules/plex/src/plex/session_persistence_tests.rs +++ b/rust-modules/plex/src/plex/session_persistence_tests.rs @@ -584,7 +584,7 @@ fn clear_under_a_redirected_legacy_fixture_never_touches_the_canonical_authority /// `signout-leaves-token-in-unswept-candidates`: `clear()` must actually reach /// `persistence::cleanup_after_confirmed_clear()` after a durable canonical commit — the step /// that retires the full recognized migration-candidate set -/// (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON wrapper on ARM), +/// (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON wrapper where the helper is canonical), /// which is a strict superset of the legacy `auth_paths()` list `clear()`'s own loop sweeps. /// /// **On the honesty of this test**: `persistence::bootstrap`/`cleanup_after_confirmed_clear`