feat: multi-ruleset realms and strictly isolated portable characters

This commit is contained in:
Дмитрий committed 2026-10-22 13:04:57 +05:00
1 parent d9c10c4564
commit 58a99f0a6d
35 files changed
+736 -124

No files matched your search

+12
View File
@@ -16,6 +16,10 @@ pub const MIN_PASSWORD: usize = 8;
pub const MAX_PASSWORD: usize = 16;
pub const MAX_CHARACTERS: usize = 200;
fn default_ruleset() -> String {
"coa".to_string()
}
/// A game account name: 3 to 16 ASCII letters, digits or `_`, not beginning or ending with `_`.
pub fn valid_username(s: &str) -> bool {
(MIN_USERNAME..=MAX_USERNAME).contains(&s.len())
@@ -103,6 +107,8 @@ pub enum Request {
TransferOffer {
transfer_id: Uuid,
character_id: Uuid,
#[serde(default = "default_ruleset")]
ruleset: String,
canonical_revision: u64,
content_hash: String,
total_size: usize,
@@ -273,11 +279,15 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
return invalid("the client name is too long")
}
Request::TransferOffer {
ruleset,
content_hash,
total_size,
collections,
..
} => {
if !matches!(ruleset.as_str(), "coa" | "wildcard" | "reborn") {
return invalid("transfer ruleset must be coa, wildcard, or reborn");
}
if content_hash.len() != 64 || !content_hash.chars().all(|c| c.is_ascii_hexdigit()) {
return invalid("transfer content hash must be 64 hex characters");
}
@@ -430,6 +440,7 @@ mod tests {
let offer = Request::TransferOffer {
transfer_id: tid,
character_id: cid,
ruleset: "coa".into(),
canonical_revision: 5,
content_hash: hash.clone(),
total_size: 1024,
@@ -442,6 +453,7 @@ mod tests {
let bad_hash = Request::TransferOffer {
transfer_id: tid,
character_id: cid,
ruleset: "coa".into(),
canonical_revision: 5,
content_hash: "too_short".into(),
total_size: 1024,
@@ -90,6 +90,7 @@ fn test_app_request_hostile_limits_and_validation() {
let offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: Uuid::now_v7(),
ruleset: "coa".into(),
canonical_revision: 1,
content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
total_size: 1024,
@@ -105,6 +106,7 @@ fn test_app_request_hostile_limits_and_validation() {
let bad_hash_offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: Uuid::now_v7(),
ruleset: "coa".into(),
canonical_revision: 1,
content_hash: "not_a_valid_hex_hash".into(),
total_size: 1024,
@@ -112,6 +114,18 @@ fn test_app_request_hostile_limits_and_validation() {
};
assert!(decode_request(&encode_request(&bad_hash_offer)).is_err());
// 4b. Invalid ruleset rejected
let bad_ruleset_offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: Uuid::now_v7(),
ruleset: "invalid_ruleset".into(),
canonical_revision: 1,
content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
total_size: 1024,
collections: BTreeMap::new(),
};
assert!(decode_request(&encode_request(&bad_ruleset_offer)).is_err());
// 5. TransferChunk offset out of bounds
let bad_offset_chunk = Request::TransferChunk {
transfer_id: Uuid::now_v7(),
+3 -3
View File
@@ -457,7 +457,7 @@ fn run() -> Result<(), String> {
}
("collection-states", [out]) => {
let states = OwnerService::new(&mut store)
.collection_states()
.collection_states(coa_core::portable::Ruleset::Coa)
.map_err(|e| e.to_string())?;
for s in &states {
println!(
@@ -618,7 +618,7 @@ fn run() -> Result<(), String> {
let set =
coa_core::portable::collection::IdSet::from_ids(ids).map_err(|e| e.to_string())?;
let merge = store
.merge_collection(profile, kind, &set)
.merge_collection(profile, coa_core::portable::Ruleset::Coa, kind, &set)
.map_err(|e| e.to_string())?;
println!(
"{kind}: {} id(s) added{}",
@@ -633,7 +633,7 @@ fn run() -> Result<(), String> {
let profile = store.default_profile().map_err(|e| e.to_string())?;
for kind in coa_core::portable::session::protocol::COLLECTION_KINDS {
match store
.collection_info(profile, kind)
.collection_info(profile, coa_core::portable::Ruleset::Coa, kind)
.map_err(|e| e.to_string())?
{
Some(i) => println!(
+6
View File
@@ -86,9 +86,15 @@ impl LocalBackend {
impl RealmBackend for LocalBackend {
fn info(&self, local_id: &str) -> Result<RealmInfo> {
let cfg = settings::load(&self.settings_dir)?.realms.remove(local_id);
let ruleset = self
.access(local_id)
.and_then(|a| a.db())
.and_then(|db| realm::ruleset_of(&db).map_err(|e| Error::Invalid(e.to_string())))
.unwrap_or(crate::portable::model::Ruleset::Coa);
Ok(RealmInfo {
automatic: cfg.as_ref().is_none_or(|c| !c.existing_only),
route: cfg.and_then(|c| c.route),
ruleset,
})
}
+2
View File
@@ -413,6 +413,7 @@ impl PlayerControl {
&self,
ch: &mut PlayerChannel,
character_id: Uuid,
ruleset: &str,
canonical_revision: u64,
payload: &[u8],
content_hash: [u8; 32],
@@ -423,6 +424,7 @@ impl PlayerControl {
let offer = Request::TransferOffer {
transfer_id,
character_id,
ruleset: ruleset.to_string(),
canonical_revision,
content_hash: content_hash_str.clone(),
total_size: payload.len(),
+89
View File
@@ -26,6 +26,7 @@ pub struct RealmInfo {
pub automatic: bool,
/// An address a player's game client can reach right now, when the owner has stated one. Not a relay and not discovery.
pub route: Option<String>,
pub ruleset: crate::portable::model::Ruleset,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -303,6 +304,7 @@ impl HostService {
Request::TransferOffer {
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
@@ -311,6 +313,7 @@ impl HostService {
player,
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
@@ -726,6 +729,7 @@ impl HostService {
player: &Uuid,
transfer_id: Uuid,
character_id: Uuid,
ruleset: String,
canonical_revision: u64,
content_hash: String,
total_size: usize,
@@ -741,6 +745,30 @@ impl HostService {
);
};
// 0. Strict ruleset isolation: target realm ruleset must match offer ruleset
let info = match self.backend.info(&self.local_id) {
Ok(i) => i,
Err(e) => return unavailable("reading realm info", &e),
};
let offer_ruleset = match crate::portable::model::Ruleset::parse(&ruleset) {
Ok(r) => r,
Err(_) => return err(AppError::Incompatible, "Invalid ruleset in transfer offer."),
};
if offer_ruleset != info.ruleset {
return err(
AppError::Incompatible,
"Character ruleset does not match this realm.",
);
}
for kind in collections.keys() {
if !kind.starts_with(offer_ruleset.as_str()) {
return err(
AppError::Incompatible,
"Collection kind does not belong to this ruleset.",
);
}
}
// 1. Ownership check: another player cannot overwrite a character claimed here
if let Ok(Some(claim)) = self
.store
@@ -1083,6 +1111,7 @@ impl HostService {
#[cfg(any(test, feature = "testkit"))]
pub mod fake {
use super::*;
use crate::portable::Ruleset;
#[derive(Default)]
pub struct FakeRealm {
@@ -1141,6 +1170,7 @@ pub mod fake {
impl RealmBackend for FakeRealm {
fn info(&self, _: &str) -> Result<RealmInfo> {
Ok(RealmInfo {
ruleset: Ruleset::Coa,
automatic: *self.automatic.lock().unwrap(),
route: self.route.lock().unwrap().clone(),
})
@@ -1870,6 +1900,7 @@ mod tests {
// 1. Offer
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -1943,6 +1974,7 @@ mod tests {
realm.incompatible.lock().unwrap().insert(cid);
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -1982,6 +2014,7 @@ mod tests {
let hash = hex::encode(Sha256::digest(&full));
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -2076,6 +2109,7 @@ mod tests {
let hash = hex::encode(Sha256::digest(&payload));
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -2138,6 +2172,7 @@ mod tests {
// Client starts a new transfer for the exact same committed revision: discovers committed state
let tid2 = Uuid::now_v7();
let offer2 = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid2,
character_id: cid,
canonical_revision: 1,
@@ -2174,6 +2209,7 @@ mod tests {
let hash = hex::encode(Sha256::digest(&payload));
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -2240,6 +2276,7 @@ mod tests {
let tid_impostor = Uuid::now_v7();
let impostor_offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid_impostor,
character_id: cid,
canonical_revision: 2,
@@ -2277,6 +2314,7 @@ mod tests {
&p,
"K",
Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid1,
character_id: cid,
canonical_revision: 1,
@@ -2328,6 +2366,7 @@ mod tests {
&p,
"K",
Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid2,
character_id: cid,
canonical_revision: 2,
@@ -2377,4 +2416,54 @@ mod tests {
"update, not duplicate import"
);
}
#[test]
fn cross_ruleset_transfer_offers_are_rejected_before_mutation() {
let (realm, s, p, _acc) = claimed_setup();
let mut session = Session::default();
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
// 1. Host is CoA, offer is Wildcard -> Rejected
let wc_offer = Request::TransferOffer {
ruleset: "wildcard".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: "a".repeat(64),
total_size: 100,
collections: BTreeMap::new(),
};
let r = s.handle(&mut session, &p, "K", wc_offer);
assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. }));
// 2. Host is CoA, offer is Reborn -> Rejected
let rb_offer = Request::TransferOffer {
ruleset: "reborn".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: "a".repeat(64),
total_size: 100,
collections: BTreeMap::new(),
};
let r = s.handle(&mut session, &p, "K", rb_offer);
assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. }));
// 3. Collection kinds for another ruleset -> Rejected
let foreign_coll_offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: "a".repeat(64),
total_size: 100,
collections: BTreeMap::from([("wildcard:appearance".into(), vec![1, 2, 3])]),
};
let r = s.handle(&mut session, &p, "K", foreign_coll_offer);
assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. }));
// Ensure 0 DB imports happened
assert!(realm.imported.lock().unwrap().is_empty());
}
}
+5
View File
@@ -64,6 +64,11 @@ pub enum PortableError {
RealmRead(String),
#[error("the realm database is a {found} realm but a {expected} character was requested")]
WrongRealm { expected: String, found: String },
#[error("ruleset mismatch: character has {character:?}, realm expects {realm:?}")]
RulesetMismatch {
character: super::model::Ruleset,
realm: super::model::Ruleset,
},
#[error("character {character} is already on server {server_id}")]
AlreadyOnRealm {
@@ -9,7 +9,7 @@ CREATE TABLE profile (
CREATE TABLE character (
character_id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profile(profile_id),
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard')),
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')),
name TEXT NOT NULL,
race TEXT NOT NULL,
class TEXT NOT NULL,
@@ -0,0 +1,23 @@
-- Schema 9: Multi-ruleset partitioned collections and reborn ruleset support.
-- 1. Partition collection table by (profile_id, ruleset, kind)
CREATE TABLE collection_new (
profile_id TEXT NOT NULL REFERENCES profile(profile_id),
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')),
kind TEXT NOT NULL,
collection_revision INTEGER NOT NULL CHECK (collection_revision >= 1),
collection_hash BLOB NOT NULL CHECK (length(collection_hash) = 32),
format_version INTEGER NOT NULL,
item_count INTEGER NOT NULL,
updated_at TEXT NOT NULL,
payload BLOB NOT NULL,
PRIMARY KEY (profile_id, ruleset, kind)
) STRICT;
INSERT INTO collection_new (profile_id, ruleset, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload)
SELECT profile_id, 'coa', kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload
FROM collection;
DROP TABLE collection;
ALTER TABLE collection_new RENAME TO collection;
CREATE INDEX IF NOT EXISTS character_profile_ruleset ON character(profile_id, ruleset);
+77 -1
View File
@@ -59,12 +59,13 @@ pub mod limits {
use limits::*;
/// A character belongs to exactly one ruleset for its whole life; CoA and Wildcard never mix.
/// A character belongs to exactly one ruleset for its whole life; rulesets never mix.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Ruleset {
Coa,
Wildcard,
Reborn,
}
impl Ruleset {
@@ -72,12 +73,47 @@ impl Ruleset {
match self {
Ruleset::Coa => "coa",
Ruleset::Wildcard => "wildcard",
Ruleset::Reborn => "reborn",
}
}
pub fn display_name(self) -> &'static str {
match self {
Ruleset::Coa => "Conquest of Azeroth",
Ruleset::Wildcard => "Wildcard",
Ruleset::Reborn => "Warcraft Reborn",
}
}
pub fn realm_id(self) -> u32 {
match self {
Ruleset::Coa => 1,
Ruleset::Wildcard => 2,
Ruleset::Reborn => 3,
}
}
pub fn schema(self, kind: &str) -> &'static str {
match (self, kind) {
(_, "auth") => "acore_auth",
(Self::Coa, "characters") => "acore_characters",
(Self::Coa, "world") => "acore_world",
(Self::Wildcard, "characters") => "acore_characters_wildcard",
(Self::Wildcard, "world") => "acore_world_wildcard",
(Self::Reborn, "characters") => "acore_characters_reborn",
(Self::Reborn, "world") => "acore_world_reborn",
_ => "acore_characters",
}
}
pub fn collection_namespace(self) -> &'static str {
match self {
Ruleset::Coa => "coa",
Ruleset::Wildcard => "wildcard",
Ruleset::Reborn => "reborn",
}
}
pub fn parse(s: &str) -> Result<Self> {
match s {
"coa" => Ok(Ruleset::Coa),
"wildcard" => Ok(Ruleset::Wildcard),
"reborn" => Ok(Ruleset::Reborn),
other => Err(PortableError::Invalid(format!("unknown ruleset {other:?}"))),
}
}
@@ -89,6 +125,46 @@ impl std::fmt::Display for Ruleset {
}
}
impl From<crate::realms::Mode> for Ruleset {
fn from(m: crate::realms::Mode) -> Self {
match m {
crate::realms::Mode::Coa => Ruleset::Coa,
crate::realms::Mode::Wildcard => Ruleset::Wildcard,
crate::realms::Mode::Reborn => Ruleset::Reborn,
}
}
}
impl From<Ruleset> for crate::realms::Mode {
fn from(r: Ruleset) -> Self {
match r {
Ruleset::Coa => crate::realms::Mode::Coa,
Ruleset::Wildcard => crate::realms::Mode::Wildcard,
Ruleset::Reborn => crate::realms::Mode::Reborn,
}
}
}
impl From<coa_registry_proto::caps::Ruleset> for Ruleset {
fn from(r: coa_registry_proto::caps::Ruleset) -> Self {
match r {
coa_registry_proto::caps::Ruleset::Coa => Ruleset::Coa,
coa_registry_proto::caps::Ruleset::Wildcard => Ruleset::Wildcard,
coa_registry_proto::caps::Ruleset::Reborn => Ruleset::Reborn,
}
}
}
impl From<Ruleset> for coa_registry_proto::caps::Ruleset {
fn from(r: Ruleset) -> Self {
match r {
Ruleset::Coa => coa_registry_proto::caps::Ruleset::Coa,
Ruleset::Wildcard => coa_registry_proto::caps::Ruleset::Wildcard,
Ruleset::Reborn => coa_registry_proto::caps::Ruleset::Reborn,
}
}
}
/// Binary data as base64 text in the serialised form.
#[derive(Clone, PartialEq, Eq, Default)]
pub struct Bytes(pub Vec<u8>);
@@ -11,7 +11,6 @@ use crate::db::Db;
use super::super::collection::IdSet;
use super::super::error::{PortableError, Result};
use super::super::model::Ruleset;
use super::knowledge::{is_bank_vanity_item, RealmKnowledge};
use super::plan::FAIL;
use super::ruleset_of;
@@ -22,8 +21,12 @@ 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)),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
Ok(("account_appearance_collection", "appearance_id", true))
}
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => {
Ok(("account_vanity_collection", "item_id", false))
}
other => Err(PortableError::Invalid(format!(
"collection kind {other:?} is not carried"
))),
@@ -34,11 +37,12 @@ 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(),
));
fn check_ruleset(db: &Db, kind: &str) -> Result<()> {
let r = ruleset_of(db)?;
if !kind.starts_with(r.as_str()) {
return Err(PortableError::Invalid(format!(
"collection kind {kind:?} does not belong to realm ruleset {r:?}"
)));
}
Ok(())
}
@@ -62,7 +66,7 @@ pub fn account_of(db: &Db, local_guid: u32) -> Result<Option<u32>> {
/// 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)?;
check_ruleset(db, kind)?;
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}"))
@@ -82,7 +86,7 @@ pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result<String> {
/// 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)?;
check_ruleset(db, kind)?;
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();
@@ -91,7 +95,7 @@ pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
.trim()
.parse()
.map_err(|_| PortableError::CorruptSnapshot(format!("{line:?} is not an id")))?;
if kind == "coa:vanity" && is_bank_vanity_item(id) {
if (kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") && is_bank_vanity_item(id) {
continue;
}
ids.push(id);
@@ -117,10 +121,10 @@ pub fn apply_set(
canonical: &IdSet,
knowledge: &RealmKnowledge,
) -> Result<Applied> {
coa_only(db)?;
check_ruleset(db, kind)?;
let (table, column, has_source) = layout(kind)?;
let known = |id: u32| match kind {
"coa:appearance" => knowledge.knows_appearance(id),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => knowledge.knows_appearance(id),
_ => knowledge.knows_vanity(id) && !is_bank_vanity_item(id),
};
let held = read_set(db, account, kind)?;
@@ -130,7 +134,7 @@ pub fn apply_set(
.ids()
.iter()
.copied()
.filter(|id| !(kind == "coa:vanity" && is_bank_vanity_item(*id)))
.filter(|id| !((kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") && is_bank_vanity_item(*id)))
{
if !known(id) {
applied.unknown += 1;
@@ -168,9 +168,9 @@ fn account_collections_are_read_cheaply_unioned_and_written_without_duplicates_o
let (mut store, _) = fresh_store();
let profile = store.default_profile().unwrap();
store
.merge_collection(profile, APPEARANCE, &wardrobe)
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &wardrobe)
.unwrap();
store.merge_collection(profile, VANITY, &vanity).unwrap();
store.merge_collection(profile, Ruleset::Coa, VANITY, &vanity).unwrap();
let fingerprint_a = fingerprint(&r.a, 5001, APPEARANCE).unwrap();
assert_eq!(
fingerprint(&r.a, 5001, APPEARANCE).unwrap(),
@@ -331,10 +331,10 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections(
reconcile_session(&r.b, &mut store, id, B, true, None).unwrap();
for kind in [APPEARANCE, VANITY] {
store
.merge_collection(profile, kind, &read_set(&r.b, ACCOUNT, kind).unwrap())
.merge_collection(profile, Ruleset::Coa, kind, &read_set(&r.b, ACCOUNT, kind).unwrap())
.unwrap();
store
.merge_collection(profile, kind, &read_set(&r.a, 5001, kind).unwrap())
.merge_collection(profile, Ruleset::Coa, kind, &read_set(&r.a, 5001, kind).unwrap())
.unwrap();
}
@@ -343,7 +343,7 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections(
let updated =
update_realm_character(&r.a, &mut store, id, "realm-a", &options(a_known.clone())).unwrap();
assert!(updated.updated, "{updated:?}");
let (_, canonical_wardrobe) = store.collection(profile, APPEARANCE).unwrap().unwrap();
let (_, canonical_wardrobe) = store.collection(profile, Ruleset::Coa, APPEARANCE).unwrap().unwrap();
let applied = apply_set(&r.a, 5001, APPEARANCE, &canonical_wardrobe, &a_known).unwrap();
assert_eq!(applied.inserted, 1, "only 1300 is new to A");
assert_eq!(
+1 -1
View File
@@ -55,7 +55,7 @@ pub fn ruleset_of(db: &Db) -> Result<Ruleset> {
match db.realm() {
Mode::Coa => Ok(Ruleset::Coa),
Mode::Wildcard => Ok(Ruleset::Wildcard),
Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supported on Warcraft Reborn realms yet.".into())),
Mode::Reborn => Ok(Ruleset::Reborn),
}
}
@@ -14,7 +14,7 @@ use super::super::extension::{
};
use super::super::ids::CharacterId;
use super::super::model::PortableCharacter;
use super::super::session::protocol::{COLLECTION_KINDS, PROTOCOL_VERSION};
use super::super::session::protocol::{collection_kinds, PROTOCOL_VERSION};
use super::super::store::Store;
use super::import::ImportOptions;
use super::script::SchemaProbe;
@@ -103,7 +103,10 @@ pub fn assemble(
collection_kinds: if probe.has("account_appearance_collection")
&& probe.has("account_vanity_collection")
{
COLLECTION_KINDS.iter().map(|k| k.to_string()).collect()
collection_kinds(ruleset_of(db)?)
.iter()
.map(|k| k.to_string())
.collect()
} else {
Default::default()
},
+1 -1
View File
@@ -729,7 +729,7 @@ fn the_wildcard_ruleset_uses_its_own_namespace_and_quarantines_wildcard_state()
let wc_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Wildcard);
let coa_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Coa);
let reborn_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Reborn);
assert!(ruleset_of(&reborn_db).is_err());
assert_eq!(ruleset_of(&reborn_db).unwrap(), Ruleset::Reborn);
assert_eq!(
(ruleset_of(&wc_db).unwrap(), ruleset_of(&coa_db).unwrap()),
(Ruleset::Wildcard, Ruleset::Coa)
+11 -2
View File
@@ -112,6 +112,7 @@ pub struct RealmAccess {
pub job_dir: PathBuf,
pub data_dir: PathBuf,
pub game_server_users: Vec<String>,
pub mode: Option<crate::realms::Mode>,
source: Source,
}
@@ -198,6 +199,7 @@ impl RealmAccess {
job_dir: PathBuf::from(&d.job_dir),
data_dir: PathBuf::from(&d.data_dir),
game_server_users: d.game_server_users.clone(),
mode: None,
source: Source::Descriptor(Box::new(d)),
})
}
@@ -219,6 +221,7 @@ impl RealmAccess {
job_dir: root.join("Core").join("PortableImport"),
data_dir: root.join("Data"),
game_server_users: default_game_users(),
mode: None,
source: Source::Install {
root: root.to_path_buf(),
},
@@ -228,13 +231,19 @@ impl RealmAccess {
/// The database with full rights (imports and updates of a stopped realm, reading characters).
pub fn db(&self) -> Result<Db> {
match &self.source {
Source::Install { root } => Db::from_repack(root, Account::Admin),
Source::Install { root } => {
let mut d = Db::from_repack(root, Account::Admin)?;
if let Some(m) = self.mode {
d = d.for_realm(m);
}
Ok(d)
}
Source::Descriptor(d) => Ok(Db::with_tools(
PathBuf::from(&d.mysql_bin),
d.db_port,
leak(&d.db_user),
d.db_password.expose(),
Mode::Coa,
self.mode.unwrap_or(Mode::Coa),
)),
}
}
+33 -15
View File
@@ -136,6 +136,7 @@ struct Saved {
#[derive(Debug, Clone)]
pub struct ClaimBundle {
pub character_id: CharacterId,
pub ruleset: super::super::model::Ruleset,
pub payload: Vec<u8>,
pub content_hash: [u8; 32],
pub collections: BTreeMap<String, Vec<u32>>,
@@ -1438,18 +1439,18 @@ impl PortableService {
let model = self.host.load_current(character_id)?;
let encoded = super::super::snapshot::encode(&model)?;
let mut collections = BTreeMap::new();
if realm::ruleset_of(&db)? == super::super::model::Ruleset::Coa {
if let Some(account) = realm::collections::account_of(&db, local_guid)? {
for kind in ["coa:appearance", "coa:vanity"] {
if let Ok(set) = realm::collections::read_set(&db, account, kind) {
collections.insert(kind.to_string(), set.ids().to_vec());
}
let realm_ruleset = realm::ruleset_of(&db)?;
if let Some(account) = realm::collections::account_of(&db, local_guid)? {
for kind in super::super::session::protocol::collection_kinds(realm_ruleset) {
if let Ok(set) = realm::collections::read_set(&db, account, kind) {
collections.insert(kind.to_string(), set.ids().to_vec());
}
}
}
self.publish();
Ok(ClaimBundle {
character_id,
ruleset: model.ruleset,
payload: encoded.payload,
content_hash: encoded.content_hash,
collections,
@@ -1473,17 +1474,17 @@ impl PortableService {
"The character data does not belong to the character that was claimed.",
));
}
let ruleset = model.ruleset;
if self.owner.character(character_id).is_err() {
self.owner
.create_character_with_id(self.owner_profile, model, realm_id)?;
}
for (kind, ids) in collections {
if !matches!(kind.as_str(), "coa:appearance" | "coa:vanity") {
continue;
if kind.starts_with(ruleset.as_str()) {
let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?;
self.owner
.merge_collection(self.owner_profile, ruleset, kind, &set)?;
}
let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?;
self.owner
.merge_collection(self.owner_profile, kind, &set)?;
}
self.publish();
self.state()
@@ -1499,13 +1500,14 @@ impl PortableService {
let model = self.owner.load_current(cid)?;
let encoded = super::super::snapshot::encode(&model)?;
let mut collections = BTreeMap::new();
for kind in ["coa:appearance", "coa:vanity"] {
if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, kind) {
for kind in super::super::session::protocol::collection_kinds(model.ruleset) {
if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, model.ruleset, kind) {
collections.insert(kind.to_string(), set.ids().to_vec());
}
}
Ok(ClaimBundle {
character_id: cid,
ruleset: model.ruleset,
payload: encoded.payload,
content_hash: encoded.content_hash,
collections,
@@ -1591,6 +1593,21 @@ impl PortableService {
let opts = self.options(&access, &caps);
// Preflight compatibility check before ANY mutation
let db_ruleset = super::super::realm::ruleset_of(&db)?;
if model.ruleset != db_ruleset {
return Err(fail(
"incompatible",
"Character ruleset does not match realm database ruleset.",
));
}
let caps_ruleset: crate::portable::model::Ruleset = caps.content.ruleset.into();
if model.ruleset != caps_ruleset {
return Err(fail(
"incompatible",
"Character ruleset does not match realm capability ruleset.",
));
}
let ops = [Operation::OnlineImport, Operation::RuntimeSession];
let report = self.report(&model, &caps, &opts, &ops, true);
if verdict_of(report.verdict()) == Verdict::Incompatible {
@@ -1606,9 +1623,9 @@ impl PortableService {
// Monotonic union of collections
for (kind, ids) in &params.collections {
if matches!(kind.as_str(), "coa:appearance" | "coa:vanity") {
if kind.starts_with(model.ruleset.as_str()) {
if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) {
let _ = self.host.merge_collection(self.host_profile, kind, &set);
let _ = self.host.merge_collection(self.host_profile, model.ruleset, kind, &set);
}
}
}
@@ -1625,6 +1642,7 @@ impl PortableService {
);
let offer = super::super::session::protocol::SessionOffer {
protocol_version: super::super::session::protocol::PROTOCOL_VERSION,
ruleset: model.ruleset,
session_id,
character_id: cid,
server_id: realm_id.to_string(),
@@ -7,7 +7,7 @@ use super::*;
use crate::portable::collection::IdSet;
use crate::portable::fixtures::geared_level_eighty;
use crate::portable::ids::{CharacterId, SessionId};
use crate::portable::model::PortableCharacter;
use crate::portable::model::{PortableCharacter, Ruleset};
use crate::portable::realm::knowledge::RealmKnowledge;
use crate::portable::store::Store;
@@ -328,10 +328,10 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() {
// the Owner already holds a big wardrobe from other realms
let profile = owner.default_profile().unwrap();
owner
.merge_collection(profile, APPEARANCE, &ids(1..=500))
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=500))
.unwrap();
owner
.merge_collection(profile, VANITY, &ids(1000..=1010))
.merge_collection(profile, Ruleset::Coa, 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));
@@ -344,7 +344,7 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() {
// 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();
let (_, canonical) = o.store().collection(profile, Ruleset::Coa, APPEARANCE).unwrap().unwrap();
assert_eq!(canonical.len(), 501);
assert!(
canonical.contains(700) && canonical.contains(1) && canonical.contains(500),
@@ -371,12 +371,12 @@ 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))
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=40))
.unwrap();
owner
.merge_collection(profile, VANITY, &ids(50..=60))
.merge_collection(profile, Ruleset::Coa, VANITY, &ids(50..=60))
.unwrap();
let states = OwnerService::new(&mut owner).collection_states().unwrap();
let states = OwnerService::new(&mut owner).collection_states(Ruleset::Coa).unwrap();
assert_eq!(states.len(), 2);
let mut host = Store::open_in_memory().unwrap();
@@ -416,7 +416,7 @@ fn hostile_or_broken_collection_messages_change_nothing() {
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())
collection_to_json(&CollectionObserved::new(SERVER, Ruleset::Coa, APPEARANCE, &ids(1..=10)).unwrap())
.unwrap();
assert_eq!(
o.handle_collection(&good).unwrap().outcome,
@@ -424,7 +424,7 @@ fn hostile_or_broken_collection_messages_change_nothing() {
);
let state_of = |o: &OwnerService| {
o.store()
.collection_info(profile, APPEARANCE)
.collection_info(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap()
};
@@ -555,7 +555,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() {
assert_eq!(realm.full_reads, reads);
let stored = o
.store()
.collection_info(profile, APPEARANCE)
.collection_info(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap();
assert_eq!(stored.count, count as usize);
@@ -565,7 +565,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() {
let mut empty_realm = FakeRealm::new(GUID);
empty_realm.knowledge = realm.knowledge.clone();
let state = o
.collection_states()
.collection_states(Ruleset::Coa)
.unwrap()
.into_iter()
.find(|s| s.kind == APPEARANCE)
@@ -627,7 +627,7 @@ fn a_lost_acknowledgement_resends_the_same_set_and_the_owner_counts_it_once() {
.any(|p| p.kind == APPEARANCE));
assert_eq!(
o.store()
.collection_info(profile, APPEARANCE)
.collection_info(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap()
.revision,
+13 -5
View File
@@ -176,6 +176,12 @@ impl<'a> HostService<'a> {
found: model.character_id,
});
}
if offer.ruleset != model.ruleset {
return Err(PortableError::RulesetMismatch {
character: model.ruleset,
realm: offer.ruleset,
});
}
self.store
.host_install_copy(profile, &model, offer.canonical_revision, "owner")?;
self.store.host_prepare_session(offer, &model)
@@ -606,8 +612,9 @@ impl<'a> HostService<'a> {
let Some(account) = bridge.account_of(guid)? else {
continue;
};
for kind in COLLECTION_KINDS {
self.observe_collection(bridge, account, kind, now_secs, events)?;
let character = self.store.character(s.character_id)?;
for kind in collection_kinds(character.ruleset) {
self.observe_collection(bridge, account, character.ruleset, kind, now_secs, events)?;
}
}
Ok(())
@@ -619,6 +626,7 @@ impl<'a> HostService<'a> {
&mut self,
bridge: &mut dyn RealmBridge,
account: u32,
ruleset: crate::portable::model::Ruleset,
kind: &str,
now_secs: u64,
events: &mut Vec<HostEvent>,
@@ -644,7 +652,7 @@ impl<'a> HostService<'a> {
)?;
return Ok(());
}
let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, kind, &set)?)?;
let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, ruleset, kind, &set)?)?;
self.store.host_collection_observe(
&self.server_id,
account,
@@ -674,7 +682,7 @@ impl<'a> HostService<'a> {
account: u32,
ack: &CollectionAck,
) -> Result<Option<Applied>> {
if !carried_kind(&ack.kind) {
if !carried_kind_for(&ack.kind, ack.ruleset) {
return Err(PortableError::Invalid(
"the acknowledgement is for a kind that is not carried".into(),
));
@@ -742,7 +750,7 @@ impl<'a> HostService<'a> {
account: u32,
state: &CollectionState,
) -> Result<Option<Applied>> {
if !carried_kind(&state.kind) {
if !carried_kind_for(&state.kind, state.ruleset) {
return Err(PortableError::Invalid(
"the collection kind is not carried".into(),
));
+13 -10
View File
@@ -49,10 +49,12 @@ impl<'a> OwnerService<'a> {
pub fn handle_collection(&mut self, bytes: &[u8]) -> Result<CollectionAck> {
let msg: CollectionObserved = collection_from_json(bytes)?;
let profile = self.store.default_profile()?;
let ruleset = msg.ruleset;
let rejected = |store: &Store, reason: &str| -> Result<CollectionAck> {
let info = store.collection_info(profile, &msg.kind).ok().flatten();
let info = store.collection_info(profile, ruleset, &msg.kind).ok().flatten();
Ok(CollectionAck {
protocol_version: PROTOCOL_VERSION,
ruleset,
kind: msg.kind.clone(),
outcome: CollectionOutcome::Rejected(reason.to_string()),
collection_revision: info.as_ref().map_or(0, |i| i.revision),
@@ -60,17 +62,17 @@ impl<'a> OwnerService<'a> {
canonical: None,
})
};
if !carried_kind(&msg.kind) {
return rejected(self.store, "this collection kind is not carried");
if !carried_kind_for(&msg.kind, ruleset) {
return rejected(self.store, "this collection kind is not carried for this ruleset");
}
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 merge = self.store.merge_collection(profile, ruleset, &msg.kind, &observed)?;
let (info, canonical) = self
.store
.collection(profile, &msg.kind)?
.collection(profile, ruleset, &msg.kind)?
.map(|(i, s)| (Some(i), s))
.unwrap_or((None, IdSet::new()));
let canonical_state = match (
@@ -78,12 +80,13 @@ impl<'a> OwnerService<'a> {
observed.count_new(&canonical) == 0 && canonical.count_new(&observed) == 0,
) {
(Some(info), false) => {
Some(CollectionState::new(&msg.kind, info.revision, &canonical)?)
Some(CollectionState::new(ruleset, &msg.kind, info.revision, &canonical)?)
}
_ => None,
};
Ok(CollectionAck {
protocol_version: PROTOCOL_VERSION,
ruleset,
kind: msg.kind,
outcome: if merge.changed {
CollectionOutcome::Applied
@@ -97,12 +100,12 @@ impl<'a> OwnerService<'a> {
}
/// 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>> {
pub fn collection_states(&mut self, ruleset: crate::portable::model::Ruleset) -> 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)?);
for kind in collection_kinds(ruleset) {
if let Some((info, set)) = self.store.collection(profile, ruleset, kind)? {
out.push(CollectionState::new(ruleset, kind, info.revision, &set)?);
}
}
Ok(out)
@@ -128,7 +128,7 @@ fn a_changed_content_profile_makes_the_realm_report_its_collections_again_and_re
} = rig(|_| {});
let profile = owner.default_profile().unwrap();
owner
.merge_collection(profile, APPEARANCE, &ids(1..=500))
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=500))
.unwrap();
// the realm's client data knows 1..=300 of the canonical 500
realm.knowledge = RealmKnowledge::new(ids(1..=300), IdSet::new());
@@ -186,7 +186,7 @@ fn a_changed_content_profile_makes_the_realm_report_its_collections_again_and_re
);
assert_eq!(
o.store()
.collection(profile, APPEARANCE)
.collection(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap()
.1
@@ -21,6 +21,12 @@ pub const PROTOCOL_VERSION: u32 = 2;
pub const MAX_MESSAGE_BYTES: usize = MAX_COMPRESSED_BYTES * 4 / 3 + 64 * 1024;
/// The most item/pet ids an acknowledgement lists.
pub const MAX_ACK_IDS: usize = 20_000;
/// The largest serialized collection message accepted.
pub const MAX_COLLECTION_MESSAGE_BYTES: usize = 1024 * 1024;
fn default_session_ruleset() -> super::super::model::Ruleset {
super::super::model::Ruleset::Coa
}
/// A sealed snapshot: the hash of the canonical JSON and the compressed bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -79,6 +85,8 @@ impl Envelope {
#[serde(deny_unknown_fields)]
pub struct SessionOffer {
pub protocol_version: u32,
#[serde(default = "default_session_ruleset")]
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -123,6 +131,8 @@ impl SessionProgression {
#[serde(deny_unknown_fields)]
pub struct PortableSessionStarted {
pub protocol_version: u32,
#[serde(default = "default_session_ruleset")]
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -139,6 +149,8 @@ pub struct PortableSessionStarted {
#[serde(deny_unknown_fields)]
pub struct PortableCheckpoint {
pub protocol_version: u32,
#[serde(default = "default_session_ruleset")]
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -188,6 +200,8 @@ pub struct NextSession {
#[serde(deny_unknown_fields)]
pub struct OwnerAck {
pub protocol_version: u32,
#[serde(default = "default_session_ruleset")]
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
/// 0 acknowledges `PortableSessionStarted`.
pub sequence: u64,
@@ -250,16 +264,17 @@ impl PortableSessionStarted {
if let Some(p) = &progression {
p.validate()?;
}
let b0 = Envelope::seal(b0)?;
let sealed_b0 = Envelope::seal(b0)?;
Ok(Self {
protocol_version: PROTOCOL_VERSION,
ruleset: b0.ruleset,
session_id,
character_id,
server_id: server_id.to_string(),
base_canonical_revision,
baseline_generation,
content_hash: b0.content_hash.clone(),
b0,
content_hash: sealed_b0.content_hash.clone(),
b0: sealed_b0,
progression,
})
}
@@ -279,6 +294,7 @@ impl PortableCheckpoint {
let realm_snapshot = Envelope::seal(b1)?;
Ok(Self {
protocol_version: PROTOCOL_VERSION,
ruleset: b1.ruleset,
session_id,
character_id,
server_id: server_id.to_string(),
@@ -300,15 +316,32 @@ impl PortableCheckpoint {
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;
/// The collection kinds the protocol carries.
pub const COLLECTION_KINDS: [&str; 6] = [
"coa:appearance",
"coa:vanity",
"wildcard:appearance",
"wildcard:vanity",
"reborn:appearance",
"reborn:vanity",
];
pub fn collection_kinds(ruleset: super::super::model::Ruleset) -> &'static [&'static str] {
match ruleset {
super::super::model::Ruleset::Coa => &["coa:appearance", "coa:vanity"],
super::super::model::Ruleset::Wildcard => &["wildcard:appearance", "wildcard:vanity"],
super::super::model::Ruleset::Reborn => &["reborn:appearance", "reborn:vanity"],
}
}
pub fn carried_kind(kind: &str) -> bool {
valid_kind(kind) && COLLECTION_KINDS.contains(&kind)
}
pub fn carried_kind_for(kind: &str, ruleset: super::super::model::Ruleset) -> bool {
valid_kind(kind) && collection_kinds(ruleset).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)]
@@ -365,6 +398,8 @@ impl CompactSet {
#[serde(deny_unknown_fields)]
pub struct CollectionObserved {
pub protocol_version: u32,
#[serde(default = "default_session_ruleset")]
pub ruleset: super::super::model::Ruleset,
pub server_id: String,
pub kind: String,
pub set: CompactSet,
@@ -375,6 +410,8 @@ pub struct CollectionObserved {
#[serde(deny_unknown_fields)]
pub struct CollectionState {
pub protocol_version: u32,
#[serde(default = "default_session_ruleset")]
pub ruleset: super::super::model::Ruleset,
pub kind: String,
pub collection_revision: u64,
pub set: CompactSet,
@@ -400,6 +437,8 @@ pub enum CollectionOutcome {
#[serde(deny_unknown_fields)]
pub struct CollectionAck {
pub protocol_version: u32,
#[serde(default = "default_session_ruleset")]
pub ruleset: super::super::model::Ruleset,
pub kind: String,
pub outcome: CollectionOutcome,
pub collection_revision: u64,
@@ -440,14 +479,15 @@ pub fn collection_from_json<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
}
impl CollectionObserved {
pub fn new(server_id: &str, kind: &str, set: &IdSet) -> Result<Self> {
if !carried_kind(kind) {
pub fn new(server_id: &str, ruleset: super::super::model::Ruleset, kind: &str, set: &IdSet) -> Result<Self> {
if !carried_kind_for(kind, ruleset) {
return Err(PortableError::Invalid(format!(
"collection kind {kind:?} is not carried"
"collection kind {kind:?} is not carried for {ruleset:?}"
)));
}
Ok(Self {
protocol_version: PROTOCOL_VERSION,
ruleset,
server_id: server_id.to_string(),
kind: kind.to_string(),
set: CompactSet::seal(kind, set)?,
@@ -456,9 +496,10 @@ impl CollectionObserved {
}
impl CollectionState {
pub fn new(kind: &str, revision: u64, set: &IdSet) -> Result<Self> {
pub fn new(ruleset: super::super::model::Ruleset, kind: &str, revision: u64, set: &IdSet) -> Result<Self> {
Ok(Self {
protocol_version: PROTOCOL_VERSION,
ruleset,
kind: kind.to_string(),
collection_revision: revision,
set: CompactSet::seal(kind, set)?,
+80 -11
View File
@@ -27,6 +27,7 @@ const MIGRATIONS: &[&str] = &[
include_str!("migrations/006_collections.sql"),
include_str!("migrations/007_capabilities.sql"),
include_str!("migrations/008_projection.sql"),
include_str!("migrations/009_multiruleset.sql"),
];
pub const DEFAULT_HISTORY_KEEP: u32 = 20;
@@ -173,12 +174,12 @@ impl Store {
}
fn init(conn: Connection) -> Result<Store> {
conn.pragma_update(None, "foreign_keys", true)?;
conn.busy_timeout(std::time::Duration::from_secs(5))?;
let _ = conn.pragma_update(None, "journal_mode", "WAL");
let _ = conn.pragma_update(None, "synchronous", "NORMAL");
let mut store = Store { conn };
store.migrate()?;
store.conn.pragma_update(None, "foreign_keys", true)?;
Ok(store)
}
@@ -328,6 +329,23 @@ impl Store {
read_character(&self.conn, id)
}
pub fn get_character(
&self,
id: CharacterId,
expected_ruleset: Option<Ruleset>,
) -> Result<CharacterRecord> {
let rec = read_character(&self.conn, id)?;
if let Some(expected) = expected_ruleset {
if rec.ruleset != expected {
return Err(PortableError::RulesetMismatch {
character: rec.ruleset,
realm: expected,
});
}
}
Ok(rec)
}
pub fn list_characters(&self, profile: ProfileId) -> Result<Vec<CharacterRecord>> {
let mut stmt = self.conn.prepare(
"SELECT character_id FROM character WHERE profile_id = ?1 ORDER BY character_id",
@@ -340,6 +358,22 @@ impl Store {
.collect()
}
pub fn list_characters_by_ruleset(
&self,
profile: ProfileId,
ruleset: Ruleset,
) -> Result<Vec<CharacterRecord>> {
let mut stmt = self.conn.prepare(
"SELECT character_id FROM character WHERE profile_id = ?1 AND ruleset = ?2 ORDER BY character_id",
)?;
let ids: Vec<String> = stmt
.query_map(params![profile.to_string(), ruleset.as_str()], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?;
ids.iter()
.map(|text| read_character(&self.conn, text.parse()?))
.collect()
}
/// Every character of every profile (an overview for tools; normally the UI lists one profile).
pub fn list_characters_all(&self) -> Result<Vec<CharacterRecord>> {
let mut stmt = self
@@ -663,6 +697,7 @@ impl Store {
pub fn merge_collection(
&mut self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
incoming: &IdSet,
) -> Result<CollectionMerge> {
@@ -682,7 +717,7 @@ impl Store {
"profile {profile} does not exist"
)));
}
let stored = read_collection(&tx, profile, kind)?;
let stored = read_collection(&tx, profile, ruleset, kind)?;
let (current_set, revision) = match &stored {
Some((info, set)) => (set.clone(), info.revision),
None => (IdSet::new(), 0),
@@ -701,11 +736,11 @@ impl Store {
let payload = merged.encode();
let at = now();
tx.execute(
"INSERT INTO collection(profile_id, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
ON CONFLICT(profile_id, kind) DO UPDATE SET collection_revision = excluded.collection_revision, collection_hash = excluded.collection_hash,
"INSERT INTO collection(profile_id, ruleset, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(profile_id, ruleset, kind) DO UPDATE SET collection_revision = excluded.collection_revision, collection_hash = excluded.collection_hash,
format_version = excluded.format_version, item_count = excluded.item_count, updated_at = excluded.updated_at, payload = excluded.payload",
params![profile.to_string(), kind, (revision + 1) as i64, hash.as_slice(), PORTABLE_COLLECTION_FORMAT_VERSION, merged.len() as i64, at, payload],
params![profile.to_string(), ruleset.as_str(), kind, (revision + 1) as i64, hash.as_slice(), PORTABLE_COLLECTION_FORMAT_VERSION, merged.len() as i64, at, payload],
)?;
tx.commit()?;
Ok(CollectionMerge {
@@ -725,13 +760,14 @@ impl Store {
pub fn collection_info(
&self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<CollectionInfo>> {
let row = self
.conn
.query_row(
"SELECT collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND kind = ?2",
params![profile.to_string(), kind],
"SELECT collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND ruleset = ?2 AND kind = ?3",
params![profile.to_string(), ruleset.as_str(), kind],
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec<u8>>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?)),
)
.optional()?;
@@ -750,9 +786,41 @@ impl Store {
pub fn collection(
&self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<(CollectionInfo, IdSet)>> {
read_collection(&self.conn, profile, kind)
read_collection(&self.conn, profile, ruleset, kind)
}
pub fn list_collections(
&self,
profile: ProfileId,
ruleset: Ruleset,
) -> Result<Vec<CollectionInfo>> {
let mut stmt = self.conn.prepare(
"SELECT kind, collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND ruleset = ?2 ORDER BY kind",
)?;
let rows = stmt.query_map(params![profile.to_string(), ruleset.as_str()], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, Vec<u8>>(2)?,
r.get::<_, i64>(3)?,
r.get::<_, String>(4)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (kind, revision, hash, count, updated_at) = row?;
out.push(CollectionInfo {
kind,
revision: revision as u64,
hash: hash_from_blob(hash)?,
count: count as usize,
updated_at,
});
}
Ok(out)
}
/// Rewrite the current revision exactly as format 1 stored it (the stores of Phases 1-5 hold such snapshots). Tests only.
@@ -776,12 +844,13 @@ impl Store {
fn read_collection(
conn: &Connection,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<(CollectionInfo, IdSet)>> {
let row = conn
.query_row(
"SELECT collection_revision, collection_hash, item_count, updated_at, payload FROM collection WHERE profile_id = ?1 AND kind = ?2",
params![profile.to_string(), kind],
"SELECT collection_revision, collection_hash, item_count, updated_at, payload FROM collection WHERE profile_id = ?1 AND ruleset = ?2 AND kind = ?3",
params![profile.to_string(), ruleset.as_str(), kind],
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec<u8>>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?, r.get::<_, Vec<u8>>(4)?)),
)
.optional()?;
+23 -3
View File
@@ -104,6 +104,7 @@ fn head_hash(conn: &Connection, id: CharacterId, revision: u64) -> Result<[u8; 3
}
fn ack(
ruleset: Ruleset,
session: SessionId,
sequence: u64,
outcome: AckOutcome,
@@ -112,6 +113,7 @@ fn ack(
) -> OwnerAck {
OwnerAck {
protocol_version: PROTOCOL_VERSION,
ruleset,
session_id: session,
sequence,
outcome,
@@ -136,9 +138,10 @@ fn owned_ids(
(items, pets)
}
fn offer_from_row(row: &OwnerRow) -> SessionOffer {
fn offer_from_row(row: &OwnerRow, ruleset: Ruleset) -> SessionOffer {
SessionOffer {
protocol_version: PROTOCOL_VERSION,
ruleset,
session_id: row.session_id,
character_id: row.character_id,
server_id: row.server_id.clone(),
@@ -163,6 +166,7 @@ fn open_offer(tx: &Transaction<'_>, id: CharacterId, server_id: &str) -> Result<
)?;
Ok(offer_from_row(
&read_owner_row(tx, session)?.expect("just inserted"),
record.ruleset,
))
}
@@ -186,7 +190,7 @@ impl Store {
return Err(PortableError::SessionOpen);
}
if row.c0_revision == record.revision {
return Ok(offer_from_row(&row));
return Ok(offer_from_row(&row, record.ruleset));
}
tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![live, now()])?;
}
@@ -200,6 +204,7 @@ impl Store {
let tx = self.write_tx()?;
let Some(row) = read_owner_row(&tx, msg.session_id)? else {
return Ok(ack(
msg.ruleset,
msg.session_id,
0,
AckOutcome::Rejected("unknown session".into()),
@@ -207,9 +212,11 @@ impl Store {
[0; 32],
));
};
let record = read_character(&tx, row.character_id)?;
let current_hash = head_hash(&tx, row.character_id, row.head_revision)?;
let reject = |why: &str| {
ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::Rejected(why.into()),
@@ -217,6 +224,9 @@ impl Store {
current_hash,
)
};
if msg.ruleset != record.ruleset {
return Ok(reject("the message ruleset does not match the character"));
}
if msg.character_id != row.character_id || msg.server_id != row.server_id {
return Ok(reject("the message does not belong to this session"));
}
@@ -237,6 +247,7 @@ impl Store {
&& row.progression == msg.progression
{
let mut a = ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::Duplicate,
@@ -253,6 +264,7 @@ impl Store {
"offered" => {}
_ => {
return Ok(ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::StaleSession,
@@ -299,6 +311,7 @@ impl Store {
)?;
tx.commit()?;
let mut a = ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::Applied,
@@ -315,6 +328,7 @@ impl Store {
let tx = self.write_tx()?;
let Some(row) = read_owner_row(&tx, msg.session_id)? else {
return Ok(ack(
msg.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Rejected("unknown session".into()),
@@ -325,9 +339,12 @@ impl Store {
let record = read_character(&tx, row.character_id)?;
let seen_hash = head_hash(&tx, row.character_id, record.revision)?;
let outcome =
|o: AckOutcome| ack(msg.session_id, msg.sequence, o, record.revision, seen_hash);
|o: AckOutcome| ack(record.ruleset, msg.session_id, msg.sequence, o, record.revision, seen_hash);
let reject = |why: &str| outcome(AckOutcome::Rejected(why.into()));
if msg.ruleset != record.ruleset {
return Ok(reject("the checkpoint ruleset does not match the character"));
}
if msg.character_id != row.character_id || msg.server_id != row.server_id {
return Ok(reject("the message does not belong to this session"));
}
@@ -354,6 +371,7 @@ impl Store {
}
let revision = revision as u64;
let mut a = ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Duplicate,
@@ -390,6 +408,7 @@ impl Store {
tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![msg.session_id.to_string(), now()])?;
tx.commit()?;
return Ok(ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::StaleSession,
@@ -457,6 +476,7 @@ impl Store {
};
let mut a = ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Applied,
+15 -14
View File
@@ -918,16 +918,17 @@ fn schema_1_item_mappings_survive_the_migration_as_unverified() {
fn collection_union_never_removes_and_unchanged_means_no_revision() {
let (mut store, profile) = fresh();
let kind = "coa:wardrobe";
assert!(store.collection(profile, kind).unwrap().is_none());
let ruleset = Ruleset::Coa;
assert!(store.collection(profile, ruleset, kind).unwrap().is_none());
// nothing stored, nothing incoming: nothing is created
let empty = store
.merge_collection(profile, kind, &IdSet::new())
.merge_collection(profile, ruleset, kind, &IdSet::new())
.unwrap();
assert!(!empty.changed && empty.info.is_none());
let first = store
.merge_collection(profile, kind, &IdSet::from_ids([10, 20, 30]).unwrap())
.merge_collection(profile, ruleset, kind, &IdSet::from_ids([10, 20, 30]).unwrap())
.unwrap();
assert!(first.changed);
assert_eq!(first.added, 3);
@@ -936,7 +937,7 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() {
// another realm returns a subset: nothing is lost, nothing changes
let subset = store
.merge_collection(profile, kind, &IdSet::from_ids([20]).unwrap())
.merge_collection(profile, ruleset, kind, &IdSet::from_ids([20]).unwrap())
.unwrap();
assert!(!subset.changed);
assert_eq!(
@@ -945,13 +946,13 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() {
"same revision, same hash"
);
let same = store
.merge_collection(profile, kind, &IdSet::from_ids([10, 20, 30]).unwrap())
.merge_collection(profile, ruleset, kind, &IdSet::from_ids([10, 20, 30]).unwrap())
.unwrap();
assert!(!same.changed);
// a realm with new unlocks (and without the old ones) only adds
let more = store
.merge_collection(profile, kind, &IdSet::from_ids([30, 40, 5]).unwrap())
.merge_collection(profile, ruleset, kind, &IdSet::from_ids([30, 40, 5]).unwrap())
.unwrap();
assert!(more.changed);
assert_eq!(more.added, 2);
@@ -959,22 +960,22 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() {
assert_eq!((info2.revision, info2.count), (2, 5));
assert_ne!(info2.hash, info1.hash);
let (info, set) = store.collection(profile, kind).unwrap().unwrap();
let (info, set) = store.collection(profile, ruleset, kind).unwrap().unwrap();
assert_eq!(set.ids(), &[5, 10, 20, 30, 40]);
assert_eq!(info, info2);
assert_eq!(
store.collection_info(profile, kind).unwrap().unwrap(),
store.collection_info(profile, ruleset, kind).unwrap().unwrap(),
info2
);
// kinds are separate collections
assert!(store
.collection_info(profile, "coa:vanity")
.collection_info(profile, ruleset, "coa:vanity")
.unwrap()
.is_none());
assert!(
store
.merge_collection(profile, "wardrobe", &IdSet::new())
.merge_collection(profile, ruleset, "wardrobe", &IdSet::new())
.is_err(),
"kinds must be namespaced"
);
@@ -990,7 +991,7 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() {
] {
let ids: Vec<u32> = (0..count).map(|n| n * 7 + (n % 5)).collect();
let set = IdSet::from_ids(ids).unwrap();
let merge = store.merge_collection(profile, kind, &set).unwrap();
let merge = store.merge_collection(profile, Ruleset::Coa, kind, &set).unwrap();
assert_eq!(merge.added, count as usize);
let stored_bytes: i64 = store
.conn
@@ -1004,7 +1005,7 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() {
stored_bytes < count as i64 * 2 + 16,
"{kind}: {count} ids took {stored_bytes} bytes"
);
let (_, back) = store.collection(profile, kind).unwrap().unwrap();
let (_, back) = store.collection(profile, Ruleset::Coa, kind).unwrap().unwrap();
assert_eq!(back, set);
}
}
@@ -1013,7 +1014,7 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() {
fn a_tampered_collection_is_detected() {
let (mut store, profile) = fresh();
store
.merge_collection(profile, "coa:vanity", &IdSet::from_ids([1, 2, 3]).unwrap())
.merge_collection(profile, Ruleset::Coa, "coa:vanity", &IdSet::from_ids([1, 2, 3]).unwrap())
.unwrap();
let forged = IdSet::from_ids([1, 2, 3, 4]).unwrap().encode();
store
@@ -1021,7 +1022,7 @@ fn a_tampered_collection_is_detected() {
.execute("UPDATE collection SET payload = ?1", [forged])
.unwrap();
assert!(matches!(
store.collection(profile, "coa:vanity"),
store.collection(profile, Ruleset::Coa, "coa:vanity"),
Err(PortableError::CorruptSnapshot(_))
));
}
+21 -4
View File
@@ -122,22 +122,39 @@ pub fn modules_of(root: &Path) -> Vec<ModuleEntry> {
out
}
/// The realm a local id names: an installed server (`srv-<install id>` or the bare install id) or a prepared descriptor.
/// The realm a local id names: an installed server (`srv-<install id>`, `srv-<install id>:<ruleset>` or the bare install id) or a prepared descriptor.
pub fn find_access(
descriptors: &Path,
installs: &[(String, PathBuf)],
local_id: &str,
) -> Option<RealmAccess> {
let (base_id, explicit_mode) = if let Some((base, rs)) = local_id.split_once(':') {
let m = match rs {
"coa" => Some(crate::realms::Mode::Coa),
"wildcard" => Some(crate::realms::Mode::Wildcard),
"reborn" => Some(crate::realms::Mode::Reborn),
_ => None,
};
(base, m)
} else {
(local_id, None)
};
if let Some((id, root)) = installs
.iter()
.find(|(id, _)| format!("srv-{id}") == local_id || id == local_id)
.find(|(id, _)| format!("srv-{id}") == base_id || id == base_id)
{
return Some(RealmAccess::from_install(id, root));
let mut access = RealmAccess::from_install(id, root);
if let Some(m) = explicit_mode {
access.id = format!("srv-{id}:{}", m.name());
access.name = format!("{} — {}", access.name, m.label());
access.mode = Some(m);
}
return Some(access);
}
let (found, _) = load_descriptors(descriptors);
found
.into_iter()
.find(|d| d.id == local_id)
.find(|d| d.id == local_id || d.id == base_id)
.and_then(|d| RealmAccess::from_descriptor(d).ok())
}
+2 -1
View File
@@ -229,7 +229,8 @@ impl ListQuery {
q.ruleset = Some(match value.as_str() {
"coa" => Ruleset::Coa,
"wildcard" => Ruleset::Wildcard,
_ => return invalid("ruleset is coa or wildcard"),
"reborn" => Ruleset::Reborn,
_ => return invalid("ruleset is coa, wildcard or reborn"),
})
}
"cap_min" => q.cap_min = Some(number("cap_min", &value, 255)?),
+11 -1
View File
@@ -20,11 +20,12 @@ pub const MAX_CATALOG_ENTRIES: usize = 8;
const MAX_TOKEN: usize = 64;
const MAX_IDENTITY: usize = 128;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Ruleset {
Coa,
Wildcard,
Reborn,
}
impl Ruleset {
@@ -32,6 +33,15 @@ impl Ruleset {
match self {
Ruleset::Coa => "coa",
Ruleset::Wildcard => "wildcard",
Ruleset::Reborn => "reborn",
}
}
pub fn display_name(self) -> &'static str {
match self {
Ruleset::Coa => "Conquest of Azeroth",
Ruleset::Wildcard => "Wildcard",
Ruleset::Reborn => "Warcraft Reborn",
}
}
}