Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c0cd7c2c15 | |||
| ac002d8255 | |||
| 0fc1fa139e | |||
| 4f0c5bb808 | |||
| a6b22df666 | |||
| b402c01918 | |||
| be478acde7 | |||
| 379873765d | |||
| 713a292057 | |||
| 58c2dfd0a9 | |||
| 710555bd7e | |||
| 42a5f3bc3b | |||
| 19647b5209 | |||
| d8a255869c | |||
| f0336d784d | |||
| a218999243 | |||
| 55fa7df2bf | |||
| b2341c652b | |||
| 021c5d6ad8 | |||
| d1264a7797 | |||
| 7a5f03987d | |||
| 8eb316751d | |||
| d0c1db6c1d | |||
| 0d5204b5ec |
@@ -6,6 +6,47 @@ project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.42.0] — 2026-07-06
|
||||
|
||||
### Added
|
||||
|
||||
- **CI workspace gate.** New `test.yml` workflow runs clippy (deny warnings)
|
||||
and the full test suite on every master push and PR — previously no CI ran
|
||||
tests at all. Caught its own first bug (missing Bevy native deps) on its
|
||||
own PR. (#135)
|
||||
- **Schedule ambiguity gate.** A headless test builds the gameplay plugin
|
||||
cluster with Bevy ambiguity detection promoted to error. The initial
|
||||
measurement found 302 system pairs with conflicting data access and no
|
||||
ordering; four burn-down batches (PRs #146–#149) took it to ZERO the same
|
||||
day, and the gate now enforces 0. Keyboard consumption, board painting,
|
||||
and HUD updates all have deterministic order for the first time.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Browser canvas 36% smaller.** `canvas_bg.wasm` shrank 36.2 MB → 23.2 MB
|
||||
via a size-focused `wasm-release` profile (fat LTO, single codegen unit,
|
||||
opt-level "s"); verified visually identical in production. (#134)
|
||||
- **Quaternions API adoption.** Canonical `FOUNDATIONS`/`TABLEAUS` consts in
|
||||
`solitaire_core` replace five scattered enum lists; upstream
|
||||
`Suit::SUITS`/`Rank::RANKS` replace nine hand-rolled arrays, with the
|
||||
texture-atlas indexing re-keyed through tested canonical helpers. Net
|
||||
−177 lines. (#137)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Sync push race.** The server's load→merge→store cycle now runs in one
|
||||
transaction; concurrent pushes from two devices can no longer overwrite
|
||||
each other's merge. (#136)
|
||||
- **Refresh-token rotation is single-use under concurrency** — rotation
|
||||
gates on the DELETE's row count, so a stolen-then-replayed refresh token
|
||||
loses the race and gets 401. (#136)
|
||||
- **Exit sync push actually completes.** Was a detached task killed by
|
||||
process teardown; now a bounded 2-second blocking wait on the app's final
|
||||
frame. (#138)
|
||||
- **Server auth hardening.** Login timing no longer reveals whether a
|
||||
username exists; concurrent duplicate registration returns 409 instead of
|
||||
500; avatar uploads are magic-byte checked. (#144, issues #139–#141)
|
||||
|
||||
## [0.41.1] — 2026-07-06
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -19,5 +19,33 @@ pub use klondike::{DrawStockConfig, Foundation, Klondike, KlondikeInstruction, K
|
||||
// former `solitaire_data::solver` wrapper module.
|
||||
pub use game_state::{DEFAULT_SOLVE_MOVES_BUDGET, DEFAULT_SOLVE_STATES_BUDGET, SolveOutcome};
|
||||
|
||||
/// All four foundation slots, in slot order.
|
||||
///
|
||||
/// Canonical iteration source for `Foundation` — upstream `klondike` has no
|
||||
/// `Foundation::ALL` (unlike `Suit::SUITS` / `Rank::RANKS` in `card_game`),
|
||||
/// and inherent impls cannot be added to a foreign type, so the workspace
|
||||
/// const lives here. Use this instead of hand-rolling `[Foundation; 4]`
|
||||
/// arrays; scattered copies can silently diverge.
|
||||
pub const FOUNDATIONS: [Foundation; 4] = [
|
||||
Foundation::Foundation1,
|
||||
Foundation::Foundation2,
|
||||
Foundation::Foundation3,
|
||||
Foundation::Foundation4,
|
||||
];
|
||||
|
||||
/// All seven tableau columns, in column order (left to right on screen).
|
||||
///
|
||||
/// Canonical iteration source for `Tableau` — see [`FOUNDATIONS`] for why
|
||||
/// this lives here rather than upstream.
|
||||
pub const TABLEAUS: [Tableau; 7] = [
|
||||
Tableau::Tableau1,
|
||||
Tableau::Tableau2,
|
||||
Tableau::Tableau3,
|
||||
Tableau::Tableau4,
|
||||
Tableau::Tableau5,
|
||||
Tableau::Tableau6,
|
||||
Tableau::Tableau7,
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod proptest_tests;
|
||||
|
||||
@@ -74,9 +74,11 @@ pub const ALL_RANKS: [Rank; 13] = [
|
||||
Rank::King,
|
||||
];
|
||||
|
||||
/// Every suit in `Clubs, Diamonds, Hearts, Spades` order — matches
|
||||
/// `card_plugin::load_card_images` so the suit index used here lines
|
||||
/// up with `CardImageSet.faces[suit]`.
|
||||
/// Iteration order for the SVG generator and the pin test only —
|
||||
/// output files are keyed by `suit_filename`, so no runtime index
|
||||
/// depends on this order. Kept local (not `Suit::SUITS`) because
|
||||
/// reordering would churn the pinned snapshot ordering for no
|
||||
/// benefit.
|
||||
pub const ALL_SUITS: [Suit; 4] = [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades];
|
||||
|
||||
/// The rank component of the on-disk filename — `A`, `2`..`10`, `J`,
|
||||
|
||||
@@ -46,6 +46,11 @@ pub struct AutoCompleteState {
|
||||
/// Plugin that drives the auto-complete sequence.
|
||||
pub struct AutoCompletePlugin;
|
||||
|
||||
/// Set wrapping the auto-complete detect/drive chain; HUD readers of
|
||||
/// [`AutoCompleteState`] order themselves after it (#143).
|
||||
#[derive(bevy::ecs::schedule::SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct AutoComplete;
|
||||
|
||||
impl Plugin for AutoCompletePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<AutoCompleteState>()
|
||||
@@ -58,7 +63,9 @@ impl Plugin for AutoCompletePlugin {
|
||||
drive_auto_complete,
|
||||
)
|
||||
.chain()
|
||||
.after(GameMutation),
|
||||
.in_set(AutoComplete)
|
||||
.after(GameMutation)
|
||||
.before(crate::card_plugin::BoardVisuals),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +137,23 @@ pub const RED_SUIT_COLOUR_HC: Color = Color::srgb(1.000, 0.408, 0.408);
|
||||
/// high-contrast boost path.
|
||||
pub const BLACK_SUIT_COLOUR: Color = Color::srgb(0.910, 0.910, 0.910);
|
||||
|
||||
/// Canonical outer index of `s` in [`CardImageSet::faces`].
|
||||
///
|
||||
/// Derived from the upstream `card_game::Suit` discriminants (0..=3 in
|
||||
/// `Suit::SUITS` order), so every reader and writer of `faces` computes
|
||||
/// the same layout from the same source. Three hand-rolled copies of this
|
||||
/// mapping once lived in card_plugin and theme/plugin and were one
|
||||
/// reorder away from drawing the wrong art.
|
||||
pub(crate) const fn suit_index(s: solitaire_core::Suit) -> usize {
|
||||
s as usize
|
||||
}
|
||||
|
||||
/// Canonical inner index of `r` in [`CardImageSet::faces`] — upstream
|
||||
/// `card_game::Rank` discriminants are 1..=13 in `Rank::RANKS` order.
|
||||
pub(crate) const fn rank_index(r: solitaire_core::Rank) -> usize {
|
||||
r as usize - 1
|
||||
}
|
||||
|
||||
/// Pre-loaded [`Handle<Image>`]s for card face and back PNG textures.
|
||||
///
|
||||
/// Loaded once at startup by [`load_card_images`]. When this resource is
|
||||
@@ -146,8 +163,10 @@ pub const BLACK_SUIT_COLOUR: Color = Color::srgb(0.910, 0.910, 0.910);
|
||||
pub struct CardImageSet {
|
||||
/// Per-card face images indexed by `[suit][rank]`.
|
||||
///
|
||||
/// Suit order: Clubs=0, Diamonds=1, Hearts=2, Spades=3.
|
||||
/// Rank order: Ace=0, Two=1 … King=12.
|
||||
/// Layout is pinned to the upstream declaration order — index with
|
||||
/// [`suit_index`] / [`rank_index`], never a hand-rolled match.
|
||||
/// Suit order: `Suit::SUITS` (Spades=0, Hearts=1, Clubs=2, Diamonds=3).
|
||||
/// Rank order: `Rank::RANKS` (Ace=0 … King=12).
|
||||
pub faces: [[Handle<Image>; 13]; 4],
|
||||
/// One handle per unlockable card-back design (indices 0–4). These
|
||||
/// correspond to the legacy `assets/cards/backs/back_N.png` art, indexed
|
||||
@@ -514,6 +533,17 @@ fn should_apply_resize(now_secs: f32, last_applied_secs: f32) -> bool {
|
||||
/// Renders cards by reading `GameStateResource` on `StateChangedEvent`.
|
||||
pub struct CardPlugin;
|
||||
|
||||
/// System set for everything that paints the board: card sprites, pile
|
||||
/// markers, shadows, highlights, badges. Members mutate `Sprite` /
|
||||
/// `Transform` on board entities and run as a deterministic chain (see the
|
||||
/// registration in [`CardPlugin`]'s `build`); table-plugin marker painters
|
||||
/// order themselves after this set. UI-domain systems that touch `Sprite`/
|
||||
/// `Transform` on non-board entities (HUD text pulses, modal cards) declare
|
||||
/// `.ambiguous_with(BoardVisuals)` instead — the entity domains are
|
||||
/// disjoint by design (#143).
|
||||
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct BoardVisuals;
|
||||
|
||||
impl Plugin for CardPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
// PostStartup ensures TablePlugin's Startup system has inserted
|
||||
@@ -539,33 +569,45 @@ impl Plugin for CardPlugin {
|
||||
update_stock_empty_indicator_startup,
|
||||
),
|
||||
)
|
||||
// Layout recompute (UpdateOnResize) always precedes board
|
||||
// painting, and the painters run as ONE deterministic chain in
|
||||
// data-flow order: layout refinement → card authority → anims →
|
||||
// shadows → highlights → indicators → resize snapping → labels.
|
||||
// Every painter mutates card/marker Sprite+Transform, so without
|
||||
// the chain each pair is a scheduler ambiguity (#143). All
|
||||
// members are cheap and mostly change-gated; sequential
|
||||
// execution is not a cost that matters here.
|
||||
.configure_sets(
|
||||
Update,
|
||||
LayoutSystem::UpdateOnResize.before(BoardVisuals),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
update_tableau_fan_frac
|
||||
.after(GameMutation)
|
||||
.before(sync_cards_on_change),
|
||||
sync_cards_on_change.after(GameMutation),
|
||||
resync_cards_on_settings_change.before(sync_cards_on_change),
|
||||
start_flip_anim.after(GameMutation),
|
||||
update_tableau_fan_frac,
|
||||
resync_cards_on_settings_change,
|
||||
sync_cards_on_change,
|
||||
start_flip_anim,
|
||||
tick_flip_anim,
|
||||
update_drag_shadow,
|
||||
update_card_shadows_on_drag.after(sync_cards_on_change),
|
||||
tick_hint_highlight,
|
||||
update_card_shadows_on_drag,
|
||||
handle_right_click,
|
||||
tick_right_click_highlights,
|
||||
clear_right_click_highlights_on_state_change.after(GameMutation),
|
||||
clear_right_click_highlights_on_state_change,
|
||||
clear_right_click_highlights_on_pause,
|
||||
update_stock_empty_indicator.after(GameMutation),
|
||||
tick_hint_highlight,
|
||||
update_stock_empty_indicator,
|
||||
update_stock_count_badge
|
||||
.after(GameMutation)
|
||||
.run_if(resource_changed::<GameStateResource>),
|
||||
collect_resize_events.after(LayoutSystem::UpdateOnResize),
|
||||
snap_cards_on_window_resize.after(collect_resize_events),
|
||||
),
|
||||
collect_resize_events,
|
||||
snap_cards_on_window_resize,
|
||||
resize_android_corner_labels,
|
||||
)
|
||||
.chain()
|
||||
.in_set(BoardVisuals)
|
||||
.after(GameMutation),
|
||||
);
|
||||
|
||||
app.add_systems(Update, resize_android_corner_labels);
|
||||
app.add_systems(PostUpdate, rebuild_card_entity_index);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,25 +105,12 @@ pub(super) fn load_card_images(asset_server: Option<Res<AssetServer>>, mut comma
|
||||
return;
|
||||
};
|
||||
|
||||
const SUITS: [Suit; 4] = [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades];
|
||||
const RANKS: [Rank; 13] = [
|
||||
Rank::Ace,
|
||||
Rank::Two,
|
||||
Rank::Three,
|
||||
Rank::Four,
|
||||
Rank::Five,
|
||||
Rank::Six,
|
||||
Rank::Seven,
|
||||
Rank::Eight,
|
||||
Rank::Nine,
|
||||
Rank::Ten,
|
||||
Rank::Jack,
|
||||
Rank::Queen,
|
||||
Rank::King,
|
||||
];
|
||||
|
||||
// faces[suit_index(s)][rank_index(r)] — see the canonical helpers in
|
||||
// card_plugin::mod; building from SUITS/RANKS order matches them.
|
||||
let faces: [[Handle<Image>; 13]; 4] = std::array::from_fn(|si| {
|
||||
std::array::from_fn(|ri| asset_server.load(card_face_asset_path(RANKS[ri], SUITS[si])))
|
||||
std::array::from_fn(|ri| {
|
||||
asset_server.load(card_face_asset_path(Rank::RANKS[ri], Suit::SUITS[si]))
|
||||
})
|
||||
});
|
||||
let backs =
|
||||
std::array::from_fn(|i| asset_server.load(format!("cards/backs/classic/back_{i}.png")));
|
||||
@@ -149,27 +136,8 @@ pub(super) fn card_sprite(
|
||||
) -> Sprite {
|
||||
if let Some(set) = card_images {
|
||||
let image = if face_up {
|
||||
let suit_idx = match card.suit() {
|
||||
Suit::Clubs => 0,
|
||||
Suit::Diamonds => 1,
|
||||
Suit::Hearts => 2,
|
||||
Suit::Spades => 3,
|
||||
};
|
||||
let rank_idx = match card.rank() {
|
||||
Rank::Ace => 0,
|
||||
Rank::Two => 1,
|
||||
Rank::Three => 2,
|
||||
Rank::Four => 3,
|
||||
Rank::Five => 4,
|
||||
Rank::Six => 5,
|
||||
Rank::Seven => 6,
|
||||
Rank::Eight => 7,
|
||||
Rank::Nine => 8,
|
||||
Rank::Ten => 9,
|
||||
Rank::Jack => 10,
|
||||
Rank::Queen => 11,
|
||||
Rank::King => 12,
|
||||
};
|
||||
let suit_idx = suit_index(card.suit());
|
||||
let rank_idx = rank_index(card.rank());
|
||||
set.faces[suit_idx][rank_idx].clone()
|
||||
} else if let Some(theme_back) = &set.theme_back {
|
||||
// Active theme provides its own back — always wins over the
|
||||
@@ -519,23 +487,10 @@ pub(super) fn all_cards(game: &GameState) -> Vec<(Card, bool)> {
|
||||
let mut cards: Vec<(Card, bool)> = Vec::with_capacity(52);
|
||||
cards.extend(game.stock_cards());
|
||||
cards.extend(game.waste_cards());
|
||||
for foundation in [
|
||||
Foundation::Foundation1,
|
||||
Foundation::Foundation2,
|
||||
Foundation::Foundation3,
|
||||
Foundation::Foundation4,
|
||||
] {
|
||||
for foundation in solitaire_core::FOUNDATIONS {
|
||||
cards.extend(game.pile(KlondikePile::Foundation(foundation)));
|
||||
}
|
||||
for tableau in [
|
||||
Tableau::Tableau1,
|
||||
Tableau::Tableau2,
|
||||
Tableau::Tableau3,
|
||||
Tableau::Tableau4,
|
||||
Tableau::Tableau5,
|
||||
Tableau::Tableau6,
|
||||
Tableau::Tableau7,
|
||||
] {
|
||||
for tableau in solitaire_core::TABLEAUS {
|
||||
cards.extend(game.pile(KlondikePile::Tableau(tableau)));
|
||||
}
|
||||
cards
|
||||
|
||||
@@ -63,6 +63,29 @@ pub struct GameOverScreen;
|
||||
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct GameMutation;
|
||||
|
||||
/// System set for every writer of [`crate::events::NewGameRequestEvent`].
|
||||
///
|
||||
/// Many UI entry points fire this trigger (buttons, keyboard, modals,
|
||||
/// mode pickers). Their relative append order within a frame is
|
||||
/// meaningless — consumers drain the whole queue — so members are
|
||||
/// registered `.in_set(NewGameRequestWriters).ambiguous_with(NewGameRequestWriters)`
|
||||
/// to declare writer-vs-writer order irrelevant instead of leaving it as an
|
||||
/// ambiguity (#143). Only ever combine with `.ambiguous_with` on the same
|
||||
/// set; do NOT hang ordering edges off this set.
|
||||
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct NewGameRequestWriters;
|
||||
|
||||
/// Self-ambiguous set for writers of `UndoRequestEvent` — same rationale as
|
||||
/// [`NewGameRequestWriters`]: consumers drain the queue, append order is
|
||||
/// meaningless (#143).
|
||||
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct UndoRequestWriters;
|
||||
|
||||
/// Self-ambiguous set for writers of `InfoToastEvent` — toasts queue in
|
||||
/// arrival order and any same-frame order is fine (#143).
|
||||
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct InfoToastWriters;
|
||||
|
||||
/// Persistence path for the in-progress game state file. `None` disables I/O.
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct GameStatePath(pub Option<PathBuf>);
|
||||
@@ -208,28 +231,66 @@ impl Plugin for GamePlugin {
|
||||
.add_message::<AppLifecycle>()
|
||||
// add_message is idempotent; SettingsPlugin also registers this.
|
||||
.add_message::<crate::settings_plugin::SettingsChangedEvent>()
|
||||
.add_systems(Update, poll_pending_new_game_seed.before(GameMutation))
|
||||
.add_systems(
|
||||
Update,
|
||||
poll_pending_new_game_seed
|
||||
.before(GameMutation)
|
||||
.in_set(NewGameRequestWriters)
|
||||
.ambiguous_with(NewGameRequestWriters),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(handle_new_game, handle_draw, handle_move, handle_undo)
|
||||
.chain()
|
||||
.in_set(GameMutation),
|
||||
)
|
||||
.add_systems(Update, check_no_moves.after(GameMutation))
|
||||
.add_systems(
|
||||
Update,
|
||||
check_no_moves
|
||||
.after(GameMutation)
|
||||
.before(crate::card_plugin::BoardVisuals)
|
||||
.in_set(InfoToastWriters)
|
||||
.ambiguous_with(InfoToastWriters),
|
||||
)
|
||||
.add_systems(Update, record_replay_on_win.after(GameMutation))
|
||||
.add_systems(Update, handle_confirm_input.after(GameMutation))
|
||||
.add_systems(Update, handle_confirm_button_input.after(GameMutation))
|
||||
.add_systems(Update, handle_game_over_input.after(GameMutation))
|
||||
.add_systems(Update, handle_game_over_button_input.after(GameMutation))
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
handle_confirm_input,
|
||||
handle_confirm_button_input,
|
||||
handle_game_over_input,
|
||||
handle_game_over_button_input,
|
||||
)
|
||||
.after(GameMutation)
|
||||
.before(crate::ui_focus::FocusKeys)
|
||||
.in_set(NewGameRequestWriters)
|
||||
.ambiguous_with(NewGameRequestWriters)
|
||||
.in_set(UndoRequestWriters)
|
||||
.ambiguous_with(UndoRequestWriters),
|
||||
)
|
||||
// Restore prompt: spawn the modal once the splash is gone,
|
||||
// route Continue / New Game intents back into the existing
|
||||
// GameMutation flow.
|
||||
.add_systems(Update, spawn_restore_prompt_if_pending)
|
||||
.add_systems(Update, handle_restore_prompt.before(GameMutation))
|
||||
.add_systems(Update, sync_settings_to_game.before(GameMutation))
|
||||
// All pre-mutation game-state writers are chained: elapsed
|
||||
// time ticks first, settings sync next, then the restore prompt —
|
||||
// a deterministic spine instead of three unordered ResMut holders
|
||||
// (ambiguity burn-down, #143).
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
tick_elapsed_time,
|
||||
sync_settings_to_game,
|
||||
spawn_restore_prompt_if_pending,
|
||||
handle_restore_prompt
|
||||
.in_set(NewGameRequestWriters)
|
||||
.ambiguous_with(NewGameRequestWriters),
|
||||
)
|
||||
.chain()
|
||||
.after(crate::settings_plugin::SettingsMutation)
|
||||
.before(GameMutation),
|
||||
)
|
||||
.init_resource::<AutoSaveTimer>()
|
||||
.add_systems(Update, tick_elapsed_time)
|
||||
.add_systems(Update, auto_save_game_state)
|
||||
.add_systems(Update, auto_save_game_state.after(GameMutation))
|
||||
.add_systems(Last, save_game_state_on_exit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ use crate::events::{
|
||||
UndoRequestEvent, WinStreakMilestoneEvent,
|
||||
};
|
||||
use crate::font_plugin::FontResource;
|
||||
use crate::game_plugin::GameMutation;
|
||||
use crate::game_plugin::{GameMutation, NewGameRequestWriters};
|
||||
#[cfg(target_os = "android")]
|
||||
use crate::input_plugin::TouchDragSet;
|
||||
use crate::layout::HUD_BAND_HEIGHT;
|
||||
@@ -54,6 +54,7 @@ use crate::time_attack_plugin::TimeAttackResource;
|
||||
use crate::ui_focus::{FocusGroup, Focusable};
|
||||
use crate::ui_modal::ModalScrim;
|
||||
use crate::ui_theme::SPACE_2;
|
||||
use crate::ui_theme::UiTextFx;
|
||||
use crate::ui_theme::{
|
||||
ACCENT_PRIMARY, ACCENT_SECONDARY, BG_ELEVATED, BG_ELEVATED_HI, BG_ELEVATED_PRESSED,
|
||||
BG_HUD_BAND, BORDER_SUBTLE, HighContrastBorder, MOTION_SCORE_PULSE_SECS,
|
||||
@@ -153,6 +154,13 @@ pub struct HudColumn;
|
||||
#[derive(Component, Debug)]
|
||||
pub struct HudActionBar;
|
||||
|
||||
/// Set wrapping the chained HUD button/popover interaction systems. Other
|
||||
/// keyboard consumers order themselves around it (e.g.
|
||||
/// [`crate::ui_focus::FocusKeys`] runs after) so input-consumption order is
|
||||
/// deterministic (#143).
|
||||
#[derive(bevy::ecs::schedule::SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct HudButtons;
|
||||
|
||||
/// Marker on the text node inside each touch-layout action-bar button.
|
||||
/// Used by `resize_action_bar_labels` to update font size on window resize.
|
||||
#[derive(Component, Debug)]
|
||||
@@ -467,23 +475,56 @@ impl Plugin for HudPlugin {
|
||||
// defensively so the HUD plugin works standalone in tests.
|
||||
.add_message::<WindowResized>()
|
||||
.add_systems(Startup, (spawn_hud_band, spawn_hud, spawn_action_buttons, spawn_hud_avatar))
|
||||
.add_systems(Update, update_hud.after(GameMutation))
|
||||
.add_systems(
|
||||
Update,
|
||||
apply_hud_visibility.before(LayoutSystem::UpdateOnResize),
|
||||
)
|
||||
.add_systems(Update, restore_hud_on_modal)
|
||||
.add_systems(Update, (update_hud_avatar, handle_avatar_button))
|
||||
.add_systems(Update, update_won_previously.after(GameMutation))
|
||||
.add_systems(Update, announce_auto_complete.after(GameMutation))
|
||||
// HUD text updaters run as one deterministic chain (they write
|
||||
// disjoint Text nodes, but Bevy can't prove it); update_hud also
|
||||
// reads AutoCompleteState, so the chain sits after the
|
||||
// auto-complete detect/drive chain (#143).
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
update_hud,
|
||||
update_selection_hud.run_if(
|
||||
resource_exists_and_changed::<SelectionState>
|
||||
.or(resource_exists_and_changed::<GameStateResource>),
|
||||
),
|
||||
update_won_previously,
|
||||
)
|
||||
.chain()
|
||||
.after(GameMutation)
|
||||
.after(crate::auto_complete_plugin::AutoComplete)
|
||||
.in_set(UiTextFx)
|
||||
.ambiguous_with(UiTextFx),
|
||||
)
|
||||
// HUD chrome visibility: modal-restore writes HudVisibility, the
|
||||
// applier consumes it, and the layout recompute reads it — a
|
||||
// fixed chain instead of three racing systems (#143).
|
||||
.add_systems(
|
||||
Update,
|
||||
(restore_hud_on_modal, apply_hud_visibility)
|
||||
.chain()
|
||||
.before(LayoutSystem::UpdateOnResize),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
update_hud_avatar.after(crate::settings_plugin::SettingsMutation),
|
||||
handle_avatar_button.ambiguous_with(HudButtons),
|
||||
),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
announce_auto_complete
|
||||
.after(GameMutation)
|
||||
.after(crate::auto_complete_plugin::AutoComplete)
|
||||
.in_set(crate::game_plugin::InfoToastWriters)
|
||||
.ambiguous_with(crate::game_plugin::InfoToastWriters),
|
||||
)
|
||||
// Typography rescale touches HUD TextFont only, but orders after
|
||||
// the board painters that resize card/label text (#143).
|
||||
.add_systems(
|
||||
Update,
|
||||
update_hud_typography.after(crate::card_plugin::BoardVisuals),
|
||||
)
|
||||
.add_systems(Update, update_hud_typography)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
@@ -492,24 +533,40 @@ impl Plugin for HudPlugin {
|
||||
advance_score_floater,
|
||||
)
|
||||
.chain()
|
||||
.after(GameMutation),
|
||||
.after(GameMutation)
|
||||
.in_set(UiTextFx)
|
||||
.ambiguous_with(UiTextFx)
|
||||
.ambiguous_with(crate::card_plugin::BoardVisuals),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(start_streak_flourish, advance_streak_flourish)
|
||||
.chain()
|
||||
.after(GameMutation),
|
||||
.after(GameMutation)
|
||||
.in_set(UiTextFx)
|
||||
.ambiguous_with(UiTextFx)
|
||||
.ambiguous_with(crate::card_plugin::BoardVisuals),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
handle_new_game_button,
|
||||
handle_undo_button,
|
||||
handle_new_game_button
|
||||
.in_set(NewGameRequestWriters)
|
||||
.ambiguous_with(NewGameRequestWriters),
|
||||
handle_undo_button
|
||||
.in_set(crate::game_plugin::UndoRequestWriters)
|
||||
.ambiguous_with(crate::game_plugin::UndoRequestWriters)
|
||||
.before(GameMutation),
|
||||
handle_pause_button,
|
||||
handle_help_button,
|
||||
handle_hint_button,
|
||||
handle_hint_button
|
||||
.after(GameMutation)
|
||||
.in_set(crate::game_plugin::InfoToastWriters)
|
||||
.ambiguous_with(crate::game_plugin::InfoToastWriters),
|
||||
handle_modes_button,
|
||||
handle_mode_option_click,
|
||||
handle_mode_option_click
|
||||
.in_set(NewGameRequestWriters)
|
||||
.ambiguous_with(NewGameRequestWriters),
|
||||
handle_modes_backdrop_click,
|
||||
close_modes_popover_on_escape,
|
||||
handle_menu_button,
|
||||
@@ -517,7 +574,10 @@ impl Plugin for HudPlugin {
|
||||
handle_menu_backdrop_click,
|
||||
close_menu_popover_on_escape,
|
||||
paint_action_buttons,
|
||||
),
|
||||
)
|
||||
.chain()
|
||||
.in_set(HudButtons)
|
||||
.before(crate::ui_focus::FocusKeys),
|
||||
)
|
||||
// Fade lives in `Last` so it always overrides whatever the
|
||||
// hover/paint pass set on `BackgroundColor` this frame.
|
||||
|
||||
@@ -28,6 +28,7 @@ use bevy::window::PrimaryWindow;
|
||||
#[cfg(not(target_os = "android"))]
|
||||
use bevy::window::{MonitorSelection, WindowMode};
|
||||
use solitaire_core::{Foundation, KlondikeInstruction, KlondikePile, Tableau};
|
||||
use solitaire_core::{FOUNDATIONS, TABLEAUS};
|
||||
use solitaire_core::{Card, Suit};
|
||||
use solitaire_core::game_state::GameState;
|
||||
|
||||
@@ -1329,13 +1330,13 @@ const DOUBLE_TAP_FLASH_SECS: f32 = 0.35;
|
||||
pub fn best_destination(card: &Card, game: &GameState) -> Option<KlondikePile> {
|
||||
let source = game.pile_containing_card(card.clone())?;
|
||||
|
||||
for foundation in foundations() {
|
||||
for foundation in FOUNDATIONS {
|
||||
let dest = KlondikePile::Foundation(foundation);
|
||||
if game.can_move_cards(&source, &dest, 1) {
|
||||
return Some(dest);
|
||||
}
|
||||
}
|
||||
for tableau in tableaus() {
|
||||
for tableau in TABLEAUS {
|
||||
let dest = KlondikePile::Tableau(tableau);
|
||||
if game.can_move_cards(&source, &dest, 1) {
|
||||
return Some(dest);
|
||||
@@ -1356,7 +1357,7 @@ pub fn best_tableau_destination_for_stack(
|
||||
game: &GameState,
|
||||
stack_count: usize,
|
||||
) -> Option<(KlondikePile, usize)> {
|
||||
for tableau in tableaus() {
|
||||
for tableau in TABLEAUS {
|
||||
let dest = KlondikePile::Tableau(tableau);
|
||||
if game.can_move_cards(from, &dest, stack_count) {
|
||||
return Some((dest, stack_count));
|
||||
@@ -1692,7 +1693,7 @@ pub(crate) fn hint_piles(
|
||||
fn legacy_all_hints(game: &GameState) -> Vec<(KlondikePile, KlondikePile)> {
|
||||
let sources: Vec<KlondikePile> = {
|
||||
let mut s = vec![KlondikePile::Stock];
|
||||
for tableau in tableaus() {
|
||||
for tableau in TABLEAUS {
|
||||
s.push(KlondikePile::Tableau(tableau));
|
||||
}
|
||||
s
|
||||
@@ -1706,7 +1707,7 @@ fn legacy_all_hints(game: &GameState) -> Vec<(KlondikePile, KlondikePile)> {
|
||||
let Some(_card) = from_pile.last().filter(|(_, face_up)| *face_up) else {
|
||||
continue;
|
||||
};
|
||||
for foundation in foundations() {
|
||||
for foundation in FOUNDATIONS {
|
||||
let dest = KlondikePile::Foundation(foundation);
|
||||
if game.can_move_cards(from, &dest, 1) {
|
||||
hints.push((*from, dest));
|
||||
@@ -1728,7 +1729,7 @@ fn legacy_all_hints(game: &GameState) -> Vec<(KlondikePile, KlondikePile)> {
|
||||
if already_has_foundation_hint {
|
||||
continue;
|
||||
}
|
||||
for tableau in tableaus() {
|
||||
for tableau in TABLEAUS {
|
||||
let dest = KlondikePile::Tableau(tableau);
|
||||
if game.can_move_cards(from, &dest, 1) {
|
||||
hints.push((*from, dest));
|
||||
@@ -1742,13 +1743,13 @@ fn legacy_all_hints(game: &GameState) -> Vec<(KlondikePile, KlondikePile)> {
|
||||
// should never hint Foundation→Foundation. Here we handle the return path
|
||||
// separately so the guarded `take_from_foundation` rule is respected.
|
||||
if game.take_from_foundation {
|
||||
for foundation in foundations() {
|
||||
for foundation in FOUNDATIONS {
|
||||
let from = KlondikePile::Foundation(foundation);
|
||||
let from_pile = pile_cards(game, &from);
|
||||
let Some(_card) = from_pile.last().filter(|(_, face_up)| *face_up) else {
|
||||
continue;
|
||||
};
|
||||
for tableau in tableaus() {
|
||||
for tableau in TABLEAUS {
|
||||
let dest = KlondikePile::Tableau(tableau);
|
||||
if game.can_move_cards(&from, &dest, 1) {
|
||||
hints.push((from, dest));
|
||||
@@ -1782,26 +1783,7 @@ fn pile_cards(game: &GameState, pile: &KlondikePile) -> Vec<(Card, bool)> {
|
||||
}
|
||||
}
|
||||
|
||||
const fn foundations() -> [Foundation; 4] {
|
||||
[
|
||||
Foundation::Foundation1,
|
||||
Foundation::Foundation2,
|
||||
Foundation::Foundation3,
|
||||
Foundation::Foundation4,
|
||||
]
|
||||
}
|
||||
|
||||
const fn tableaus() -> [Tableau; 7] {
|
||||
[
|
||||
Tableau::Tableau1,
|
||||
Tableau::Tableau2,
|
||||
Tableau::Tableau3,
|
||||
Tableau::Tableau4,
|
||||
Tableau::Tableau5,
|
||||
Tableau::Tableau6,
|
||||
Tableau::Tableau7,
|
||||
]
|
||||
}
|
||||
|
||||
const fn tableau_number(tableau: Tableau) -> u8 {
|
||||
match tableau {
|
||||
|
||||
@@ -43,6 +43,7 @@ pub mod replay_overlay;
|
||||
pub mod replay_playback;
|
||||
pub mod resources;
|
||||
pub mod safe_area;
|
||||
mod schedule_checks;
|
||||
pub mod selection_plugin;
|
||||
pub mod settings_plugin;
|
||||
pub mod splash_plugin;
|
||||
|
||||
@@ -220,32 +220,11 @@ mod tests {
|
||||
] {
|
||||
game.set_test_foundation_cards(foundation, Vec::new());
|
||||
}
|
||||
for tableau in [
|
||||
Tableau::Tableau1,
|
||||
Tableau::Tableau2,
|
||||
Tableau::Tableau3,
|
||||
Tableau::Tableau4,
|
||||
Tableau::Tableau5,
|
||||
Tableau::Tableau6,
|
||||
Tableau::Tableau7,
|
||||
] {
|
||||
for tableau in solitaire_core::TABLEAUS {
|
||||
game.set_test_tableau_cards(tableau, Vec::new());
|
||||
}
|
||||
let suits = [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades];
|
||||
let ranks_below_king = [
|
||||
Rank::Ace,
|
||||
Rank::Two,
|
||||
Rank::Three,
|
||||
Rank::Four,
|
||||
Rank::Five,
|
||||
Rank::Six,
|
||||
Rank::Seven,
|
||||
Rank::Eight,
|
||||
Rank::Nine,
|
||||
Rank::Ten,
|
||||
Rank::Jack,
|
||||
Rank::Queen,
|
||||
];
|
||||
let suits = Suit::SUITS;
|
||||
let ranks_below_king = &Rank::RANKS[..12]; // everything below King
|
||||
for (foundation, suit) in [
|
||||
Foundation::Foundation1,
|
||||
Foundation::Foundation2,
|
||||
|
||||
@@ -48,6 +48,7 @@ use bevy::math::Vec2;
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::PrimaryWindow;
|
||||
use solitaire_core::{Foundation, KlondikePile, Tableau};
|
||||
use solitaire_core::{FOUNDATIONS, TABLEAUS};
|
||||
use solitaire_core::Card;
|
||||
use solitaire_core::game_state::GameState;
|
||||
|
||||
@@ -254,13 +255,13 @@ pub fn legal_destinations_for_card(
|
||||
game: &GameState,
|
||||
) -> Vec<KlondikePile> {
|
||||
let mut out = Vec::new();
|
||||
for foundation in foundations() {
|
||||
for foundation in FOUNDATIONS {
|
||||
let dest = KlondikePile::Foundation(foundation);
|
||||
if game.can_move_cards(source_pile, &dest, 1) {
|
||||
out.push(dest);
|
||||
}
|
||||
}
|
||||
for tableau in tableaus() {
|
||||
for tableau in TABLEAUS {
|
||||
let dest = KlondikePile::Tableau(tableau);
|
||||
if game.can_move_cards(source_pile, &dest, 1) {
|
||||
out.push(dest);
|
||||
@@ -360,26 +361,7 @@ fn pile_cards(game: &GameState, pile: &KlondikePile) -> Vec<(Card, bool)> {
|
||||
}
|
||||
|
||||
|
||||
const fn foundations() -> [Foundation; 4] {
|
||||
[
|
||||
Foundation::Foundation1,
|
||||
Foundation::Foundation2,
|
||||
Foundation::Foundation3,
|
||||
Foundation::Foundation4,
|
||||
]
|
||||
}
|
||||
|
||||
const fn tableaus() -> [Tableau; 7] {
|
||||
[
|
||||
Tableau::Tableau1,
|
||||
Tableau::Tableau2,
|
||||
Tableau::Tableau3,
|
||||
Tableau::Tableau4,
|
||||
Tableau::Tableau5,
|
||||
Tableau::Tableau6,
|
||||
Tableau::Tableau7,
|
||||
]
|
||||
}
|
||||
|
||||
/// Builds the `(destination, anchor)` list for a fresh radial open.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Schedule hygiene checks (issue #143).
|
||||
//!
|
||||
//! Bevy runs systems with conflicting data access in nondeterministic order
|
||||
//! unless an ordering edge exists. Nothing enforced this historically, and
|
||||
//! the headless gameplay cluster carries a large legacy backlog of such
|
||||
//! pairs — most benign (event/resource writers that never observably race),
|
||||
//! but unproven. Rather than a permanently red hard-error test or no test
|
||||
//! at all, this is a RATCHET: the count may only go down. New conflicting
|
||||
//! pairs fail CI immediately; the backlog can be triaged incrementally
|
||||
//! (add `.before`/`.after` where order matters, `.ambiguous_with` where it
|
||||
//! provably doesn't, then lower `AMBIGUITY_BASELINE`).
|
||||
//!
|
||||
//! To see the offending pair names, add the `bevy_debug` / debug feature to
|
||||
//! the bevy dev-dependency (system names are stripped otherwise) and set
|
||||
//! `ambiguity_detection: LogLevel::Error` manually.
|
||||
//!
|
||||
//! Scope note: `CoreGamePlugin` (the full composition) performs real
|
||||
//! storage/platform I/O in `build` and cannot run in a unit test; the
|
||||
//! cluster below is the same one the engine's headless behaviour tests use.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bevy::ecs::schedule::{LogLevel, ScheduleBuildSettings};
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::auto_complete_plugin::AutoCompletePlugin;
|
||||
use crate::card_plugin::CardPlugin;
|
||||
use crate::game_plugin::GamePlugin;
|
||||
use crate::hud_plugin::HudPlugin;
|
||||
use crate::settings_plugin::SettingsPlugin;
|
||||
use crate::table_plugin::TablePlugin;
|
||||
use crate::ui_focus::UiFocusPlugin;
|
||||
use crate::ui_modal::UiModalPlugin;
|
||||
|
||||
/// The backlog (302 pairs on 2026-07-06) was burned down to ZERO the
|
||||
/// same day (#143, PRs #146–#149) — this is now a hard gate. If your
|
||||
/// change trips this assertion you have added a pair of systems with
|
||||
/// conflicting data access and no ordering edge: add `.before`/`.after`
|
||||
/// where order matters, or `.ambiguous_with` the relevant domain set
|
||||
/// (BoardVisuals, MarkerVisuals, UiTextFx, HudButtons, writer sets)
|
||||
/// where it provably does not. Do not raise this constant.
|
||||
const AMBIGUITY_BASELINE: usize = 0;
|
||||
|
||||
fn cluster_app() -> App {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(MinimalPlugins)
|
||||
.add_plugins(GamePlugin)
|
||||
.add_plugins(TablePlugin)
|
||||
.add_plugins(CardPlugin)
|
||||
.add_plugins(HudPlugin)
|
||||
.add_plugins(AutoCompletePlugin)
|
||||
.add_plugins(UiModalPlugin)
|
||||
.add_plugins(UiFocusPlugin)
|
||||
.add_plugins(SettingsPlugin::headless());
|
||||
app.init_resource::<ButtonInput<KeyCode>>();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_schedule_ambiguities_do_not_grow() {
|
||||
let mut app = cluster_app();
|
||||
app.edit_schedule(Update, |s| {
|
||||
s.set_build_settings(ScheduleBuildSettings {
|
||||
ambiguity_detection: LogLevel::Error,
|
||||
..Default::default()
|
||||
});
|
||||
});
|
||||
|
||||
// With LogLevel::Error the first schedule build panics when any
|
||||
// ambiguity exists, and the panic message begins with the pair
|
||||
// count. Catch it and ratchet on that count. (Parsing a panic
|
||||
// message is brittle by design — if a Bevy upgrade rewords it,
|
||||
// this test fails loudly and the parse below needs one-line
|
||||
// maintenance, which is preferable to losing the ratchet.)
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
app.update();
|
||||
}));
|
||||
|
||||
let count = match result {
|
||||
Ok(()) => 0,
|
||||
Err(payload) => {
|
||||
let msg = payload
|
||||
.downcast_ref::<String>()
|
||||
.cloned()
|
||||
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
|
||||
.unwrap_or_default();
|
||||
let parsed = msg
|
||||
.split(" pairs of systems")
|
||||
.next()
|
||||
.and_then(|prefix| prefix.split_whitespace().last())
|
||||
.and_then(|n| n.parse::<usize>().ok());
|
||||
parsed.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"ambiguity panic message no longer parseable (Bevy upgrade?): {msg}"
|
||||
)
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
count, AMBIGUITY_BASELINE,
|
||||
"system-order ambiguities changed from the enforced baseline. \
|
||||
Add .before/.after or .ambiguous_with at the new registration site \
|
||||
(or, if the count legitimately dropped below a nonzero baseline, \
|
||||
lower AMBIGUITY_BASELINE).",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,14 @@ pub struct PendingWindowGeometry {
|
||||
#[derive(Message, Debug, Clone)]
|
||||
pub struct SettingsChangedEvent(pub Settings);
|
||||
|
||||
/// System set for the systems that mutate [`SettingsResource`] every frame
|
||||
/// (hotkeys and window-geometry persistence). Ordered before
|
||||
/// [`crate::game_plugin::GameMutation`]; readers of settings should sit
|
||||
/// after this set (directly, or transitively via `.after(GameMutation)`)
|
||||
/// so they observe the current frame's settings deterministically (#143).
|
||||
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct SettingsMutation;
|
||||
|
||||
/// Marker on the root Settings panel entity.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct SettingsPanel;
|
||||
@@ -372,16 +380,37 @@ impl Plugin for SettingsPlugin {
|
||||
// also runs cleanly under `MinimalPlugins` (tests).
|
||||
.add_message::<WindowResized>()
|
||||
.add_message::<WindowMoved>()
|
||||
// Settings changes land before game logic runs: the mutator
|
||||
// chain (volume keys → geometry record → geometry persist) is a
|
||||
// deterministic spine, and the whole set precedes GameMutation so
|
||||
// every reader already ordered after GameMutation sees this
|
||||
// frame's settings transitively (ambiguity burn-down, #143).
|
||||
.configure_sets(
|
||||
Update,
|
||||
SettingsMutation
|
||||
.after(crate::layout::LayoutSystem::UpdateOnResize)
|
||||
.before(crate::game_plugin::GameMutation),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
handle_volume_keys,
|
||||
toggle_settings_screen,
|
||||
scroll_settings_panel,
|
||||
crate::ui_modal::touch_scroll_panel::<SettingsPanelScrollable>,
|
||||
record_window_geometry_changes,
|
||||
persist_window_geometry_after_debounce,
|
||||
),
|
||||
)
|
||||
.chain()
|
||||
.in_set(SettingsMutation),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
toggle_settings_screen
|
||||
.before(crate::ui_focus::FocusKeys)
|
||||
.ambiguous_with(crate::hud_plugin::HudButtons),
|
||||
scroll_settings_panel,
|
||||
crate::ui_modal::touch_scroll_panel::<SettingsPanelScrollable>,
|
||||
)
|
||||
.chain(),
|
||||
);
|
||||
|
||||
if self.ui_enabled {
|
||||
|
||||
@@ -272,12 +272,21 @@ fn poll_pull_result(
|
||||
}
|
||||
}
|
||||
|
||||
/// Last-schedule system: starts a best-effort push of the current local state
|
||||
/// on [`AppExit`] without blocking the Bevy main thread.
|
||||
/// Upper bound on how long [`push_on_exit`] may block the closing app.
|
||||
/// Long enough for one healthy round-trip; short enough that quitting
|
||||
/// never feels hung when the server is unreachable.
|
||||
const EXIT_PUSH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Last-schedule system: pushes the current local state on [`AppExit`],
|
||||
/// blocking the main thread for at most [`EXIT_PUSH_TIMEOUT`].
|
||||
///
|
||||
/// The detached task may be cut short by process teardown, so local atomic
|
||||
/// persistence remains the durable source of truth even if the final remote
|
||||
/// push does not complete.
|
||||
/// This deliberately blocks: the previous detached-task version was almost
|
||||
/// always cut short by process teardown, so the final session's push
|
||||
/// silently never happened (2026-07-06 review, finding M3). A bounded wait
|
||||
/// during the app's final frame is invisible to the player and lets the
|
||||
/// round-trip actually complete on a healthy network. On timeout or error
|
||||
/// the push is skipped — local atomic persistence remains the durable
|
||||
/// source of truth and the next launch's pull/push converges.
|
||||
fn push_on_exit(
|
||||
mut exit_events: MessageReader<AppExit>,
|
||||
provider: Res<SyncProviderResource>,
|
||||
@@ -292,16 +301,17 @@ fn push_on_exit(
|
||||
exit_events.clear();
|
||||
|
||||
let payload = build_payload(&stats.0, &achievements.0, &progress.0);
|
||||
let provider = provider.0.clone();
|
||||
let rt = rt.0.clone();
|
||||
AsyncComputeTaskPool::get()
|
||||
.spawn(async move {
|
||||
match rt.block_on(provider.push(&payload)) {
|
||||
Ok(_) | Err(SyncError::UnsupportedPlatform) => {}
|
||||
Err(e) => warn!("sync push on exit failed: {e}"),
|
||||
let result = rt
|
||||
.0
|
||||
.block_on(async { tokio::time::timeout(EXIT_PUSH_TIMEOUT, provider.0.push(&payload)).await });
|
||||
match result {
|
||||
Ok(Ok(_)) | Ok(Err(SyncError::UnsupportedPlatform)) => {}
|
||||
Ok(Err(e)) => warn!("sync push on exit failed: {e}"),
|
||||
Err(_) => warn!(
|
||||
"sync push on exit timed out after {}s; will sync on next launch",
|
||||
EXIT_PUSH_TIMEOUT.as_secs()
|
||||
),
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Update-schedule system: on each `GameWonEvent` push the just-completed
|
||||
|
||||
@@ -6,10 +6,12 @@
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::WindowResized;
|
||||
use solitaire_core::{Foundation, KlondikePile, Tableau};
|
||||
use solitaire_core::KlondikePile;
|
||||
use solitaire_core::{FOUNDATIONS, TABLEAUS};
|
||||
use solitaire_core::Suit;
|
||||
|
||||
use crate::events::{HintVisualEvent, StateChangedEvent};
|
||||
use crate::game_plugin::GameMutation;
|
||||
use crate::hud_plugin::HudVisibility;
|
||||
use crate::layout::{
|
||||
Layout, LayoutResource, LayoutSystem, TABLE_COLOUR, apply_dynamic_tableau_fan, compute_layout,
|
||||
@@ -83,6 +85,13 @@ pub struct HintPileHighlight {
|
||||
/// Registers the table background and pile-marker rendering.
|
||||
pub struct TablePlugin;
|
||||
|
||||
/// Set wrapping the pile-marker painter chain (theme, hint highlights,
|
||||
/// visibility). Runs after [`crate::card_plugin::BoardVisuals`]; chrome-fx
|
||||
/// systems that touch `Visibility` on UI entities declare themselves
|
||||
/// ambiguous with it (#143).
|
||||
#[derive(bevy::ecs::schedule::SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct MarkerVisuals;
|
||||
|
||||
impl Plugin for TablePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
// Register WindowResized so the plugin works under MinimalPlugins in
|
||||
@@ -99,10 +108,18 @@ impl Plugin for TablePlugin {
|
||||
(
|
||||
on_safe_area_changed.before(LayoutSystem::UpdateOnResize),
|
||||
on_window_resized.in_set(LayoutSystem::UpdateOnResize),
|
||||
// Marker painters: deterministic chain after the card
|
||||
// paint pipeline — markers and cards share Sprite/
|
||||
// Transform access (#143).
|
||||
(
|
||||
apply_theme_on_settings_change,
|
||||
apply_hint_pile_highlight,
|
||||
tick_hint_pile_highlights,
|
||||
sync_pile_marker_visibility,
|
||||
sync_pile_marker_visibility.after(GameMutation),
|
||||
)
|
||||
.chain()
|
||||
.in_set(MarkerVisuals)
|
||||
.after(crate::card_plugin::BoardVisuals),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -280,10 +297,10 @@ fn spawn_pile_markers(commands: &mut Commands, layout: &Layout) {
|
||||
|
||||
let mut piles: Vec<KlondikePile> = Vec::with_capacity(12);
|
||||
piles.push(KlondikePile::Stock);
|
||||
for foundation in foundations() {
|
||||
for foundation in FOUNDATIONS {
|
||||
piles.push(KlondikePile::Foundation(foundation));
|
||||
}
|
||||
for tableau in tableaus() {
|
||||
for tableau in TABLEAUS {
|
||||
piles.push(KlondikePile::Tableau(tableau));
|
||||
}
|
||||
|
||||
@@ -576,31 +593,13 @@ fn pile_cards(
|
||||
}
|
||||
}
|
||||
|
||||
const fn foundations() -> [Foundation; 4] {
|
||||
[
|
||||
Foundation::Foundation1,
|
||||
Foundation::Foundation2,
|
||||
Foundation::Foundation3,
|
||||
Foundation::Foundation4,
|
||||
]
|
||||
}
|
||||
|
||||
const fn tableaus() -> [Tableau; 7] {
|
||||
[
|
||||
Tableau::Tableau1,
|
||||
Tableau::Tableau2,
|
||||
Tableau::Tableau3,
|
||||
Tableau::Tableau4,
|
||||
Tableau::Tableau5,
|
||||
Tableau::Tableau6,
|
||||
Tableau::Tableau7,
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::game_plugin::GamePlugin;
|
||||
use solitaire_core::{Foundation, Tableau};
|
||||
|
||||
/// Minimal headless app — omits windowing so pile markers are spawned with
|
||||
/// the default 1280×800 layout and no camera is created.
|
||||
@@ -940,7 +939,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn suit_symbol_all_four_are_distinct() {
|
||||
let symbols: Vec<&str> = [Suit::Spades, Suit::Hearts, Suit::Diamonds, Suit::Clubs]
|
||||
let symbols: Vec<&str> = Suit::SUITS
|
||||
.iter()
|
||||
.map(suit_symbol)
|
||||
.collect();
|
||||
|
||||
@@ -62,22 +62,10 @@ impl CardKey {
|
||||
/// Iterator over all 52 valid keys, in suit-major / rank-ascending order.
|
||||
/// Used to enumerate the manifest's required entries.
|
||||
pub fn all() -> impl Iterator<Item = CardKey> {
|
||||
const SUITS: [Suit; 4] = [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades];
|
||||
const RANKS: [Rank; 13] = [
|
||||
Rank::Ace,
|
||||
Rank::Two,
|
||||
Rank::Three,
|
||||
Rank::Four,
|
||||
Rank::Five,
|
||||
Rank::Six,
|
||||
Rank::Seven,
|
||||
Rank::Eight,
|
||||
Rank::Nine,
|
||||
Rank::Ten,
|
||||
Rank::Jack,
|
||||
Rank::Queen,
|
||||
Rank::King,
|
||||
];
|
||||
// Order-independent enumeration — consumers check completeness and
|
||||
// round-trips, never positions.
|
||||
const SUITS: [Suit; 4] = Suit::SUITS;
|
||||
const RANKS: [Rank; 13] = Rank::RANKS;
|
||||
SUITS
|
||||
.into_iter()
|
||||
.flat_map(|s| RANKS.into_iter().map(move |r| CardKey::new(s, r)))
|
||||
|
||||
@@ -17,7 +17,7 @@ use solitaire_core::{Rank, Suit};
|
||||
use crate::assets::{
|
||||
bundled_theme_url, classic_theme_svg_bytes, dark_theme_svg_bytes, rasterize_svg, user_theme_dir,
|
||||
};
|
||||
use crate::card_plugin::CardImageSet;
|
||||
use crate::card_plugin::{CardImageSet, rank_index, suit_index};
|
||||
use crate::events::StateChangedEvent;
|
||||
|
||||
use super::loader::CardThemeLoader;
|
||||
@@ -242,22 +242,8 @@ fn sync_card_image_set_with_active_theme(
|
||||
/// `theme_back` when present, so writing here is sufficient to make
|
||||
/// every face-down card pick up the theme's art on the next sync.
|
||||
fn apply_theme_to_card_image_set(theme: &CardTheme, image_set: &mut CardImageSet) {
|
||||
for suit in [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades] {
|
||||
for rank in [
|
||||
Rank::Ace,
|
||||
Rank::Two,
|
||||
Rank::Three,
|
||||
Rank::Four,
|
||||
Rank::Five,
|
||||
Rank::Six,
|
||||
Rank::Seven,
|
||||
Rank::Eight,
|
||||
Rank::Nine,
|
||||
Rank::Ten,
|
||||
Rank::Jack,
|
||||
Rank::Queen,
|
||||
Rank::King,
|
||||
] {
|
||||
for suit in Suit::SUITS {
|
||||
for rank in Rank::RANKS {
|
||||
if let Some(handle) = theme.faces.get(&CardKey::new(suit, rank)) {
|
||||
image_set.faces[suit_index(suit)][rank_index(rank)] = handle.clone();
|
||||
}
|
||||
@@ -266,36 +252,7 @@ fn apply_theme_to_card_image_set(theme: &CardTheme, image_set: &mut CardImageSet
|
||||
image_set.theme_back = Some(theme.back.clone());
|
||||
}
|
||||
|
||||
/// Index used by [`CardImageSet::faces`] for a given suit. Mirrors
|
||||
/// the `card_plugin` doc comment: Clubs=0, Diamonds=1, Hearts=2, Spades=3.
|
||||
const fn suit_index(s: Suit) -> usize {
|
||||
match s {
|
||||
Suit::Clubs => 0,
|
||||
Suit::Diamonds => 1,
|
||||
Suit::Hearts => 2,
|
||||
Suit::Spades => 3,
|
||||
}
|
||||
}
|
||||
|
||||
/// Index used by [`CardImageSet::faces`] for a given rank.
|
||||
/// Ace=0, Two=1 … King=12.
|
||||
const fn rank_index(r: Rank) -> usize {
|
||||
match r {
|
||||
Rank::Ace => 0,
|
||||
Rank::Two => 1,
|
||||
Rank::Three => 2,
|
||||
Rank::Four => 3,
|
||||
Rank::Five => 4,
|
||||
Rank::Six => 5,
|
||||
Rank::Seven => 6,
|
||||
Rank::Eight => 7,
|
||||
Rank::Nine => 8,
|
||||
Rank::Ten => 9,
|
||||
Rank::Jack => 10,
|
||||
Rank::Queen => 11,
|
||||
Rank::King => 12,
|
||||
}
|
||||
}
|
||||
|
||||
/// Switches the active theme to the one served at
|
||||
/// `themes://<theme_id>/theme.ron`. Returns the new `Handle<CardTheme>`
|
||||
@@ -446,21 +403,17 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suit_index_ranges_match_card_plugin_layout() {
|
||||
assert_eq!(suit_index(Suit::Clubs), 0);
|
||||
assert_eq!(suit_index(Suit::Diamonds), 1);
|
||||
assert_eq!(suit_index(Suit::Hearts), 2);
|
||||
assert_eq!(suit_index(Suit::Spades), 3);
|
||||
fn suit_index_matches_upstream_suits_order() {
|
||||
for (i, s) in Suit::SUITS.iter().enumerate() {
|
||||
assert_eq!(suit_index(*s), i, "faces outer layout = Suit::SUITS order");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rank_index_starts_at_ace_zero_and_ends_at_king_twelve() {
|
||||
assert_eq!(rank_index(Rank::Ace), 0);
|
||||
assert_eq!(rank_index(Rank::Two), 1);
|
||||
assert_eq!(rank_index(Rank::Ten), 9);
|
||||
assert_eq!(rank_index(Rank::Jack), 10);
|
||||
assert_eq!(rank_index(Rank::Queen), 11);
|
||||
assert_eq!(rank_index(Rank::King), 12);
|
||||
fn rank_index_matches_upstream_ranks_order() {
|
||||
for (i, r) in Rank::RANKS.iter().enumerate() {
|
||||
assert_eq!(rank_index(*r), i, "faces inner layout = Rank::RANKS order");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -117,6 +117,13 @@ pub struct FocusedButton(pub Option<Entity>);
|
||||
/// gains keyboard navigation without per-plugin wiring.
|
||||
pub struct UiFocusPlugin;
|
||||
|
||||
/// Set on [`handle_focus_keys`], the focus-ring keyboard navigator. It runs
|
||||
/// AFTER every app-level keyboard consumer (HUD buttons/popovers, restore
|
||||
/// prompt, settings toggle) so Esc/Tab consumption order is defined instead
|
||||
/// of scheduler-dependent (#143).
|
||||
#[derive(bevy::ecs::schedule::SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct FocusKeys;
|
||||
|
||||
impl Plugin for UiFocusPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<FocusedButton>()
|
||||
@@ -147,9 +154,19 @@ impl Plugin for UiFocusPlugin {
|
||||
(
|
||||
sync_focus_on_mouse_click,
|
||||
clear_hud_focus_on_unhover,
|
||||
handle_focus_keys,
|
||||
update_focus_overlay,
|
||||
pulse_focus_overlay,
|
||||
handle_focus_keys
|
||||
.in_set(FocusKeys)
|
||||
.after(crate::game_plugin::GameMutation),
|
||||
update_focus_overlay
|
||||
.in_set(crate::ui_theme::UiTextFx)
|
||||
.ambiguous_with(crate::ui_theme::UiTextFx)
|
||||
.ambiguous_with(crate::card_plugin::BoardVisuals)
|
||||
.ambiguous_with(crate::table_plugin::MarkerVisuals),
|
||||
pulse_focus_overlay
|
||||
.after(crate::settings_plugin::SettingsMutation)
|
||||
.in_set(crate::ui_theme::UiTextFx)
|
||||
.ambiguous_with(crate::ui_theme::UiTextFx)
|
||||
.ambiguous_with(crate::card_plugin::BoardVisuals),
|
||||
)
|
||||
.chain(),
|
||||
);
|
||||
|
||||
@@ -695,7 +695,12 @@ impl Plugin for UiModalPlugin {
|
||||
advance_modal_enter,
|
||||
paint_modal_buttons,
|
||||
)
|
||||
.chain(),
|
||||
.chain()
|
||||
.after(crate::settings_plugin::SettingsMutation)
|
||||
.in_set(crate::ui_theme::UiTextFx)
|
||||
.ambiguous_with(crate::ui_theme::UiTextFx)
|
||||
.ambiguous_with(crate::card_plugin::BoardVisuals)
|
||||
.ambiguous_with(crate::hud_plugin::HudButtons),
|
||||
);
|
||||
// Click-outside-to-dismiss is independent of the open
|
||||
// animation chain — it reads `just_pressed(Left)` and runs
|
||||
|
||||
@@ -698,3 +698,12 @@ mod tests {
|
||||
assert_eq!(scaled_duration(0.18, AnimSpeed::Instant), 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// System set for text/UI visual effects that animate `Transform`/`Sprite`
|
||||
/// on chrome entities (HUD score pulse, streak flourish, modal enter, focus
|
||||
/// ring). These never touch board entities, so members are declared
|
||||
/// `.ambiguous_with(BoardVisuals)` and `.ambiguous_with(UiTextFx)` — the
|
||||
/// entity domains are disjoint by construction and relative order within a
|
||||
/// frame is invisible (#143).
|
||||
#[derive(bevy::ecs::schedule::SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct UiTextFx;
|
||||
|
||||
+104
-17
@@ -74,6 +74,15 @@ struct UserRow {
|
||||
/// bcrypt work factor. Cost 12 ≈ 300 ms on modern hardware — balances security against registration latency.
|
||||
pub const BCRYPT_COST: u32 = 12;
|
||||
|
||||
/// Static bcrypt hash used to equalise login timing when the username does
|
||||
/// not exist (issue #139: user-enumeration timing oracle). Both login paths
|
||||
/// must pay the same bcrypt cost; this hash is verified against when there
|
||||
/// is no real one. Computed once at first use with the same [`BCRYPT_COST`]
|
||||
/// as real hashes. `None` only if bcrypt itself fails on a constant input —
|
||||
/// in that case the dummy verify is skipped rather than panicking.
|
||||
static DUMMY_PASSWORD_HASH: std::sync::LazyLock<Option<String>> =
|
||||
std::sync::LazyLock::new(|| hash("ferrous-dummy-timing-pad", BCRYPT_COST).ok());
|
||||
|
||||
async fn hash_password(password: String) -> Result<String, AppError> {
|
||||
tokio::task::spawn_blocking(move || hash(password, BCRYPT_COST))
|
||||
.await
|
||||
@@ -208,6 +217,10 @@ pub async fn register(
|
||||
let password_hash = hash_password(body.password).await?;
|
||||
let now = Utc::now().to_rfc3339();
|
||||
|
||||
// The SELECT above is a friendly fast path; the UNIQUE constraint is the
|
||||
// real arbiter. A concurrent registration that slips between the two
|
||||
// surfaces as a unique violation here — map it to the same 409 the
|
||||
// fast path produces instead of a raw 500 (issue #140).
|
||||
sqlx::query!(
|
||||
"INSERT INTO users (id, username, password_hash, created_at) VALUES (?, ?, ?, ?)",
|
||||
user_id,
|
||||
@@ -216,7 +229,11 @@ pub async fn register(
|
||||
now
|
||||
)
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|e| match &e {
|
||||
sqlx::Error::Database(db) if db.is_unique_violation() => AppError::UsernameTaken,
|
||||
_ => AppError::from(e),
|
||||
})?;
|
||||
|
||||
let access_token = make_access_token(&user_id, &state.jwt_secret)?;
|
||||
let (refresh_token, refresh_jti) = make_refresh_token(&user_id, &state.jwt_secret)?;
|
||||
@@ -242,7 +259,16 @@ pub async fn login(
|
||||
.fetch_optional(&state.pool)
|
||||
.await?;
|
||||
|
||||
let row = row.ok_or(AppError::InvalidCredentials)?;
|
||||
let Some(row) = row else {
|
||||
// Unknown username: burn a bcrypt verify against a static dummy hash
|
||||
// so this path costs the same as a wrong-password attempt. Returning
|
||||
// immediately here would let response timing reveal which usernames
|
||||
// exist (issue #139).
|
||||
if let Some(dummy) = DUMMY_PASSWORD_HASH.as_ref() {
|
||||
let _ = verify_password(body.password, dummy.clone()).await;
|
||||
}
|
||||
return Err(AppError::InvalidCredentials);
|
||||
};
|
||||
let row_id = row
|
||||
.id
|
||||
.ok_or_else(|| AppError::Internal("user id missing".into()))?;
|
||||
@@ -283,23 +309,20 @@ pub async fn refresh(
|
||||
// Tokens without jti predate rotation — require re-login.
|
||||
let jti = claims.jti.ok_or(AppError::Unauthorized)?;
|
||||
|
||||
// Verify this jti is still live (not yet consumed or from a deleted account).
|
||||
// SQLite TEXT columns are always nullable in sqlx; flatten the double-Option.
|
||||
let exists: Option<String> =
|
||||
sqlx::query_scalar!("SELECT jti FROM refresh_tokens WHERE jti = ?", jti)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?
|
||||
.flatten();
|
||||
|
||||
if exists.is_none() {
|
||||
return Err(AppError::Unauthorized);
|
||||
}
|
||||
|
||||
// Consume the old token before issuing new ones. If the insert below
|
||||
// fails, the user loses this session (must re-login) — safe by design.
|
||||
sqlx::query!("DELETE FROM refresh_tokens WHERE jti = ?", jti)
|
||||
// Consume the old token before issuing new ones, gating on the DELETE
|
||||
// actually removing a row. rows_affected == 0 covers both "jti never
|
||||
// existed / account deleted" and "a concurrent refresh already consumed
|
||||
// it" — the previous SELECT-then-DELETE let two concurrent refreshes
|
||||
// both pass the check and both mint fresh token pairs. The DELETE is
|
||||
// the mutex: whoever removes the row wins; everyone else gets 401.
|
||||
// If the insert below fails, the user loses this session (must
|
||||
// re-login) — safe by design.
|
||||
let deleted = sqlx::query!("DELETE FROM refresh_tokens WHERE jti = ?", jti)
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
if deleted.rows_affected() != 1 {
|
||||
return Err(AppError::Unauthorized);
|
||||
}
|
||||
|
||||
let new_access = make_access_token(&claims.sub, &state.jwt_secret)?;
|
||||
let (new_refresh, new_jti) = make_refresh_token(&claims.sub, &state.jwt_secret)?;
|
||||
@@ -365,6 +388,22 @@ const AVATAR_MAX_BYTES: usize = 1024 * 1024;
|
||||
///
|
||||
/// The `Content-Type` header must be one of `image/jpeg`, `image/png`,
|
||||
/// `image/webp`, or `image/gif`. The previous avatar file is replaced in-place.
|
||||
/// Returns `true` when `body` begins with the magic bytes of the image type
|
||||
/// implied by `ext` (the extension derived from the declared Content-Type).
|
||||
///
|
||||
/// Avatars are re-served under the stored extension, so the extension must be
|
||||
/// derived from the content itself — a client header is not evidence of what
|
||||
/// the bytes are (issue #141).
|
||||
fn magic_bytes_match(ext: &str, body: &[u8]) -> bool {
|
||||
match ext {
|
||||
"png" => body.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]),
|
||||
"jpg" => body.starts_with(&[0xFF, 0xD8, 0xFF]),
|
||||
"gif" => body.starts_with(b"GIF87a") || body.starts_with(b"GIF89a"),
|
||||
"webp" => body.len() >= 12 && body.starts_with(b"RIFF") && &body[8..12] == b"WEBP",
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn upload_avatar(
|
||||
State(state): State<AppState>,
|
||||
user: AuthenticatedUser,
|
||||
@@ -390,6 +429,14 @@ pub async fn upload_avatar(
|
||||
if body.len() > AVATAR_MAX_BYTES {
|
||||
return Err(AppError::BadRequest("avatar must be ≤ 1 MB".into()));
|
||||
}
|
||||
// The stored extension decides how the file is re-served, so it must be
|
||||
// backed by the bytes, not just the client's Content-Type header
|
||||
// (issue #141).
|
||||
if !magic_bytes_match(ext, &body) {
|
||||
return Err(AppError::BadRequest(
|
||||
"avatar bytes do not match the declared image type".into(),
|
||||
));
|
||||
}
|
||||
|
||||
// Write to avatars/ directory, replacing any previous file for this user.
|
||||
tokio::fs::create_dir_all("avatars")
|
||||
@@ -590,6 +637,46 @@ mod tests {
|
||||
assert!(username_chars_ok(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn magic_bytes_match_accepts_real_signatures() {
|
||||
assert!(magic_bytes_match(
|
||||
"png",
|
||||
&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0x00]
|
||||
));
|
||||
assert!(magic_bytes_match("jpg", &[0xFF, 0xD8, 0xFF, 0xE0, 0x00]));
|
||||
assert!(magic_bytes_match("gif", b"GIF89a\x00\x00"));
|
||||
assert!(magic_bytes_match("gif", b"GIF87a\x00\x00"));
|
||||
assert!(magic_bytes_match("webp", b"RIFF\x00\x00\x00\x00WEBPVP8 "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn magic_bytes_match_rejects_mismatched_or_bogus_content() {
|
||||
// HTML declared as PNG — the exact spoof the check exists to stop.
|
||||
assert!(!magic_bytes_match("png", b"<html><script>"));
|
||||
// Real PNG bytes declared as JPEG: extension must match the bytes.
|
||||
assert!(!magic_bytes_match(
|
||||
"jpg",
|
||||
&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]
|
||||
));
|
||||
// Truncated / empty bodies never match.
|
||||
assert!(!magic_bytes_match("png", &[0x89, b'P']));
|
||||
assert!(!magic_bytes_match("webp", b"RIFF1234WEB"));
|
||||
assert!(!magic_bytes_match("gif", b""));
|
||||
// Unknown extensions are never accepted.
|
||||
assert!(!magic_bytes_match("svg", b"<svg xmlns="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dummy_password_hash_is_available_and_verifiable() {
|
||||
// The login timing pad (issue #139) must be a real bcrypt hash so the
|
||||
// unknown-user path pays a genuine verify at BCRYPT_COST.
|
||||
let dummy = DUMMY_PASSWORD_HASH
|
||||
.as_ref()
|
||||
.expect("bcrypt of a constant input must succeed");
|
||||
assert!(verify("ferrous-dummy-timing-pad", dummy).unwrap_or(false));
|
||||
assert!(!verify("wrong-password", dummy).unwrap_or(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn username_chars_ok_rejects_unicode_letters() {
|
||||
// Non-ASCII characters must be rejected even if they look like letters.
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
use axum::{Json, extract::State};
|
||||
use chrono::Utc;
|
||||
use sqlx::SqlitePool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use solitaire_sync::{
|
||||
@@ -26,13 +25,19 @@ struct SyncRow {
|
||||
|
||||
/// Load the stored `SyncPayload` for `user_id` from the database.
|
||||
/// Returns `None` if this user has not pushed any data yet.
|
||||
async fn load_sync_row(pool: &SqlitePool, user_id: &str) -> Result<Option<SyncRow>, AppError> {
|
||||
///
|
||||
/// Executor-generic so `push` can run it inside its transaction while
|
||||
/// `pull` keeps passing the pool directly.
|
||||
async fn load_sync_row(
|
||||
exec: impl sqlx::Executor<'_, Database = sqlx::Sqlite>,
|
||||
user_id: &str,
|
||||
) -> Result<Option<SyncRow>, AppError> {
|
||||
let row = sqlx::query_as!(
|
||||
SyncRow,
|
||||
"SELECT stats_json, achievements_json, progress_json FROM sync_state WHERE user_id = ?",
|
||||
user_id
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(exec)
|
||||
.await?;
|
||||
Ok(row)
|
||||
}
|
||||
@@ -69,7 +74,7 @@ fn row_to_payload(row: &SyncRow, user_id: &str) -> Result<SyncPayload, AppError>
|
||||
|
||||
/// Persist a `SyncPayload` for `user_id` using an upsert.
|
||||
async fn store_payload(
|
||||
pool: &SqlitePool,
|
||||
exec: impl sqlx::Executor<'_, Database = sqlx::Sqlite>,
|
||||
user_id: &str,
|
||||
payload: &SyncPayload,
|
||||
) -> Result<(), AppError> {
|
||||
@@ -92,7 +97,7 @@ async fn store_payload(
|
||||
progress_json,
|
||||
now
|
||||
)
|
||||
.execute(pool)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
@@ -159,12 +164,20 @@ pub async fn push(
|
||||
return Err(AppError::BadRequest("user_id mismatch".into()));
|
||||
}
|
||||
|
||||
let server_payload = match load_sync_row(&state.pool, &user.user_id).await? {
|
||||
// The whole read-merge-write cycle runs in ONE transaction. Without it,
|
||||
// two devices pushing concurrently both read the same stored payload,
|
||||
// merge independently, and the second store overwrites the first merge —
|
||||
// the server visibly regresses until the losing device pushes again.
|
||||
// SQLite serialises writers, so the second transaction simply waits.
|
||||
let mut tx = state.pool.begin().await?;
|
||||
|
||||
let server_payload = match load_sync_row(&mut *tx, &user.user_id).await? {
|
||||
Some(row) => row_to_payload(&row, &user.user_id)?,
|
||||
None => {
|
||||
// First push — nothing to merge against; store directly.
|
||||
store_payload(&state.pool, &user.user_id, &client_payload).await?;
|
||||
update_leaderboard_if_opted_in(&state.pool, &user.user_id, &client_payload).await?;
|
||||
store_payload(&mut *tx, &user.user_id, &client_payload).await?;
|
||||
update_leaderboard_if_opted_in(&mut tx, &user.user_id, &client_payload).await?;
|
||||
tx.commit().await?;
|
||||
return Ok(Json(SyncResponse {
|
||||
merged: client_payload,
|
||||
server_time: Utc::now(),
|
||||
@@ -175,8 +188,9 @@ pub async fn push(
|
||||
|
||||
let (merged, conflicts) = merge(&client_payload, &server_payload);
|
||||
|
||||
store_payload(&state.pool, &user.user_id, &merged).await?;
|
||||
update_leaderboard_if_opted_in(&state.pool, &user.user_id, &merged).await?;
|
||||
store_payload(&mut *tx, &user.user_id, &merged).await?;
|
||||
update_leaderboard_if_opted_in(&mut tx, &user.user_id, &merged).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(Json(SyncResponse {
|
||||
merged,
|
||||
@@ -188,16 +202,18 @@ pub async fn push(
|
||||
/// If the user is opted in to the leaderboard, update their row with the
|
||||
/// better of the stored and incoming `best_single_score` / `fastest_win_seconds`.
|
||||
///
|
||||
/// The opt-in check and the update are performed atomically in a single
|
||||
/// conditional UPDATE (WHERE EXISTS subquery) to avoid a TOCTOU race where
|
||||
/// the user opts out between the check and the write.
|
||||
/// Runs on the caller's transaction connection, so the opt-in check and the
|
||||
/// update are atomic with the surrounding push — an opt-out between the check
|
||||
/// and the write can no longer interleave. (An earlier doc comment claimed
|
||||
/// this was a single conditional UPDATE; it has always been two statements —
|
||||
/// the enclosing transaction is what actually provides the atomicity.)
|
||||
async fn update_leaderboard_if_opted_in(
|
||||
pool: &SqlitePool,
|
||||
conn: &mut sqlx::SqliteConnection,
|
||||
user_id: &str,
|
||||
payload: &SyncPayload,
|
||||
) -> Result<(), AppError> {
|
||||
let opted_in = sqlx::query!("SELECT leaderboard_opt_in FROM users WHERE id = ?", user_id)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(&mut *conn)
|
||||
.await?
|
||||
.map(|r| r.leaderboard_opt_in)
|
||||
.unwrap_or(0);
|
||||
@@ -231,7 +247,7 @@ async fn update_leaderboard_if_opted_in(
|
||||
now,
|
||||
user_id
|
||||
)
|
||||
.execute(pool)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1649,63 +1649,63 @@ function __wbg_get_imports() {
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000001: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 114880, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hfb2e9a2f0bbd9ecc);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 61868, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hd94d76233321402f);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000002: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000003: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Array<any>"), NamedExternref("ResizeObserver")], shim_idx: 9866, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h876550298b312ff8);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Array<any>"), NamedExternref("ResizeObserver")], shim_idx: 7314, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hfc779804ccb0943e);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000004: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Array<any>")], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_3);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Array<any>")], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_3);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000005: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_4);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_4);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000006: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("FocusEvent")], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_5);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("FocusEvent")], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_5);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000007: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_6);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_6);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000008: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("PageTransitionEvent")], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_7);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("PageTransitionEvent")], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_7);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_0000000000000009: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("PointerEvent")], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_8);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("PointerEvent")], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_8);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_000000000000000a: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("WheelEvent")], shim_idx: 9853, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_9);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("WheelEvent")], shim_idx: 7311, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_9);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_000000000000000b: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Option(NamedExternref("Blob"))], shim_idx: 9863, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h657f46feffff6fe4);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Option(NamedExternref("Blob"))], shim_idx: 7312, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hfd77696cd35180b1);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_000000000000000c: function(arg0, arg1) {
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 9857, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h545edb23183e448a);
|
||||
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 7313, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
|
||||
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hebcd362fbbe0fc8c);
|
||||
return ret;
|
||||
},
|
||||
__wbindgen_cast_000000000000000d: function(arg0) {
|
||||
@@ -1769,55 +1769,55 @@ function __wbg_get_imports() {
|
||||
};
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h545edb23183e448a(arg0, arg1) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h545edb23183e448a(arg0, arg1);
|
||||
function wasm_bindgen__convert__closures_____invoke__hebcd362fbbe0fc8c(arg0, arg1) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__hebcd362fbbe0fc8c(arg0, arg1);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_3(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_3(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_3(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_3(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_4(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_4(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_4(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_4(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_5(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_5(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_5(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_5(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_6(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_6(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_6(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_6(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_7(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_7(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_7(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_7(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_8(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_8(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_8(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_8(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_9(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h15aa57dbc666225a_9(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_9(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h26ff63c654218354_9(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__hfb2e9a2f0bbd9ecc(arg0, arg1, arg2) {
|
||||
const ret = wasm.wasm_bindgen__convert__closures_____invoke__hfb2e9a2f0bbd9ecc(arg0, arg1, arg2);
|
||||
function wasm_bindgen__convert__closures_____invoke__hd94d76233321402f(arg0, arg1, arg2) {
|
||||
const ret = wasm.wasm_bindgen__convert__closures_____invoke__hd94d76233321402f(arg0, arg1, arg2);
|
||||
if (ret[1]) {
|
||||
throw takeFromExternrefTable0(ret[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h876550298b312ff8(arg0, arg1, arg2, arg3) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h876550298b312ff8(arg0, arg1, arg2, arg3);
|
||||
function wasm_bindgen__convert__closures_____invoke__hfc779804ccb0943e(arg0, arg1, arg2, arg3) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__hfc779804ccb0943e(arg0, arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
function wasm_bindgen__convert__closures_____invoke__h657f46feffff6fe4(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__h657f46feffff6fe4(arg0, arg1, isLikeNone(arg2) ? 0 : addToExternrefTable0(arg2));
|
||||
function wasm_bindgen__convert__closures_____invoke__hfd77696cd35180b1(arg0, arg1, arg2) {
|
||||
wasm.wasm_bindgen__convert__closures_____invoke__hfd77696cd35180b1(arg0, arg1, isLikeNone(arg2) ? 0 : addToExternrefTable0(arg2));
|
||||
}
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
+21
-69
@@ -19,7 +19,7 @@
|
||||
//! is the contract.
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use solitaire_core::{Foundation, KlondikeInstruction, KlondikePile, Tableau};
|
||||
use solitaire_core::{KlondikeInstruction, KlondikePile};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use solitaire_core::{Card, Deck, Rank, Suit};
|
||||
use solitaire_core::error::MoveError;
|
||||
@@ -145,21 +145,10 @@ impl ReplayPlayer {
|
||||
let pile_cards = |t: KlondikePile| -> Vec<CardSnapshot> {
|
||||
self.game.pile(t).iter().map(CardSnapshot::from).collect()
|
||||
};
|
||||
let foundations: [Vec<CardSnapshot>; 4] = [
|
||||
pile_cards(KlondikePile::Foundation(Foundation::Foundation1)),
|
||||
pile_cards(KlondikePile::Foundation(Foundation::Foundation2)),
|
||||
pile_cards(KlondikePile::Foundation(Foundation::Foundation3)),
|
||||
pile_cards(KlondikePile::Foundation(Foundation::Foundation4)),
|
||||
];
|
||||
let tableaus: [Vec<CardSnapshot>; 7] = [
|
||||
pile_cards(KlondikePile::Tableau(Tableau::Tableau1)),
|
||||
pile_cards(KlondikePile::Tableau(Tableau::Tableau2)),
|
||||
pile_cards(KlondikePile::Tableau(Tableau::Tableau3)),
|
||||
pile_cards(KlondikePile::Tableau(Tableau::Tableau4)),
|
||||
pile_cards(KlondikePile::Tableau(Tableau::Tableau5)),
|
||||
pile_cards(KlondikePile::Tableau(Tableau::Tableau6)),
|
||||
pile_cards(KlondikePile::Tableau(Tableau::Tableau7)),
|
||||
];
|
||||
let foundations: [Vec<CardSnapshot>; 4] = solitaire_core::FOUNDATIONS
|
||||
.map(|f| pile_cards(KlondikePile::Foundation(f)));
|
||||
let tableaus: [Vec<CardSnapshot>; 7] =
|
||||
solitaire_core::TABLEAUS.map(|t| pile_cards(KlondikePile::Tableau(t)));
|
||||
StateSnapshot {
|
||||
step_idx: self.step_idx,
|
||||
total_steps: self.moves.len(),
|
||||
@@ -353,21 +342,9 @@ fn legal_moves_for_game(game: &GameState) -> Vec<DebugMove> {
|
||||
fn invariant_report_for_game(game: &GameState, legal_moves: &[DebugMove]) -> DebugInvariantReport {
|
||||
let stock = game.stock_cards();
|
||||
let waste = game.waste_cards();
|
||||
let foundations = [
|
||||
game.pile(KlondikePile::Foundation(Foundation::Foundation1)),
|
||||
game.pile(KlondikePile::Foundation(Foundation::Foundation2)),
|
||||
game.pile(KlondikePile::Foundation(Foundation::Foundation3)),
|
||||
game.pile(KlondikePile::Foundation(Foundation::Foundation4)),
|
||||
];
|
||||
let tableaus = [
|
||||
game.pile(KlondikePile::Tableau(Tableau::Tableau1)),
|
||||
game.pile(KlondikePile::Tableau(Tableau::Tableau2)),
|
||||
game.pile(KlondikePile::Tableau(Tableau::Tableau3)),
|
||||
game.pile(KlondikePile::Tableau(Tableau::Tableau4)),
|
||||
game.pile(KlondikePile::Tableau(Tableau::Tableau5)),
|
||||
game.pile(KlondikePile::Tableau(Tableau::Tableau6)),
|
||||
game.pile(KlondikePile::Tableau(Tableau::Tableau7)),
|
||||
];
|
||||
let foundations =
|
||||
solitaire_core::FOUNDATIONS.map(|f| game.pile(KlondikePile::Foundation(f)));
|
||||
let tableaus = solitaire_core::TABLEAUS.map(|t| game.pile(KlondikePile::Tableau(t)));
|
||||
|
||||
let mut seen: std::collections::HashSet<Card> = std::collections::HashSet::new();
|
||||
let mut duplicate_cards = Vec::new();
|
||||
@@ -488,21 +465,9 @@ impl SolitaireGame {
|
||||
.iter()
|
||||
.map(CardSnapshot::from)
|
||||
.collect(),
|
||||
foundations: [
|
||||
cards(KlondikePile::Foundation(Foundation::Foundation1)),
|
||||
cards(KlondikePile::Foundation(Foundation::Foundation2)),
|
||||
cards(KlondikePile::Foundation(Foundation::Foundation3)),
|
||||
cards(KlondikePile::Foundation(Foundation::Foundation4)),
|
||||
],
|
||||
tableaus: [
|
||||
cards(KlondikePile::Tableau(Tableau::Tableau1)),
|
||||
cards(KlondikePile::Tableau(Tableau::Tableau2)),
|
||||
cards(KlondikePile::Tableau(Tableau::Tableau3)),
|
||||
cards(KlondikePile::Tableau(Tableau::Tableau4)),
|
||||
cards(KlondikePile::Tableau(Tableau::Tableau5)),
|
||||
cards(KlondikePile::Tableau(Tableau::Tableau6)),
|
||||
cards(KlondikePile::Tableau(Tableau::Tableau7)),
|
||||
],
|
||||
foundations: solitaire_core::FOUNDATIONS
|
||||
.map(|f| cards(KlondikePile::Foundation(f))),
|
||||
tableaus: solitaire_core::TABLEAUS.map(|t| cards(KlondikePile::Tableau(t))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,34 +478,21 @@ impl SolitaireGame {
|
||||
let slot: u8 = s["foundation-".len()..]
|
||||
.parse()
|
||||
.map_err(|_| format!("bad pile: {s}"))?;
|
||||
if slot >= 4 {
|
||||
return Err(format!("foundation slot out of range: {slot}"));
|
||||
}
|
||||
Ok(KlondikePile::Foundation(match slot {
|
||||
0 => Foundation::Foundation1,
|
||||
1 => Foundation::Foundation2,
|
||||
2 => Foundation::Foundation3,
|
||||
3 => Foundation::Foundation4,
|
||||
_ => return Err(format!("foundation slot out of range: {slot}")),
|
||||
}))
|
||||
let foundation = solitaire_core::FOUNDATIONS
|
||||
.get(slot as usize)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("foundation slot out of range: {slot}"))?;
|
||||
Ok(KlondikePile::Foundation(foundation))
|
||||
}
|
||||
_ if s.starts_with("tableau-") => {
|
||||
let col: usize = s["tableau-".len()..]
|
||||
.parse()
|
||||
.map_err(|_| format!("bad pile: {s}"))?;
|
||||
if col >= 7 {
|
||||
return Err(format!("tableau col out of range: {col}"));
|
||||
}
|
||||
Ok(KlondikePile::Tableau(match col {
|
||||
0 => Tableau::Tableau1,
|
||||
1 => Tableau::Tableau2,
|
||||
2 => Tableau::Tableau3,
|
||||
3 => Tableau::Tableau4,
|
||||
4 => Tableau::Tableau5,
|
||||
5 => Tableau::Tableau6,
|
||||
6 => Tableau::Tableau7,
|
||||
_ => return Err(format!("tableau col out of range: {col}")),
|
||||
}))
|
||||
let tableau = solitaire_core::TABLEAUS
|
||||
.get(col)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("tableau col out of range: {col}"))?;
|
||||
Ok(KlondikePile::Tableau(tableau))
|
||||
}
|
||||
_ => Err(format!("unknown pile: {s}")),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user