mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 19:25:56 +00:00
feat(portable): Phase 6 audit, appearance section, collections channel (WIP: Manager side)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cfcace8337
commit
b2b2009b0d
49 files changed
+1873
-40
No files matched your search
@@ -140,7 +140,7 @@ fn run() -> Result<(), String> {
|
||||
("host-run", [owner_dir, server]) => {
|
||||
let mut owner = Store::open(&PathBuf::from(owner_dir)).map_err(|e| e.to_string())?;
|
||||
let mut host = Store::open(&host_dir).map_err(|e| e.to_string())?;
|
||||
let mut service = HostService::new(&mut host, server, HostConfig { checkpoint_interval_secs: interval });
|
||||
let mut service = HostService::new(&mut host, server, HostConfig { checkpoint_interval_secs: interval, ..HostConfig::default() });
|
||||
let start = std::time::Instant::now();
|
||||
println!("host running for {server}; Ctrl-C to stop");
|
||||
loop {
|
||||
|
||||
@@ -79,6 +79,7 @@ pub fn naked_level_one() -> PortableCharacter {
|
||||
actions: Vec::new(),
|
||||
pets: Vec::new(),
|
||||
settings: BTreeMap::new(),
|
||||
wardrobe: Default::default(),
|
||||
client_data: BTreeMap::new(),
|
||||
extensions: BTreeMap::new(),
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! * scalars: `ours` wins where `base != ours`; otherwise `target` is kept;
|
||||
//! * accumulators (money, honor totals, kills, arena points, xp inside a level): the *difference* `ours - base` is added;
|
||||
//! * bit sets (known currencies, titles, explored zones, taxi nodes): bits gained are added, bits lost are removed;
|
||||
//! * keyed collections (spells, skills, reputation, quests, action buttons, settings, ...): keys added in `ours` are added,
|
||||
//! * keyed collections (spells, skills, reputation, quests, action buttons, settings, selected appearances and outfits, ...): keys added in `ours` are added,
|
||||
//! keys removed in `ours` are removed, values changed in `ours` are replaced;
|
||||
//! * items and pets are matched by their **portable id**: present in `target` and `base`: delta applied, or removed when
|
||||
//! `ours` lacks it (the player got rid of it); in `target` only (filtered away by the realm before `base`): **kept**, or
|
||||
@@ -327,6 +327,10 @@ pub fn merge3(target: &PortableCharacter, base: &PortableCharacter, ours: &Porta
|
||||
out.actions = actions.into_iter().map(|((spec, button), (action, kind))| ActionButton { spec, button, action, kind }).collect();
|
||||
|
||||
cx.map("settings", &mut out.settings, &base.settings, &ours.settings);
|
||||
cx.map("wardrobe.active", &mut out.wardrobe.active, &base.wardrobe.active, &ours.wardrobe.active);
|
||||
cx.map("wardrobe.outfits", &mut out.wardrobe.outfits, &base.wardrobe.outfits, &ours.wardrobe.outfits);
|
||||
cx.scalar("wardrobe.can_see_item", &mut out.wardrobe.can_see_item, &base.wardrobe.can_see_item, &ours.wardrobe.can_see_item);
|
||||
cx.scalar("wardrobe.can_see_spell", &mut out.wardrobe.can_see_spell, &base.wardrobe.can_see_spell, &ours.wardrobe.can_see_spell);
|
||||
cx.map("client_data", &mut out.client_data, &base.client_data, &ours.client_data);
|
||||
}
|
||||
// extensions are the canonical character's own (quarantined data); a realm never contributes to them
|
||||
|
||||
@@ -426,3 +426,90 @@ fn random_realm_normalisation_never_leaks_into_the_canonical_character() {
|
||||
assert!(m.changes.is_empty(), "round {round}: {:?}", m.changes);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Phase 6: the selected appearances travel with the character and never touch an item ---------------------------------
|
||||
|
||||
fn with_wardrobe(mut m: PortableCharacter, active: &[(u8, u32)], outfits: &[(&str, &[u32])]) -> PortableCharacter {
|
||||
m.wardrobe.active = active.iter().copied().collect();
|
||||
m.wardrobe.outfits = outfits.iter().map(|(n, ids)| (n.to_string(), ids.to_vec())).collect();
|
||||
m.normalized()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_appearance_made_in_a_session_reaches_the_canonical_character_without_touching_an_item() {
|
||||
let c0 = with_wardrobe(c0(), &[(1, 100)], &[]);
|
||||
let (b0, _) = normalized_by_the_realm(&c0);
|
||||
let mut b1 = b0.clone();
|
||||
b1.wardrobe.active.insert(3, 303);
|
||||
b1.wardrobe.active.insert(56, 5600);
|
||||
b1.wardrobe.outfits.insert("Sunday".into(), vec![100, 0, 303]);
|
||||
b1.wardrobe.can_see_spell = false;
|
||||
let merged = merge3(&c0, &b0, &b1, Mode::Lenient).unwrap();
|
||||
assert_eq!(merged.model.wardrobe.active, [(1, 100), (3, 303), (56, 5600)].into_iter().collect());
|
||||
assert_eq!(merged.model.wardrobe.outfits["Sunday"], vec![100, 0, 303]);
|
||||
assert!(merged.model.wardrobe.can_see_item && !merged.model.wardrobe.can_see_spell);
|
||||
assert!(merged.items.added.is_empty() && merged.items.removed.is_empty() && merged.items.changed.is_empty());
|
||||
assert_eq!(merged.model.items, c0.items, "reconciling an appearance can never create, change or delete a gameplay item");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_appearance_the_realm_does_not_know_stays_canonical_through_any_number_of_sessions() {
|
||||
// the canonical character wears 999 and 1000, which the realm never showed (B0 and B1 lack them)
|
||||
let c0 = with_wardrobe(c0(), &[(1, 100), (2, 999)], &[("Far away", &[999, 1000])]);
|
||||
let (mut b0, _) = normalized_by_the_realm(&c0);
|
||||
b0.wardrobe = Default::default();
|
||||
let mut b1 = b0.clone();
|
||||
b1.wardrobe.active.insert(3, 303);
|
||||
let merged = merge3(&c0, &b0, &b1, Mode::Lenient).unwrap();
|
||||
assert_eq!(merged.model.wardrobe.active.get(&1), Some(&100));
|
||||
assert_eq!(merged.model.wardrobe.active.get(&2), Some(&999), "kept");
|
||||
assert_eq!(merged.model.wardrobe.active.get(&3), Some(&303), "and the session's choice is added");
|
||||
assert!(merged.model.wardrobe.outfits.contains_key("Far away"));
|
||||
// again, from the merged result as the next session's canonical character
|
||||
let again = merge3(&merged.model, &b0, &b1, Mode::Lenient).unwrap();
|
||||
assert_eq!(again.model.wardrobe, merged.model.wardrobe, "repeatable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deselecting_and_deleting_in_a_session_removes_them_from_the_canonical_character() {
|
||||
let c0 = with_wardrobe(c0(), &[(1, 100), (3, 303)], &[("A", &[100]), ("B", &[303])]);
|
||||
let b0 = c0.clone();
|
||||
let mut b1 = b0.clone();
|
||||
b1.wardrobe.active.remove(&3);
|
||||
b1.wardrobe.outfits.remove("B");
|
||||
let merged = merge3(&c0, &b0, &b1, Mode::Lenient).unwrap();
|
||||
assert_eq!(merged.model.wardrobe.active, [(1, 100)].into_iter().collect());
|
||||
assert_eq!(merged.model.wardrobe.outfits.keys().collect::<Vec<_>>(), ["A"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_conflicts_only_where_both_sides_changed_the_same_category_differently() {
|
||||
// target = the realm now, base = what it was synced with, ours = the new canonical character
|
||||
let base = with_wardrobe(c0(), &[(1, 100), (3, 303)], &[]);
|
||||
let mut target = base.clone();
|
||||
target.wardrobe.active.insert(1, 101);
|
||||
target.wardrobe.active.insert(9, 909);
|
||||
let mut ours = base.clone();
|
||||
ours.wardrobe.active.insert(3, 304);
|
||||
let merged = merge3(&target, &base, &ours, Mode::Strict).unwrap();
|
||||
assert!(merged.conflicts.is_empty(), "{:?}", merged.conflicts);
|
||||
assert_eq!(merged.model.wardrobe.active, [(1, 101), (3, 304), (9, 909)].into_iter().collect(), "each side's own change survives");
|
||||
let mut ours = base.clone();
|
||||
ours.wardrobe.active.insert(1, 102);
|
||||
let merged = merge3(&target, &base, &ours, Mode::Strict).unwrap();
|
||||
assert_eq!(merged.conflicts.len(), 1);
|
||||
assert!(merged.conflicts[0].path.contains("wardrobe.active"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_without_a_wardrobe_has_the_bytes_it_had_before_the_section_existed() {
|
||||
let model = c0();
|
||||
assert!(model.wardrobe.is_empty());
|
||||
let json = String::from_utf8(crate::portable::snapshot::canonical_json(&model).unwrap()).unwrap();
|
||||
assert!(!json.contains("wardrobe"), "an empty section is not serialised, so every older snapshot keeps its hash");
|
||||
let worn = with_wardrobe(model, &[(1, 100)], &[]);
|
||||
let json = String::from_utf8(crate::portable::snapshot::canonical_json(&worn).unwrap()).unwrap();
|
||||
assert!(json.contains("\"wardrobe\":{\"active\":{\"1\":100}}"), "{json}");
|
||||
let back: PortableCharacter = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, worn);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Schema 6: account collections of the HOST (Phase 6). What the Host has read from a realm account and what the Owner has
|
||||
-- acknowledged of it. Nothing here is canonical: the Owner's `collection` table (revision + hash + compact id set per profile
|
||||
-- and kind) is. A realm is asked for its sets again only when the cheap `fingerprint` of its tables changes.
|
||||
|
||||
CREATE TABLE host_collection (
|
||||
server_id TEXT NOT NULL,
|
||||
account INTEGER NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
-- count / max / checksum of the realm's rows at the last full read: equal fingerprint means nothing to read
|
||||
fingerprint TEXT NOT NULL,
|
||||
-- hash of the set read at that time
|
||||
observed_hash BLOB CHECK (observed_hash IS NULL OR length(observed_hash) = 32),
|
||||
-- hash of the realm set the Owner has acknowledged (a realm set whose hash equals this one is never sent again)
|
||||
acked_hash BLOB CHECK (acked_hash IS NULL OR length(acked_hash) = 32),
|
||||
canonical_revision INTEGER NOT NULL DEFAULT 0,
|
||||
canonical_hash BLOB CHECK (canonical_hash IS NULL OR length(canonical_hash) = 32),
|
||||
-- the CollectionObserved message not yet acknowledged
|
||||
pending BLOB,
|
||||
checked_at INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY (server_id, account, kind)
|
||||
) STRICT;
|
||||
@@ -39,6 +39,10 @@ pub mod limits {
|
||||
pub const MAX_SETTINGS: usize = 4_096;
|
||||
pub const MAX_SETTING_VALUES: usize = 4_096;
|
||||
pub const MAX_SETTING_SOURCE_BYTES: usize = 128;
|
||||
/// Appearance categories are `1..68` in the realm (`APPEARANCE_CATEGORY_COUNT = 69`).
|
||||
pub const MAX_APPEARANCE_CATEGORY: u8 = 68;
|
||||
pub const MAX_APPEARANCE_OUTFITS: usize = 100;
|
||||
pub const MAX_APPEARANCE_OUTFIT_NAME_BYTES: usize = 64;
|
||||
pub const MAX_CLIENT_BLOBS: usize = 8;
|
||||
pub const MAX_CLIENT_BLOB_BYTES: usize = 64 * 1024;
|
||||
pub const MAX_RAW_TEXT_BYTES: usize = 8 * 1024;
|
||||
@@ -314,6 +318,66 @@ pub struct PortablePet {
|
||||
pub declined_names: Option<[String; 5]>,
|
||||
}
|
||||
|
||||
/// What a character looks like by choice (Phase 6): the **selected** appearance per category, the two visibility switches
|
||||
/// and the saved outfits. All ids are appearance ids of the character's `content_namespace` (for CoA: `Appearances.dbc`).
|
||||
///
|
||||
/// This is selection state only. What the account has *unlocked* is a profile collection (`coa:appearance`, `coa:vanity`),
|
||||
/// and no gameplay item is referenced from here, so reconciling it can never create or delete an item.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PortableAppearance {
|
||||
/// Category (`character_appearance.category_id`, 1..=68) -> appearance id.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub active: BTreeMap<u8, u32>,
|
||||
/// `character_appearance_settings.can_see_item`; a missing row means `true`.
|
||||
#[serde(default = "yes", skip_serializing_if = "is_yes")]
|
||||
pub can_see_item: bool,
|
||||
/// `character_appearance_settings.can_see_spell`; a missing row means `true`.
|
||||
#[serde(default = "yes", skip_serializing_if = "is_yes")]
|
||||
pub can_see_spell: bool,
|
||||
/// Saved outfits by name: the appearance ids in the order the realm stores them (0 = nothing in that category).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub outfits: BTreeMap<String, Vec<u32>>,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_yes(v: &bool) -> bool {
|
||||
*v
|
||||
}
|
||||
|
||||
impl Default for PortableAppearance {
|
||||
fn default() -> Self {
|
||||
Self { active: BTreeMap::new(), can_see_item: true, can_see_spell: true, outfits: BTreeMap::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl PortableAppearance {
|
||||
/// Nothing selected, nothing saved, both switches at the realm default: serialised as absent, so a character without an
|
||||
/// appearance has exactly the bytes (and hash) it had before this section existed.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.active.is_empty() && self.outfits.is_empty() && self.can_see_item && self.can_see_spell
|
||||
}
|
||||
|
||||
/// Every appearance id mentioned anywhere (selection and outfits), without 0.
|
||||
pub fn ids(&self) -> BTreeSet<u32> {
|
||||
self.active.values().chain(self.outfits.values().flatten()).copied().filter(|id| *id != 0).collect()
|
||||
}
|
||||
|
||||
/// The part of this appearance a destination that knows `known` can hold: a selection of an unknown id and an outfit
|
||||
/// that mentions one are left out (they stay in the canonical character, see `PORTABLE_APPEARANCE.md`).
|
||||
pub fn restricted_to(&self, known: impl Fn(u32) -> bool) -> PortableAppearance {
|
||||
PortableAppearance {
|
||||
active: self.active.iter().filter(|(_, id)| known(**id)).map(|(c, id)| (*c, *id)).collect(),
|
||||
can_see_item: self.can_see_item,
|
||||
can_see_spell: self.can_see_spell,
|
||||
outfits: self.outfits.iter().filter(|(_, ids)| ids.iter().all(|id| *id == 0 || known(*id))).map(|(n, ids)| (n.clone(), ids.clone())).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ClientBlob {
|
||||
@@ -366,6 +430,9 @@ pub struct PortableCharacter {
|
||||
/// CoA gameplay state (`character_settings`): source -> integer vector. Only allow-listed sources are carried
|
||||
/// (policy lives with the exporter).
|
||||
pub settings: BTreeMap<String, Vec<u32>>,
|
||||
/// Selected appearances, visibility switches and saved outfits (absent in snapshots made before Phase 6).
|
||||
#[serde(default, skip_serializing_if = "PortableAppearance::is_empty")]
|
||||
pub wardrobe: PortableAppearance,
|
||||
/// Per-character client blobs by account-data type (macros = 5).
|
||||
pub client_data: BTreeMap<u8, ClientBlob>,
|
||||
/// Module data by extension namespace (`mod:<module>`), kept even when unsupported by a realm.
|
||||
@@ -544,6 +611,25 @@ impl PortableCharacter {
|
||||
}
|
||||
}
|
||||
|
||||
// appearance
|
||||
if self.wardrobe.outfits.len() > MAX_APPEARANCE_OUTFITS {
|
||||
return too_many("saved outfits", MAX_APPEARANCE_OUTFITS);
|
||||
}
|
||||
if let Some(category) = self.wardrobe.active.keys().find(|c| **c == 0 || **c > MAX_APPEARANCE_CATEGORY) {
|
||||
return invalid(format!("appearance category {category} is out of range"));
|
||||
}
|
||||
if self.wardrobe.active.values().any(|id| *id == 0) {
|
||||
return invalid("an active appearance cannot be 0 (a category without a selection has no entry)");
|
||||
}
|
||||
for (name, ids) in &self.wardrobe.outfits {
|
||||
if name.is_empty() || name.len() > MAX_APPEARANCE_OUTFIT_NAME_BYTES || name.chars().any(|c| (c as u32) < 0x20) {
|
||||
return invalid("an outfit name must have 1 to 64 bytes and no control characters");
|
||||
}
|
||||
if ids.len() > MAX_APPEARANCE_CATEGORY as usize + 1 {
|
||||
return too_many("appearances in one outfit", MAX_APPEARANCE_CATEGORY as usize + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// settings, client blobs, extensions
|
||||
if self.settings.len() > MAX_SETTINGS {
|
||||
return too_many("settings sources", MAX_SETTINGS);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Phase 6: the account collections of a realm (`account_appearance_collection`, `account_vanity_collection`).
|
||||
//!
|
||||
//! * **Read**: a cheap fingerprint of the realm rows (count, maximum, sum, checksum) says whether anything changed; the ids are
|
||||
//! read only when it did. Nothing here ever writes while reading.
|
||||
//! * **Write**: `INSERT IGNORE` only, exactly like the core itself, so it is safe on a running realm (the core loads an
|
||||
//! account's collection once at login and never deletes a row). Only ids the destination's client data knows are written;
|
||||
//! the rest stay canonical. `source_item` is bookkeeping the core never reads back, so it is written as 0.
|
||||
//! * The four bank vanity items open the personal Ascension bank, which is out of scope: they are neither read nor written.
|
||||
|
||||
use crate::db::Db;
|
||||
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::error::{PortableError, Result};
|
||||
use super::knowledge::{is_bank_vanity_item, RealmKnowledge};
|
||||
use super::plan::FAIL;
|
||||
use super::ruleset_of;
|
||||
use super::super::model::Ruleset;
|
||||
|
||||
/// How many rows one INSERT carries.
|
||||
const CHUNK: usize = 2_000;
|
||||
|
||||
/// `(table, id column, columns written)` of a collection kind.
|
||||
fn layout(kind: &str) -> Result<(&'static str, &'static str, bool)> {
|
||||
match kind {
|
||||
"coa:appearance" => Ok(("account_appearance_collection", "appearance_id", true)),
|
||||
"coa:vanity" => Ok(("account_vanity_collection", "item_id", false)),
|
||||
other => Err(PortableError::Invalid(format!("collection kind {other:?} is not carried"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn realm_error(e: crate::Error) -> PortableError {
|
||||
PortableError::RealmRead(e.to_string())
|
||||
}
|
||||
|
||||
fn coa_only(db: &Db) -> Result<()> {
|
||||
if ruleset_of(db) != Ruleset::Coa {
|
||||
return Err(PortableError::Invalid("collections are carried for CoA realms only (Wildcard transfer is disabled)".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The game account that owns a character.
|
||||
pub fn account_of(db: &Db, local_guid: u32) -> Result<Option<u32>> {
|
||||
let out = db.query(&format!("SELECT account FROM acore_characters.characters WHERE guid = {local_guid}")).map_err(realm_error)?;
|
||||
out.lines().find(|l| !l.trim().is_empty()).map(|l| l.trim().parse::<u32>().map_err(|_| PortableError::CorruptSnapshot(format!("{l:?} is not an account id")))).transpose()
|
||||
}
|
||||
|
||||
/// Count, maximum, sum and checksum of the account's rows of this kind: one cheap aggregate over the primary key.
|
||||
pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result<String> {
|
||||
coa_only(db)?;
|
||||
let (table, column, _) = layout(kind)?;
|
||||
let out = db
|
||||
.query(&format!("SELECT COUNT(*), IFNULL(MAX(`{column}`), 0), IFNULL(SUM(`{column}`), 0), IFNULL(BIT_XOR(CRC32(`{column}`)), 0) FROM acore_characters.`{table}` WHERE `account_id` = {account}"))
|
||||
.map_err(realm_error)?;
|
||||
let cells: Vec<&str> = out.trim().split('\t').collect();
|
||||
if cells.len() != 4 || cells.iter().any(|c| c.is_empty() || !c.bytes().all(|b| b.is_ascii_digit())) {
|
||||
return Err(PortableError::CorruptSnapshot(format!("unexpected collection fingerprint {out:?}")));
|
||||
}
|
||||
Ok(cells.join(":"))
|
||||
}
|
||||
|
||||
/// The ids of the account in this realm, without the bank vanity items.
|
||||
pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
|
||||
coa_only(db)?;
|
||||
let (table, column, _) = layout(kind)?;
|
||||
let out = db.query(&format!("SELECT `{column}` FROM acore_characters.`{table}` WHERE `account_id` = {account} ORDER BY `{column}`")).map_err(realm_error)?;
|
||||
let mut ids = Vec::new();
|
||||
for line in out.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let id: u32 = line.trim().parse().map_err(|_| PortableError::CorruptSnapshot(format!("{line:?} is not an id")))?;
|
||||
if kind == "coa:vanity" && is_bank_vanity_item(id) {
|
||||
continue;
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
IdSet::from_ids(ids)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Applied {
|
||||
/// Ids written to the realm now.
|
||||
pub inserted: usize,
|
||||
/// Canonical ids the realm's client data does not know: kept canonical, not written.
|
||||
pub unknown: usize,
|
||||
/// Canonical ids the realm already had.
|
||||
pub already: usize,
|
||||
}
|
||||
|
||||
/// Union the canonical set into the account's rows: only ids the realm knows and does not hold yet are inserted.
|
||||
pub fn apply_set(db: &Db, account: u32, kind: &str, canonical: &IdSet, knowledge: &RealmKnowledge) -> Result<Applied> {
|
||||
coa_only(db)?;
|
||||
let (table, column, has_source) = layout(kind)?;
|
||||
let known = |id: u32| match kind {
|
||||
"coa:appearance" => knowledge.knows_appearance(id),
|
||||
_ => knowledge.knows_vanity(id) && !is_bank_vanity_item(id),
|
||||
};
|
||||
let held = read_set(db, account, kind)?;
|
||||
let mut applied = Applied::default();
|
||||
let mut wanted = Vec::new();
|
||||
for id in canonical.ids().iter().copied().filter(|id| !(kind == "coa:vanity" && is_bank_vanity_item(*id))) {
|
||||
if !known(id) {
|
||||
applied.unknown += 1;
|
||||
} else if held.contains(id) {
|
||||
applied.already += 1;
|
||||
} else {
|
||||
wanted.push(id);
|
||||
}
|
||||
}
|
||||
if wanted.is_empty() {
|
||||
return Ok(applied);
|
||||
}
|
||||
let mut script = String::new();
|
||||
script.push_str("START TRANSACTION;\n");
|
||||
script.push_str(&format!("DO IF((SELECT COUNT(*) FROM acore_auth.account WHERE id = {account}) = 1, 1, {FAIL});\n"));
|
||||
for chunk in wanted.chunks(CHUNK) {
|
||||
let (columns, rows) = if has_source {
|
||||
("`account_id`, `appearance_id`, `source_item`", chunk.iter().map(|id| format!("({account}, {id}, 0)")).collect::<Vec<_>>().join(","))
|
||||
} else {
|
||||
("`account_id`, `item_id`", chunk.iter().map(|id| format!("({account}, {id})")).collect::<Vec<_>>().join(","))
|
||||
};
|
||||
script.push_str(&format!("INSERT IGNORE INTO acore_characters.`{table}` ({columns}) VALUES {rows};\n"));
|
||||
}
|
||||
script.push_str("COMMIT;\n");
|
||||
let _ = column;
|
||||
db.query(&script).map_err(realm_error)?;
|
||||
applied.inserted = wanted.len();
|
||||
Ok(applied)
|
||||
}
|
||||
@@ -226,6 +226,7 @@ pub fn build(raw: &RawExport, req: &ExportRequest<'_>) -> Result<Exported> {
|
||||
actions,
|
||||
pets,
|
||||
settings,
|
||||
wardrobe: wardrobe(raw)?,
|
||||
client_data,
|
||||
extensions,
|
||||
}
|
||||
@@ -438,3 +439,32 @@ fn settings(raw: &RawExport, ruleset: Ruleset) -> Result<(BTreeMap<String, Vec<u
|
||||
}
|
||||
Ok((carried, quarantined))
|
||||
}
|
||||
|
||||
/// The character's selected appearances, visibility switches and outfits. Rows the realm itself would ignore (a category
|
||||
/// outside its table, an appearance of 0) are left out, so the model is what the realm actually shows.
|
||||
fn wardrobe(raw: &RawExport) -> Result<PortableAppearance> {
|
||||
let mut out = PortableAppearance::default();
|
||||
if raw.has("appearance") {
|
||||
for r in raw.section("appearance")?.iter() {
|
||||
let (category, appearance) = (r.u32("category")?, r.u32("appearance")?);
|
||||
if (1..=limits::MAX_APPEARANCE_CATEGORY as u32).contains(&category) && appearance != 0 {
|
||||
out.active.insert(category as u8, appearance);
|
||||
}
|
||||
}
|
||||
}
|
||||
if raw.has("appearance_settings") {
|
||||
if let Some(r) = raw.section("appearance_settings")?.iter().next() {
|
||||
out.can_see_item = r.u32("see_item")? != 0;
|
||||
out.can_see_spell = r.u32("see_spell")? != 0;
|
||||
}
|
||||
}
|
||||
if raw.has("appearance_outfits") {
|
||||
for r in raw.section("appearance_outfits")?.iter() {
|
||||
let name = r.text("name")?;
|
||||
// the realm tokenises on spaces and reads an unparsable token as 0
|
||||
let ids = r.text("appearances")?.split(' ').filter(|t| !t.is_empty()).map(|t| t.parse::<u32>().unwrap_or(0)).collect();
|
||||
out.outfits.insert(name, ids);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -41,11 +41,14 @@ pub struct ImportOptions {
|
||||
pub recovery_grace: Duration,
|
||||
/// How long recovery waits for an import that is still running in the realm.
|
||||
pub lock_wait_seconds: u32,
|
||||
/// What the destination's client data knows (appearances, vanity items). Without it no appearance or collection is
|
||||
/// written to the realm (all of it stays canonical); see `PORTABLE_APPEARANCE.md`.
|
||||
pub knowledge: Option<std::sync::Arc<super::knowledge::RealmKnowledge>>,
|
||||
}
|
||||
|
||||
impl Default for ImportOptions {
|
||||
fn default() -> Self {
|
||||
Self { max_characters_per_account: 10, game_server_users: vec!["acore".to_string()], recovery_grace: Duration::from_secs(30), lock_wait_seconds: 30 }
|
||||
Self { max_characters_per_account: 10, game_server_users: vec!["acore".to_string()], recovery_grace: Duration::from_secs(30), lock_wait_seconds: 30, knowledge: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,7 +275,7 @@ pub fn import_character_in_session(db: &Db, store: &mut Store, character_id: Cha
|
||||
let pets = planned_pets(&model);
|
||||
let ticket = store.begin_import(character_id, server_id, record.revision, &items, &pets)?;
|
||||
|
||||
let plan = match build_plan(&model, &PlanContext { ruleset: ruleset_of(db), account, revision: record.revision, nonce: ticket.nonce, max_characters_per_account: opts.max_characters_per_account, game_server_users: &opts.game_server_users, probe: &probe, session: session.map(|session_id| SessionArm { session_id, character_id, generation: 1 }) }) {
|
||||
let plan = match build_plan(&model, &PlanContext { ruleset: ruleset_of(db), account, revision: record.revision, nonce: ticket.nonce, max_characters_per_account: opts.max_characters_per_account, game_server_users: &opts.game_server_users, probe: &probe, session: session.map(|session_id| SessionArm { session_id, character_id, generation: 1 }), knowledge: opts.knowledge.as_deref() }) {
|
||||
Ok(plan) => plan,
|
||||
Err(e) => {
|
||||
store.abort_import(ticket.import_id, &format!("the import plan could not be built: {e}"))?;
|
||||
|
||||
@@ -16,7 +16,7 @@ fn probe_with(tables: &[&str]) -> SchemaProbe {
|
||||
}
|
||||
|
||||
fn ctx<'a>(probe: &'a SchemaProbe, users: &'a [String]) -> PlanContext<'a> {
|
||||
PlanContext { ruleset: Ruleset::Coa, account: 5001, revision: 3, nonce: [11, 22, 33, 44], max_characters_per_account: 10, game_server_users: users, probe, session: None }
|
||||
PlanContext { ruleset: Ruleset::Coa, account: 5001, revision: 3, nonce: [11, 22, 33, 44], max_characters_per_account: 10, game_server_users: users, probe, session: None, knowledge: None }
|
||||
}
|
||||
|
||||
fn users() -> Vec<String> {
|
||||
@@ -356,3 +356,30 @@ fn stock_talents_are_never_written_because_a_bad_row_kills_the_realm() {
|
||||
// and the transaction asserts that the character has none, so a leftover row of an earlier character cannot survive either
|
||||
assert!(plan.script.contains("acore_characters.character_talent WHERE guid = @char) = 0,"));
|
||||
}
|
||||
|
||||
// ---- Phase 6: selected appearances ----------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn selected_appearances_are_written_only_for_ids_the_realm_knows_and_the_result_is_asserted() {
|
||||
let mut model = geared_level_eighty();
|
||||
model.wardrobe.active.insert(1, 100);
|
||||
model.wardrobe.active.insert(2, 200);
|
||||
model.wardrobe.outfits.insert("Sunday".into(), vec![100, 0]);
|
||||
model.wardrobe.outfits.insert("Far".into(), vec![100, 200]);
|
||||
model.wardrobe.can_see_spell = false;
|
||||
let k = super::knowledge::RealmKnowledge::new(crate::portable::collection::IdSet::from_ids([100]).unwrap(), Default::default());
|
||||
let u = users();
|
||||
let plan = build_plan(&model, &PlanContext { knowledge: Some(&k), ..ctx(&all_tables(), &u) }).unwrap();
|
||||
assert_eq!(plan.counts.wardrobe, 1 + 1 + 1, "one selection, one outfit, one visibility row");
|
||||
let script = &plan.script;
|
||||
assert!(script.contains("INSERT INTO acore_characters.`character_appearance` (`guid`, `category_id`, `appearance_id`) VALUES\n (@char, 1, 100);"), "{script}");
|
||||
assert!(!script.contains("(@char, 2, 200)") && !script.contains(&hex::encode("100 200")), "ids the realm does not know are never written");
|
||||
assert!(script.contains("acore_characters.character_appearance WHERE guid = @char"), "the number of rows is asserted before the commit");
|
||||
let commit = script.find("COMMIT;").unwrap();
|
||||
assert!(script.find("character_appearance_outfit WHERE guid = @char").unwrap() < commit);
|
||||
|
||||
let none = build_plan(&model, &PlanContext { knowledge: None, ..ctx(&all_tables(), &u) }).unwrap();
|
||||
assert_eq!(none.counts.wardrobe, 0);
|
||||
assert!(!none.script.contains("INSERT INTO acore_characters.`character_appearance`"));
|
||||
assert!(none.not_applied_settings.contains(&"wardrobe".to_string()), "reported as kept canonical, not applied");
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! What a destination realm **knows** (Phase 6): the appearance ids and vanity items of its client data.
|
||||
//!
|
||||
//! The appearance and vanity systems of CoA are driven by client tables the core loads at startup, not by database rows:
|
||||
//! `Appearances.dbc` (field 0 is the appearance id) and `VanityCollection.dbc` (field 1 is the vanity item entry), both in
|
||||
//! `<DataDir>/dbc`. An id outside those tables cannot be shown or selected by the realm, so it is never **written** to that
|
||||
//! realm; it stays in the canonical character and the profile collection, and is written when the character or the
|
||||
//! account reaches a realm that does know it.
|
||||
//!
|
||||
//! Woodworking appearances are synthesised by the core at startup and are not in the table: this Manager treats them as
|
||||
//! unknown to a destination (they are kept, never applied), which is the documented limitation of Phase 6.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::error::{PortableError, Result};
|
||||
|
||||
/// The four vanity items that open the personal Ascension bank. The bank is out of scope, so they are not part of the
|
||||
/// portable vanity collection (`AscensionCollectionService::BankVanityItems`).
|
||||
pub const BANK_VANITY_ITEMS: [u32; 4] = [110_000, 134_985, 509_892, 1_180_097];
|
||||
|
||||
pub fn is_bank_vanity_item(item: u32) -> bool {
|
||||
BANK_VANITY_ITEMS.contains(&item)
|
||||
}
|
||||
|
||||
const HEADER: usize = 20;
|
||||
/// Largest DBC read (the tables are a few MB).
|
||||
const MAX_DBC_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Default)]
|
||||
pub struct RealmKnowledge {
|
||||
appearances: IdSet,
|
||||
vanity: IdSet,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RealmKnowledge {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "RealmKnowledge({} appearances, {} vanity items)", self.appearances.len(), self.vanity.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl RealmKnowledge {
|
||||
pub fn new(appearances: IdSet, vanity: IdSet) -> Self {
|
||||
Self { appearances, vanity }
|
||||
}
|
||||
|
||||
/// Read `<data_dir>/dbc/Appearances.dbc` and `VanityCollection.dbc`.
|
||||
pub fn from_data_dir(data_dir: &Path) -> Result<Self> {
|
||||
let dbc = data_dir.join("dbc");
|
||||
let appearances = read_ids(&dbc.join("Appearances.dbc"), 0, 9)?;
|
||||
let vanity = read_ids(&dbc.join("VanityCollection.dbc"), 1, 77)?;
|
||||
Ok(Self { appearances: IdSet::from_ids(appearances)?, vanity: IdSet::from_ids(vanity)? })
|
||||
}
|
||||
|
||||
pub fn knows_appearance(&self, id: u32) -> bool {
|
||||
self.appearances.contains(id)
|
||||
}
|
||||
|
||||
pub fn knows_vanity(&self, item: u32) -> bool {
|
||||
self.vanity.contains(item)
|
||||
}
|
||||
|
||||
pub fn appearance_count(&self) -> usize {
|
||||
self.appearances.len()
|
||||
}
|
||||
|
||||
pub fn vanity_count(&self) -> usize {
|
||||
self.vanity.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of one DWORD column of a WDBC file (`WDBC`, record count, field count, record size, string size, records, strings).
|
||||
/// Zero ids are not records of anything and are skipped, as the core does.
|
||||
fn read_ids(path: &Path, id_dword: usize, minimum_dwords: usize) -> Result<Vec<u32>> {
|
||||
let bad = |what: &str| PortableError::SchemaMismatch(format!("{}: {what}", path.display()));
|
||||
let size = std::fs::metadata(path).map_err(|e| bad(&format!("cannot be read ({e})")))?.len();
|
||||
if size > MAX_DBC_BYTES {
|
||||
return Err(bad("is unreasonably large"));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| bad(&format!("cannot be read ({e})")))?;
|
||||
if bytes.len() < HEADER || &bytes[..4] != b"WDBC" {
|
||||
return Err(bad("is not a WDBC file"));
|
||||
}
|
||||
let field = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes")) as u64;
|
||||
let (records, record_size, strings) = (field(4), field(12), field(16));
|
||||
if HEADER as u64 + records * record_size + strings != bytes.len() as u64 {
|
||||
return Err(bad("header does not match the file size"));
|
||||
}
|
||||
if records > 0 && record_size < (minimum_dwords as u64) * 4 {
|
||||
return Err(bad("records are too small for this table"));
|
||||
}
|
||||
let record_size = record_size as usize;
|
||||
let mut ids = Vec::with_capacity(records as usize);
|
||||
for row in 0..records as usize {
|
||||
let at = HEADER + row * record_size + id_dword * 4;
|
||||
let id = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes"));
|
||||
if id != 0 {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn write_test_dbc(path: &Path, ids: &[u32], id_dword: usize, dwords: usize) {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(b"WDBC");
|
||||
out.extend_from_slice(&(ids.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(dwords as u32).to_le_bytes());
|
||||
out.extend_from_slice(&((dwords * 4) as u32).to_le_bytes());
|
||||
out.extend_from_slice(&1u32.to_le_bytes());
|
||||
for id in ids {
|
||||
for d in 0..dwords {
|
||||
out.extend_from_slice(&(if d == id_dword { *id } else { 7 }).to_le_bytes());
|
||||
}
|
||||
}
|
||||
out.push(0);
|
||||
std::fs::write(path, out).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_ids_of_the_two_client_tables_are_read_and_nothing_else_is_trusted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("dbc")).unwrap();
|
||||
write_test_dbc(&dir.path().join("dbc/Appearances.dbc"), &[5, 0, 9, 9, 100], 0, 9);
|
||||
write_test_dbc(&dir.path().join("dbc/VanityCollection.dbc"), &[1000, 2000], 1, 77);
|
||||
let k = RealmKnowledge::from_data_dir(dir.path()).unwrap();
|
||||
assert!(k.knows_appearance(5) && k.knows_appearance(9) && k.knows_appearance(100));
|
||||
assert!(!k.knows_appearance(0) && !k.knows_appearance(6));
|
||||
assert_eq!((k.appearance_count(), k.vanity_count()), (3, 2));
|
||||
assert!(k.knows_vanity(1000) && !k.knows_vanity(1));
|
||||
|
||||
// a truncated file, a wrong magic and a missing file are refused, never half read
|
||||
let path = dir.path().join("dbc/Appearances.dbc");
|
||||
let mut bytes = std::fs::read(&path).unwrap();
|
||||
bytes.truncate(bytes.len() - 5);
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
assert!(RealmKnowledge::from_data_dir(dir.path()).is_err());
|
||||
std::fs::write(&path, b"NOPE0000000000000000000").unwrap();
|
||||
assert!(RealmKnowledge::from_data_dir(dir.path()).is_err());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert!(RealmKnowledge::from_data_dir(dir.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bank_vanity_items_are_recognised() {
|
||||
assert!(is_bank_vanity_item(110_000) && is_bank_vanity_item(1_180_097));
|
||||
assert!(!is_bank_vanity_item(110_001));
|
||||
}
|
||||
}
|
||||
@@ -298,7 +298,7 @@ fn imports_are_refused_before_anything_is_written() {
|
||||
// ... and if the server starts between the preflight and the transaction, the transaction's own guard stops it
|
||||
let probe = super::probe(&r.b).unwrap();
|
||||
let users = vec!["acore".to_string()];
|
||||
let plan = build_plan(&model, &PlanContext { ruleset: Ruleset::Coa, account: ACCOUNT, revision: 1, nonce: [1, 2, 3, 4], max_characters_per_account: 10, game_server_users: &users, probe: &probe, session: None }).unwrap();
|
||||
let plan = build_plan(&model, &PlanContext { ruleset: Ruleset::Coa, account: ACCOUNT, revision: 1, nonce: [1, 2, 3, 4], max_characters_per_account: 10, game_server_users: &users, probe: &probe, session: None, knowledge: None }).unwrap();
|
||||
assert!(run_realm_import(&r.b, &plan).is_err(), "the in-transaction guard must refuse while the game server's session exists");
|
||||
session.join().unwrap();
|
||||
|
||||
@@ -352,7 +352,7 @@ fn a_crash_between_the_two_commits_is_recovered_from_the_marker_in_the_realm() {
|
||||
// the realm commits ... and the Manager "dies" before it records anything
|
||||
let ticket = store.begin_import(id, B, 1, &import::planned_items(&model), &[]).unwrap();
|
||||
let users = vec!["acore".to_string()];
|
||||
let plan = build_plan(&model, &PlanContext { ruleset: Ruleset::Coa, account: ACCOUNT, revision: 1, nonce: ticket.nonce, max_characters_per_account: 10, game_server_users: &users, probe: &probe, session: None }).unwrap();
|
||||
let plan = build_plan(&model, &PlanContext { ruleset: Ruleset::Coa, account: ACCOUNT, revision: 1, nonce: ticket.nonce, max_characters_per_account: 10, game_server_users: &users, probe: &probe, session: None, knowledge: None }).unwrap();
|
||||
let (alloc, committed) = run_realm_import(&r.b, &plan).unwrap();
|
||||
assert!(committed);
|
||||
assert_eq!(store.import_entry(ticket.import_id).unwrap().state, ImportState::Prepared);
|
||||
@@ -418,7 +418,7 @@ fn a_realm_that_no_longer_matches_the_plan_is_flagged_not_guessed_about() {
|
||||
let probe = super::probe(&r.b).unwrap();
|
||||
let ticket = store.begin_import(id, B, 1, &import::planned_items(&model), &[]).unwrap();
|
||||
let users = vec!["acore".to_string()];
|
||||
let plan = build_plan(&model, &PlanContext { ruleset: Ruleset::Coa, account: ACCOUNT, revision: 1, nonce: ticket.nonce, max_characters_per_account: 10, game_server_users: &users, probe: &probe, session: None }).unwrap();
|
||||
let plan = build_plan(&model, &PlanContext { ruleset: Ruleset::Coa, account: ACCOUNT, revision: 1, nonce: ticket.nonce, max_characters_per_account: 10, game_server_users: &users, probe: &probe, session: None, knowledge: None }).unwrap();
|
||||
let (alloc, _) = run_realm_import(&r.b, &plan).unwrap();
|
||||
// someone deletes an item of the new character before the Manager recovers
|
||||
r.b.query(&format!("DELETE FROM acore_characters.item_instance WHERE guid = {}", alloc.item_base + 3)).unwrap();
|
||||
|
||||
@@ -220,7 +220,7 @@ fn prepare_update(r: &Realms, store: &mut Store, id: CharacterId) -> (crate::por
|
||||
let schema = probe(&r.b).unwrap();
|
||||
let users = opts().game_server_users;
|
||||
let revision = canonical_revision(store, id);
|
||||
let ctx = |nonce| UpdateContext { ruleset: Ruleset::Coa, local_guid: guid, revision, nonce, game_server_users: &users, probe: &schema, items: &items, pets: &pets, session: None };
|
||||
let ctx = |nonce| UpdateContext { ruleset: Ruleset::Coa, local_guid: guid, revision, nonce, game_server_users: &users, probe: &schema, items: &items, pets: &pets, session: None, knowledge: None };
|
||||
let draft = build_update(&exported.model, &merged.model, &ctx([0; 4])).unwrap();
|
||||
let by_id: std::collections::HashMap<_, _> = merged.model.items.iter().map(|i| (i.id, i)).collect();
|
||||
let plan = UpdatePlan {
|
||||
|
||||
@@ -10,8 +10,10 @@
|
||||
//! Writing into a realm is Phase 3 and will use prepared statements / the realm's own import path.
|
||||
|
||||
pub mod blockers;
|
||||
pub mod collections;
|
||||
pub mod export;
|
||||
pub mod import;
|
||||
pub mod knowledge;
|
||||
pub mod online;
|
||||
pub mod plan;
|
||||
pub mod policy;
|
||||
@@ -20,6 +22,7 @@ pub mod registry;
|
||||
pub mod script;
|
||||
pub mod sqlenc;
|
||||
pub mod update;
|
||||
pub mod wardrobe;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
||||
@@ -46,16 +46,21 @@ struct SessionHeader {
|
||||
|
||||
/// What the realm needs of a character: no extensions (opaque module payloads the realm cannot apply), only the settings the
|
||||
/// policy carries.
|
||||
pub fn job_model(model: &PortableCharacter) -> PortableCharacter {
|
||||
pub fn job_model(model: &PortableCharacter, knowledge: Option<&super::knowledge::RealmKnowledge>) -> PortableCharacter {
|
||||
let mut m = model.clone();
|
||||
m.extensions.clear();
|
||||
// the selected appearances the realm's client data knows; without that knowledge none is sent (all stays canonical)
|
||||
m.wardrobe = match knowledge {
|
||||
Some(k) => m.wardrobe.restricted_to(|id| k.knows_appearance(id)),
|
||||
None => Default::default(),
|
||||
};
|
||||
m.settings.retain(|source, _| classify_setting(source, m.ruleset) == Disposition::Carry);
|
||||
m
|
||||
}
|
||||
|
||||
/// The bytes of a job file: the header, a newline, the canonical JSON of the character.
|
||||
pub fn job_bytes(job_id: ImportId, nonce: [u32; 4], account: u32, revision: u64, max_characters: u32, model: &PortableCharacter, session: Option<(SessionId, u32)>) -> Result<Vec<u8>> {
|
||||
let snapshot_json = snapshot::canonical_json(&job_model(model))?;
|
||||
pub fn job_bytes(job_id: ImportId, nonce: [u32; 4], account: u32, revision: u64, max_characters: u32, model: &PortableCharacter, session: Option<(SessionId, u32)>, knowledge: Option<&super::knowledge::RealmKnowledge>) -> Result<Vec<u8>> {
|
||||
let snapshot_json = snapshot::canonical_json(&job_model(model, knowledge))?;
|
||||
let header = JobHeader {
|
||||
job_id,
|
||||
nonce,
|
||||
@@ -118,7 +123,7 @@ pub fn import_character_online(ra: &mut Ra, store: &mut Store, character_id: Cha
|
||||
let ticket = store.begin_import(character_id, server_id, record.revision, &planned_items(&model), &planned_pets(&model))?;
|
||||
let (job_file, result_file) = job_paths(job_dir, ticket.import_id);
|
||||
let write = || -> Result<()> {
|
||||
let bytes = job_bytes(ticket.import_id, ticket.nonce, account, record.revision, opts.max_characters_per_account, &model, session.map(|s| (s, 1)))?;
|
||||
let bytes = job_bytes(ticket.import_id, ticket.nonce, account, record.revision, opts.max_characters_per_account, &model, session.map(|s| (s, 1)), opts.knowledge.as_deref())?;
|
||||
let temp = job_file.with_extension("job.tmp");
|
||||
std::fs::write(&temp, bytes)?;
|
||||
std::fs::rename(&temp, &job_file)?;
|
||||
@@ -178,7 +183,7 @@ mod tests {
|
||||
model.settings.insert("core.spell_charge.1".into(), vec![9]);
|
||||
model.settings.insert("core.ascension_build.54".into(), vec![1, 2]);
|
||||
let id = ImportId::new();
|
||||
let bytes = job_bytes(id, [1, 2, 3, 4], 7001, 5, 10, &model, Some((SessionId::new(), 1))).unwrap();
|
||||
let bytes = job_bytes(id, [1, 2, 3, 4], 7001, 5, 10, &model, Some((SessionId::new(), 1)), None).unwrap();
|
||||
let split = bytes.iter().position(|b| *b == b'\n').unwrap();
|
||||
let header: serde_json::Value = serde_json::from_slice(&bytes[..split]).unwrap();
|
||||
let body = &bytes[split + 1..];
|
||||
@@ -191,6 +196,6 @@ mod tests {
|
||||
assert!(sent.extensions.is_empty(), "opaque module payloads are not shipped to the realm");
|
||||
assert!(sent.settings.contains_key("core.ascension_build.54") && !sent.settings.contains_key("core.spell_charge.1"));
|
||||
assert_eq!(sent.items.len(), model.items.len());
|
||||
assert!(job_bytes(id, [0; 4], 1, 1, 10, &model, None).unwrap().len() > 100);
|
||||
assert!(job_bytes(id, [0; 4], 1, 1, 10, &model, None, None).unwrap().len() > 100);
|
||||
}
|
||||
}
|
||||
@@ -140,6 +140,8 @@ pub struct PlanContext<'a> {
|
||||
pub probe: &'a SchemaProbe,
|
||||
/// Arm a runtime portable session for the arrival: the core takes the baseline at its first load.
|
||||
pub session: Option<SessionArm>,
|
||||
/// What the destination's client data knows: appearances it does not know are not written.
|
||||
pub knowledge: Option<&'a super::knowledge::RealmKnowledge>,
|
||||
}
|
||||
|
||||
/// The portable session a character arrives with (`coa_portable_session` state 0).
|
||||
@@ -169,6 +171,7 @@ pub struct PlanCounts {
|
||||
pub declined: usize,
|
||||
pub settings: usize,
|
||||
pub macros: usize,
|
||||
pub wardrobe: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -478,6 +481,20 @@ pub fn build_plan(model: &PortableCharacter, ctx: &PlanContext<'_>) -> Result<Im
|
||||
_ => not_applied.push(source.clone()),
|
||||
}
|
||||
}
|
||||
// selected appearances: only what the destination's client data knows
|
||||
let wardrobe_rows = match super::wardrobe::writable(&model.wardrobe, None, ctx.knowledge, ctx.probe) {
|
||||
Some(w) => {
|
||||
counts.wardrobe = super::wardrobe::row_count(&w);
|
||||
inserts.extend(super::wardrobe::inserts(&w)?);
|
||||
Some(w)
|
||||
}
|
||||
None => {
|
||||
if !model.wardrobe.is_empty() {
|
||||
not_applied.push("wardrobe".to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
// extensions (module data this importer does not apply) stay in the snapshot only
|
||||
not_applied.extend(model.extensions.keys().cloned());
|
||||
counts.settings = settings.len();
|
||||
@@ -577,6 +594,10 @@ pub fn build_plan(model: &PortableCharacter, ctx: &PlanContext<'_>) -> Result<Im
|
||||
line(assert_count("acore_characters.character_action WHERE guid = @char", counts.actions));
|
||||
line(assert_count("acore_characters.character_pet WHERE owner = @char", counts.pets));
|
||||
line(assert_count("acore_characters.character_settings WHERE guid = @char", counts.settings + 1));
|
||||
if let Some(w) = &wardrobe_rows {
|
||||
line(assert_count("acore_characters.character_appearance WHERE guid = @char", w.active.len()));
|
||||
line(assert_count("acore_characters.character_appearance_outfit WHERE guid = @char", w.outfits.len()));
|
||||
}
|
||||
if ctx.session.is_some() {
|
||||
line(assert_count("acore_characters.coa_portable_session WHERE guid = @char", 1));
|
||||
}
|
||||
|
||||
@@ -247,6 +247,7 @@ pub fn update_realm_character_in_session(db: &Db, store: &mut Store, id: Charact
|
||||
items: &view.items,
|
||||
pets: &view.pets,
|
||||
session: session.map(|session_id| SessionArm { session_id, character_id: id, generation: 1 }),
|
||||
knowledge: opts.knowledge.as_deref(),
|
||||
};
|
||||
// the plan (what is added, what is removed) does not depend on the nonce
|
||||
let draft = build_update(&view.exported.model, &merged.model, &context([0; 4]))?;
|
||||
@@ -386,5 +387,5 @@ pub fn summarize(merged: &PortableCharacter, current: &PortableCharacter) -> Res
|
||||
let pets: HashMap<PortablePetId, u32> = current.pets.iter().enumerate().map(|(i, p)| (p.id, i as u32 + 1)).collect();
|
||||
let users = ["acore".to_string()];
|
||||
let schema = super::script::SchemaProbe::default();
|
||||
Ok(build_update(current, merged, &UpdateContext { ruleset: current.ruleset, local_guid: 1, revision: 1, nonce: [0; 4], game_server_users: &users, probe: &schema, items: &items, pets: &pets, session: None })?.counts)
|
||||
Ok(build_update(current, merged, &UpdateContext { ruleset: current.ruleset, local_guid: 1, revision: 1, nonce: [0; 4], game_server_users: &users, probe: &schema, items: &items, pets: &pets, session: None, knowledge: None })?.counts)
|
||||
}
|
||||
@@ -4,7 +4,9 @@
|
||||
//!
|
||||
//! * `Portable` exported in v1;
|
||||
//! * `Deferred` portable later by decision (equipment sets, per-character wardrobe, personal bank, codex);
|
||||
//! * `Collection` account-wide collections (Phase 6);
|
||||
//! * `Appearance` the character's selected appearances, outfits and visibility switches (Phase 6, carried in
|
||||
//! `PortableCharacter::wardrobe`; the tables belong to an optional module);
|
||||
//! * `Collection` account-wide permanent unlocks (Phase 6, a profile collection, not part of the character);
|
||||
//! * `AccountLocal` account / realm-account state, never carried;
|
||||
//! * `CharacterLocal` per-character state that is deliberately not portable (cooldowns, auras, mail links, ...);
|
||||
//! * `Blocking` per-character state of an active challenge / game mode / Manastorm: while it exists the
|
||||
@@ -18,6 +20,7 @@
|
||||
pub enum TableClass {
|
||||
Portable,
|
||||
Deferred,
|
||||
Appearance,
|
||||
Collection,
|
||||
AccountLocal,
|
||||
CharacterLocal,
|
||||
@@ -76,9 +79,9 @@ pub const TABLES: &[(&str, TableClass)] = &[
|
||||
("character_achievement_offline_updates", TableClass::CharacterLocal),
|
||||
("character_achievement_progress", TableClass::CharacterLocal),
|
||||
("character_action", TableClass::Portable),
|
||||
("character_appearance", TableClass::Deferred),
|
||||
("character_appearance_outfit", TableClass::Deferred),
|
||||
("character_appearance_settings", TableClass::Deferred),
|
||||
("character_appearance", TableClass::Appearance),
|
||||
("character_appearance_outfit", TableClass::Appearance),
|
||||
("character_appearance_settings", TableClass::Appearance),
|
||||
("character_arena_stats", TableClass::CharacterLocal),
|
||||
("character_ascension_state", TableClass::CharacterLocal),
|
||||
("character_aura", TableClass::CharacterLocal),
|
||||
@@ -272,9 +275,6 @@ mod tests {
|
||||
fn deferred_and_blocking_tables_match_the_decisions() {
|
||||
let deferred: BTreeSet<&str> = [
|
||||
"character_equipmentsets",
|
||||
"character_appearance",
|
||||
"character_appearance_outfit",
|
||||
"character_appearance_settings",
|
||||
"mod_ascension_bank_tab",
|
||||
"mod_ascension_bank_item",
|
||||
"mod_ascension_bank_money",
|
||||
@@ -284,6 +284,8 @@ mod tests {
|
||||
.into_iter()
|
||||
.collect();
|
||||
assert_eq!(of(TableClass::Deferred), deferred);
|
||||
let appearance: BTreeSet<&str> = ["character_appearance", "character_appearance_outfit", "character_appearance_settings"].into_iter().collect();
|
||||
assert_eq!(of(TableClass::Appearance), appearance);
|
||||
let blocking: BTreeSet<&str> = ["coa_character_challenge", "coa_character_gamemode", "coa_custom_trial_active", "ascension_manastorm_cache"].into_iter().collect();
|
||||
assert_eq!(of(TableClass::Blocking), blocking);
|
||||
let collections: BTreeSet<&str> = ["account_appearance_collection", "account_vanity_collection"].into_iter().collect();
|
||||
|
||||
@@ -261,6 +261,17 @@ pub fn queries(guid: u32, probe: &SchemaProbe) -> Result<Vec<Query>> {
|
||||
query("macros", &[("time", "d.`time`"), ("data", hex!("d.data"))], "acore_characters.character_account_data d WHERE d.guid = {guid} AND d.`type` = 5", guid),
|
||||
];
|
||||
|
||||
// The character's selected appearances (Phase 6): the tables exist only where the appearance module does.
|
||||
if probe.has("character_appearance") {
|
||||
out.push(query("appearance", &[("category", "a.category_id"), ("appearance", "a.appearance_id")], "acore_characters.character_appearance a WHERE a.guid = {guid} ORDER BY a.category_id", guid));
|
||||
}
|
||||
if probe.has("character_appearance_settings") {
|
||||
out.push(query("appearance_settings", &[("see_item", "a.can_see_item"), ("see_spell", "a.can_see_spell")], "acore_characters.character_appearance_settings a WHERE a.guid = {guid}", guid));
|
||||
}
|
||||
if probe.has("character_appearance_outfit") {
|
||||
out.push(query("appearance_outfits", &[("name", hex!("o.name")), ("appearances", hex!("o.appearances"))], "acore_characters.character_appearance_outfit o WHERE o.guid = {guid} ORDER BY o.name", guid));
|
||||
}
|
||||
|
||||
// The portable session marker of the core: read in the same snapshot as the character, so the marker says which save the rows are.
|
||||
if probe.has("coa_portable_session") {
|
||||
out.push(query(
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -222,6 +222,14 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
1 1101
|
||||
4 1104
|
||||
56 1156
|
||||
#T:appearance_settings
|
||||
1 0
|
||||
#T:appearance_outfits
|
||||
x53756E6461792062657374 x31313031203020302031313034
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -344,6 +344,9 @@ x636F72652E77696C64636172642E6361726473 x31203220
|
||||
x6D6F642E6578616D706C652E6E65775F66656174757265 x392038203720
|
||||
#T:macros
|
||||
1790000000 xFD2992936477103705783B2983ECDABC6F022B53FF446C4155EA1E0E31DF205D8B3FC6F87451B67413FD007D6B323F14D2FE5614DAB33BA9139D96F75EFE4E174239ED1136FC75F79A48242521E33AEE5A6F823526D45D0BCE04EA37BE3AF121DD56A5FB7426D3F9E8B71B94D4206BE32D2ACF91F3DD3AE245F707FD03E94EE0DAB632509D06D513DC0F8890EA7C3948CC225BDCBB0C8AF86CD220B053D96EDAF1447490F93185D89F27D586C80F528A4A487656EF877AF17D72DBC23E00ED38E64E2AA1CB0016697726654CBAE0465CCC0004677C123BC01ED87E7238E14295CDBBBF62DE4B7FAEDC776E0E9C0D6A047568D3719575223E440FAA36F1C5EF21FF2EFD915A8B3AB8234101E50332C8379D4E27FC28857EC526B00C50CBE696AE954521913EA5066031762940E310A5A4277DDAABB670AFCC984E06B3C55F3E0BEAD7E755F14A3E9FE98C46E9A32B2640668918AB1097C40FA5471006036F036469813F251E49C242543C82523BAB6E3CC5F165786319C50034233D86B4ADBB9CC7E105754FFF50808B70322090CCF883C207B250E0388124AA04FD08124D1F5F720DE546CA8E73DDC9E71BB1C5A0DF67B65CCC8AFCEDE46054CFD44B452B322D76B54CB041D9BB49F0CCC5EA584C30CD67BFE1DC599924483F019E05500EB6584A2F7AFCF838555047C3C901C74DD155E9EC10D3EFDB7A63CED430E92B6478676B56BDB7C204D131962AA83F14C7490D31847CAD304928DD3BF148BAE93DD0D82D1A361A455F6CAA3DBD1705F0281CFFF36CA6488F367560221D2C1BF44DBF05A48B9AB810F4A870E5E64A53181AAD6AB9AC484363468D130001FF20656E64
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -27,6 +27,9 @@
|
||||
3002 xD0A4D0B0D0BDD0B3D0B0 xD0A4D0B0D0BDD0B3D183 xD0A4D0B0D0BDD0B3 xD0A4D0B0D0BDD0B3D0BED0BC xD0A4D0B0D0BDD0B3D0B5
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
1
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#T:pet_declined
|
||||
#T:settings
|
||||
#T:macros
|
||||
#T:appearance
|
||||
#T:appearance_settings
|
||||
#T:appearance_outfits
|
||||
#T:portable_session
|
||||
#T:block:challenge
|
||||
0
|
||||
|
||||
@@ -638,3 +638,9 @@ INSERT INTO acore_characters.`characters` (`guid`, `account`, `name`, `race`, `c
|
||||
INSERT INTO acore_characters.coa_character_gamemode (guid, gameMode) VALUES (1012, 0);
|
||||
INSERT INTO acore_characters.coa_challenge_completion (guid, challengeId, level, completeTime, startTime) VALUES (1012, 5, 1, 1790000100, 1790000000);
|
||||
INSERT INTO acore_characters.coa_character_condition (guid, flag) VALUES (1012, 'finished_once');
|
||||
-- Phase 6: selected appearances of the geared character 1002 and the permanent unlocks of its account 5001.
|
||||
INSERT INTO acore_characters.character_appearance (guid, category_id, appearance_id) VALUES (1002, 1, 1101), (1002, 4, 1104), (1002, 56, 1156);
|
||||
INSERT INTO acore_characters.character_appearance_settings (guid, can_see_item, can_see_spell) VALUES (1002, 1, 0);
|
||||
INSERT INTO acore_characters.character_appearance_outfit (guid, name, appearances) VALUES (1002, 'Sunday best', '1101 0 0 1104');
|
||||
INSERT INTO acore_characters.account_appearance_collection (account_id, appearance_id, source_item) VALUES (5001, 1101, 40001), (5001, 1104, 40004), (5001, 1156, 0), (5001, 1200, 40200);
|
||||
INSERT INTO acore_characters.account_vanity_collection (account_id, item_id) VALUES (5001, 50001), (5001, 50002), (5001, 110000);
|
||||
@@ -81,6 +81,17 @@ fn a_naked_level_one_character() {
|
||||
roundtrip(m);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_appearances_visibility_and_outfits_are_exported_as_the_realm_shows_them() {
|
||||
let e = export(1002);
|
||||
let w = &e.model.wardrobe;
|
||||
assert_eq!(w.active, [(1, 1101), (4, 1104), (56, 1156)].into_iter().collect());
|
||||
assert!(w.can_see_item && !w.can_see_spell);
|
||||
assert_eq!(w.outfits["Sunday best"], vec![1101, 0, 0, 1104]);
|
||||
assert!(export(1001).model.wardrobe.is_empty(), "a character that never touched its wardrobe has none");
|
||||
roundtrip(&e.model);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_geared_character_with_bags_enchants_gems_and_special_items() {
|
||||
let e = export(1002);
|
||||
|
||||
@@ -39,6 +39,8 @@ pub struct UpdateContext<'a> {
|
||||
pub pets: &'a HashMap<PortablePetId, u32>,
|
||||
/// Arm a runtime portable session on the updated character (state 0: the core takes the baseline at its next load).
|
||||
pub session: Option<super::plan::SessionArm>,
|
||||
/// What the destination's client data knows: appearances it does not know are not written.
|
||||
pub knowledge: Option<&'a super::knowledge::RealmKnowledge>,
|
||||
}
|
||||
|
||||
/// What the script does, in numbers (and as the plan the journal records).
|
||||
@@ -318,6 +320,19 @@ pub fn build_update(current: &PortableCharacter, merged: &PortableCharacter, ctx
|
||||
}
|
||||
}
|
||||
|
||||
// selected appearances: replaced as a whole when what the realm can hold differs from what it shows
|
||||
if let Some(desired) = super::wardrobe::writable(&merged.wardrobe, Some(¤t.wardrobe), ctx.knowledge, ctx.probe) {
|
||||
if desired != current.wardrobe {
|
||||
counts.keyed_rows += super::wardrobe::row_count(¤t.wardrobe) + super::wardrobe::row_count(&desired);
|
||||
for table in super::wardrobe::TABLES {
|
||||
st.delete(Delete::new(table, char_key()));
|
||||
}
|
||||
for insert in super::wardrobe::inserts(&desired)? {
|
||||
st.insert(insert);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- items ------------------------------------------------------------------------------------------------------
|
||||
let cur_items: HashMap<PortableItemId, &PortableItem> = current.items.iter().map(|i| (i.id, i)).collect();
|
||||
let new_items: HashMap<PortableItemId, &PortableItem> = merged.items.iter().map(|i| (i.id, i)).collect();
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::script::SchemaProbe;
|
||||
use super::update::*;
|
||||
|
||||
fn probe() -> SchemaProbe {
|
||||
let tables = ["reserved_name", "item_refund_instance", "item_soulbound_trade_data", "pet_aura", "pet_spell_cooldown", "character_pet_declinedname", "character_gifts"];
|
||||
let tables = ["reserved_name", "item_refund_instance", "item_soulbound_trade_data", "pet_aura", "pet_spell_cooldown", "character_pet_declinedname", "character_gifts", "character_appearance", "character_appearance_settings", "character_appearance_outfit"];
|
||||
SchemaProbe { tables: tables.iter().map(|t| t.to_string()).collect(), character_columns: Default::default() }
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ fn script_of(current: &PortableCharacter, merged: &PortableCharacter) -> UpdateS
|
||||
let (items, pets) = realm_ids(current);
|
||||
let users = ["acore".to_string()];
|
||||
let probe = probe();
|
||||
build_update(current, merged, &UpdateContext { ruleset: Ruleset::Coa, local_guid: 4242, revision: 9, nonce: [1, 2, 3, 4], game_server_users: &users, probe: &probe, items: &items, pets: &pets, session: None }).unwrap()
|
||||
build_update(current, merged, &UpdateContext { ruleset: Ruleset::Coa, local_guid: 4242, revision: 9, nonce: [1, 2, 3, 4], game_server_users: &users, probe: &probe, items: &items, pets: &pets, session: None, knowledge: None }).unwrap()
|
||||
}
|
||||
|
||||
fn statements(script: &UpdateScript) -> Vec<&str> {
|
||||
@@ -184,7 +184,7 @@ fn what_a_character_is_cannot_be_changed_in_place() {
|
||||
let (items, pets) = realm_ids(¤t);
|
||||
let users = ["acore".to_string()];
|
||||
let probe = probe();
|
||||
let ctx = UpdateContext { ruleset: Ruleset::Coa, local_guid: 1, revision: 2, nonce: [0; 4], game_server_users: &users, probe: &probe, items: &items, pets: &pets, session: None };
|
||||
let ctx = UpdateContext { ruleset: Ruleset::Coa, local_guid: 1, revision: 2, nonce: [0; 4], game_server_users: &users, probe: &probe, items: &items, pets: &pets, session: None, knowledge: None };
|
||||
let mut merged = current.clone();
|
||||
merged.identity.gender ^= 1;
|
||||
assert!(build_update(¤t, &merged, &ctx).is_err(), "gender");
|
||||
@@ -225,3 +225,68 @@ fn the_report_parses_and_a_lost_commit_is_visible() {
|
||||
assert!(parse_update_report("").is_err());
|
||||
assert!(parse_update_report("#R:alloc\t1\t2\t3\t4\t5\n").is_err());
|
||||
}
|
||||
|
||||
// ---- Phase 6: selected appearances ----------------------------------------------------------------------------------------
|
||||
|
||||
fn script_known(current: &PortableCharacter, merged: &PortableCharacter, known: Option<&super::knowledge::RealmKnowledge>) -> UpdateScript {
|
||||
let (items, pets) = realm_ids(current);
|
||||
let users = ["acore".to_string()];
|
||||
let probe = probe();
|
||||
build_update(current, merged, &UpdateContext { ruleset: Ruleset::Coa, local_guid: 4242, revision: 9, nonce: [1, 2, 3, 4], game_server_users: &users, probe: &probe, items: &items, pets: &pets, session: None, knowledge: known }).unwrap()
|
||||
}
|
||||
|
||||
fn knows(ids: &[u32]) -> super::knowledge::RealmKnowledge {
|
||||
super::knowledge::RealmKnowledge::new(super::super::collection::IdSet::from_ids(ids.iter().copied()).unwrap(), Default::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_appearance_replaces_the_three_tables_and_touches_no_item() {
|
||||
let current = geared_level_eighty();
|
||||
let mut merged = current.clone();
|
||||
merged.wardrobe.active.insert(1, 100);
|
||||
merged.wardrobe.active.insert(3, 303);
|
||||
merged.wardrobe.outfits.insert("Sunday".into(), vec![100, 0, 303]);
|
||||
merged.wardrobe.can_see_item = false;
|
||||
let k = knows(&[100, 303]);
|
||||
let script = script_known(¤t, &merged, Some(&k));
|
||||
let w = writes(&script);
|
||||
for table in ["character_appearance", "character_appearance_settings", "character_appearance_outfit"] {
|
||||
assert!(w.iter().any(|l| l.starts_with(&format!("DELETE FROM acore_characters.`{table}` WHERE `guid` = @char"))), "{table}");
|
||||
}
|
||||
assert!(w.iter().any(|l| l.starts_with("INSERT INTO acore_characters.`character_appearance` ")));
|
||||
assert!(w.iter().any(|l| l.starts_with("INSERT INTO acore_characters.`character_appearance_outfit`")));
|
||||
assert!(w.iter().any(|l| l.starts_with("INSERT INTO acore_characters.`character_appearance_settings`")));
|
||||
assert!(!script.script.contains("item_instance") || script.counts.items_added + script.counts.items_removed + script.counts.items_changed == 0);
|
||||
assert_eq!((script.counts.items_added, script.counts.items_removed, script.counts.items_moved), (0, 0, 0), "no gameplay item is created, deleted or moved");
|
||||
assert_eq!(script.counts.keyed_rows, 4, "two selections, one outfit, one visibility row");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_appearance_the_realm_does_not_know_is_not_written_and_one_it_already_shows_is_kept() {
|
||||
let mut current = geared_level_eighty();
|
||||
current.wardrobe.active.insert(5, 555); // the realm itself shows this one (e.g. a synthesised appearance)
|
||||
let mut merged = current.clone();
|
||||
merged.wardrobe.active.insert(1, 100);
|
||||
merged.wardrobe.active.insert(2, 200); // unknown to this realm
|
||||
merged.wardrobe.outfits.insert("Mixed".into(), vec![100, 200]);
|
||||
let k = knows(&[100]);
|
||||
let script = script_known(¤t, &merged, Some(&k));
|
||||
let start = script.script.find("INSERT INTO acore_characters.`character_appearance` ").unwrap();
|
||||
let insert = script.script[start..].split(';').next().unwrap().to_string();
|
||||
assert!(insert.contains(", 1, 100)") && insert.contains(", 5, 555)"), "{insert}");
|
||||
assert!(!insert.contains(", 2, 200)"), "unknown to the realm: stays canonical, never written: {insert}");
|
||||
assert!(!script.script.contains("character_appearance_outfit` (") || !script.script.contains(&hex::encode("100 200")), "an outfit that mentions an unknown id is held back");
|
||||
|
||||
// without knowledge of the realm's client data nothing at all is written
|
||||
let none = script_known(¤t, &merged, None);
|
||||
assert!(!none.script.contains("character_appearance"), "no knowledge, no write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_appearance_writes_nothing() {
|
||||
let mut current = geared_level_eighty();
|
||||
current.wardrobe.active.insert(1, 100);
|
||||
let k = knows(&[100]);
|
||||
let script = script_known(¤t, ¤t.clone(), Some(&k));
|
||||
assert!(!script.script.contains("character_appearance"), "{}", script.script);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Writing a character's selected appearances (`PortableCharacter::wardrobe`) to a realm: shared by the importer (a new
|
||||
//! character) and the in-place update (a delta). The three tables belong to the appearance module, so they are written
|
||||
//! only where all three exist, and only what the realm **knows** (see [`super::knowledge`]).
|
||||
|
||||
use super::super::error::Result;
|
||||
use super::super::model::PortableAppearance;
|
||||
use super::knowledge::RealmKnowledge;
|
||||
use super::script::SchemaProbe;
|
||||
use super::sqlenc::{Insert, Val};
|
||||
|
||||
pub const TABLES: [&str; 3] = ["character_appearance", "character_appearance_settings", "character_appearance_outfit"];
|
||||
|
||||
pub fn tables_present(probe: &SchemaProbe) -> bool {
|
||||
TABLES.iter().all(|t| probe.has(t))
|
||||
}
|
||||
|
||||
/// The part of `desired` this realm can hold, or `None` when it cannot hold any (no knowledge of its client data, or no
|
||||
/// appearance tables). Whatever the realm already shows (`present`) is always kept writable: the realm itself put it there.
|
||||
pub fn writable(desired: &PortableAppearance, present: Option<&PortableAppearance>, knowledge: Option<&RealmKnowledge>, probe: &SchemaProbe) -> Option<PortableAppearance> {
|
||||
let knowledge = knowledge?;
|
||||
if !tables_present(probe) {
|
||||
return None;
|
||||
}
|
||||
let held = present.map(PortableAppearance::ids).unwrap_or_default();
|
||||
Some(desired.restricted_to(|id| knowledge.knows_appearance(id) || held.contains(&id)))
|
||||
}
|
||||
|
||||
/// The rows of `w` for the character `@char`, in the realm's own formats: a missing settings row means "both visible", and an
|
||||
/// outfit is a space separated list.
|
||||
pub fn inserts(w: &PortableAppearance) -> Result<[Insert; 3]> {
|
||||
let mut active = Insert::new("character_appearance", &["guid", "category_id", "appearance_id"]);
|
||||
for (category, appearance) in &w.active {
|
||||
active.row(vec![Val::Expr("@char"), Val::u(*category), Val::u(*appearance)])?;
|
||||
}
|
||||
let mut settings = Insert::new("character_appearance_settings", &["guid", "can_see_item", "can_see_spell"]);
|
||||
if !(w.can_see_item && w.can_see_spell) {
|
||||
settings.row(vec![Val::Expr("@char"), Val::u(w.can_see_item as u8), Val::u(w.can_see_spell as u8)])?;
|
||||
}
|
||||
let mut outfits = Insert::new("character_appearance_outfit", &["guid", "name", "appearances"]);
|
||||
for (name, ids) in &w.outfits {
|
||||
let text = ids.iter().map(u32::to_string).collect::<Vec<_>>().join(" ");
|
||||
outfits.row(vec![Val::Expr("@char"), Val::text(name.clone()), Val::text(text)])?;
|
||||
}
|
||||
Ok([active, settings, outfits])
|
||||
}
|
||||
|
||||
/// How many rows [`inserts`] writes.
|
||||
pub fn row_count(w: &PortableAppearance) -> usize {
|
||||
w.active.len() + w.outfits.len() + usize::from(!(w.can_see_item && w.can_see_spell))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::portable::collection::IdSet;
|
||||
|
||||
fn probe(all: bool) -> SchemaProbe {
|
||||
SchemaProbe { tables: TABLES.iter().take(if all { 3 } else { 2 }).map(|t| t.to_string()).collect(), character_columns: Default::default() }
|
||||
}
|
||||
|
||||
fn sample() -> PortableAppearance {
|
||||
let mut w = PortableAppearance::default();
|
||||
w.active.insert(1, 100);
|
||||
w.active.insert(3, 300);
|
||||
w.outfits.insert("Sunday".into(), vec![100, 0, 300]);
|
||||
w.outfits.insert("Mixed".into(), vec![100, 999]);
|
||||
w
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_known_ids_are_written_and_what_the_realm_already_shows_is_kept() {
|
||||
let k = RealmKnowledge::new(IdSet::from_ids([100, 300]).unwrap(), IdSet::new());
|
||||
let w = writable(&sample(), None, Some(&k), &probe(true)).unwrap();
|
||||
assert_eq!(w.active.len(), 2);
|
||||
assert!(w.outfits.contains_key("Sunday") && !w.outfits.contains_key("Mixed"), "an outfit that mentions an unknown id is held back whole");
|
||||
|
||||
// the realm shows 999 itself (a synthesised appearance): it stays writable
|
||||
let mut present = PortableAppearance::default();
|
||||
present.outfits.insert("Mixed".into(), vec![100, 999]);
|
||||
let w = writable(&sample(), Some(&present), Some(&k), &probe(true)).unwrap();
|
||||
assert!(w.outfits.contains_key("Mixed"));
|
||||
|
||||
assert!(writable(&sample(), None, None, &probe(true)).is_none(), "no knowledge of the client data: nothing is written");
|
||||
assert!(writable(&sample(), None, Some(&k), &probe(false)).is_none(), "no appearance tables: nothing is written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_use_the_realm_formats_and_hostile_names_are_hex() {
|
||||
let mut w = sample();
|
||||
w.can_see_spell = false;
|
||||
w.outfits.insert("x'); DROP TABLE characters; --".into(), vec![1]);
|
||||
let [a, s, o] = inserts(&w).unwrap();
|
||||
assert_eq!(a.len() + s.len() + o.len(), row_count(&w));
|
||||
let sql = o.sql().unwrap();
|
||||
assert!(!sql.contains("DROP") && sql.contains(&hex::encode("100 0 300")), "{sql}");
|
||||
assert_eq!(s.len(), 1);
|
||||
let default = inserts(&PortableAppearance::default()).unwrap();
|
||||
assert!(default.iter().all(Insert::is_empty), "the defaults are the absence of rows, like the realm's own");
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::error::Result;
|
||||
use super::super::realm::collections::Applied;
|
||||
use super::super::ids::{CharacterId, PortableItemId, PortablePetId, SessionId};
|
||||
use super::super::realm::Exported;
|
||||
|
||||
@@ -75,4 +77,15 @@ pub trait RealmBridge {
|
||||
fn release(&mut self, session: SessionId) -> Result<()>;
|
||||
/// Put the character's marker back to "waiting for baseline" with a new session (the character is offline).
|
||||
fn arm(&mut self, local_guid: u32, session: SessionId, character: CharacterId, revision: u64, generation: u32) -> Result<()>;
|
||||
|
||||
// ---- account collections (Phase 6) --------------------------------------------------------------------------------------
|
||||
|
||||
/// The game account that owns the character.
|
||||
fn account_of(&mut self, local_guid: u32) -> Result<Option<u32>>;
|
||||
/// A cheap fingerprint of the account's rows of one collection kind: equal fingerprints mean nothing changed.
|
||||
fn collection_fingerprint(&mut self, account: u32, kind: &str) -> Result<String>;
|
||||
/// The account's ids of one kind.
|
||||
fn read_collection(&mut self, account: u32, kind: &str) -> Result<IdSet>;
|
||||
/// Union the canonical ids into the account: only ids the realm knows and lacks are written.
|
||||
fn apply_collection(&mut self, account: u32, kind: &str, canonical: &IdSet) -> Result<Applied>;
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! Phase 6 on the simulated realm: the selected appearances ride in the character checkpoints, the account collections travel on
|
||||
//! their own channel and only when their hash changed, and a realm that lacks an unlock never removes it.
|
||||
|
||||
use super::fake::*;
|
||||
use super::protocol::*;
|
||||
use super::*;
|
||||
use crate::portable::collection::IdSet;
|
||||
use crate::portable::fixtures::geared_level_eighty;
|
||||
use crate::portable::model::PortableCharacter;
|
||||
use crate::portable::ids::{CharacterId, SessionId};
|
||||
use crate::portable::realm::knowledge::RealmKnowledge;
|
||||
use crate::portable::store::Store;
|
||||
|
||||
const SERVER: &str = "realm-b";
|
||||
const GUID: u32 = 4242;
|
||||
const APPEARANCE: &str = "coa:appearance";
|
||||
const VANITY: &str = "coa:vanity";
|
||||
|
||||
struct Rig {
|
||||
owner: Store,
|
||||
host: Store,
|
||||
realm: FakeRealm,
|
||||
id: CharacterId,
|
||||
session: SessionId,
|
||||
}
|
||||
|
||||
fn ids(range: std::ops::RangeInclusive<u32>) -> IdSet {
|
||||
IdSet::from_ids(range).unwrap()
|
||||
}
|
||||
|
||||
fn knows(appearances: IdSet, vanity: IdSet) -> RealmKnowledge {
|
||||
RealmKnowledge::new(appearances, vanity)
|
||||
}
|
||||
|
||||
fn rig(wardrobe: impl FnOnce(&mut PortableCharacter)) -> Rig {
|
||||
let mut owner = Store::open_in_memory().unwrap();
|
||||
let mut host = Store::open_in_memory().unwrap();
|
||||
let profile = owner.default_profile().unwrap();
|
||||
let mut model = geared_level_eighty();
|
||||
wardrobe(&mut model);
|
||||
let id = owner.create_character(profile, model, "realm-a").unwrap();
|
||||
let offer = OwnerService::new(&mut owner).offer(id, SERVER).unwrap();
|
||||
let host_profile = host.default_profile().unwrap();
|
||||
let mut realm = FakeRealm::new(GUID);
|
||||
{
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
h.accept_offer(host_profile, &offer).unwrap();
|
||||
realm.import(&mut host, id, SERVER, offer.canonical_revision, offer.session_id).unwrap();
|
||||
HostService::new(&mut host, SERVER, HostConfig::default()).bind(offer.session_id, GUID).unwrap();
|
||||
}
|
||||
Rig { owner, host, realm, id, session: offer.session_id }
|
||||
}
|
||||
|
||||
fn deliver_characters(h: &mut HostService, o: &mut OwnerService, realm: &mut FakeRealm) {
|
||||
for m in h.outbox().unwrap() {
|
||||
let ack = if m.started { o.handle_started(&m.bytes) } else { o.handle_checkpoint(&m.bytes) }.unwrap();
|
||||
h.receive_ack(realm, &ack).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry every queued collection message to the Owner and its answer back. Returns the acknowledgements.
|
||||
fn deliver_collections(h: &mut HostService, o: &mut OwnerService, realm: &mut FakeRealm) -> Vec<CollectionAck> {
|
||||
let mut acks = Vec::new();
|
||||
for m in h.collection_outbox().unwrap() {
|
||||
let ack = o.handle_collection(&m.bytes).unwrap();
|
||||
h.receive_collection_ack(realm, m.account, &ack).unwrap();
|
||||
acks.push(ack);
|
||||
}
|
||||
acks
|
||||
}
|
||||
|
||||
fn start(h: &mut HostService, o: &mut OwnerService, realm: &mut FakeRealm) -> Vec<HostEvent> {
|
||||
realm.login();
|
||||
let events = h.tick(realm, 0).unwrap();
|
||||
deliver_characters(h, o, realm);
|
||||
events
|
||||
}
|
||||
|
||||
fn queued(events: &[HostEvent]) -> Vec<(String, usize)> {
|
||||
events.iter().filter_map(|e| if let HostEvent::CollectionQueued { kind, count } = e { Some((kind.clone(), *count)) } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selected_appearance_travels_in_the_checkpoints_and_no_item_is_created_or_deleted() {
|
||||
let Rig { mut owner, mut host, mut realm, id, session } = rig(|m| {
|
||||
m.wardrobe.active.insert(1, 100);
|
||||
});
|
||||
let c0 = owner.load_current(id).unwrap();
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
assert_eq!(start(&mut h, &mut o, &mut realm).iter().filter(|e| matches!(e, HostEvent::BaselineTaken { .. })).count(), 1);
|
||||
|
||||
realm.play(|m| {
|
||||
m.wardrobe.active.insert(3, 303);
|
||||
m.wardrobe.active.insert(56, 5600);
|
||||
m.wardrobe.outfits.insert("Sunday".into(), vec![100, 0, 303]);
|
||||
m.wardrobe.can_see_item = false;
|
||||
});
|
||||
h.tick(&mut realm, 100).unwrap();
|
||||
h.tick(&mut realm, 101).unwrap();
|
||||
deliver_characters(&mut h, &mut o, &mut realm);
|
||||
let c1 = o.store().load_current(id).unwrap();
|
||||
assert_eq!(c1.wardrobe.active, [(1, 100), (3, 303), (56, 5600)].into_iter().collect());
|
||||
assert_eq!(c1.wardrobe.outfits["Sunday"], vec![100, 0, 303]);
|
||||
assert!(!c1.wardrobe.can_see_item && c1.wardrobe.can_see_spell);
|
||||
let normalised = |m: &crate::portable::model::PortableCharacter| m.items.iter().map(|i| (i.entry.clone(), i.slot, i.count)).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(normalised(&c1), normalised(&c0), "applying an appearance never creates, changes or deletes a gameplay item");
|
||||
|
||||
// deselecting a category, deleting an outfit, then logout
|
||||
realm.play(|m| {
|
||||
m.wardrobe.active.remove(&56);
|
||||
m.wardrobe.outfits.clear();
|
||||
});
|
||||
realm.logout();
|
||||
h.tick(&mut realm, 200).unwrap();
|
||||
deliver_characters(&mut h, &mut o, &mut realm);
|
||||
let c2 = o.store().load_current(id).unwrap();
|
||||
assert_eq!(c2.wardrobe.active, [(1, 100), (3, 303)].into_iter().collect());
|
||||
assert!(c2.wardrobe.outfits.is_empty());
|
||||
assert_eq!(o.session(session).unwrap().unwrap().0, "closed");
|
||||
assert_eq!(normalised(&c2), normalised(&c0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_appearance_the_realm_cannot_show_stays_canonical_through_the_whole_session() {
|
||||
// the canonical character wears 999, which this realm never showed: its B0 and B1 do not have it
|
||||
let Rig { mut owner, mut host, mut realm, id, .. } = rig(|m| {
|
||||
m.wardrobe.active.insert(1, 100);
|
||||
m.wardrobe.active.insert(2, 999);
|
||||
m.wardrobe.outfits.insert("Far away".into(), vec![999, 1000]);
|
||||
});
|
||||
realm.db.wardrobe = Default::default();
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
start(&mut h, &mut o, &mut realm);
|
||||
realm.play(|m| {
|
||||
m.wardrobe.active.insert(3, 303);
|
||||
});
|
||||
h.tick(&mut realm, 100).unwrap();
|
||||
h.tick(&mut realm, 101).unwrap();
|
||||
deliver_characters(&mut h, &mut o, &mut realm);
|
||||
realm.logout();
|
||||
h.tick(&mut realm, 200).unwrap();
|
||||
deliver_characters(&mut h, &mut o, &mut realm);
|
||||
let c = o.store().load_current(id).unwrap();
|
||||
assert_eq!(c.wardrobe.active.get(&2), Some(&999), "kept");
|
||||
assert_eq!(c.wardrobe.active.get(&3), Some(&303), "and what the player chose here is added");
|
||||
assert!(c.wardrobe.outfits.contains_key("Far away"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_collection_is_sent_only_when_its_hash_changed_and_never_with_a_checkpoint() {
|
||||
let Rig { mut owner, mut host, mut realm, .. } = rig(|_| {});
|
||||
realm.knowledge = knows(ids(1..=10_000), ids(1..=100));
|
||||
realm.unlock(APPEARANCE, 1..=5);
|
||||
realm.unlock(VANITY, [7, 9]);
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
|
||||
// the session starts: both collections are looked at once and sent
|
||||
let events = start_collecting(&mut h, &mut o, &mut realm);
|
||||
assert_eq!(queued(&events), vec![(APPEARANCE.to_string(), 5), (VANITY.to_string(), 2)]);
|
||||
let acks = deliver_collections(&mut h, &mut o, &mut realm);
|
||||
assert!(acks.iter().all(|a| a.outcome == CollectionOutcome::Applied && a.canonical.is_none()), "{acks:?}");
|
||||
assert_eq!(acks[0].collection_revision, 1);
|
||||
let reads = realm.full_reads;
|
||||
assert!(h.collection_outbox().unwrap().is_empty());
|
||||
|
||||
// a 60-second checkpoint cadence never touches the collections: the interval is 300 s and nothing changed
|
||||
for now in [100, 160, 220] {
|
||||
h.tick(&mut realm, now).unwrap();
|
||||
deliver_characters(&mut h, &mut o, &mut realm);
|
||||
}
|
||||
assert_eq!(realm.full_reads, reads, "nothing was read");
|
||||
|
||||
// due, but the fingerprint is the same: still nothing read, nothing sent
|
||||
let before = realm.fingerprints;
|
||||
let events = h.tick(&mut realm, 400).unwrap();
|
||||
assert!(realm.fingerprints > before, "the cheap look happened");
|
||||
assert_eq!(realm.full_reads, reads, "an unchanged fingerprint reads nothing");
|
||||
assert!(queued(&events).is_empty() && h.collection_outbox().unwrap().is_empty());
|
||||
|
||||
// the player unlocks more: the next look reads and sends the compact set once
|
||||
realm.unlock(APPEARANCE, [6, 77]);
|
||||
let events = h.tick(&mut realm, 800).unwrap();
|
||||
assert_eq!(queued(&events), vec![(APPEARANCE.to_string(), 7)]);
|
||||
let acks = deliver_collections(&mut h, &mut o, &mut realm);
|
||||
assert_eq!((acks.len(), &acks[0].outcome, acks[0].collection_revision), (1, &CollectionOutcome::Applied, 2));
|
||||
assert!(queued(&h.tick(&mut realm, 1200).unwrap()).is_empty(), "and then it is quiet again");
|
||||
|
||||
// no checkpoint message contains a collection
|
||||
for m in h.store().host_message(rig_session(&h), 1).unwrap().into_iter() {
|
||||
let text = String::from_utf8(m).unwrap();
|
||||
assert!(!text.contains("collection") && !text.contains("\"ids\""), "a checkpoint carries no wardrobe");
|
||||
}
|
||||
}
|
||||
|
||||
fn rig_session(h: &HostService) -> SessionId {
|
||||
h.store().host_live_sessions(SERVER).unwrap().into_iter().next().unwrap().session_id
|
||||
}
|
||||
|
||||
fn start_collecting(h: &mut HostService, o: &mut OwnerService, realm: &mut FakeRealm) -> Vec<HostEvent> {
|
||||
start(h, o, realm)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() {
|
||||
let Rig { mut owner, mut host, mut realm, .. } = rig(|_| {});
|
||||
// the Owner already holds a big wardrobe from other realms
|
||||
let profile = owner.default_profile().unwrap();
|
||||
owner.merge_collection(profile, APPEARANCE, &ids(1..=500)).unwrap();
|
||||
owner.merge_collection(profile, VANITY, &ids(1000..=1010)).unwrap();
|
||||
// this realm knows only part of it and holds only a few
|
||||
realm.knowledge = knows(ids(1..=300), ids(1000..=1005));
|
||||
realm.unlock(APPEARANCE, [5, 6, 700]);
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
start(&mut h, &mut o, &mut realm);
|
||||
let acks = deliver_collections(&mut h, &mut o, &mut realm);
|
||||
|
||||
// the Owner unioned the realm's ids (700 included: the realm showed it) and kept everything else
|
||||
let appearance_ack = acks.iter().find(|a| a.kind == APPEARANCE).unwrap();
|
||||
assert_eq!(appearance_ack.outcome, CollectionOutcome::Applied);
|
||||
let (_, canonical) = o.store().collection(profile, APPEARANCE).unwrap().unwrap();
|
||||
assert_eq!(canonical.len(), 501);
|
||||
assert!(canonical.contains(700) && canonical.contains(1) && canonical.contains(500), "nothing was removed");
|
||||
|
||||
// the realm received what its client data knows: 1..=300 minus what it had; the ids it cannot show stay canonical only
|
||||
assert!((1..=300).all(|id| realm.appearance_rows.contains(id)));
|
||||
assert!(!realm.appearance_rows.contains(301) && !realm.appearance_rows.contains(500), "unknown to this realm: not written");
|
||||
assert!(realm.appearance_rows.contains(700), "its own row is never removed");
|
||||
assert!((1000..=1005).all(|id| realm.vanity_rows.contains(id)) && !realm.vanity_rows.contains(1006));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_with_unlocks_arrives_on_a_second_realm_from_the_owners_state_alone() {
|
||||
let mut owner = Store::open_in_memory().unwrap();
|
||||
let profile = owner.default_profile().unwrap();
|
||||
owner.merge_collection(profile, APPEARANCE, &ids(1..=40)).unwrap();
|
||||
owner.merge_collection(profile, VANITY, &ids(50..=60)).unwrap();
|
||||
let states = OwnerService::new(&mut owner).collection_states().unwrap();
|
||||
assert_eq!(states.len(), 2);
|
||||
|
||||
let mut host = Store::open_in_memory().unwrap();
|
||||
let mut realm = FakeRealm::new(GUID);
|
||||
realm.knowledge = knows(ids(1..=30), ids(50..=60));
|
||||
realm.unlock(APPEARANCE, [3]);
|
||||
let mut h = HostService::new(&mut host, "realm-c", HostConfig::default());
|
||||
for state in &states {
|
||||
let applied = h.receive_collection_state(&mut realm, 1, state).unwrap().unwrap();
|
||||
assert_eq!(applied.unknown, if state.kind == APPEARANCE { 10 } else { 0 });
|
||||
}
|
||||
assert_eq!(realm.appearance_rows.len(), 30);
|
||||
assert_eq!(realm.vanity_rows.len(), 11);
|
||||
// the same state again writes nothing
|
||||
let writes = realm.collection_writes;
|
||||
for state in &states {
|
||||
assert_eq!(h.receive_collection_state(&mut realm, 1, state).unwrap().unwrap().inserted, 0);
|
||||
}
|
||||
assert_eq!(realm.collection_writes, writes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_or_broken_collection_messages_change_nothing() {
|
||||
let mut owner = Store::open_in_memory().unwrap();
|
||||
let profile = owner.default_profile().unwrap();
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
let good = collection_to_json(&CollectionObserved::new(SERVER, APPEARANCE, &ids(1..=10)).unwrap()).unwrap();
|
||||
assert_eq!(o.handle_collection(&good).unwrap().outcome, CollectionOutcome::Applied);
|
||||
let state_of = |o: &OwnerService| o.store().collection_info(profile, APPEARANCE).unwrap().unwrap();
|
||||
let before = state_of(&o);
|
||||
|
||||
// garbage, wrong version, unknown field, over the size cap: errors, nothing changes
|
||||
assert!(o.handle_collection(b"not json").is_err());
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&good).unwrap();
|
||||
v["protocol_version"] = 99.into();
|
||||
assert!(o.handle_collection(&serde_json::to_vec(&v).unwrap()).is_err());
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&good).unwrap();
|
||||
v["extra"] = 1.into();
|
||||
assert!(o.handle_collection(&serde_json::to_vec(&v).unwrap()).is_err());
|
||||
assert!(o.handle_collection(&vec![b' '; MAX_COLLECTION_MESSAGE_BYTES + 1]).is_err());
|
||||
|
||||
// parsed but not acceptable: answered with a rejection, never merged
|
||||
for (what, edit) in [
|
||||
("a hash that does not match", Box::new(|v: &mut serde_json::Value| v["set"]["hash"] = "00".repeat(32).into()) as Box<dyn Fn(&mut serde_json::Value)>),
|
||||
("a count that does not match", Box::new(|v: &mut serde_json::Value| v["set"]["count"] = 3.into())),
|
||||
("a kind that is not carried", Box::new(|v: &mut serde_json::Value| v["kind"] = "coa:mounts".into())),
|
||||
("a payload that is not base64", Box::new(|v: &mut serde_json::Value| v["set"]["ids"] = "***".into())),
|
||||
("a payload with trailing bytes", Box::new(|v: &mut serde_json::Value| v["set"]["ids"] = "AQoBAQEBAQEBAQEBAQEBAAAA".into())),
|
||||
] {
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&good).unwrap();
|
||||
edit(&mut v);
|
||||
let ack = o.handle_collection(&serde_json::to_vec(&v).unwrap()).unwrap();
|
||||
assert!(matches!(ack.outcome, CollectionOutcome::Rejected(_)), "{what}: {ack:?}");
|
||||
}
|
||||
assert_eq!(state_of(&o), before, "nothing was merged by any of them");
|
||||
|
||||
// a set that decodes to more ids than the cap allows is refused before it is built
|
||||
let mut huge = vec![1u8];
|
||||
huge.extend([0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
|
||||
let message = serde_json::json!({"protocol_version": 1, "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}});
|
||||
assert!(matches!(o.handle_collection(&serde_json::to_vec(&message).unwrap()).unwrap().outcome, CollectionOutcome::Rejected(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ten_thousand_and_fifty_thousand_ids_stay_cheap() {
|
||||
for count in [10_000u32, 50_000] {
|
||||
let started = std::time::Instant::now();
|
||||
let Rig { mut owner, mut host, mut realm, .. } = rig(|_| {});
|
||||
// scattered ids, as a real wardrobe is
|
||||
let scattered: Vec<u32> = (0..count).map(|i| 1 + i * 7 + (i * i) % 5).collect();
|
||||
realm.knowledge = knows(IdSet::from_ids(scattered.iter().copied()).unwrap(), IdSet::new());
|
||||
realm.unlock(APPEARANCE, scattered.iter().copied());
|
||||
let profile = owner.default_profile().unwrap();
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
let events = start(&mut h, &mut o, &mut realm);
|
||||
assert_eq!(queued(&events), vec![(APPEARANCE.to_string(), count as usize), (VANITY.to_string(), 0)], "the first look reports every kind, even an empty one");
|
||||
|
||||
let messages: Vec<_> = h.collection_outbox().unwrap().into_iter().filter(|m| m.kind == APPEARANCE).collect();
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert!(messages[0].bytes.len() < count as usize * 4, "{} ids -> {} bytes: compact, not a JSON array", count, messages[0].bytes.len());
|
||||
assert!(!String::from_utf8_lossy(&messages[0].bytes).contains(&format!("{},", scattered[1])), "no verbose id list");
|
||||
let ack = o.handle_collection(&messages[0].bytes).unwrap();
|
||||
assert_eq!(ack.outcome, CollectionOutcome::Applied);
|
||||
h.receive_collection_ack(&mut realm, messages[0].account, &ack).unwrap();
|
||||
|
||||
// unchanged: a look costs one fingerprint and reads nothing, however big the collection is
|
||||
let reads = realm.full_reads;
|
||||
h.tick(&mut realm, 400).unwrap();
|
||||
h.tick(&mut realm, 900).unwrap();
|
||||
assert_eq!(realm.full_reads, reads);
|
||||
let stored = o.store().collection_info(profile, APPEARANCE).unwrap().unwrap();
|
||||
assert_eq!(stored.count, count as usize);
|
||||
|
||||
// the Owner's answer to a realm with nothing is the whole compact set, once
|
||||
let mut empty_host = Store::open_in_memory().unwrap();
|
||||
let mut empty_realm = FakeRealm::new(GUID);
|
||||
empty_realm.knowledge = realm.knowledge.clone();
|
||||
let state = o.collection_states().unwrap().into_iter().find(|s| s.kind == APPEARANCE).unwrap();
|
||||
let applied = HostService::new(&mut empty_host, "realm-c", HostConfig::default()).receive_collection_state(&mut empty_realm, 1, &state).unwrap().unwrap();
|
||||
assert_eq!(applied.inserted, count as usize);
|
||||
assert!(started.elapsed().as_secs() < 20, "{count} ids took {:?}", started.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lost_acknowledgement_resends_the_same_set_and_the_owner_counts_it_once() {
|
||||
let Rig { mut owner, mut host, mut realm, .. } = rig(|_| {});
|
||||
realm.knowledge = knows(ids(1..=100), IdSet::new());
|
||||
realm.unlock(APPEARANCE, 1..=20);
|
||||
let profile = owner.default_profile().unwrap();
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
start(&mut h, &mut o, &mut realm);
|
||||
// the message reaches the Owner but its answer is lost
|
||||
let m = h.collection_outbox().unwrap().into_iter().find(|m| m.kind == APPEARANCE).unwrap();
|
||||
assert_eq!(o.handle_collection(&m.bytes).unwrap().outcome, CollectionOutcome::Applied);
|
||||
assert!(h.collection_outbox().unwrap().iter().any(|p| p.kind == APPEARANCE), "the Host still holds it");
|
||||
// delivered again: the union adds nothing
|
||||
let ack = o.handle_collection(&m.bytes).unwrap();
|
||||
assert_eq!(ack.outcome, CollectionOutcome::Unchanged);
|
||||
h.receive_collection_ack(&mut realm, m.account, &ack).unwrap();
|
||||
assert!(!h.collection_outbox().unwrap().iter().any(|p| p.kind == APPEARANCE));
|
||||
assert_eq!(o.store().collection_info(profile, APPEARANCE).unwrap().unwrap().revision, 1, "one revision, not two");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_host_has_not_had_acknowledged_survives_a_restart_and_what_it_has_acknowledged_is_not_sent_again() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let owner_dir = dir.path().join("owner");
|
||||
let host_dir = dir.path().join("host");
|
||||
let Rig { owner: _, host: _, mut realm, .. } = rig(|_| {});
|
||||
realm.knowledge = knows(ids(1..=100), IdSet::new());
|
||||
realm.unlock(APPEARANCE, 1..=10);
|
||||
// the same character on file-backed stores
|
||||
let mut owner = Store::open(&owner_dir).unwrap();
|
||||
let mut host = Store::open(&host_dir).unwrap();
|
||||
let profile = owner.default_profile().unwrap();
|
||||
let id = owner.create_character(profile, geared_level_eighty(), "realm-a").unwrap();
|
||||
let offer = OwnerService::new(&mut owner).offer(id, SERVER).unwrap();
|
||||
let host_profile = host.default_profile().unwrap();
|
||||
HostService::new(&mut host, SERVER, HostConfig::default()).accept_offer(host_profile, &offer).unwrap();
|
||||
realm.import(&mut host, id, SERVER, offer.canonical_revision, offer.session_id).unwrap();
|
||||
{
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
h.bind(offer.session_id, GUID).unwrap();
|
||||
realm.login();
|
||||
h.tick(&mut realm, 0).unwrap();
|
||||
assert!(h.collection_outbox().unwrap().iter().any(|m| m.kind == APPEARANCE));
|
||||
}
|
||||
drop(host);
|
||||
|
||||
// the Host process restarts: the unacknowledged message is still there, the realm is not read again for it
|
||||
let mut host = Store::open(&host_dir).unwrap();
|
||||
let reads = realm.full_reads;
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
let pending: Vec<_> = h.collection_outbox().unwrap();
|
||||
assert!(pending.iter().any(|m| m.kind == APPEARANCE));
|
||||
for m in &pending {
|
||||
let ack = o.handle_collection(&m.bytes).unwrap();
|
||||
h.receive_collection_ack(&mut realm, m.account, &ack).unwrap();
|
||||
}
|
||||
assert!(h.collection_outbox().unwrap().is_empty());
|
||||
assert_eq!(realm.full_reads, reads);
|
||||
|
||||
// another restart: acknowledged is acknowledged, and the unchanged fingerprint means no read and no message
|
||||
drop(h);
|
||||
drop(host);
|
||||
let mut host = Store::open(&host_dir).unwrap();
|
||||
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
|
||||
let events = h.tick(&mut realm, 5000).unwrap();
|
||||
assert!(queued(&events).is_empty() && h.collection_outbox().unwrap().is_empty());
|
||||
assert_eq!(realm.full_reads, reads, "nothing was read again after the first look of the two kinds");
|
||||
}
|
||||
@@ -3,10 +3,13 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::error::{PortableError, Result};
|
||||
use super::super::identity::item_identity;
|
||||
use super::super::ids::{CharacterId, ContentId, PortableItemId, PortablePetId, SessionId};
|
||||
use super::super::model::*;
|
||||
use super::super::realm::collections::Applied;
|
||||
use super::super::realm::knowledge::RealmKnowledge;
|
||||
use super::super::realm::Exported;
|
||||
use super::super::store::{pet_identity, ImportAllocation, ItemObservation, PetObservation, PlannedItem, PlannedPet, Store};
|
||||
use super::bridge::*;
|
||||
@@ -30,6 +33,16 @@ pub struct FakeRealm {
|
||||
pub saves: u32,
|
||||
pub released: Vec<SessionId>,
|
||||
pub normalize: fn(&mut FakeRealm),
|
||||
/// The game account of the character and its two collection tables.
|
||||
pub account: u32,
|
||||
pub appearance_rows: IdSet,
|
||||
pub vanity_rows: IdSet,
|
||||
/// The realm's client data: what it can show.
|
||||
pub knowledge: RealmKnowledge,
|
||||
/// How often the collections were fingerprinted, read in full and written (the tests prove "nothing changed, nothing read").
|
||||
pub fingerprints: u32,
|
||||
pub full_reads: u32,
|
||||
pub collection_writes: u32,
|
||||
}
|
||||
|
||||
pub fn new_internal_item(n: u64, slot: u8, entry: u64) -> PortableItem {
|
||||
@@ -70,6 +83,13 @@ impl FakeRealm {
|
||||
saves: 0,
|
||||
released: vec![],
|
||||
normalize: |_| {},
|
||||
account: 1,
|
||||
appearance_rows: IdSet::new(),
|
||||
vanity_rows: IdSet::new(),
|
||||
knowledge: RealmKnowledge::default(),
|
||||
fingerprints: 0,
|
||||
full_reads: 0,
|
||||
collection_writes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,4 +276,69 @@ impl RealmBridge for FakeRealm {
|
||||
self.row = Some(SessionRow { guid: local_guid, session_id: session, character_id: character, imported_revision: revision, generation, state: RowState::WaitingBaseline, checkpoint_seq: 0, save_seq });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn account_of(&mut self, local_guid: u32) -> Result<Option<u32>> {
|
||||
Ok((local_guid == self.guid).then_some(self.account))
|
||||
}
|
||||
|
||||
fn collection_fingerprint(&mut self, account: u32, kind: &str) -> Result<String> {
|
||||
assert_eq!(account, self.account);
|
||||
self.fingerprints += 1;
|
||||
let set = self.rows(kind)?;
|
||||
Ok(format!("{}:{}:{}", set.len(), set.ids().last().copied().unwrap_or(0), set.ids().iter().map(|i| *i as u64).sum::<u64>()))
|
||||
}
|
||||
|
||||
fn read_collection(&mut self, account: u32, kind: &str) -> Result<IdSet> {
|
||||
assert_eq!(account, self.account);
|
||||
self.full_reads += 1;
|
||||
Ok(self.rows(kind)?.clone())
|
||||
}
|
||||
|
||||
fn apply_collection(&mut self, account: u32, kind: &str, canonical: &IdSet) -> Result<Applied> {
|
||||
assert_eq!(account, self.account);
|
||||
let knows = |id: u32| if kind == "coa:appearance" { self.knowledge.knows_appearance(id) } else { self.knowledge.knows_vanity(id) };
|
||||
let held = self.rows(kind)?.clone();
|
||||
let mut applied = Applied::default();
|
||||
let mut add = Vec::new();
|
||||
for id in canonical.ids().iter().copied() {
|
||||
if !knows(id) {
|
||||
applied.unknown += 1;
|
||||
} else if held.contains(id) {
|
||||
applied.already += 1;
|
||||
} else {
|
||||
add.push(id);
|
||||
}
|
||||
}
|
||||
applied.inserted = add.len();
|
||||
if !add.is_empty() {
|
||||
self.collection_writes += 1;
|
||||
let union = held.union(&IdSet::from_ids(add)?);
|
||||
*self.rows_mut(kind)? = union;
|
||||
}
|
||||
Ok(applied)
|
||||
}
|
||||
}
|
||||
|
||||
impl FakeRealm {
|
||||
fn rows(&self, kind: &str) -> Result<&IdSet> {
|
||||
match kind {
|
||||
"coa:appearance" => Ok(&self.appearance_rows),
|
||||
"coa:vanity" => Ok(&self.vanity_rows),
|
||||
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn rows_mut(&mut self, kind: &str) -> Result<&mut IdSet> {
|
||||
match kind {
|
||||
"coa:appearance" => Ok(&mut self.appearance_rows),
|
||||
"coa:vanity" => Ok(&mut self.vanity_rows),
|
||||
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The player unlocks ids (the core `INSERT IGNORE`s them).
|
||||
pub fn unlock(&mut self, kind: &str, ids: impl IntoIterator<Item = u32>) {
|
||||
let union = self.rows(kind).unwrap().union(&IdSet::from_ids(ids).unwrap());
|
||||
*self.rows_mut(kind).unwrap() = union;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
//! The Host's session driver: arms sessions, takes the automatic baseline, runs checkpoints and queues the messages the
|
||||
//! Owner must receive. It never decides what the canonical character becomes and never opens the Owner's database.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::error::{PortableError, Result};
|
||||
use super::super::realm::collections::Applied;
|
||||
use super::super::ids::{CharacterId, PortableItemId, PortablePetId, ProfileId, SessionId};
|
||||
use super::super::store::{AckEffect, HostSession, HostState, OutboxMessage, Store};
|
||||
use super::super::store::{AckEffect, CollectionOutboxMessage, HostSession, HostState, OutboxMessage, Store};
|
||||
use super::bridge::{CheckpointReply, RealmBridge, RealmRead, RowState};
|
||||
use super::protocol::*;
|
||||
|
||||
@@ -13,11 +15,14 @@ use super::protocol::*;
|
||||
pub struct HostConfig {
|
||||
/// Seconds between checkpoints of a running session.
|
||||
pub checkpoint_interval_secs: u64,
|
||||
/// Seconds between looks at the account collections of a running session (a look is one cheap query per kind; the
|
||||
/// collection is read and sent only when its fingerprint changed). A session start and a final checkpoint always look.
|
||||
pub collection_interval_secs: u64,
|
||||
}
|
||||
|
||||
impl Default for HostConfig {
|
||||
fn default() -> Self {
|
||||
Self { checkpoint_interval_secs: 60 }
|
||||
Self { checkpoint_interval_secs: 60, collection_interval_secs: 300 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +41,8 @@ pub enum HostEvent {
|
||||
/// The realm shows another session than the Host armed: the Host's session is closed.
|
||||
SessionReplaced { session: SessionId },
|
||||
Refused { session: SessionId, why: String },
|
||||
/// The realm account's collection of this kind changed: the whole compact set was queued for the Owner.
|
||||
CollectionQueued { kind: String, count: usize },
|
||||
}
|
||||
|
||||
pub struct HostService<'a> {
|
||||
@@ -44,11 +51,13 @@ pub struct HostService<'a> {
|
||||
config: HostConfig,
|
||||
/// When the last checkpoint of each session was requested (not persisted: after a restart the first tick checkpoints).
|
||||
last_checkpoint: HashMap<SessionId, u64>,
|
||||
/// When the account collections of each session were last looked at.
|
||||
last_collection: HashMap<SessionId, u64>,
|
||||
}
|
||||
|
||||
impl<'a> HostService<'a> {
|
||||
pub fn new(store: &'a mut Store, server_id: &str, config: HostConfig) -> Self {
|
||||
Self { store, server_id: server_id.to_string(), config, last_checkpoint: HashMap::new() }
|
||||
Self { store, server_id: server_id.to_string(), config, last_checkpoint: HashMap::new(), last_collection: HashMap::new() }
|
||||
}
|
||||
|
||||
pub fn store(&self) -> &Store {
|
||||
@@ -98,6 +107,14 @@ impl<'a> HostService<'a> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let forced: HashSet<SessionId> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
HostEvent::BaselineTaken { session } | HostEvent::CheckpointQueued { session, final_checkpoint: true, .. } => Some(*session),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
self.sync_collections(bridge, now_secs, &forced, &mut events)?;
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
@@ -196,4 +213,95 @@ impl<'a> HostService<'a> {
|
||||
let guid = s.local_guid.ok_or_else(|| PortableError::Invalid("the next session has no realm character".into()))?;
|
||||
bridge.arm(guid, session, character, revision, s.generation)
|
||||
}
|
||||
|
||||
// ---- account collections (Phase 6) --------------------------------------------------------------------------------------
|
||||
|
||||
fn sync_collections(&mut self, bridge: &mut dyn RealmBridge, now_secs: u64, forced: &HashSet<SessionId>, events: &mut Vec<HostEvent>) -> Result<()> {
|
||||
for s in self.store.host_live_sessions(&self.server_id)? {
|
||||
let (Some(guid), HostState::Open) = (s.local_guid, s.state) else { continue };
|
||||
let due = forced.contains(&s.session_id) || self.last_collection.get(&s.session_id).is_none_or(|t| now_secs >= *t + self.config.collection_interval_secs);
|
||||
if !due {
|
||||
continue;
|
||||
}
|
||||
self.last_collection.insert(s.session_id, now_secs);
|
||||
let Some(account) = bridge.account_of(guid)? else { continue };
|
||||
for kind in COLLECTION_KINDS {
|
||||
self.observe_collection(bridge, account, kind, now_secs, events)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One look at one account collection: nothing is read or sent unless its fingerprint changed, and nothing is sent when the
|
||||
/// Owner already acknowledged exactly the set the realm shows.
|
||||
fn observe_collection(&mut self, bridge: &mut dyn RealmBridge, account: u32, kind: &str, now_secs: u64, events: &mut Vec<HostEvent>) -> Result<()> {
|
||||
let fingerprint = bridge.collection_fingerprint(account, kind)?;
|
||||
let row = self.store.host_collection(&self.server_id, account, kind)?;
|
||||
if row.as_ref().is_some_and(|r| r.fingerprint == fingerprint) {
|
||||
return Ok(());
|
||||
}
|
||||
let set = bridge.read_collection(account, kind)?;
|
||||
let hash = set.hash(kind);
|
||||
// the first look always reports (even an empty set): that is how the Owner learns of the realm and answers with what it holds
|
||||
let already = row.as_ref().and_then(|r| r.acked_hash) == Some(hash);
|
||||
if already {
|
||||
self.store.host_collection_observe(&self.server_id, account, kind, &fingerprint, &hash, None, now_secs)?;
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, kind, &set)?)?;
|
||||
self.store.host_collection_observe(&self.server_id, account, kind, &fingerprint, &hash, Some(&bytes), now_secs)?;
|
||||
events.push(HostEvent::CollectionQueued { kind: kind.to_string(), count: set.len() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collection messages waiting for the Owner.
|
||||
pub fn collection_outbox(&self) -> Result<Vec<CollectionOutboxMessage>> {
|
||||
self.store.host_collection_outbox(&self.server_id)
|
||||
}
|
||||
|
||||
/// The Owner's answer to a `CollectionObserved` of `account`. When the canonical set has ids the realm lacked, the ones its
|
||||
/// client data knows are written to the account now.
|
||||
pub fn receive_collection_ack(&mut self, bridge: &mut dyn RealmBridge, account: u32, ack: &CollectionAck) -> Result<Option<Applied>> {
|
||||
if !carried_kind(&ack.kind) {
|
||||
return Err(PortableError::Invalid("the acknowledgement is for a kind that is not carried".into()));
|
||||
}
|
||||
if let CollectionOutcome::Rejected(_) = &ack.outcome {
|
||||
self.store.host_collection_drop_pending(&self.server_id, account, &ack.kind)?;
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(row) = self.store.host_collection(&self.server_id, account, &ack.kind)? else { return Ok(None) };
|
||||
let Some(observed) = row.observed_hash else { return Ok(None) };
|
||||
// an Owner that holds nothing of this kind yet answers with an empty hash
|
||||
let hash: Option<[u8; 32]> = if ack.collection_hash.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(hex::decode(&ack.collection_hash).ok().and_then(|b| <[u8; 32]>::try_from(b.as_slice()).ok()).ok_or_else(|| PortableError::Invalid("the acknowledgement has a bad collection hash".into()))?)
|
||||
};
|
||||
match &ack.canonical {
|
||||
Some(state) => self.apply_canonical(bridge, account, state),
|
||||
None => {
|
||||
self.store.host_collection_acknowledge(&self.server_id, account, &ack.kind, None, None, &observed, ack.collection_revision, hash.as_ref())?;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical collection of one kind (from an acknowledgement, or sent on its own to a realm that has none of it).
|
||||
pub fn receive_collection_state(&mut self, bridge: &mut dyn RealmBridge, account: u32, state: &CollectionState) -> Result<Option<Applied>> {
|
||||
self.apply_canonical(bridge, account, state)
|
||||
}
|
||||
|
||||
fn apply_canonical(&mut self, bridge: &mut dyn RealmBridge, account: u32, state: &CollectionState) -> Result<Option<Applied>> {
|
||||
if !carried_kind(&state.kind) {
|
||||
return Err(PortableError::Invalid("the collection kind is not carried".into()));
|
||||
}
|
||||
let canonical: IdSet = state.set.open(&state.kind)?;
|
||||
let applied = bridge.apply_collection(account, &state.kind, &canonical)?;
|
||||
// what the realm shows now is a subset of the canonical set, so it adds nothing the Owner does not hold
|
||||
let fingerprint = bridge.collection_fingerprint(account, &state.kind)?;
|
||||
let now_hash = bridge.read_collection(account, &state.kind)?.hash(&state.kind);
|
||||
let canonical_hash = state.set.hash_bytes()?;
|
||||
self.store.host_collection_acknowledge(&self.server_id, account, &state.kind, Some(&fingerprint), Some(&now_hash), &now_hash, state.collection_revision, Some(&canonical_hash))?;
|
||||
Ok(Some(applied))
|
||||
}
|
||||
}
|
||||
@@ -7,21 +7,31 @@ use crate::ra::Ra;
|
||||
|
||||
use super::super::error::{PortableError, Result};
|
||||
use super::super::ids::{CharacterId, PortableItemId, PortablePetId, SessionId};
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::realm::collections::{self, Applied};
|
||||
use super::super::realm::knowledge::RealmKnowledge;
|
||||
use super::super::realm::{probe, read_session_character};
|
||||
use super::bridge::*;
|
||||
|
||||
pub struct LiveBridge<'a> {
|
||||
db: &'a Db,
|
||||
ra: Option<Ra>,
|
||||
knowledge: Option<std::sync::Arc<RealmKnowledge>>,
|
||||
}
|
||||
|
||||
impl<'a> LiveBridge<'a> {
|
||||
pub fn new(db: &'a Db, ra: Ra) -> Self {
|
||||
Self { db, ra: Some(ra) }
|
||||
Self { db, ra: Some(ra), knowledge: None }
|
||||
}
|
||||
|
||||
pub fn without_console(db: &'a Db) -> Self {
|
||||
Self { db, ra: None }
|
||||
Self { db, ra: None, knowledge: None }
|
||||
}
|
||||
|
||||
/// What the realm's client data knows: without it no account collection is ever written to the realm.
|
||||
pub fn with_knowledge(mut self, knowledge: Option<std::sync::Arc<RealmKnowledge>>) -> Self {
|
||||
self.knowledge = knowledge;
|
||||
self
|
||||
}
|
||||
|
||||
fn console(&mut self) -> Result<&mut Ra> {
|
||||
@@ -95,4 +105,21 @@ COMMIT;"
|
||||
self.db.query(&sql).map_err(realm_error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn account_of(&mut self, local_guid: u32) -> Result<Option<u32>> {
|
||||
collections::account_of(self.db, local_guid)
|
||||
}
|
||||
|
||||
fn collection_fingerprint(&mut self, account: u32, kind: &str) -> Result<String> {
|
||||
collections::fingerprint(self.db, account, kind)
|
||||
}
|
||||
|
||||
fn read_collection(&mut self, account: u32, kind: &str) -> Result<IdSet> {
|
||||
collections::read_set(self.db, account, kind)
|
||||
}
|
||||
|
||||
fn apply_collection(&mut self, account: u32, kind: &str, canonical: &IdSet) -> Result<Applied> {
|
||||
let knowledge = self.knowledge.clone().ok_or_else(|| PortableError::Invalid("the realm's client data is not known: no collection can be written".into()))?;
|
||||
collections::apply_set(self.db, account, kind, canonical, &knowledge)
|
||||
}
|
||||
}
|
||||
@@ -211,7 +211,7 @@ fn a_running_worldserver_takes_its_own_baseline_and_checkpoints_one_character_wi
|
||||
wait_until("the core's baseline marker", 90, || state_of(&r.b, guid).is_some_and(|row| row.state == RowState::BaselineReady));
|
||||
assert!(ra.run(&format!("portable status {guid}")).unwrap().contains("gated 1"), "the core holds the player until the Host has taken B0");
|
||||
|
||||
let mut host = HostService::new(&mut rig.host, B, HostConfig { checkpoint_interval_secs: 1 });
|
||||
let mut host = HostService::new(&mut rig.host, B, HostConfig { checkpoint_interval_secs: 1, ..HostConfig::default() });
|
||||
let mut owner = OwnerService::new(&mut rig.owner);
|
||||
let mut bridge = LiveBridge::new(&r.b, server.ra());
|
||||
tick_until(&mut host, &mut bridge, &clock, "the baseline", |e| matches!(e, HostEvent::BaselineTaken { .. }));
|
||||
@@ -375,7 +375,7 @@ fn the_core_imports_characters_into_a_running_realm_like_the_offline_importer_do
|
||||
let record = store.character(id).unwrap();
|
||||
let model = store.load_snapshot(id, record.revision).unwrap();
|
||||
let ticket = store.begin_import(id, B, record.revision, &crate::portable::realm::import::planned_items(&model), &crate::portable::realm::import::planned_pets(&model)).unwrap();
|
||||
let bytes = crate::portable::realm::online::job_bytes(ticket.import_id, ticket.nonce, ACCOUNT, record.revision, 10, &model, None).unwrap();
|
||||
let bytes = crate::portable::realm::online::job_bytes(ticket.import_id, ticket.nonce, ACCOUNT, record.revision, 10, &model, None, None).unwrap();
|
||||
let file = jobs.join(format!("{}.job", ticket.import_id));
|
||||
std::fs::write(&file, &bytes).unwrap();
|
||||
let before = number(&r.b, "SELECT COUNT(*) FROM acore_characters.characters");
|
||||
@@ -401,9 +401,9 @@ fn the_core_imports_characters_into_a_running_realm_like_the_offline_importer_do
|
||||
};
|
||||
let mut impossible = imported[0].3.clone();
|
||||
impossible.items[0].entry = crate::portable::ids::ContentId::new("coa", "item", 4_000_000_000).unwrap();
|
||||
refused(crate::portable::realm::online::job_bytes(ticket.import_id, [9, 9, 9, 9], ACCOUNT, 1, 10, &impossible, None).unwrap(), "an item the realm does not know");
|
||||
refused(crate::portable::realm::online::job_bytes(ticket.import_id, [9, 9, 9, 8], 99_999_999, 1, 10, &model, None).unwrap(), "an account that does not exist");
|
||||
let mut tampered = crate::portable::realm::online::job_bytes(ticket.import_id, [9, 9, 9, 7], ACCOUNT, 1, 10, &model, None).unwrap();
|
||||
refused(crate::portable::realm::online::job_bytes(ticket.import_id, [9, 9, 9, 9], ACCOUNT, 1, 10, &impossible, None, None).unwrap(), "an item the realm does not know");
|
||||
refused(crate::portable::realm::online::job_bytes(ticket.import_id, [9, 9, 9, 8], 99_999_999, 1, 10, &model, None, None).unwrap(), "an account that does not exist");
|
||||
let mut tampered = crate::portable::realm::online::job_bytes(ticket.import_id, [9, 9, 9, 7], ACCOUNT, 1, 10, &model, None, None).unwrap();
|
||||
let last = tampered.len() - 3;
|
||||
tampered[last] ^= 1;
|
||||
refused(tampered, "a snapshot that does not match its hash");
|
||||
|
||||
@@ -10,6 +10,8 @@ pub use owner::OwnerService;
|
||||
#[cfg(test)]
|
||||
mod fake;
|
||||
#[cfg(test)]
|
||||
mod collection_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod live_session;
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The Owner's entry points: the only place a message from a realm enters the canonical store.
|
||||
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::error::Result;
|
||||
use super::super::ids::{CharacterId, SessionId};
|
||||
use super::super::store::Store;
|
||||
@@ -38,4 +39,59 @@ impl<'a> OwnerService<'a> {
|
||||
pub fn session(&self, session: SessionId) -> Result<Option<(String, u64, u64)>> {
|
||||
self.store.owner_session_info(session)
|
||||
}
|
||||
|
||||
// ---- account collections (Phase 6) --------------------------------------------------------------------------------------
|
||||
|
||||
/// `CollectionObserved` as bytes from a transport: the realm account's set is **unioned** into the profile's collection
|
||||
/// (nothing is ever removed because a realm lacks it). The answer carries the canonical set only when it has ids the realm
|
||||
/// did not show. A message that cannot be parsed is an error and changes nothing; one that is parsed but not acceptable is
|
||||
/// answered with `Rejected`.
|
||||
pub fn handle_collection(&mut self, bytes: &[u8]) -> Result<CollectionAck> {
|
||||
let msg: CollectionObserved = collection_from_json(bytes)?;
|
||||
let profile = self.store.default_profile()?;
|
||||
let rejected = |store: &Store, reason: &str| -> Result<CollectionAck> {
|
||||
let info = store.collection_info(profile, &msg.kind).ok().flatten();
|
||||
Ok(CollectionAck {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
kind: msg.kind.clone(),
|
||||
outcome: CollectionOutcome::Rejected(reason.to_string()),
|
||||
collection_revision: info.as_ref().map_or(0, |i| i.revision),
|
||||
collection_hash: info.map_or_else(String::new, |i| hex::encode(i.hash)),
|
||||
canonical: None,
|
||||
})
|
||||
};
|
||||
if !carried_kind(&msg.kind) {
|
||||
return rejected(self.store, "this collection kind is not carried");
|
||||
}
|
||||
let observed = match msg.set.open(&msg.kind) {
|
||||
Ok(set) => set,
|
||||
Err(e) => return rejected(self.store, &e.to_string()),
|
||||
};
|
||||
let merge = self.store.merge_collection(profile, &msg.kind, &observed)?;
|
||||
let (info, canonical) = self.store.collection(profile, &msg.kind)?.map(|(i, s)| (Some(i), s)).unwrap_or((None, IdSet::new()));
|
||||
let canonical_state = match (&info, observed.count_new(&canonical) == 0 && canonical.count_new(&observed) == 0) {
|
||||
(Some(info), false) => Some(CollectionState::new(&msg.kind, info.revision, &canonical)?),
|
||||
_ => None,
|
||||
};
|
||||
Ok(CollectionAck {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
kind: msg.kind,
|
||||
outcome: if merge.changed { CollectionOutcome::Applied } else { CollectionOutcome::Unchanged },
|
||||
collection_revision: info.as_ref().map_or(0, |i| i.revision),
|
||||
collection_hash: info.map_or_else(String::new, |i| hex::encode(i.hash)),
|
||||
canonical: canonical_state,
|
||||
})
|
||||
}
|
||||
|
||||
/// The canonical collections as messages (for a realm that has none of them yet, or a new one).
|
||||
pub fn collection_states(&mut self) -> Result<Vec<CollectionState>> {
|
||||
let profile = self.store.default_profile()?;
|
||||
let mut out = Vec::new();
|
||||
for kind in COLLECTION_KINDS {
|
||||
if let Some((info, set)) = self.store.collection(profile, kind)? {
|
||||
out.push(CollectionState::new(kind, info.revision, &set)?);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -179,3 +179,135 @@ impl PortableCheckpoint {
|
||||
Ok(Self { protocol_version: PROTOCOL_VERSION, session_id, character_id, server_id: server_id.to_string(), base_canonical_revision, sequence, final_checkpoint, content_hash: realm_snapshot.content_hash.clone(), realm_snapshot })
|
||||
}
|
||||
}
|
||||
|
||||
// ---- account collections (Phase 6) --------------------------------------------------------------------------------------------
|
||||
//
|
||||
// A collection is a set of ids that only grows (the wardrobe, the vanity items). It never rides in a character checkpoint: the
|
||||
// Host sends it when the hash of what its realm shows changed, and the Owner answers with the canonical set only when that has
|
||||
// ids the realm lacks. The set travels in its compact form (sorted, delta + varint, base64), never as a JSON array of ids.
|
||||
|
||||
use super::super::collection::{valid_kind, IdSet, MAX_ENCODED_BYTES};
|
||||
|
||||
/// The collection kinds the v1 protocol carries.
|
||||
pub const COLLECTION_KINDS: [&str; 2] = ["coa:appearance", "coa:vanity"];
|
||||
/// A collection message carries at most one encoded set (base64: 4/3) plus a little structure.
|
||||
pub const MAX_COLLECTION_MESSAGE_BYTES: usize = MAX_ENCODED_BYTES * 4 / 3 + 64 * 1024;
|
||||
|
||||
pub fn carried_kind(kind: &str) -> bool {
|
||||
valid_kind(kind) && COLLECTION_KINDS.contains(&kind)
|
||||
}
|
||||
|
||||
/// A compact id set as it travels: hash of the kind and content, number of ids, base64 of [`IdSet::encode`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CompactSet {
|
||||
pub hash: String,
|
||||
pub count: u32,
|
||||
pub ids: String,
|
||||
}
|
||||
|
||||
impl CompactSet {
|
||||
pub fn seal(kind: &str, set: &IdSet) -> Result<CompactSet> {
|
||||
Ok(CompactSet { hash: hex::encode(set.hash(kind)), count: u32::try_from(set.len()).map_err(|_| PortableError::LimitExceeded("a collection is too large".into()))?, ids: base64::engine::general_purpose::STANDARD.encode(set.encode()) })
|
||||
}
|
||||
|
||||
/// Decode and verify against the kind: size cap before decoding, then count and hash must match what was announced.
|
||||
pub fn open(&self, kind: &str) -> Result<IdSet> {
|
||||
if self.ids.len() > MAX_ENCODED_BYTES * 4 / 3 + 8 {
|
||||
return Err(PortableError::LimitExceeded("the collection payload is over the limit".into()));
|
||||
}
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(&self.ids).map_err(|_| PortableError::Invalid("the collection payload is not base64".into()))?;
|
||||
let set = IdSet::decode(&bytes)?;
|
||||
if set.len() != self.count as usize {
|
||||
return Err(PortableError::Invalid("the collection does not have the announced number of ids".into()));
|
||||
}
|
||||
if hex::encode(set.hash(kind)) != self.hash {
|
||||
return Err(PortableError::Invalid("the collection does not match its hash".into()));
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
pub fn hash_bytes(&self) -> Result<[u8; 32]> {
|
||||
let bytes = hex::decode(&self.hash).map_err(|_| PortableError::Invalid("the collection hash is not hex".into()))?;
|
||||
<[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| PortableError::Invalid("the collection hash is not 32 bytes".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Host -> Owner: the realm account shows this set of one kind. Sent only when its hash changed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CollectionObserved {
|
||||
pub protocol_version: u32,
|
||||
pub server_id: String,
|
||||
pub kind: String,
|
||||
pub set: CompactSet,
|
||||
}
|
||||
|
||||
/// Owner -> Host: the canonical set of one kind at a revision.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CollectionState {
|
||||
pub protocol_version: u32,
|
||||
pub kind: String,
|
||||
pub collection_revision: u64,
|
||||
pub set: CompactSet,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields, tag = "status", content = "reason", rename_all = "snake_case")]
|
||||
pub enum CollectionOutcome {
|
||||
/// The union added ids: a new collection revision.
|
||||
Applied,
|
||||
/// The Owner already held everything the realm showed.
|
||||
Unchanged,
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
/// Owner -> Host.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CollectionAck {
|
||||
pub protocol_version: u32,
|
||||
pub kind: String,
|
||||
pub outcome: CollectionOutcome,
|
||||
pub collection_revision: u64,
|
||||
pub collection_hash: String,
|
||||
/// Present only when the canonical set has ids the realm did not show: the realm applies what it knows of them.
|
||||
pub canonical: Option<CollectionState>,
|
||||
}
|
||||
|
||||
pub fn collection_to_json<T: Serialize>(message: &T) -> Result<Vec<u8>> {
|
||||
let bytes = serde_json::to_vec(message)?;
|
||||
if bytes.len() > MAX_COLLECTION_MESSAGE_BYTES {
|
||||
return Err(PortableError::LimitExceeded(format!("a collection message is limited to {MAX_COLLECTION_MESSAGE_BYTES} bytes")));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Parse a collection message: size first, protocol version second, unknown fields refused.
|
||||
pub fn collection_from_json<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
|
||||
if bytes.len() > MAX_COLLECTION_MESSAGE_BYTES {
|
||||
return Err(PortableError::LimitExceeded(format!("a collection message is limited to {MAX_COLLECTION_MESSAGE_BYTES} bytes")));
|
||||
}
|
||||
let value: serde_json::Value = serde_json::from_slice(bytes)?;
|
||||
let version = value.get("protocol_version").and_then(|v| v.as_u64()).ok_or_else(|| PortableError::Invalid("the message has no protocol version".into()))?;
|
||||
if version != PROTOCOL_VERSION as u64 {
|
||||
return Err(PortableError::UnsupportedFormat { found: version.min(u32::MAX as u64) as u32, supported: PROTOCOL_VERSION });
|
||||
}
|
||||
Ok(serde_json::from_value(value)?)
|
||||
}
|
||||
|
||||
impl CollectionObserved {
|
||||
pub fn new(server_id: &str, kind: &str, set: &IdSet) -> Result<Self> {
|
||||
if !carried_kind(kind) {
|
||||
return Err(PortableError::Invalid(format!("collection kind {kind:?} is not carried")));
|
||||
}
|
||||
Ok(Self { protocol_version: PROTOCOL_VERSION, server_id: server_id.to_string(), kind: kind.to_string(), set: CompactSet::seal(kind, set)? })
|
||||
}
|
||||
}
|
||||
|
||||
impl CollectionState {
|
||||
pub fn new(kind: &str, revision: u64, set: &IdSet) -> Result<Self> {
|
||||
Ok(Self { protocol_version: PROTOCOL_VERSION, kind: kind.to_string(), collection_revision: revision, set: CompactSet::seal(kind, set)? })
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,7 @@ fn the_whole_session_from_an_automatic_baseline_to_the_final_checkpoint() {
|
||||
realm.login();
|
||||
assert!(realm.gated, "the core holds the player until B0 exists");
|
||||
let events = h.tick(&mut realm, 0).unwrap();
|
||||
assert_eq!(events, vec![HostEvent::BaselineTaken { session }]);
|
||||
assert_eq!(without_collections(events), vec![HostEvent::BaselineTaken { session }]);
|
||||
assert!(!realm.gated, "released only after B0 was persisted");
|
||||
let acks = deliver(&mut h, &mut o, &mut realm);
|
||||
assert_eq!((acks.len(), &acks[0].outcome), (1, &AckOutcome::Applied));
|
||||
@@ -172,6 +172,11 @@ fn the_whole_session_from_an_automatic_baseline_to_the_final_checkpoint() {
|
||||
assert_eq!(synced, o.store().load_current(id).unwrap(), "the Host's realm is synchronised with what the Owner now holds");
|
||||
}
|
||||
|
||||
/// The collections have their own tests (`collection_tests.rs`): the character tests look at the character's events only.
|
||||
fn without_collections(events: Vec<HostEvent>) -> Vec<HostEvent> {
|
||||
events.into_iter().filter(|e| !matches!(e, HostEvent::CollectionQueued { .. })).collect()
|
||||
}
|
||||
|
||||
/// The bytes of a message the Host queued (kept in the outbox table after acknowledgement).
|
||||
fn host_outbox_history(h: &HostService, session: SessionId, sequence: u64) -> Vec<u8> {
|
||||
h.store().host_message(session, sequence).unwrap().expect("the message is kept")
|
||||
@@ -208,7 +213,7 @@ fn a_host_that_never_answers_never_lets_the_player_play_and_the_baseline_is_reta
|
||||
assert!(!realm.online && realm.row.as_ref().unwrap().state == RowState::BaselineReady && realm.released.is_empty());
|
||||
realm.login();
|
||||
assert!(realm.gated);
|
||||
assert_eq!(h.tick(&mut realm, 0).unwrap(), vec![HostEvent::BaselineTaken { session }]);
|
||||
assert_eq!(without_collections(h.tick(&mut realm, 0).unwrap()), vec![HostEvent::BaselineTaken { session }]);
|
||||
deliver(&mut h, &mut o, &mut realm);
|
||||
realm.play(|m| m.progression.money += 1);
|
||||
assert_eq!(revision(&o, id), 10);
|
||||
|
||||
@@ -18,7 +18,7 @@ use super::versions::{PORTABLE_COLLECTION_FORMAT_VERSION, SNAPSHOT_FORMAT_VERSIO
|
||||
pub const DATABASE_FILE: &str = "portable.db";
|
||||
/// `PRAGMA application_id`: "COAP". Refuses to adopt an unrelated SQLite file.
|
||||
const APPLICATION_ID: i64 = 0x434F_4150;
|
||||
const MIGRATIONS: &[&str] = &[include_str!("migrations/001_init.sql"), include_str!("migrations/002_item_mapping_lifecycle.sql"), include_str!("migrations/003_import_journal.sql"), include_str!("migrations/004_reconciliation.sql"), include_str!("migrations/005_sessions.sql")];
|
||||
const MIGRATIONS: &[&str] = &[include_str!("migrations/001_init.sql"), include_str!("migrations/002_item_mapping_lifecycle.sql"), include_str!("migrations/003_import_journal.sql"), include_str!("migrations/004_reconciliation.sql"), include_str!("migrations/005_sessions.sql"), include_str!("migrations/006_collections.sql")];
|
||||
|
||||
pub const DEFAULT_HISTORY_KEEP: u32 = 20;
|
||||
pub const MAX_HISTORY_KEEP: u32 = 1_000;
|
||||
|
||||
@@ -330,3 +330,92 @@ impl Store {
|
||||
Ok(AckEffect::Finished { next_session: next.session_id, next_revision: next.canonical_revision })
|
||||
}
|
||||
}
|
||||
|
||||
// ---- account collections (Phase 6) ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// What the Host remembers of one realm account's collection of one kind.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HostCollection {
|
||||
pub fingerprint: String,
|
||||
pub observed_hash: Option<[u8; 32]>,
|
||||
pub acked_hash: Option<[u8; 32]>,
|
||||
pub canonical_revision: u64,
|
||||
pub canonical_hash: Option<[u8; 32]>,
|
||||
pub pending: Option<Vec<u8>>,
|
||||
pub checked_at: u64,
|
||||
}
|
||||
|
||||
/// A collection message waiting for the Owner.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CollectionOutboxMessage {
|
||||
pub account: u32,
|
||||
pub kind: String,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
fn opt_hash(blob: Option<Vec<u8>>) -> Result<Option<[u8; 32]>> {
|
||||
blob.map(|b| <[u8; 32]>::try_from(b.as_slice()).map_err(|_| PortableError::CorruptSnapshot("a stored collection hash is not 32 bytes".into()))).transpose()
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn host_collection(&self, server_id: &str, account: u32, kind: &str) -> Result<Option<HostCollection>> {
|
||||
type Raw = (String, Option<Vec<u8>>, Option<Vec<u8>>, i64, Option<Vec<u8>>, Option<Vec<u8>>, i64);
|
||||
let raw: Option<Raw> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT fingerprint, observed_hash, acked_hash, canonical_revision, canonical_hash, pending, checked_at FROM host_collection WHERE server_id = ?1 AND account = ?2 AND kind = ?3",
|
||||
params![server_id, account, kind],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?)),
|
||||
)
|
||||
.optional()?;
|
||||
raw.map(|(fingerprint, observed, acked, revision, canonical, pending, checked_at)| {
|
||||
Ok(HostCollection { fingerprint, observed_hash: opt_hash(observed)?, acked_hash: opt_hash(acked)?, canonical_revision: revision as u64, canonical_hash: opt_hash(canonical)?, pending, checked_at: checked_at as u64 })
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// The realm account was read: remember the fingerprint and the hash of what it showed, and queue `pending` for the Owner
|
||||
/// (or none when the Owner already acknowledged exactly this set). A newer observation replaces an older pending one.
|
||||
pub fn host_collection_observe(&mut self, server_id: &str, account: u32, kind: &str, fingerprint: &str, observed: &[u8; 32], pending: Option<&[u8]>, checked_at: u64) -> Result<()> {
|
||||
let tx = self.write_tx()?;
|
||||
tx.execute(
|
||||
"INSERT INTO host_collection(server_id, account, kind, fingerprint, observed_hash, pending, checked_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
|
||||
ON CONFLICT(server_id, account, kind) DO UPDATE SET fingerprint = excluded.fingerprint, observed_hash = excluded.observed_hash, pending = excluded.pending,
|
||||
checked_at = excluded.checked_at, updated_at = excluded.updated_at",
|
||||
params![server_id, account, kind, fingerprint, observed.as_slice(), pending, checked_at as i64, now()],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The Owner acknowledged `acked` (the hash of the realm set it was sent, or of the set the realm holds after the canonical
|
||||
/// ids were applied): the pending message is dropped and the canonical revision remembered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn host_collection_acknowledge(&mut self, server_id: &str, account: u32, kind: &str, fingerprint: Option<&str>, observed: Option<&[u8; 32]>, acked: &[u8; 32], canonical_revision: u64, canonical_hash: Option<&[u8; 32]>) -> Result<()> {
|
||||
let tx = self.write_tx()?;
|
||||
let at = now();
|
||||
tx.execute(
|
||||
"INSERT INTO host_collection(server_id, account, kind, fingerprint, observed_hash, acked_hash, canonical_revision, canonical_hash, pending, updated_at)
|
||||
VALUES (?1, ?2, ?3, COALESCE(?4, ''), ?5, ?6, ?7, ?8, NULL, ?9)
|
||||
ON CONFLICT(server_id, account, kind) DO UPDATE SET fingerprint = COALESCE(?4, fingerprint), observed_hash = COALESCE(?5, observed_hash), acked_hash = excluded.acked_hash,
|
||||
canonical_revision = excluded.canonical_revision, canonical_hash = COALESCE(excluded.canonical_hash, canonical_hash), pending = NULL, updated_at = excluded.updated_at",
|
||||
params![server_id, account, kind, fingerprint, observed.map(|h| h.as_slice()), acked.as_slice(), canonical_revision as i64, canonical_hash.map(|h| h.as_slice()), at],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drop a pending message the Owner will never accept.
|
||||
pub fn host_collection_drop_pending(&mut self, server_id: &str, account: u32, kind: &str) -> Result<()> {
|
||||
let tx = self.write_tx()?;
|
||||
tx.execute("UPDATE host_collection SET pending = NULL, updated_at = ?4 WHERE server_id = ?1 AND account = ?2 AND kind = ?3", params![server_id, account, kind, now()])?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn host_collection_outbox(&self, server_id: &str) -> Result<Vec<CollectionOutboxMessage>> {
|
||||
let mut stmt = self.conn.prepare("SELECT account, kind, pending FROM host_collection WHERE server_id = ?1 AND pending IS NOT NULL ORDER BY account, kind")?;
|
||||
let rows = stmt.query_map([server_id], |r| Ok(CollectionOutboxMessage { account: r.get::<_, i64>(0)? as u32, kind: r.get(1)?, bytes: r.get(2)? }))?;
|
||||
Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user