Phase 8 (part 1): level-cap projection model, capabilities v2, session protocol v2, projected merge

Profile version 2 with a progression block (v1 migrated with no progression), the core's
projection decision (hold) applied to a working copy, per-realm context storage (schema 8),
key-wise merge of build records with the canonical level and xp frozen, session pin in the
v2 messages, mid-session progression change ends the session under the old pin.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Sonnet 5.5 committed 2026-10-07 10:39:04 +05:00
1 parent 297bd39101
commit 426808527b
37 files changed
+2150 -95

No files matched your search

+149 -8
View File
@@ -16,6 +16,11 @@
//!
//! A change of anything in `content` changes `content_profile_hash`; the Manager remembers the hash a realm had when a character was last
//! synchronised with it and re-evaluates what it held back when the hash moves, even if the canonical revision did not.
//!
//! **Progression (Phase 8)** is not part of the content hash: it says how far a character may progress on the realm (`MaxPlayerLevel`),
//! under which rules the core projects a higher-level character down to it, and an opaque signature of everything those rules read.
//! Profile version 1 had no such block; a stored v1 profile is *migrated* (its content and hash are unchanged) with no progression, which
//! every operation reads as "the realm must be probed again" and never as "no cap".
use std::collections::{BTreeMap, BTreeSet};
@@ -26,7 +31,9 @@ use super::error::{PortableError, Result};
use super::model::Ruleset;
/// Version of this profile's shape.
pub const PROFILE_VERSION: u32 = 1;
pub const PROFILE_VERSION: u32 = 2;
/// The profile version this Manager migrates from.
pub const PROFILE_VERSION_V1: u32 = 1;
/// The most extension namespaces a profile lists.
pub const MAX_PROFILE_EXTENSIONS: usize = 64;
/// The largest serialised profile accepted from outside.
@@ -42,6 +49,8 @@ pub enum Feature {
Wardrobe,
/// Account collections (`coa:appearance`, `coa:vanity`).
Collections,
/// The core projects a character above its level cap down to it (`portable project`, the job's `projection` header).
LevelProjection,
}
impl Feature {
@@ -50,6 +59,7 @@ impl Feature {
Feature::RuntimeSessions => "runtime_sessions",
Feature::Wardrobe => "wardrobe",
Feature::Collections => "collections",
Feature::LevelProjection => "level_projection",
}
}
}
@@ -182,6 +192,42 @@ impl ContentProfile {
}
}
/// How far a character may progress on a realm and what its core projects to get there (Phase 8). From the running core, never guessed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Progression {
/// `MaxPlayerLevel` of the running core. It cannot change while the core runs.
pub max_player_level: u32,
/// Version of the projection exchange (`portable project`, the job's `projection` header).
pub projection_protocol: u32,
/// Version of the projection policy (what is held at a level, and how).
pub projection_policy_version: u32,
/// Opaque, deterministic: moves whenever the cap, the content-scaling layout, the progression tables or the effective item levels move.
pub progression_signature: String,
pub scaling_enabled: bool,
}
impl Progression {
pub fn validate(&self) -> Result<()> {
let bad = |what: &str| PortableError::Invalid(format!("realm progression: {what}"));
if self.max_player_level == 0 || self.max_player_level > 255 {
return Err(bad("the level cap is out of range"));
}
if self.projection_protocol == 0 || self.projection_policy_version == 0 {
return Err(bad("a version is 0"));
}
if self.progression_signature.len() != 64 || !self.progression_signature.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return Err(bad("the signature is not a SHA-256"));
}
Ok(())
}
/// The words the core stores in `coa.portable.pin` for this progression (see [`super::projection::ProgressionPin::words`]).
pub fn pin_words(&self) -> Vec<u32> {
super::projection::ProgressionPin::native(self, &"0".repeat(64)).words()
}
}
/// A realm's capabilities as they are published and compared.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -191,17 +237,54 @@ pub struct RealmCapabilities {
pub content: ContentProfile,
/// Lower-case hex of [`ContentProfile::hash`].
pub content_profile_hash: String,
/// `None`: not known (a profile migrated from version 1, a stopped realm never probed through its core). Never read as "no cap".
#[serde(default)]
pub progression: Option<Progression>,
}
/// Profile version 1, as it was stored before Phase 8.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
struct RealmCapabilitiesV1 {
#[allow(dead_code)]
profile_version: u32,
core: Option<CoreIdentity>,
content: ContentProfileV1,
content_profile_hash: String,
}
/// Content of a version 1 profile: no `level_projection` feature can be in it.
type ContentProfileV1 = ContentProfile;
impl RealmCapabilities {
pub fn new(core: Option<CoreIdentity>, mut content: ContentProfile) -> Result<Self> {
pub fn new(core: Option<CoreIdentity>, content: ContentProfile) -> Result<Self> {
Self::build(core, content, None)
}
/// A profile with the progression of the realm's core (or without it, for a realm whose core could not be asked).
pub fn build(core: Option<CoreIdentity>, mut content: ContentProfile, progression: Option<Progression>) -> Result<Self> {
content.extensions.sort_by(|a, b| a.namespace.cmp(&b.namespace));
let content_profile_hash = hex::encode(content.hash()?);
let caps = Self { profile_version: PROFILE_VERSION, core, content, content_profile_hash };
let caps = Self { profile_version: PROFILE_VERSION, core, content, content_profile_hash, progression };
caps.validate()?;
Ok(caps)
}
pub fn with_progression(mut self, progression: Progression) -> Result<Self> {
progression.validate()?;
self.progression = Some(progression);
Ok(self)
}
/// The realm's progression is not known: every operation that depends on the cap needs a probe through the core first.
pub fn needs_reprobe(&self) -> bool {
self.progression.is_none()
}
pub fn progression_signature(&self) -> Option<&str> {
self.progression.as_ref().map(|p| p.progression_signature.as_str())
}
pub fn hash(&self) -> &str {
&self.content_profile_hash
}
@@ -248,6 +331,11 @@ impl RealmCapabilities {
if hex::encode(c.hash()?) != self.content_profile_hash {
return Err(bad("the content profile hash does not match the content"));
}
match &self.progression {
Some(p) => p.validate()?,
None if c.supports(Feature::LevelProjection) => return Err(bad("level projection is claimed without a progression block")),
None => {}
}
Ok(())
}
@@ -259,13 +347,17 @@ impl RealmCapabilities {
Ok(bytes)
}
/// Parse and validate a profile from outside: size first, version before anything else is trusted, unknown fields refused.
/// Parse and validate a profile from outside: size first, version before anything else is trusted, unknown fields refused. A version 1
/// profile is migrated (see the module documentation); a newer one than this Manager knows is refused.
pub fn from_json(bytes: &[u8]) -> Result<Self> {
if bytes.len() > MAX_PROFILE_BYTES {
return Err(PortableError::LimitExceeded(format!("a profile is limited to {MAX_PROFILE_BYTES} bytes")));
}
let value: serde_json::Value = serde_json::from_slice(bytes)?;
let version = value.get("profile_version").and_then(|v| v.as_u64()).ok_or_else(|| PortableError::Invalid("the profile has no version".into()))?;
if version == PROFILE_VERSION_V1 as u64 {
return Self::migrate_v1(value);
}
if version != PROFILE_VERSION as u64 {
return Err(PortableError::UnsupportedFormat { found: version.min(u32::MAX as u64) as u32, supported: PROFILE_VERSION });
}
@@ -273,6 +365,16 @@ impl RealmCapabilities {
caps.validate()?;
Ok(caps)
}
fn migrate_v1(value: serde_json::Value) -> Result<Self> {
let old: RealmCapabilitiesV1 = serde_json::from_value(value)?;
if old.content.supports(Feature::LevelProjection) {
return Err(PortableError::Invalid("a version 1 profile cannot claim level projection".into()));
}
let caps = Self { profile_version: PROFILE_VERSION, core: old.core, content: old.content, content_profile_hash: old.content_profile_hash, progression: None };
caps.validate()?;
Ok(caps)
}
}
/// What the realm's core says about itself in answer to `portable capabilities` (RA). Strict: the Manager trusts nothing it does not
@@ -284,6 +386,9 @@ pub struct CoreReport {
pub ruleset: String,
pub core: CoreIdentity,
pub portable: CorePortable,
/// Report version 2 and later. A version 1 core cannot say what its cap is.
#[serde(default)]
pub progression: Option<Progression>,
pub extension_namespaces: Vec<String>,
pub client_data: BTreeMap<String, Option<CatalogEntry>>,
}
@@ -305,8 +410,14 @@ impl CoreReport {
return Err(PortableError::LimitExceeded("the core's capability report is too large".into()));
}
let report: CoreReport = serde_json::from_str(line).map_err(|e| PortableError::Invalid(format!("the core's capability report is not valid: {e}")))?;
if report.report_version != 1 {
return Err(PortableError::UnsupportedFormat { found: report.report_version, supported: 1 });
if report.report_version != 1 && report.report_version != 2 {
return Err(PortableError::UnsupportedFormat { found: report.report_version, supported: 2 });
}
match (&report.progression, report.report_version) {
(Some(p), 2) => p.validate()?,
(None, 1) => {}
(Some(_), _) => return Err(PortableError::Invalid("a version 1 report cannot carry a progression block".into())),
(None, _) => return Err(PortableError::Invalid("the core's capability report has no progression block".into())),
}
if report.ruleset != "coa" {
return Err(PortableError::Invalid(format!("the core reports ruleset {:?}; only coa is carried", report.ruleset)));
@@ -406,7 +517,7 @@ mod tests {
unknown["extra"] = 1.into();
assert!(RealmCapabilities::from_json(&bytes(&unknown)).is_err());
let mut newer = value.clone();
newer["profile_version"] = 2.into();
newer["profile_version"] = 3.into();
assert!(matches!(RealmCapabilities::from_json(&bytes(&newer)), Err(PortableError::UnsupportedFormat { .. })));
value["content"]["client_catalog"]["Appearances.dbc"]["sha256"] = "not hex".into();
assert!(RealmCapabilities::from_json(&bytes(&value)).is_err());
@@ -424,6 +535,35 @@ mod tests {
assert!(RealmCapabilities::new(None, bad).is_err());
}
#[test]
fn a_version_one_profile_is_migrated_with_no_progression_and_never_with_a_made_up_one() {
let caps = RealmCapabilities::new(None, sample()).unwrap();
let mut old: serde_json::Value = serde_json::from_slice(&caps.to_json().unwrap()).unwrap();
old["profile_version"] = 1.into();
old.as_object_mut().unwrap().remove("progression");
let migrated = RealmCapabilities::from_json(&serde_json::to_vec(&old).unwrap()).unwrap();
assert_eq!(migrated.profile_version, PROFILE_VERSION);
assert!(migrated.needs_reprobe() && migrated.progression.is_none());
assert_eq!(migrated.content_profile_hash, caps.content_profile_hash, "the content, and its hash, are the same");
let mut with_block = old.clone();
with_block["progression"] = serde_json::json!({"max_player_level": 60});
assert!(RealmCapabilities::from_json(&serde_json::to_vec(&with_block).unwrap()).is_err(), "a v1 profile has no progression to carry");
}
#[test]
fn progression_is_validated_and_its_pin_words_are_stable() {
let p = Progression { max_player_level: 60, projection_protocol: 1, projection_policy_version: 1, progression_signature: "ab".repeat(32), scaling_enabled: true };
let caps = RealmCapabilities::build(None, sample(), Some(p.clone())).unwrap();
assert_eq!(RealmCapabilities::from_json(&caps.to_json().unwrap()).unwrap(), caps);
assert_eq!(p.pin_words(), vec![1, 60, 0xabababab, 0xabababab, 0xabababab, 0xabababab, 0xabababab, 0xabababab, 0xabababab, 0xabababab]);
for bad in [Progression { max_player_level: 0, ..p.clone() }, Progression { projection_protocol: 0, ..p.clone() }, Progression { progression_signature: "zz".into(), ..p.clone() }] {
assert!(RealmCapabilities::build(None, sample(), Some(bad)).is_err());
}
let mut claims = sample();
claims.features.insert(Feature::LevelProjection);
assert!(RealmCapabilities::build(None, claims, None).is_err(), "level projection is claimed only with the progression block");
}
#[test]
fn the_core_report_is_parsed_strictly() {
let line = r#"{"report_version":1,"ruleset":"coa","core":{"commit":"abc","branch":"feat/x","date":"2026-10-06"},"portable":{"job_formats":[2],"character_formats":[2],"session_marker_version":1,"features":["runtime_sessions","wardrobe"]},"extension_namespaces":[],"client_data":{"Appearances.dbc":{"sha256":"abababababababababababababababababababababababababababababababab","records":3},"ItemSet.dbc":null}}"#;
@@ -431,7 +571,8 @@ mod tests {
assert!(report.has_feature("wardrobe") && !report.has_feature("collections"));
assert_eq!(report.catalog().len(), 1, "a table the core could not read is not in the catalog");
assert!(CoreReport::parse("Unknown command").is_err(), "an older core has no such command");
assert!(CoreReport::parse(&line.replace("\"report_version\":1", "\"report_version\":2")).is_err());
assert!(CoreReport::parse(&line.replace("\"report_version\":1", "\"report_version\":3")).is_err());
assert!(CoreReport::parse(&line.replace("\"report_version\":1", "\"report_version\":2")).is_err(), "a version 2 report must carry its progression block");
assert!(CoreReport::parse(&line.replace("\"coa\"", "\"wildcard\"")).is_err());
assert!(CoreReport::parse(&line.replace("\"records\":3", "\"records\":3,\"x\":1")).is_err());
assert!(CoreReport::parse(&line.replace("Appearances.dbc", "Secret.dbc")).is_err());
+40 -6
View File
@@ -53,6 +53,8 @@ pub enum Topic {
Wardrobe,
Collection(String),
Extension(String),
/// The realm's level cap against the character's level (Phase 8).
Progression,
}
impl std::fmt::Display for Topic {
@@ -66,6 +68,7 @@ impl std::fmt::Display for Topic {
Topic::Wardrobe => f.write_str("wardrobe"),
Topic::Collection(kind) => write!(f, "collection {kind}"),
Topic::Extension(ns) => write!(f, "extension {ns}"),
Topic::Progression => f.write_str("progression"),
}
}
}
@@ -74,6 +77,9 @@ impl std::fmt::Display for Topic {
pub enum Outcome {
Compatible(Topic),
Held { topic: Topic, held: usize, applicable: usize, reason: String },
/// The character is above the realm's level cap and is given to the realm as a working copy at the cap; what the copy cannot hold stays
/// canonical. The core decides what that is when the operation runs.
Projected { topic: Topic, from: u32, to: u32 },
Unsupported { topic: Topic, reason: String },
Blocking { topic: Topic, reason: String },
}
@@ -81,7 +87,7 @@ pub enum Outcome {
impl Outcome {
pub fn topic(&self) -> &Topic {
match self {
Outcome::Compatible(t) | Outcome::Held { topic: t, .. } | Outcome::Unsupported { topic: t, .. } | Outcome::Blocking { topic: t, .. } => t,
Outcome::Compatible(t) | Outcome::Held { topic: t, .. } | Outcome::Projected { topic: t, .. } | Outcome::Unsupported { topic: t, .. } | Outcome::Blocking { topic: t, .. } => t,
}
}
}
@@ -91,6 +97,7 @@ impl std::fmt::Display for Outcome {
match self {
Outcome::Compatible(t) => write!(f, "{t}: compatible"),
Outcome::Held { topic, held, applicable, reason } => write!(f, "{topic}: {applicable} applied, {held} held back in the canonical character ({reason})"),
Outcome::Projected { topic, from, to } => write!(f, "{topic}: level {from} is above the realm's cap {to}: projected to {to}, what the working copy cannot hold stays in the canonical character"),
Outcome::Unsupported { topic, reason } => write!(f, "{topic}: not supported by this realm, nothing applied and nothing lost ({reason})"),
Outcome::Blocking { topic, reason } => write!(f, "{topic}: BLOCKS the operation ({reason})"),
}
@@ -149,6 +156,8 @@ pub struct Inputs<'a> {
/// The Owner's canonical collections that would be applied to the realm's account alongside.
pub collections: &'a [(&'a str, &'a IdSet)],
pub extensions: Option<&'a ExtensionRegistry>,
/// Something can decide what a projection holds when the operation runs: a running core (an online import) or a decision supplied from one.
pub projection_decider: bool,
}
pub fn evaluate(i: &Inputs<'_>) -> CompatibilityReport {
@@ -185,6 +194,8 @@ pub fn evaluate(i: &Inputs<'_>) -> CompatibilityReport {
}
}
out.push(progression_outcome(i));
if let Some(k) = i.knowledge {
if let Some(why) = catalog_mismatch(k, i.capabilities) {
out.push(Outcome::Blocking { topic: Topic::ClientData, reason: why });
@@ -202,6 +213,28 @@ pub fn evaluate(i: &Inputs<'_>) -> CompatibilityReport {
CompatibilityReport { operation: i.operation, content_profile_hash: i.capabilities.content_profile_hash.clone(), outcomes: out }
}
fn progression_outcome(i: &Inputs<'_>) -> Outcome {
use super::projection::{activation, Activation, POLICY_VERSION, PROTOCOL};
let topic = Topic::Progression;
let Some(p) = &i.capabilities.progression else {
return Outcome::Blocking { topic, reason: "the realm's progression profile is not known (a profile from before level projection, or a realm probed without its core): probe it through its core first".into() };
};
match activation(i.model.progression.level, p) {
Activation::None => Outcome::Compatible(topic),
Activation::Active { canonical_level, projected_level } => {
if !i.capabilities.content.supports(Feature::LevelProjection) {
Outcome::Blocking { topic, reason: format!("the character is level {canonical_level} and the realm's cap is {projected_level}, and its core cannot project") }
} else if p.projection_protocol != PROTOCOL || p.projection_policy_version != POLICY_VERSION {
Outcome::Blocking { topic, reason: format!("the core projects with protocol {} / policy {}; this Manager speaks {PROTOCOL} / {POLICY_VERSION}", p.projection_protocol, p.projection_policy_version) }
} else if !i.projection_decider {
Outcome::Blocking { topic, reason: format!("the character is level {canonical_level} and the realm's cap is {projected_level}: only a running core can say what a projection holds (start the realm, or supply a projection made by its core)") }
} else {
Outcome::Projected { topic, from: canonical_level, to: projected_level }
}
}
}
}
/// The client tables the Manager read must be the ones the realm's profile describes.
fn catalog_mismatch(knowledge: &RealmKnowledge, caps: &RealmCapabilities) -> Option<String> {
for (name, mine) in knowledge.catalog() {
@@ -287,19 +320,20 @@ mod tests {
fn profile(features: &[Feature], jobs: &[u32]) -> RealmCapabilities {
let mut catalog = ClientCatalog::new();
catalog.insert("Appearances.dbc".into(), CatalogEntry { sha256: "ab".repeat(32), records: 3 });
RealmCapabilities::new(
RealmCapabilities::build(
None,
ContentProfile {
ruleset: Ruleset::Coa,
character_formats: ContentProfile::manager_formats(),
online_import_job_formats: jobs.to_vec(),
session_protocol: 1,
collection_protocol: 1,
session_protocol: 2,
collection_protocol: 2,
features: features.iter().copied().collect(),
collection_kinds: ["coa:appearance".to_string(), "coa:vanity".to_string()].into_iter().collect(),
extensions: vec![],
client_catalog: catalog,
},
Some(Progression { max_player_level: 80, projection_protocol: 1, projection_policy_version: 1, progression_signature: "cd".repeat(32), scaling_enabled: true }),
)
.unwrap()
}
@@ -313,7 +347,7 @@ mod tests {
}
fn run(op: Operation, model: &PortableCharacter, caps: &RealmCapabilities, k: Option<&RealmKnowledge>, collections: &[(&str, &IdSet)], reg: Option<&ExtensionRegistry>) -> CompatibilityReport {
evaluate(&Inputs { operation: op, model, capabilities: caps, knowledge: k, collections, extensions: reg })
evaluate(&Inputs { operation: op, model, capabilities: caps, knowledge: k, collections, extensions: reg, projection_decider: true })
}
#[test]
@@ -390,7 +424,7 @@ mod tests {
reg.register(FakeAdapter::new(2, 3)).unwrap();
let mut caps = profile(&all(), &[2]).content;
caps.extensions = vec![ExtensionSupport { namespace: "mod:fake".into(), module_version: "1.0.0".into(), formats: FormatRange::new(2, 3) }];
let caps = RealmCapabilities::new(None, caps).unwrap();
let caps = RealmCapabilities::build(None, caps, profile(&all(), &[2]).progression).unwrap();
let r = run(Operation::Update, &model, &caps, None, &[], Some(&reg));
assert_eq!(r.outcome(&Topic::Extension("mod:fake".into())), Some(&Outcome::Compatible(Topic::Extension("mod:fake".into()))));
assert!(matches!(r.outcome(&Topic::Extension("mod:other".into())), Some(Outcome::Held { reason, .. }) if reason.contains("does not have this module")));
+4
View File
@@ -54,6 +54,10 @@ pub enum PortableError {
ImportState { import_id: ImportId, state: String },
#[error("this realm cannot take the {operation}; nothing was written: {}", .reasons.join("; "))]
Incompatible { operation: String, reasons: Vec<String> },
#[error("this character is level {character_level} and the realm's cap is {cap}: it must be projected, and only a running core can say what a projection holds (start the realm, or supply a projection made by its core); nothing was written")]
ProjectionNeedsRunningCore { character_level: u32, cap: u32 },
#[error("the realm's progression profile is not the one this was projected for: {0}")]
ProgressionChanged(String),
#[error("the import was refused before anything was written: {}", .0.iter().map(|p| p.to_string()).collect::<Vec<_>>().join("; "))]
ImportRefused(Vec<ImportProblem>),
#[error("import {import_id} needs attention: {detail}")]
+86 -7
View File
@@ -23,6 +23,12 @@
//! taken from `ours` if it has come back; in `base` only (the realm's own addition / filtered at the target): ignored;
//! new in `ours`: added.
//!
//! **Under a level-cap projection** ([`MergeProjection`]) two things change: the level and the xp of the working copy are the realm's own
//! (the cap, xp 0) and never reach the canonical character, and the build records the core rewrites at every save
//! (`core.ascension_slot.*`, `core.ascension_build.*`, `core.ascension_bar.*`) are merged **key by key** instead of as one value, so that
//! what the realm could not hold survives in the canonical record. Everything else is as above: what the projection holds is absent from
//! the realm's `B0` and `B1`, which is exactly "filtered away by the realm: kept".
//!
//! [`Mode::Strict`] additionally reports a **conflict** when `target` and `ours` both departed from `base` and disagree;
//! [`Mode::Lenient`] (sessions) takes `ours`.
@@ -32,6 +38,16 @@ use std::fmt::Debug;
use super::error::{PortableError, Result};
use super::ids::{PortableItemId, PortablePetId};
use super::model::*;
use super::projection::settings::{classify, Record};
/// How a projected character is merged: see the module documentation.
#[derive(Clone, Debug, Default)]
pub struct MergeProjection {
/// The canonical level and xp stay as they are (a session reconciling a working copy into its canonical character).
pub freeze_progression: bool,
/// Build records the core could not take apart: the realm's value is ignored.
pub blocked: BTreeSet<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
@@ -211,6 +227,47 @@ impl Ctx {
}
}
/// The settings of a projected character: build records key by key, blocked ones untouched, the rest as one value each.
fn projected_settings(&mut self, target: &mut BTreeMap<String, Vec<u32>>, base: &BTreeMap<String, Vec<u32>>, ours: &BTreeMap<String, Vec<u32>>, projection: &MergeProjection) {
let special = |k: &String| classify(k).is_some() || projection.blocked.contains(k);
let plain = |m: &BTreeMap<String, Vec<u32>>| -> BTreeMap<String, Vec<u32>> { m.iter().filter(|(k, _)| !special(k)).map(|(k, v)| (k.clone(), v.clone())).collect() };
let mut rest = plain(target);
self.map("settings", &mut rest, &plain(base), &plain(ours));
target.retain(|k, _| special(k));
target.extend(rest);
let sources: BTreeSet<&String> = ours.keys().filter(|k| special(k)).collect();
for source in sources {
if projection.blocked.contains(source) {
self.left_alone.push(format!("settings[{source:?}]: not merged, the projection could not take it apart"));
continue;
}
let Some(kind) = classify(source) else { continue };
let (Some(o), t) = (ours.get(source), target.get(source)) else { continue };
let Some(ours_record) = Record::parse(kind, o) else {
self.left_alone.push(format!("settings[{source:?}]: the realm's value is not a build record, left alone"));
continue;
};
let Some(t) = t else {
self.changes.push(format!("settings[{source:?}]: added"));
target.insert(source.clone(), ours_record.write());
continue;
};
let Some(mut merged) = Record::parse(kind, t) else {
self.left_alone.push(format!("settings[{source:?}]: the canonical value is not a build record, left alone"));
continue;
};
let base_record = base.get(source).and_then(|b| Record::parse(kind, b)).unwrap_or_else(|| Record::parse(kind, &empty_record(kind)).expect("an empty record parses"));
self.scalar(&format!("settings[{source:?}].head"), &mut merged.head, &base_record.head, &ours_record.head);
self.map(&format!("settings[{source:?}].entries"), &mut merged.entries, &base_record.entries, &ours_record.entries);
self.map(&format!("settings[{source:?}].buttons"), &mut merged.buttons, &base_record.buttons, &ours_record.buttons);
let written = merged.write();
if Record::parse(kind, t).map(|r| r.write()).as_ref() != Some(&written) {
target.insert(source.clone(), written);
}
}
}
fn set<K: Ord + Clone + Debug>(&mut self, path: &str, target: &mut BTreeSet<K>, base: &BTreeSet<K>, ours: &BTreeSet<K>) {
let mut t: BTreeMap<K, ()> = target.iter().map(|k| (k.clone(), ())).collect();
let b: BTreeMap<K, ()> = base.iter().map(|k| (k.clone(), ())).collect();
@@ -224,8 +281,21 @@ fn to_map<T, K: Ord, V>(items: &[T], f: impl Fn(&T) -> (K, V)) -> BTreeMap<K, V>
items.iter().map(f).collect()
}
fn empty_record(kind: super::projection::settings::SettingKind) -> Vec<u32> {
use super::projection::settings::SettingKind;
match kind {
SettingKind::Slot => vec![1, 12, 0, 0, 0],
SettingKind::Build | SettingKind::Bar => vec![0],
}
}
/// Apply `base -> ours` onto `target`.
pub fn merge3(target: &PortableCharacter, base: &PortableCharacter, ours: &PortableCharacter, mode: Mode) -> Result<Merged> {
merge3_with(target, base, ours, mode, None)
}
/// [`merge3`], optionally of a projected character.
pub fn merge3_with(target: &PortableCharacter, base: &PortableCharacter, ours: &PortableCharacter, mode: Mode, projection: Option<&MergeProjection>) -> Result<Merged> {
if target.ruleset != base.ruleset || target.ruleset != ours.ruleset {
return Err(PortableError::Invalid("three characters of different rulesets cannot be merged".into()));
}
@@ -243,13 +313,19 @@ pub fn merge3(target: &PortableCharacter, base: &PortableCharacter, ours: &Porta
// ---- progression ---------------------------------------------------------------------------------------------
let (t, b, o) = (&mut out.progression, &base.progression, &ours.progression);
let leveled = b.level != o.level;
cx.scalar("progression.level", &mut t.level, &b.level, &o.level);
if leveled {
cx.scalar("progression.xp", &mut t.xp, &b.xp, &o.xp);
if projection.is_some_and(|p| p.freeze_progression) {
if b.level != o.level || b.xp != o.xp {
cx.left_alone.push(format!("progression: the realm's level {} xp {} is the working copy's own and never reaches the canonical character", o.level, o.xp));
}
} else {
let mut xp = t.xp as u64;
cx.add("progression.xp", &mut xp, b.xp as u64, o.xp as u64, u32::MAX as u64);
t.xp = xp as u32;
cx.scalar("progression.level", &mut t.level, &b.level, &o.level);
if leveled {
cx.scalar("progression.xp", &mut t.xp, &b.xp, &o.xp);
} else {
let mut xp = t.xp as u64;
cx.add("progression.xp", &mut xp, b.xp as u64, o.xp as u64, u32::MAX as u64);
t.xp = xp as u32;
}
}
macro_rules! accumulate {
($path:literal, $field:expr, $b:expr, $o:expr, $max:expr) => {{
@@ -326,7 +402,10 @@ pub fn merge3(target: &PortableCharacter, base: &PortableCharacter, ours: &Porta
cx.map("actions", &mut actions, &to_map(&base.actions, |a| ((a.spec, a.button), (a.action, a.kind))), &to_map(&ours.actions, |a| ((a.spec, a.button), (a.action, a.kind))));
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);
match projection {
Some(p) => cx.projected_settings(&mut out.settings, &base.settings, &ours.settings, p),
None => 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);
@@ -0,0 +1,34 @@
-- Schema 8: level-cap projection (Phase 8).
--
-- realm_projection what a character is shown on a realm whose level cap is below the character's level: the
-- context of the projection (levels, the canonical revision the working copy was last brought
-- to, the content profile and progression signature, the policy version) and the core's
-- decision (what is held). Absent: the character is not projected on that realm.
-- character_server_mapping.progression_pin the pin (cap, policy, progression signature, content profile hash, projected or native) the
-- character was last synchronised under, projected or not: a realm with another signature has
-- another cap or other rules
-- owner_session.progression the pin (and, when projected, the context) the Host reported when the session started;
-- every later checkpoint must carry the same pin
-- host_session.pin / host_session.reproject the pin this session runs under; reproject = the realm's progression profile changed under
-- the session: its final checkpoint was taken under the old pin and the working copy must be
-- projected again before the next session is armed
ALTER TABLE character_server_mapping ADD COLUMN progression_pin TEXT;
CREATE TABLE realm_projection (
character_id TEXT NOT NULL REFERENCES character(character_id) ON DELETE CASCADE,
server_id TEXT NOT NULL,
canonical_level INTEGER NOT NULL,
projected_level INTEGER NOT NULL,
canonical_revision INTEGER NOT NULL,
content_profile_hash TEXT NOT NULL,
progression_signature TEXT NOT NULL,
policy_version INTEGER NOT NULL,
context TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (character_id, server_id)
) STRICT;
ALTER TABLE owner_session ADD COLUMN progression TEXT;
ALTER TABLE host_session ADD COLUMN pin TEXT;
ALTER TABLE host_session ADD COLUMN reproject INTEGER NOT NULL DEFAULT 0;
+1
View File
@@ -15,6 +15,7 @@ pub mod identity;
pub mod ids;
pub mod merge;
pub mod model;
pub mod projection;
pub mod realm;
pub mod session;
pub mod snapshot;
@@ -0,0 +1,344 @@
//! Level-cap projection (Phase 8): a character above a realm's level cap is shown to the realm as a **working copy at the cap**, and what that
//! copy cannot hold stays in the canonical character.
//!
//! ```text
//! C canonical, never down-levelled (the Owner's truth)
//! P = apply(hold, C) what the realm is given: level = cap, xp 0, minus what the core *holds* at that level
//! B0, B1 what the realm shows (a projected view)
//! C' = merge3(C, B0, B1) with level and xp frozen and the build records merged key by key
//! ```
//!
//! **Who decides.** Only the running core knows the effective, post-scaling item levels and holds the CoA progression tables, so the core
//! decides what is held (`portable project`): items that its own loader would take out of the equipment slots and mail, abilities no
//! source grants at the cap, talent picks above the level or the point budget of the cap, the buttons that show such abilities, and the
//! entries of the stored builds. This module only *applies* that decision; it never reads a level requirement.
//!
//! **Why `merge3` keeps what is held.** A held item, spell or button is absent from `B0` and from `B1`, so for the merge it is "filtered away
//! by the realm": it stays canonical. The one exception is a build record the core rewrites at every save (`core.ascension_slot.*`): its
//! whole value differs between `C` and `B0`, so those records are merged key by key ([`settings`]).
pub mod settings;
use std::collections::BTreeSet;
use serde::{Deserialize, Serialize};
use super::capabilities::Progression;
use super::error::{PortableError, Result};
use super::ids::PortableItemId;
use super::model::PortableCharacter;
use super::snapshot;
/// Version of the projection policy this Manager speaks (the core reports its own; a different one is refused).
pub const POLICY_VERSION: u32 = 1;
/// Version of the projection exchange with the core.
pub const PROTOCOL: u32 = 1;
/// What one build record loses at the cap.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SettingHold {
pub source: String,
pub kind: settings::SettingKind,
/// Talent entries held (slot, build).
#[serde(default)]
pub entries: Vec<u32>,
/// Buttons held (slot actions, bar).
#[serde(default)]
pub buttons: Vec<u32>,
}
/// The core's decision for one canonical character at one cap.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectionHold {
pub protocol: u32,
pub policy_version: u32,
pub progression_signature: String,
pub max_player_level: u32,
pub canonical_level: u32,
pub projected_level: u32,
#[serde(default)]
pub held_items: Vec<PortableItemId>,
#[serde(default)]
pub held_spells: Vec<u32>,
#[serde(default)]
pub held_actions: Vec<(u8, u8)>,
#[serde(default)]
pub settings: Vec<SettingHold>,
/// Build records the core could not take apart: they are not given to the realm and never merged back.
#[serde(default)]
pub blocked_settings: Vec<String>,
/// The canonical snapshot (its content hash) this decision was made for; empty when it is only a stored decision being re-applied.
#[serde(default)]
pub subject: String,
}
/// What the core answers to `portable project`: whether the character is projected at all, and the decision when it is.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectionAnswer {
pub status: String,
pub projection: AnswerBlock,
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnswerBlock {
pub active: bool,
pub protocol: u32,
pub policy_version: u32,
pub progression_signature: String,
pub max_player_level: u32,
pub canonical_level: u32,
pub projected_level: u32,
#[serde(default)]
pub held_items: Vec<PortableItemId>,
#[serde(default)]
pub held_spells: Vec<u32>,
#[serde(default)]
pub held_actions: Vec<(u8, u8)>,
#[serde(default)]
pub settings: Vec<SettingHold>,
#[serde(default)]
pub blocked_settings: Vec<String>,
}
/// What a realm decided about a canonical character.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Decision {
/// The character's level is within the cap: the realm gets it as it is.
Native,
Projected(ProjectionHold),
}
impl ProjectionAnswer {
/// Parse the single JSON line of the console's answer (or the result file) strictly.
pub fn parse(text: &str, subject: &str) -> Result<Decision> {
let line = text.lines().map(str::trim).find(|l| l.starts_with('{')).ok_or_else(|| PortableError::Invalid("the core did not answer a projection query".into()))?;
if line.len() > 8 * 1024 * 1024 {
return Err(PortableError::LimitExceeded("the core's projection answer is too large".into()));
}
if let Ok(refused) = serde_json::from_str::<serde_json::Value>(line) {
if refused.get("status").and_then(|s| s.as_str()) == Some("refused") {
let why = refused["problems"].as_array().map(|p| p.iter().map(|x| format!("{}: {}", x["code"].as_str().unwrap_or("?"), x["detail"].as_str().unwrap_or(""))).collect::<Vec<_>>().join("; ")).unwrap_or_default();
return Err(PortableError::Invalid(format!("the core refused the projection query ({why})")));
}
}
let answer: ProjectionAnswer = serde_json::from_str(line).map_err(|e| PortableError::Invalid(format!("the core's projection answer is not valid: {e}")))?;
let b = answer.projection;
if answer.status != "ok" {
return Err(PortableError::Invalid(format!("the core's projection answer has status {:?}", answer.status)));
}
if b.protocol != PROTOCOL || b.policy_version != POLICY_VERSION {
return Err(PortableError::Invalid(format!("the core projects with protocol {} / policy {}; this Manager speaks {PROTOCOL} / {POLICY_VERSION}", b.protocol, b.policy_version)));
}
if !b.active {
return Ok(Decision::Native);
}
if b.projected_level != b.max_player_level || b.canonical_level <= b.max_player_level {
return Err(PortableError::Invalid("the core's projection is not from the character's level down to the cap".into()));
}
Ok(Decision::Projected(ProjectionHold {
protocol: b.protocol,
policy_version: b.policy_version,
progression_signature: b.progression_signature,
max_player_level: b.max_player_level,
canonical_level: b.canonical_level,
projected_level: b.projected_level,
held_items: b.held_items,
held_spells: b.held_spells,
held_actions: b.held_actions,
settings: b.settings,
blocked_settings: b.blocked_settings,
subject: subject.to_string(),
}))
}
}
/// Whether a character is projected on a realm, by level alone.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Activation {
/// The character's level is within the cap.
None,
Active { canonical_level: u32, projected_level: u32 },
}
pub fn activation(canonical_level: u8, progression: &Progression) -> Activation {
if (canonical_level as u32) > progression.max_player_level {
Activation::Active { canonical_level: canonical_level as u32, projected_level: progression.max_player_level }
} else {
Activation::None
}
}
/// The identity of a canonical snapshot for which a hold was made.
pub fn subject_of(model: &PortableCharacter) -> Result<String> {
Ok(hex::encode(snapshot::encode(model)?.content_hash))
}
impl ProjectionHold {
/// A hold applies to the snapshot it was made for.
pub fn check_subject(&self, model: &PortableCharacter) -> Result<()> {
if self.subject.is_empty() || self.subject == subject_of(model)? {
Ok(())
} else {
Err(PortableError::Invalid("the projection was made for another state of the character".into()))
}
}
pub fn is_empty(&self) -> bool {
self.held_items.is_empty() && self.held_spells.is_empty() && self.held_actions.is_empty() && self.settings.iter().all(|s| s.entries.is_empty() && s.buttons.is_empty()) && self.blocked_settings.is_empty()
}
/// The pin of this projection (what a session is bound to).
pub fn pin(&self, content_profile_hash: &str) -> ProgressionPin {
ProgressionPin { projected: true, max_player_level: self.max_player_level, policy_version: self.policy_version, progression_signature: self.progression_signature.clone(), content_profile_hash: content_profile_hash.to_string() }
}
}
/// What a character is given on a realm: the canonical character with what the realm cannot hold taken out, at the cap. A hold computed for
/// an earlier state of the character can be applied to a later one (what it names is removed, nothing else is looked at).
pub fn apply(canonical: &PortableCharacter, hold: &ProjectionHold) -> PortableCharacter {
let mut p = canonical.clone();
p.progression.level = hold.projected_level.min(u8::MAX as u32) as u8;
p.progression.xp = 0;
let held: BTreeSet<PortableItemId> = hold.held_items.iter().copied().collect();
p.items.retain(|i| !held.contains(&i.id) && !i.container.is_some_and(|c| held.contains(&c)));
let spells: BTreeSet<u32> = hold.held_spells.iter().copied().collect();
p.build.spells.retain(|(s, _)| !spells.contains(s));
let actions: BTreeSet<(u8, u8)> = hold.held_actions.iter().copied().collect();
p.actions.retain(|a| !actions.contains(&(a.spec, a.button)));
for source in &hold.blocked_settings {
p.settings.remove(source);
}
for s in &hold.settings {
let Some(values) = p.settings.get(&s.source) else { continue };
match settings::Record::parse(s.kind, values) {
Some(record) => {
let projected = record.without(&s.entries, &s.buttons).write();
p.settings.insert(s.source.clone(), projected);
}
None => {
p.settings.remove(&s.source);
}
}
}
p.normalized()
}
/// What a session or a working copy is bound to. A message under another pin is refused.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProgressionPin {
/// The character is projected (above the cap) as opposed to native.
pub projected: bool,
pub max_player_level: u32,
pub policy_version: u32,
pub progression_signature: String,
pub content_profile_hash: String,
}
impl ProgressionPin {
/// The words the core stores in `coa.portable.pin`: policy version, level cap, then the signature in eight big-endian words.
pub fn words(&self) -> Vec<u32> {
let mut words = vec![self.policy_version, self.max_player_level];
for chunk in self.progression_signature.as_bytes().chunks(8) {
words.push(u32::from_str_radix(std::str::from_utf8(chunk).unwrap_or("0"), 16).unwrap_or(0));
}
words
}
pub fn native(progression: &Progression, content_profile_hash: &str) -> Self {
Self { projected: false, max_player_level: progression.max_player_level, policy_version: progression.projection_policy_version, progression_signature: progression.progression_signature.clone(), content_profile_hash: content_profile_hash.to_string() }
}
pub fn validate(&self) -> Result<()> {
let bad = |what: &str| PortableError::Invalid(format!("progression pin: {what}"));
if self.max_player_level == 0 || self.max_player_level > 255 || self.policy_version == 0 {
return Err(bad("a number is out of range"));
}
let hex64 = |s: &str| s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
if !hex64(&self.progression_signature) || !hex64(&self.content_profile_hash) {
return Err(bad("a hash is not a SHA-256"));
}
Ok(())
}
}
/// Everything remembered of one projected character on one realm.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectionContext {
pub canonical_level: u32,
pub projected_level: u32,
/// The canonical revision the working copy was last brought to (import, update, or the last acknowledged checkpoint).
pub canonical_revision: u64,
pub content_profile_hash: String,
pub progression_signature: String,
pub projection_policy_version: u32,
pub max_player_level: u32,
pub hold: ProjectionHold,
}
impl ProjectionContext {
pub fn new(hold: ProjectionHold, canonical_revision: u64, content_profile_hash: &str) -> Self {
Self {
canonical_level: hold.canonical_level,
projected_level: hold.projected_level,
canonical_revision,
content_profile_hash: content_profile_hash.to_string(),
progression_signature: hold.progression_signature.clone(),
projection_policy_version: hold.policy_version,
max_player_level: hold.max_player_level,
hold,
}
}
pub fn pin(&self) -> ProgressionPin {
self.hold.pin(&self.content_profile_hash)
}
pub fn validate(&self) -> Result<()> {
if self.projected_level >= self.canonical_level || self.projected_level != self.max_player_level || self.hold.progression_signature != self.progression_signature {
return Err(PortableError::Invalid("the projection context is not consistent".into()));
}
self.pin().validate()
}
}
/// How the core is asked. The running core is the only source of a decision; tests supply their own.
pub trait ProjectionOracle: Send + Sync {
/// The decision for exactly this canonical character.
fn decide(&self, canonical: &PortableCharacter) -> Result<Decision>;
}
/// An oracle in the options of an operation.
#[derive(Clone)]
pub struct Oracle(pub std::sync::Arc<dyn ProjectionOracle>);
impl std::fmt::Debug for Oracle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Oracle")
}
}
/// A decision made earlier by a running core, supplied for an operation on a realm that is stopped. It answers only for the exact
/// canonical snapshot it was made for.
#[derive(Clone, Debug)]
pub struct SuppliedDecision(pub ProjectionHold);
impl ProjectionOracle for SuppliedDecision {
fn decide(&self, canonical: &PortableCharacter) -> Result<Decision> {
self.0.check_subject(canonical)?;
if self.0.subject.is_empty() {
return Err(PortableError::Invalid("a supplied projection must name the snapshot it was made for".into()));
}
Ok(Decision::Projected(self.0.clone()))
}
}
#[cfg(test)]
pub(crate) mod testing;
#[cfg(test)]
mod tests;
@@ -0,0 +1,241 @@
//! The three shapes in which the core keeps a CoA build in `character_settings` (all integer vectors), as keyed records.
//!
//! ```text
//! core.ascension_slot.<n> [1, class, spec, N, (entry, rank) * N, M, (button, action) * M, 0 ...]
//! core.ascension_build.<spec>, ...slot.<n>.build.<spec> [count, (entry * 10 + rank) * count, 0 ...]
//! core.ascension_bar.<spec>, ...slot.<n>.bar.<spec> [count, (button, spell) * count, 0 ...]
//! ```
//!
//! The codecs know **structure only**: which keys a record has and how to write it back. What a level cap allows is the core's
//! decision and arrives as a list of held keys; nothing here reads a level, a spell or an item.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SettingKind {
Slot,
Build,
Bar,
}
/// The shape a settings source name stands for, if it is one of the build shapes.
pub fn classify(source: &str) -> Option<SettingKind> {
fn number(s: &str) -> bool {
!s.is_empty() && s.len() <= 9 && s.bytes().all(|b| b.is_ascii_digit())
}
if let Some(rest) = source.strip_prefix("core.ascension_build.") {
return number(rest).then_some(SettingKind::Build);
}
if let Some(rest) = source.strip_prefix("core.ascension_bar.") {
return number(rest).then_some(SettingKind::Bar);
}
let rest = source.strip_prefix("core.ascension_slot.")?;
let (slot, tail) = rest.split_once('.').map_or((rest, None), |(s, t)| (s, Some(t)));
if !number(slot) {
return None;
}
match tail {
None => Some(SettingKind::Slot),
Some(t) => {
if let Some(spec) = t.strip_prefix("build.") {
number(spec).then_some(SettingKind::Build)
} else if let Some(spec) = t.strip_prefix("bar.") {
number(spec).then_some(SettingKind::Bar)
} else {
None
}
}
}
}
/// A build record as keyed values. `order` keeps the order the keys had, so that a record written back reads like the one that was read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Record {
pub kind: SettingKind,
/// `(class, spec)` of a slot record, zeros for the other shapes.
pub head: (u32, u32),
/// Entry -> rank (slot, build).
pub entries: BTreeMap<u32, u32>,
/// Button -> action or spell (slot actions, bar).
pub buttons: BTreeMap<u32, u32>,
pub entry_order: Vec<u32>,
pub button_order: Vec<u32>,
}
impl Record {
fn empty(kind: SettingKind) -> Self {
Self { kind, head: (0, 0), entries: BTreeMap::new(), buttons: BTreeMap::new(), entry_order: vec![], button_order: vec![] }
}
/// `None` when the values are not exactly one of the shapes (a record the codec cannot take apart is never edited).
pub fn parse(kind: SettingKind, v: &[u32]) -> Option<Record> {
let mut r = Record::empty(kind);
match kind {
SettingKind::Slot => {
if v.len() < 5 || v[0] != 1 || !(12..=32).contains(&v[1]) {
return None;
}
r.head = (v[1], v[2]);
let n = v[3] as usize;
if n > (v.len() - 5) / 2 {
return None;
}
let mut at = 4;
for _ in 0..n {
let (entry, rank) = (v[at], v[at + 1]);
at += 2;
if r.entries.insert(entry, rank).is_some() {
return None;
}
r.entry_order.push(entry);
}
let m = *v.get(at)? as usize;
at += 1;
if m > (v.len() - at) / 2 {
return None;
}
for _ in 0..m {
let (button, action) = (v[at], v[at + 1]);
at += 2;
if button >= 144 || action == 0 || r.buttons.insert(button, action).is_some() {
return None;
}
r.button_order.push(button);
}
v[at..].iter().all(|x| *x == 0).then_some(r)
}
SettingKind::Build => {
let n = *v.first()? as usize;
if n > v.len() - 1 || v[1 + n..].iter().any(|x| *x != 0) {
return None;
}
for pick in &v[1..=n] {
if *pick == 0 {
continue;
}
let (entry, rank) = (pick / 10, pick % 10);
if r.entries.insert(entry, rank).is_some() {
return None;
}
r.entry_order.push(entry);
}
Some(r)
}
SettingKind::Bar => {
let n = *v.first()? as usize;
if n > (v.len() - 1) / 2 || v[1 + 2 * n..].iter().any(|x| *x != 0) {
return None;
}
for i in 0..n {
let (button, spell) = (v[1 + 2 * i], v[2 + 2 * i]);
if spell == 0 {
continue;
}
if r.buttons.insert(button, spell).is_some() {
return None;
}
r.button_order.push(button);
}
Some(r)
}
}
}
pub fn write(&self) -> Vec<u32> {
let entries: Vec<u32> = self.ordered(&self.entry_order, &self.entries);
let buttons: Vec<u32> = self.ordered(&self.button_order, &self.buttons);
match self.kind {
SettingKind::Slot => {
let mut out = vec![1, self.head.0, self.head.1, entries.len() as u32];
for e in &entries {
out.extend([*e, self.entries[e]]);
}
out.push(buttons.len() as u32);
for b in &buttons {
out.extend([*b, self.buttons[b]]);
}
out
}
SettingKind::Build => {
let mut out = vec![entries.len() as u32];
out.extend(entries.iter().map(|e| e * 10 + self.entries[e]));
out
}
SettingKind::Bar => {
let mut out = vec![buttons.len() as u32];
for b in &buttons {
out.extend([*b, self.buttons[b]]);
}
out
}
}
}
fn ordered(&self, order: &[u32], map: &BTreeMap<u32, u32>) -> Vec<u32> {
let mut keys: Vec<u32> = order.iter().copied().filter(|k| map.contains_key(k)).collect();
let seen: BTreeSet<u32> = keys.iter().copied().collect();
keys.extend(map.keys().copied().filter(|k| !seen.contains(k)));
keys
}
/// The record without the keys the projection holds.
pub fn without(&self, entries: &[u32], buttons: &[u32]) -> Record {
let mut r = self.clone();
for e in entries {
r.entries.remove(e);
}
for b in buttons {
r.buttons.remove(b);
}
r
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_names_of_the_three_shapes_are_recognised_and_nothing_else() {
assert_eq!(classify("core.ascension_slot.0"), Some(SettingKind::Slot));
assert_eq!(classify("core.ascension_slot.12.build.34"), Some(SettingKind::Build));
assert_eq!(classify("core.ascension_slot.3.bar.61"), Some(SettingKind::Bar));
assert_eq!(classify("core.ascension_build.61"), Some(SettingKind::Build));
assert_eq!(classify("core.ascension_bar.0"), Some(SettingKind::Bar));
for other in ["core.ascension_slot.active", "core.ascension_slot.1.x", "core.ascension_build.", "core.ascension_slot.1.build.", "core.ascension_active_spec", "core.ascension_slot.1.bar.1.2", "core.ascension_build.1234567890"] {
assert_eq!(classify(other), None, "{other}");
}
}
#[test]
fn a_slot_record_round_trips_and_a_bad_one_is_not_taken_apart() {
let v = vec![1, 20, 61, 3, 100, 2, 101, 1, 102, 3, 2, 5, 900, 9, 901, 0, 0];
let r = Record::parse(SettingKind::Slot, &v).unwrap();
assert_eq!(r.head, (20, 61));
assert_eq!(r.entries.len(), 3);
assert_eq!(r.buttons.get(&5), Some(&900));
assert_eq!(r.write(), vec![1, 20, 61, 3, 100, 2, 101, 1, 102, 3, 2, 5, 900, 9, 901], "trailing padding is not kept");
let held = r.without(&[101], &[9]);
assert_eq!(held.write(), vec![1, 20, 61, 2, 100, 2, 102, 3, 1, 5, 900]);
for bad in [vec![1, 20, 61, 3, 100, 2], vec![2, 20, 61, 0, 0], vec![1, 5, 61, 0, 0], vec![1, 20, 61, 1, 100, 2, 0, 7], vec![1, 20, 61, 2, 100, 2, 100, 3, 0], vec![1, 20, 61, 0, 1, 200, 5], vec![1, 20, 61, 0, 0, 3]] {
assert!(Record::parse(SettingKind::Slot, &bad).is_none(), "{bad:?}");
}
}
#[test]
fn builds_and_bars_round_trip() {
let build = Record::parse(SettingKind::Build, &[3, 1001, 2002, 2053, 0, 0]).unwrap();
assert_eq!(build.entries.get(&100), Some(&1));
assert_eq!(build.entries.get(&205), Some(&3));
assert_eq!(build.without(&[100], &[]).write(), vec![2, 2002, 2053]);
assert!(Record::parse(SettingKind::Build, &[5, 1, 2]).is_none());
assert!(Record::parse(SettingKind::Build, &[1, 11, 7]).is_none(), "something after the picks");
let bar = Record::parse(SettingKind::Bar, &[2, 0, 500, 7, 501, 0, 0]).unwrap();
assert_eq!(bar.without(&[], &[0]).write(), vec![1, 7, 501]);
assert!(Record::parse(SettingKind::Bar, &[3, 0, 1]).is_none());
assert_eq!(Record::parse(SettingKind::Bar, &[0]).unwrap().write(), vec![0]);
}
}
@@ -0,0 +1,48 @@
//! Shared fixtures of the projection tests: a level-80 character with build records, and the decision a core at cap 60 would make for it.
use super::*;
use crate::portable::capabilities::Progression;
use crate::portable::fixtures::geared_level_eighty;
use crate::portable::model::*;
pub(crate) const SIGNATURE: &str = "bd299b9ef5863c6bf006e88a3617fac57c514b5889ea8367f87879aa1ad6d76d";
pub(crate) fn progression(cap: u32) -> Progression {
Progression { max_player_level: cap, projection_protocol: PROTOCOL, projection_policy_version: POLICY_VERSION, progression_signature: SIGNATURE.into(), scaling_enabled: true }
}
/// A level-80 character with a build record shaped like the core's: entries 100 (rank 1), 200 (rank 2), 300 (rank 1), buttons 0 and 1.
pub(crate) fn canonical() -> PortableCharacter {
let mut c = geared_level_eighty();
c.settings.insert("core.ascension_slot.0".into(), vec![1, 21, 61, 3, 100, 1, 200, 2, 300, 1, 2, 0, 500_003, 1, 500_006]);
c.settings.insert("core.ascension_build.61".into(), vec![3, 1001, 2002, 3001]);
c.settings.insert("core.ascension_bar.61".into(), vec![2, 0, 500_003, 1, 500_006]);
c.settings.insert("core.ascension_slot.active".into(), vec![0]);
c.normalized()
}
/// The decision a core at cap 60 would make for `canonical()`: the helmet (slot 0) and the first bag (with its contents) cannot be worn,
/// two abilities are not granted at 60, entries 200 and 300 are held, and the buttons showing the ability 500_006.
pub(crate) fn hold_for(c: &PortableCharacter) -> ProjectionHold {
let helmet = c.items.iter().find(|i| i.container.is_none() && i.slot == 0).unwrap().id;
let bag = c.items.iter().find(|i| i.container.is_none() && i.slot == 19).unwrap().id;
ProjectionHold {
protocol: PROTOCOL,
policy_version: POLICY_VERSION,
progression_signature: SIGNATURE.into(),
max_player_level: 60,
canonical_level: 80,
projected_level: 60,
held_items: vec![helmet, bag],
held_spells: vec![500_006, 500_009],
held_actions: vec![(0, 1)],
settings: vec![
SettingHold { source: "core.ascension_slot.0".into(), kind: settings::SettingKind::Slot, entries: vec![200, 300], buttons: vec![1] },
SettingHold { source: "core.ascension_build.61".into(), kind: settings::SettingKind::Build, entries: vec![200, 300], buttons: vec![] },
SettingHold { source: "core.ascension_bar.61".into(), kind: settings::SettingKind::Bar, entries: vec![], buttons: vec![1] },
],
blocked_settings: vec![],
subject: subject_of(c).unwrap(),
}
}
@@ -0,0 +1,216 @@
use super::testing::*;
use super::*;
use crate::portable::ids::PortableItemId;
use crate::portable::merge::{merge3_with, MergeProjection, Mode};
use crate::portable::model::*;
#[test]
fn the_activation_matrix_follows_the_level_against_the_cap() {
let at = |level: u8, cap: u32| activation(level, &progression(cap));
assert_eq!(at(80, 80), Activation::None);
assert_eq!(at(80, 70), Activation::Active { canonical_level: 80, projected_level: 70 });
assert_eq!(at(80, 60), Activation::Active { canonical_level: 80, projected_level: 60 });
assert_eq!(at(70, 60), Activation::Active { canonical_level: 70, projected_level: 60 });
assert_eq!(at(60, 60), Activation::None);
assert_eq!(at(1, 60), Activation::None);
}
#[test]
fn what_the_core_holds_is_taken_out_of_the_working_copy_and_nothing_else() {
let c = canonical();
let hold = hold_for(&c);
hold.check_subject(&c).unwrap();
let p = apply(&c, &hold);
assert_eq!((p.progression.level, p.progression.xp), (60, 0));
assert_eq!(c.progression.level, 80, "the canonical character is untouched");
let bag = hold.held_items[1];
assert!(p.items.iter().all(|i| !hold.held_items.contains(&i.id) && i.container != Some(bag)), "a held bag takes its contents with it");
assert_eq!(p.items.len(), c.items.len() - 2 - 6);
assert!(p.build.spells.iter().all(|(s, _)| *s != 500_006 && *s != 500_009));
assert_eq!(p.build.spells.len(), c.build.spells.len() - 2);
assert!(!p.actions.iter().any(|a| a.button == 1));
assert_eq!(p.settings["core.ascension_slot.0"], vec![1, 21, 61, 1, 100, 1, 1, 0, 500_003]);
assert_eq!(p.settings["core.ascension_build.61"], vec![1, 1001]);
assert_eq!(p.settings["core.ascension_bar.61"], vec![1, 0, 500_003]);
assert_eq!(p.settings["core.ascension_slot.active"], vec![0], "other settings are left alone");
assert_eq!(p.wardrobe, c.wardrobe);
assert_eq!(p.pets, c.pets);
let mut changed = c.clone();
changed.progression.money += 1;
assert!(hold.check_subject(&changed).is_err(), "a decision belongs to the state it was made for");
let mut again = hold.clone();
again.subject.clear();
again.check_subject(&changed).unwrap();
assert_eq!(apply(&changed, &again).progression.money, changed.progression.money, "a stored decision can be applied to a later state");
}
#[test]
fn a_blocked_record_is_not_given_to_the_realm() {
let c = canonical();
let mut hold = hold_for(&c);
hold.settings.retain(|s| s.source != "core.ascension_slot.0");
hold.blocked_settings = vec!["core.ascension_slot.0".into()];
let p = apply(&c, &hold);
assert!(!p.settings.contains_key("core.ascension_slot.0"));
}
/// What the realm shows right after its own first load: the same character, but the core has rewritten the build record in its own order and
/// with its own padding.
fn realm_b0(p: &PortableCharacter) -> PortableCharacter {
let mut b0 = p.clone();
b0.settings.insert("core.ascension_slot.0".into(), vec![1, 21, 61, 1, 100, 1, 1, 0, 500_003, 0, 0, 0]);
b0.normalized()
}
fn session(c0: &PortableCharacter, b0: &PortableCharacter, b1: &PortableCharacter, blocked: &[&str]) -> PortableCharacter {
let projection = MergeProjection { freeze_progression: true, blocked: blocked.iter().map(|s| s.to_string()).collect() };
merge3_with(c0, b0, b1, Mode::Lenient, Some(&projection)).unwrap().model
}
#[test]
fn a_session_on_a_projected_copy_never_down_levels_or_loses_what_was_held() {
let c0 = canonical();
let hold = hold_for(&c0);
let b0 = realm_b0(&apply(&c0, &hold));
// nothing played: the realm's own rewrite of the record changes nothing canonical
let idle = session(&c0, &b0, &b0, &[]);
assert_eq!(idle, c0, "an idle session is the canonical character exactly");
// play: gold, a new item, a new talent entry on the record, the realm's own level/xp (60, some xp), a new rep standing
let mut b1 = b0.clone();
b1.progression.money += 5_000;
b1.progression.xp = 777;
b1.reputation[0].standing += 250;
b1.settings.insert("core.ascension_slot.0".into(), vec![1, 21, 61, 2, 100, 1, 400, 1, 1, 0, 500_003, 0]);
b1.settings.insert("core.ascension_build.61".into(), vec![2, 1001, 4001]);
let mut gain = b1.items.iter().find(|i| i.container.is_none() && i.slot == 23).unwrap().clone();
gain.id = PortableItemId::new();
gain.slot = 36;
gain.entry = crate::portable::ids::ContentId::new("coa", "item", 123_456).unwrap();
b1.items.push(gain.clone());
let b1 = b1.normalized();
let c1 = session(&c0, &b0, &b1, &[]);
assert_eq!((c1.progression.level, c1.progression.xp), (80, 12_345), "the canonical level and xp are not the realm's");
assert_eq!(c1.progression.money, c0.progression.money + 5_000);
assert_eq!(c1.reputation[0].standing, c0.reputation[0].standing + 250);
assert!(c1.items.iter().any(|i| i.id == gain.id), "a gain arrives");
for held in &hold.held_items {
assert!(c1.items.iter().any(|i| i.id == *held), "a held item stays canonical");
}
assert_eq!(c1.items.len(), c0.items.len() + 1);
for spell in &hold.held_spells {
assert!(c1.build.spells.iter().any(|(s, _)| s == spell), "a held ability stays canonical");
}
assert!(c1.actions.iter().any(|a| a.button == 1), "a held button stays canonical");
let slot = settings::Record::parse(settings::SettingKind::Slot, &c1.settings["core.ascension_slot.0"]).unwrap();
assert_eq!(slot.entries.keys().copied().collect::<Vec<_>>(), vec![100, 200, 300, 400], "the record keeps what the realm could not hold and gains the new entry");
assert_eq!(slot.entries[&200], 2);
assert_eq!(slot.buttons.get(&1), Some(&500_006));
let build = settings::Record::parse(settings::SettingKind::Build, &c1.settings["core.ascension_build.61"]).unwrap();
assert_eq!(build.entries.keys().copied().collect::<Vec<_>>(), vec![100, 200, 300, 400]);
assert_eq!(c1.settings["core.ascension_bar.61"], c0.settings["core.ascension_bar.61"]);
// a checkpoint repeated, or a later one with the same play, counts nothing twice
assert_eq!(session(&c0, &b0, &b1, &[]), c1);
let mut later = b1.clone();
later.progression.money += 100;
let c2 = session(&c0, &b0, &later, &[]);
assert_eq!(c2.progression.money, c0.progression.money + 5_100);
assert_eq!(c2.items.len(), c1.items.len());
}
#[test]
fn a_talent_the_player_removed_on_the_realm_is_removed_but_a_held_one_is_not() {
let c0 = canonical();
let hold = hold_for(&c0);
let b0 = realm_b0(&apply(&c0, &hold));
let mut b1 = b0.clone();
b1.settings.insert("core.ascension_slot.0".into(), vec![1, 21, 61, 0, 1, 0, 500_003]);
let c1 = session(&c0, &b0, &b1.normalized(), &[]);
let slot = settings::Record::parse(settings::SettingKind::Slot, &c1.settings["core.ascension_slot.0"]).unwrap();
assert_eq!(slot.entries.keys().copied().collect::<Vec<_>>(), vec![200, 300], "entry 100 was dropped by the player, 200 and 300 were never the realm's to drop");
}
#[test]
fn a_record_the_core_could_not_take_apart_is_never_merged() {
let c0 = canonical();
let mut hold = hold_for(&c0);
hold.settings.retain(|s| s.source != "core.ascension_slot.0");
hold.blocked_settings = vec!["core.ascension_slot.0".into()];
let b0 = apply(&c0, &hold);
let mut b1 = b0.clone();
b1.settings.insert("core.ascension_slot.0".into(), vec![1, 21, 61, 1, 100, 1, 0]);
let c1 = session(&c0, &b0, &b1.normalized(), &["core.ascension_slot.0"]);
assert_eq!(c1.settings["core.ascension_slot.0"], c0.settings["core.ascension_slot.0"], "the realm's rewrite of a blocked record never replaces the canonical one");
}
#[test]
fn without_a_projection_the_merge_is_what_it_was() {
let c0 = canonical();
let b0 = c0.clone();
let mut b1 = c0.clone();
b1.progression.level = 81;
b1.settings.insert("core.ascension_slot.0".into(), vec![1, 21, 61, 0, 0]);
let plain = crate::portable::merge::merge3(&c0, &b0, &b1, Mode::Lenient).unwrap().model;
assert_eq!(plain.progression.level, 81);
assert_eq!(plain.settings["core.ascension_slot.0"], vec![1, 21, 61, 0, 0], "a whole value, as before");
}
#[test]
fn the_core_answer_is_parsed_strictly() {
let sig = SIGNATURE;
let item = PortableItemId::new();
let active = format!(r#"{{"status":"ok","projection":{{"active":true,"protocol":1,"policy_version":1,"progression_signature":"{sig}","max_player_level":60,"canonical_level":80,"projected_level":60,"held_items":["{item}"],"held_spells":[5,6],"held_actions":[[0,3]],"settings":[{{"source":"core.ascension_slot.0","kind":"slot","entries":[1],"buttons":[2]}}],"blocked_settings":["x"]}}}}"#);
let Decision::Projected(h) = ProjectionAnswer::parse(&active, "abc").unwrap() else { panic!("projected") };
assert_eq!((h.held_items.clone(), h.held_spells.clone(), h.held_actions.clone(), h.subject.clone()), (vec![item], vec![5, 6], vec![(0, 3)], "abc".to_string()));
assert_eq!(h.settings[0].kind, settings::SettingKind::Slot);
let native = format!(r#"{{"status":"ok","projection":{{"active":false,"protocol":1,"policy_version":1,"progression_signature":"{sig}","max_player_level":60,"canonical_level":50,"projected_level":50}}}}"#);
assert_eq!(ProjectionAnswer::parse(&native, "").unwrap(), Decision::Native);
assert!(ProjectionAnswer::parse(&format!("noise\n{native}\n"), "").is_ok(), "console noise around the line is ignored");
for bad in [
active.replace("\"protocol\":1", "\"protocol\":2"),
active.replace("\"policy_version\":1", "\"policy_version\":9"),
active.replace("\"projected_level\":60", "\"projected_level\":61"),
active.replace("\"canonical_level\":80", "\"canonical_level\":60"),
active.replace("\"status\":\"ok\"", "\"status\":\"maybe\""),
active.replace("\"held_spells\":[5,6]", "\"held_spells\":[5,6],\"extra\":1"),
active.replace(&item.to_string(), "not-a-uuid"),
"Unknown command".to_string(),
] {
assert!(ProjectionAnswer::parse(&bad, "").is_err(), "{bad}");
}
let refused = r#"{"status":"refused","problems":[{"code":"snapshot","detail":"broken"}]}"#;
let err = ProjectionAnswer::parse(refused, "").unwrap_err().to_string();
assert!(err.contains("snapshot") && err.contains("broken"), "{err}");
}
#[test]
fn the_pin_words_are_the_ones_the_core_stores() {
let words = progression(60).pin_words();
assert_eq!(words.len(), 10);
assert_eq!(&words[..3], &[1, 60, 0xbd299b9e]);
assert_eq!(words[9], 0x1ad6d76d);
}
#[test]
fn a_context_must_be_consistent() {
let c = canonical();
let hold = hold_for(&c);
let ctx = ProjectionContext::new(hold.clone(), 4, &"ab".repeat(32));
ctx.validate().unwrap();
assert!(ctx.pin().projected);
let mut bad = ctx.clone();
bad.projected_level = 80;
assert!(bad.validate().is_err());
let mut bad = ctx.clone();
bad.content_profile_hash = "nothex".into();
assert!(bad.validate().is_err());
let json = serde_json::to_string(&ctx).unwrap();
assert_eq!(serde_json::from_str::<ProjectionContext>(&json).unwrap(), ctx);
assert!(serde_json::from_str::<ProjectionContext>(&json.replace("\"canonical_level\":80", "\"canonical_level\":80,\"x\":1")).is_err());
}
+11 -4
View File
@@ -49,11 +49,14 @@ pub struct ImportOptions {
pub capabilities: Option<std::sync::Arc<super::super::capabilities::RealmCapabilities>>,
/// The extension adapters this Manager has.
pub extensions: Option<std::sync::Arc<super::super::extension::ExtensionRegistry>>,
/// Where the decision of a level-cap projection comes from when the realm is not running (a decision supplied from the realm's core);
/// a running realm is asked directly. Without either, a character above the cap is refused.
pub projection: Option<super::super::projection::Oracle>,
}
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, knowledge: None, capabilities: None, extensions: None }
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, capabilities: None, extensions: None, projection: None }
}
}
@@ -265,7 +268,7 @@ pub fn import_character(db: &Db, store: &mut Store, character_id: CharacterId, s
/// The same, arming the runtime portable session `session` on the arrival (the core takes the baseline at its first load).
pub fn import_character_in_session(db: &Db, store: &mut Store, character_id: CharacterId, server_id: &str, account: u32, opts: &ImportOptions, session: Option<SessionId>) -> Result<ImportOutcome> {
let record = store.character(character_id)?;
let model = store.load_snapshot(character_id, record.revision)?;
let canonical = store.load_snapshot(character_id, record.revision)?;
if store.server_mappings(character_id)?.iter().any(|m| m.server_id == server_id) {
return Err(PortableError::AlreadyOnRealm { character: character_id, server_id: server_id.to_string() });
}
@@ -274,7 +277,9 @@ pub fn import_character_in_session(db: &Db, store: &mut Store, character_id: Cha
if session.is_some() {
operations.push(super::super::compat::Operation::RuntimeSession);
}
let compatibility = super::profile::gate(opts, &model, &operations)?;
let compatibility = super::profile::gate(opts, &canonical, &operations)?;
let projection = super::project::plan(&canonical, record.revision, opts, None)?;
let model = projection.view.clone();
let report = preflight(db, &model, account, opts)?;
if !report.problems.is_empty() {
return Err(PortableError::ImportRefused(report.problems));
@@ -285,7 +290,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 }), knowledge: opts.knowledge.as_deref() }) {
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 }), pin: projection.pin.as_ref().map(|p| p.words()), 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}"))?;
@@ -303,6 +308,7 @@ pub fn import_character_in_session(db: &Db, store: &mut Store, character_id: Cha
Resolution::Committed(alloc) => {
// the realm's own report was lost: read the final name back
let (final_name, renamed) = read_name(db, alloc.local_guid)?;
super::project::remember(store, character_id, server_id, &projection)?;
let mut not_applied = plan.not_applied_settings;
not_applied.extend(super::profile::after_write(Some(db), store, character_id, server_id, opts, alloc.local_guid, &model, compatibility.as_ref())?);
Ok(ImportOutcome { import_id: ticket.import_id, local_guid: alloc.local_guid, final_name, renamed, items: plan.counts.items, pets: plan.counts.pets, not_applied, warnings: report.warnings })
@@ -314,6 +320,7 @@ pub fn import_character_in_session(db: &Db, store: &mut Store, character_id: Cha
};
store.finish_import(ticket.import_id, ImportAllocation { local_guid: allocation.local_guid, item_base: allocation.item_base, pet_base: allocation.pet_base })?;
super::project::remember(store, character_id, server_id, &projection)?;
let mut not_applied = plan.not_applied_settings;
not_applied.extend(super::profile::after_write(Some(db), store, character_id, server_id, opts, allocation.local_guid, &model, compatibility.as_ref())?);
Ok(ImportOutcome {
@@ -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, knowledge: 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, pin: None, knowledge: None }
}
fn users() -> Vec<String> {
@@ -308,7 +308,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, knowledge: opts().knowledge.as_deref() }).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, pin: None, knowledge: opts().knowledge.as_deref() }).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();
@@ -362,7 +362,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, knowledge: opts().knowledge.as_deref() }).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, pin: None, knowledge: opts().knowledge.as_deref() }).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);
@@ -428,7 +428,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, knowledge: opts().knowledge.as_deref() }).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, pin: None, knowledge: opts().knowledge.as_deref() }).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, knowledge: 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, pin: crate::portable::realm::update::PinWrite::Keep };
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 {
+2 -1
View File
@@ -18,6 +18,7 @@ pub mod online;
pub mod plan;
pub mod policy;
pub mod profile;
pub mod project;
pub mod reconcile;
pub mod registry;
pub mod script;
@@ -38,7 +39,7 @@ use super::store::{RealmRegistration, Store};
pub use blockers::Blocker;
pub use export::{build, session_row, ExportRequest, Exported};
pub use import::{import_character, import_character_in_session, preflight, recover_imports, resolve_import, ImportOptions, ImportOutcome, ImportProblem, PreflightReport, Resolution};
pub use reconcile::{begin_session, reconcile_session, reevaluate_realm_character, resolve_import_update, update_realm_character, update_realm_character_in_session, Reevaluation, ReconcileOutcome, SessionStart, UpdateOutcome};
pub use reconcile::{begin_session, reconcile_session, reevaluate_realm_character, reproject_session, resolve_import_update, update_realm_character, update_realm_character_in_session, Reevaluation, ReconcileOutcome, SessionStart, UpdateOutcome};
pub use script::SchemaProbe;
/// The ruleset a database belongs to is decided by which realm profile it is (`realms::Mode`), never by the caller.
+25 -6
View File
@@ -38,6 +38,17 @@ struct JobHeader {
snapshot_sha256: String,
character_id: CharacterId,
session: Option<SessionHeader>,
/// The progression the character was prepared for: the core refuses a job prepared for another one, and pins the character to it.
projection: Option<ProjectionHeader>,
}
#[derive(Debug, Serialize)]
struct ProjectionHeader {
/// The character was projected down to the cap (and the core checks that nothing above the cap is left in it).
active: bool,
level: u32,
policy_version: u32,
progression_signature: String,
}
#[derive(Debug, Serialize)]
@@ -61,7 +72,7 @@ pub fn job_model(model: &PortableCharacter, knowledge: Option<&super::knowledge:
}
/// 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)>, knowledge: Option<&super::knowledge::RealmKnowledge>) -> Result<Vec<u8>> {
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>, pin: Option<&super::super::projection::ProgressionPin>) -> Result<Vec<u8>> {
let snapshot_json = snapshot::canonical_json(&job_model(model, knowledge))?;
let header = JobHeader {
job_format: super::super::versions::ONLINE_IMPORT_JOB_FORMAT_VERSION,
@@ -73,6 +84,7 @@ pub fn job_bytes(job_id: ImportId, nonce: [u32; 4], account: u32, revision: u64,
snapshot_sha256: hex::encode(Sha256::digest(&snapshot_json)),
character_id: model.character_id,
session: session.map(|(session_id, generation)| SessionHeader { session_id, generation }),
projection: pin.map(|p| ProjectionHeader { active: p.projected, level: p.max_player_level, policy_version: p.policy_version, progression_signature: p.progression_signature.clone() }),
};
let mut out = serde_json::to_vec(&header)?;
out.push(b'\n');
@@ -126,7 +138,7 @@ pub fn import_character_online(ra: &mut Ra, store: &mut Store, character_id: Cha
#[allow(clippy::too_many_arguments)]
pub fn import_character_online_on(db: Option<&crate::db::Db>, ra: &mut Ra, store: &mut Store, character_id: CharacterId, server_id: &str, account: u32, opts: &ImportOptions, job_dir: &Path, session: Option<SessionId>) -> Result<ImportOutcome> {
let record = store.character(character_id)?;
let model = store.load_snapshot(character_id, record.revision)?;
let canonical = store.load_snapshot(character_id, record.revision)?;
if store.server_mappings(character_id)?.iter().any(|m| m.server_id == server_id) {
return Err(PortableError::AlreadyOnRealm { character: character_id, server_id: server_id.to_string() });
}
@@ -134,11 +146,16 @@ pub fn import_character_online_on(db: Option<&crate::db::Db>, ra: &mut Ra, store
if session.is_some() {
operations.push(super::super::compat::Operation::RuntimeSession);
}
let compatibility = super::profile::gate(opts, &model, &operations)?;
let compatibility = super::profile::gate(opts, &canonical, &operations)?;
let projection = {
let oracle = super::project::CoreOracle::new(ra, job_dir);
super::project::plan(&canonical, record.revision, opts, Some(&oracle))?
};
let model = projection.view.clone();
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)), opts.knowledge.as_deref())?;
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(), projection.pin.as_ref())?;
let temp = job_file.with_extension("job.tmp");
std::fs::write(&temp, bytes)?;
std::fs::rename(&temp, &job_file)?;
@@ -164,6 +181,7 @@ pub fn import_character_online_on(db: Option<&crate::db::Db>, ra: &mut Ra, store
return finish_by_recovery(store, ticket.import_id, opts);
}
store.finish_import(ticket.import_id, allocation)?;
super::project::remember(store, character_id, server_id, &projection)?;
cleanup();
let mut not_applied = r.not_applied;
not_applied.extend(super::profile::after_write(db, store, character_id, server_id, opts, r.local_guid, &model, compatibility.as_ref())?);
@@ -200,7 +218,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)), None).unwrap();
let bytes = job_bytes(id, [1, 2, 3, 4], 7001, 5, 10, &model, Some((SessionId::new(), 1)), None, 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..];
@@ -209,10 +227,11 @@ mod tests {
assert_eq!(header["nonce"], serde_json::json!([1, 2, 3, 4]));
assert!(header["session"]["session_id"].is_string());
assert!(!body.contains(&b'\n'), "the snapshot is one line");
assert!(header["projection"].is_null(), "a job without a pin carries no projection header");
let sent: PortableCharacter = serde_json::from_slice(body).unwrap();
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, None).unwrap().len() > 100);
assert!(job_bytes(id, [0; 4], 1, 1, 10, &model, None, 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>,
/// The pin the core stores in `coa.portable.pin` (the progression the character was prepared for): it refuses a session character whose pin is not its own.
pub pin: Option<Vec<u32>>,
/// What the destination's client data knows: appearances it does not know are not written.
pub knowledge: Option<&'a super::knowledge::RealmKnowledge>,
}
@@ -500,6 +502,9 @@ pub fn build_plan(model: &PortableCharacter, ctx: &PlanContext<'_>) -> Result<Im
counts.settings = settings.len();
let marker = marker_data(ctx.nonce, ctx.revision);
settings.row(vec![Val::Expr("@char"), Val::text(IMPORT_MARKER_SOURCE), Val::text(marker.clone())])?;
if let Some(words) = &ctx.pin {
settings.row(vec![Val::Expr("@char"), Val::text(super::policy::PIN_SOURCE), Val::text(words.iter().map(|w| format!("{w} ")).collect::<String>())])?;
}
inserts.push(settings);
let mut session_row = Insert::new("coa_portable_session", &["guid", "session_id", "character_id", "imported_revision", "baseline_generation", "state", "checkpoint_seq", "save_seq", "updated_at"]);
@@ -29,6 +29,10 @@ pub const IMPORT_MARKER_SOURCE: &str = "coa.portable.import";
/// them when the realm's answer was lost).
pub const ALLOC_MARKER_SOURCE: &str = "coa.portable.alloc";
/// The progression a session character was prepared for (policy version, level cap, signature words): the core refuses to let a session
/// character in when its own progression is another one.
pub const PIN_SOURCE: &str = "coa.portable.pin";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Disposition {
Carry,
+11 -2
View File
@@ -65,6 +65,10 @@ pub fn assemble(db: &Db, probe: &SchemaProbe, data_dir: Option<&Path>, core: Opt
if probe.has("coa_portable_session") && core.is_some_and(|c| c.has_feature("runtime_sessions")) {
features.insert(Feature::RuntimeSessions);
}
let progression = core.and_then(|c| c.progression.clone());
if progression.is_some() && core.is_some_and(|c| c.has_feature("level_projection")) {
features.insert(Feature::LevelProjection);
}
let mut extension_realm = NoRealm { probe };
let extensions = registry.supported_on(&mut extension_realm);
@@ -79,7 +83,11 @@ pub fn assemble(db: &Db, probe: &SchemaProbe, data_dir: Option<&Path>, core: Opt
extensions,
client_catalog: catalog,
};
RealmCapabilities::new(core.map(|c| c.core.clone()), content)
let caps = RealmCapabilities::new(core.map(|c| c.core.clone()), content)?;
match progression {
Some(p) => caps.with_progression(p),
None => Ok(caps),
}
}
/// Probe a running or stopped realm: the schema from the database, the core from RA when a console is given.
@@ -118,7 +126,8 @@ pub fn gate(opts: &ImportOptions, model: &PortableCharacter, operations: &[Opera
let Some(caps) = opts.capabilities.as_deref() else { return Ok(None) };
let mut merged: Option<CompatibilityReport> = None;
for op in operations {
let report = compat::evaluate(&Inputs { operation: *op, model, capabilities: caps, knowledge: opts.knowledge.as_deref(), collections: &[], extensions: opts.extensions.as_deref() });
let decider = opts.projection.is_some() || operations.contains(&Operation::OnlineImport);
let report = compat::evaluate(&Inputs { operation: *op, model, capabilities: caps, knowledge: opts.knowledge.as_deref(), collections: &[], extensions: opts.extensions.as_deref(), projection_decider: decider });
merged = Some(match merged {
None => report,
Some(mut m) => {
@@ -0,0 +1,241 @@
//! The realm side of level-cap projection (Phase 8): deciding, for one canonical character and one realm, what the realm is given.
//!
//! ```text
//! no capabilities nothing is evaluated: the character is given as it is (the lower layers' own tests, bare tools)
//! capabilities without progression refused: the cap is unknown, and "unknown" is never read as "no cap"
//! level <= cap native: given as it is, pinned to the realm's progression
//! level > cap projected: the realm's core decides what is held (a running core, or a decision supplied from it);
//! the realm is given `apply(hold, canonical)` and the context is remembered
//! ```
use std::path::Path;
use std::sync::Mutex;
use serde::Serialize;
use sha2::{Digest, Sha256};
use crate::ra::Ra;
use super::super::capabilities::RealmCapabilities;
use super::super::error::{PortableError, Result};
use super::super::ids::ImportId;
use super::super::model::PortableCharacter;
use super::super::projection::{activation, apply, subject_of, Activation, Decision, ProgressionPin, ProjectionAnswer, ProjectionContext, ProjectionOracle};
use super::super::snapshot;
use super::import::ImportOptions;
use super::online::job_model;
/// What a realm is given of a canonical character, and what is remembered of it.
#[derive(Debug, Clone)]
pub struct Plan {
/// What the realm is given (`apply(hold, canonical)` when projected).
pub view: PortableCharacter,
/// `Some`: the character is projected on this realm.
pub context: Option<ProjectionContext>,
/// What the character is bound to on this realm; `None` only when the options carry no capabilities.
pub pin: Option<ProgressionPin>,
}
impl Plan {
pub fn projected(&self) -> bool {
self.context.is_some()
}
}
/// The plan for `canonical` (at canonical revision `revision`) on the realm the options describe.
pub fn plan(canonical: &PortableCharacter, revision: u64, opts: &ImportOptions, live: Option<&dyn ProjectionOracle>) -> Result<Plan> {
plan_with(canonical, revision, opts.capabilities.as_deref(), live.or(opts.projection.as_ref().map(|o| &*o.0)))
}
pub fn plan_with(canonical: &PortableCharacter, revision: u64, caps: Option<&RealmCapabilities>, oracle: Option<&dyn ProjectionOracle>) -> Result<Plan> {
let Some(caps) = caps else { return Ok(Plan { view: canonical.clone(), context: None, pin: None }) };
let progression = caps.progression.as_ref().ok_or_else(|| PortableError::ProgressionChanged("the realm's progression profile is not known: probe the realm through its core first".into()))?;
match activation(canonical.progression.level, progression) {
Activation::None => Ok(Plan { view: canonical.clone(), context: None, pin: Some(ProgressionPin::native(progression, &caps.content_profile_hash)) }),
Activation::Active { canonical_level, projected_level } => {
let oracle = oracle.ok_or(PortableError::ProjectionNeedsRunningCore { character_level: canonical_level, cap: projected_level })?;
let Decision::Projected(hold) = oracle.decide(canonical)? else {
return Err(PortableError::ProgressionChanged("the core does not project a character the Manager sees above its cap".into()));
};
if hold.progression_signature != progression.progression_signature || hold.max_player_level != progression.max_player_level || hold.policy_version != progression.projection_policy_version {
return Err(PortableError::ProgressionChanged("the core decided under another progression profile than the one the realm reported".into()));
}
hold.check_subject(canonical)?;
let view = apply(canonical, &hold);
let context = ProjectionContext::new(hold, revision, &caps.content_profile_hash);
context.validate()?;
let pin = Some(context.pin());
Ok(Plan { view, context: Some(context), pin })
}
}
}
/// The header of a projection query (a job file with no import in it).
#[derive(Debug, Serialize)]
struct QueryHeader {
job_format: u32,
job_id: ImportId,
query: &'static str,
snapshot_sha256: String,
}
fn query_bytes(job_id: ImportId, model: &PortableCharacter) -> Result<Vec<u8>> {
let snapshot_json = snapshot::canonical_json(&job_model(model, None))?;
let header = QueryHeader { job_format: super::super::versions::ONLINE_IMPORT_JOB_FORMAT_VERSION, job_id, query: "project", snapshot_sha256: hex::encode(Sha256::digest(&snapshot_json)) };
let mut out = serde_json::to_vec(&header)?;
out.push(b'\n');
out.extend_from_slice(&snapshot_json);
Ok(out)
}
/// Ask a running core what a projection of this character holds (RA `portable project`): a job file in the core's job directory, only its
/// id through the console, the answer in the job's result file.
pub fn decide_with_core(ra: &mut Ra, job_dir: &Path, canonical: &PortableCharacter) -> Result<Decision> {
let id = ImportId::new();
let job = job_dir.join(format!("{id}.job"));
let result = job_dir.join(format!("{id}.result"));
let temp = job.with_extension("job.tmp");
std::fs::write(&temp, query_bytes(id, canonical)?)?;
std::fs::rename(&temp, &job)?;
let reply = ra.portable_project(id);
let answer = std::fs::read_to_string(&result);
let _ = std::fs::remove_file(&job);
let _ = std::fs::remove_file(&result);
let text = match (&reply, answer) {
(_, Ok(text)) => text,
(Err(e), Err(_)) => return Err(PortableError::RealmRead(e.to_string())),
(Ok(_), Err(e)) => return Err(PortableError::RealmRead(format!("the core wrote no projection answer: {e}"))),
};
ProjectionAnswer::parse(&text, &subject_of(canonical)?)
}
/// A running realm as an oracle.
pub struct CoreOracle<'a> {
ra: Mutex<&'a mut Ra>,
job_dir: std::path::PathBuf,
}
impl<'a> CoreOracle<'a> {
pub fn new(ra: &'a mut Ra, job_dir: &Path) -> Self {
Self { ra: Mutex::new(ra), job_dir: job_dir.to_path_buf() }
}
}
impl ProjectionOracle for CoreOracle<'_> {
fn decide(&self, canonical: &PortableCharacter) -> Result<Decision> {
let mut ra = self.ra.lock().map_err(|_| PortableError::Invalid("the console is unavailable".into()))?;
decide_with_core(&mut ra, &self.job_dir, canonical)
}
}
/// Remember what was written to a realm: the projection's context when the character is projected there, else that it is native, and the
/// pin it is bound to. Call after the realm committed (the mapping must exist).
pub fn remember(store: &mut super::super::store::Store, id: super::super::ids::CharacterId, server_id: &str, plan: &Plan) -> Result<()> {
match &plan.context {
Some(ctx) => store.set_projection_context(id, server_id, ctx),
None => {
store.clear_projection_context(id, server_id)?;
store.set_mapping_pin(id, server_id, plan.pin.as_ref())
}
}
}
/// What a stored projection context shows of a (later) canonical state: the same decision applied again.
pub fn stored_view(state: &PortableCharacter, context: Option<&ProjectionContext>) -> PortableCharacter {
match context {
Some(c) => apply(state, &c.hold),
None => state.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::portable::capabilities::*;
use crate::portable::fixtures::geared_level_eighty;
use crate::portable::model::Ruleset;
use crate::portable::projection::{ProjectionHold, SuppliedDecision, PROTOCOL};
const SIG: &str = "bd299b9ef5863c6bf006e88a3617fac57c514b5889ea8367f87879aa1ad6d76d";
pub(crate) fn caps(cap: u32, signature: &str) -> RealmCapabilities {
let content = ContentProfile {
ruleset: Ruleset::Coa,
character_formats: ContentProfile::manager_formats(),
online_import_job_formats: vec![2],
session_protocol: 2,
collection_protocol: 2,
features: [Feature::RuntimeSessions, Feature::LevelProjection].into_iter().collect(),
collection_kinds: Default::default(),
extensions: vec![],
client_catalog: Default::default(),
};
RealmCapabilities::build(None, content, Some(Progression { max_player_level: cap, projection_protocol: PROTOCOL, projection_policy_version: 1, progression_signature: signature.into(), scaling_enabled: true })).unwrap()
}
fn hold(c: &PortableCharacter, cap: u32, signature: &str) -> ProjectionHold {
ProjectionHold { protocol: PROTOCOL, policy_version: 1, progression_signature: signature.into(), max_player_level: cap, canonical_level: c.progression.level as u32, projected_level: cap, held_items: vec![c.items[0].id], held_spells: vec![], held_actions: vec![], settings: vec![], blocked_settings: vec![], subject: subject_of(c).unwrap() }
}
#[test]
fn a_character_within_the_cap_is_given_as_it_is_and_one_above_needs_a_decision() {
let c = geared_level_eighty();
let native = plan_with(&c, 3, Some(&caps(80, SIG)), None).unwrap();
assert!(!native.projected());
assert_eq!(native.view, c);
assert!(!native.pin.unwrap().projected);
let err = plan_with(&c, 3, Some(&caps(60, SIG)), None).unwrap_err();
assert!(matches!(err, PortableError::ProjectionNeedsRunningCore { character_level: 80, cap: 60 }), "{err}");
let supplied = SuppliedDecision(hold(&c, 60, SIG));
let p = plan_with(&c, 3, Some(&caps(60, SIG)), Some(&supplied)).unwrap();
assert!(p.projected());
assert_eq!(p.view.progression.level, 60);
assert_eq!(p.view.items.len(), c.items.len() - 1);
let ctx = p.context.unwrap();
assert_eq!((ctx.canonical_level, ctx.projected_level, ctx.canonical_revision), (80, 60, 3));
assert!(p.pin.unwrap().projected);
assert!(plan_with(&c, 3, None, None).unwrap().pin.is_none(), "without a profile nothing is evaluated");
}
#[test]
fn a_decision_of_another_progression_or_another_state_is_refused() {
let c = geared_level_eighty();
let other = "ab".repeat(32);
let wrong_profile = SuppliedDecision(hold(&c, 60, &other));
assert!(matches!(plan_with(&c, 3, Some(&caps(60, SIG)), Some(&wrong_profile)), Err(PortableError::ProgressionChanged(_))));
let wrong_cap = SuppliedDecision(hold(&c, 70, SIG));
assert!(matches!(plan_with(&c, 3, Some(&caps(60, SIG)), Some(&wrong_cap)), Err(PortableError::ProgressionChanged(_))));
let mut changed = c.clone();
changed.progression.money += 1;
let stale = SuppliedDecision(hold(&c, 60, SIG));
assert!(plan_with(&changed, 3, Some(&caps(60, SIG)), Some(&stale)).is_err(), "made for another state of the character");
let mut unnamed = hold(&c, 60, SIG);
unnamed.subject.clear();
assert!(plan_with(&c, 3, Some(&caps(60, SIG)), Some(&SuppliedDecision(unnamed))).is_err());
}
#[test]
fn a_profile_without_progression_is_never_read_as_no_cap() {
let c = geared_level_eighty();
let mut unknown = caps(80, SIG);
unknown.progression = None;
unknown.content.features.remove(&Feature::LevelProjection);
unknown.content_profile_hash = hex::encode(unknown.content.hash().unwrap());
assert!(matches!(plan_with(&c, 3, Some(&unknown), None), Err(PortableError::ProgressionChanged(_))));
}
#[test]
fn a_query_job_names_its_character_and_its_hash() {
let c = geared_level_eighty();
let id = ImportId::new();
let bytes = query_bytes(id, &c).unwrap();
let split = bytes.iter().position(|b| *b == b'\n').unwrap();
let header: serde_json::Value = serde_json::from_slice(&bytes[..split]).unwrap();
assert_eq!(header["query"], "project");
assert_eq!(header["job_format"], 2);
assert_eq!(header["snapshot_sha256"], hex::encode(Sha256::digest(&bytes[split + 1..])));
assert!(header.get("account").is_none() && header.get("nonce").is_none(), "a query writes nothing and carries no import data");
}
}
@@ -24,14 +24,14 @@ use crate::db::Db;
use super::super::error::{PortableError, Result};
use super::super::ids::{CharacterId, ImportId, PortableItemId, PortablePetId, SessionId};
use super::super::merge::{merge3, ItemOutcome, Mode, PetOutcome};
use super::super::merge::{merge3_with, ItemOutcome, MergeProjection, Mode, PetOutcome};
use super::super::model::PortableCharacter;
use super::super::store::{BaselineInput, ImportAllocation, ImportState, JournalEntry, JournalKind, PlannedItem, PlannedPet, Store, UpdatePlan};
use super::import::{ImportOptions, ImportProblem, Resolution};
use super::plan::{SessionArm, IMPORT_LOCK};
use super::script::{parse_output, Query};
use super::sqlenc::Val;
use super::update::{build_update, new_content, parse_update_report, UpdateContext, UpdateCounts};
use super::update::{build_update, new_content, parse_update_report, PinWrite, UpdateContext, UpdateCounts};
use super::{export_character_with_pets, probe, realm_error, ruleset_of};
use crate::portable::store::pet_identity;
@@ -133,9 +133,14 @@ pub fn reconcile_session(db: &Db, store: &mut Store, id: CharacterId, server_id:
return Err(PortableError::StaleRevision { expected: baseline.head_revision, current: record.revision });
}
let view = read_realm(db, store, id, server_id, guid)?;
let merged = merge3(&baseline.c0, &baseline.b0, &view.exported.model, Mode::Lenient)?;
let context = store.projection_context(id, server_id)?;
let projection = context.as_ref().map(|c| MergeProjection { freeze_progression: true, blocked: c.hold.blocked_settings.iter().cloned().collect() });
let merged = merge3_with(&baseline.c0, &baseline.b0, &view.exported.model, Mode::Lenient, projection.as_ref())?;
let before = record.revision;
let revision = store.commit_reconciled(id, server_id, merged.model, &view.exported.observations, &view.exported.pet_observations, note)?;
if context.is_some() {
store.advance_projection_revision(id, server_id, revision)?;
}
if close_session {
store.close_baseline(id, server_id)?;
}
@@ -217,6 +222,18 @@ pub fn update_realm_character_in_session(db: &Db, store: &mut Store, id: Charact
update_inner(db, store, id, server_id, opts, session, false)
}
/// The realm's progression (level cap or rules) moved under a runtime session: the session ended with its final checkpoint under the old
/// pin, and the next one is waiting, not armed. Project the character again for the realm as it is now (an in-place update from what the
/// realm holds to the canonical character under the new cap, which arms the next session in the same realm transaction) and release it.
/// `None`: no session of this character on this realm waits for it.
pub fn reproject_session(db: &Db, store: &mut Store, id: CharacterId, server_id: &str, opts: &ImportOptions) -> Result<Option<UpdateOutcome>> {
let Some(next) = store.host_live_sessions(server_id)?.into_iter().find(|s| s.character_id == id && s.reproject && s.state == super::super::store::HostState::Armed) else { return Ok(None) };
let outcome = update_realm_character_in_session(db, store, id, server_id, opts, Some(next.session_id))?;
let pin = store.character_pin(id, server_id)?;
store.host_clear_reproject(next.session_id, pin.as_ref())?;
Ok(Some(outcome))
}
/// What a re-evaluation did.
#[derive(Debug)]
pub struct Reevaluation {
@@ -272,11 +289,16 @@ fn update_inner(db: &Db, store: &mut Store, id: CharacterId, server_id: &str, op
return Err(PortableError::ImportInProgress { import_id: open.import_id });
}
let record = store.character(id)?;
let stored_pin = store.character_pin(id, server_id)?;
let stale_pin = !reevaluate && opts.capabilities.as_deref().and_then(|c| c.progression.as_ref()).is_some_and(|p| match &stored_pin {
Some(pin) => pin.progression_signature != p.progression_signature || pin.max_player_level != p.max_player_level || pin.policy_version != p.projection_policy_version,
None => true,
});
if reevaluate {
if record.revision != last_revision {
return Err(PortableError::Invalid("the realm is not at the canonical revision: update it first, then re-evaluate".into()));
}
} else if record.revision == last_revision {
} else if record.revision == last_revision && !stale_pin {
return Ok(UpdateOutcome { import_id: None, from_revision: last_revision, to_revision: last_revision, updated: false, counts: UpdateCounts::default(), changes: vec![], left_alone: vec![], warnings: vec![] });
}
if record.revision < last_revision {
@@ -284,11 +306,16 @@ fn update_inner(db: &Db, store: &mut Store, id: CharacterId, server_id: &str, op
}
let synced = store.synced_model(id, server_id)?.ok_or_else(|| PortableError::Invalid("the realm has no synchronised snapshot to update from".into()))?;
let canonical = store.load_current(id)?;
let old_context = store.projection_context(id, server_id)?;
if opts.capabilities.is_none() && old_context.is_some() {
return Err(PortableError::ProgressionChanged("this character is projected on this realm: the update needs the realm's current progression profile".into()));
}
let mut operations = vec![super::super::compat::Operation::Update];
if session.is_some() {
operations.push(super::super::compat::Operation::RuntimeSession);
}
let compatibility = super::profile::gate(opts, &canonical, &operations)?;
let new_plan = if reevaluate { super::project::Plan { view: super::project::stored_view(&canonical, old_context.as_ref()), context: old_context.clone(), pin: stored_pin.clone() } } else { super::project::plan(&canonical, record.revision, opts, None)? };
let view = read_realm(db, store, id, server_id, guid)?;
let merged = if reevaluate {
@@ -302,7 +329,11 @@ fn update_inner(db: &Db, store: &mut Store, id: CharacterId, server_id: &str, op
}
super::super::merge::Merged { model, changes, left_alone: vec![], conflicts: vec![], items: Default::default(), pets: Default::default() }
} else {
let merged = merge3(&view.exported.model, &synced, &canonical, Mode::Strict)?;
let base = super::project::stored_view(&synced, old_context.as_ref());
let projected = old_context.is_some() || new_plan.context.is_some();
let blocked: std::collections::BTreeSet<String> = old_context.iter().chain(new_plan.context.iter()).flat_map(|c| c.hold.blocked_settings.iter().cloned()).collect();
let projection = projected.then_some(MergeProjection { freeze_progression: false, blocked });
let merged = merge3_with(&view.exported.model, &base, &new_plan.view, Mode::Strict, projection.as_ref())?;
if !merged.conflicts.is_empty() {
return Err(PortableError::UpdateConflicts(merged.conflicts.iter().map(|c| format!("{}: {}", c.path, c.detail)).collect()));
}
@@ -320,6 +351,10 @@ fn update_inner(db: &Db, store: &mut Store, id: CharacterId, server_id: &str, op
pets: &view.pets,
session: session.map(|session_id| SessionArm { session_id, character_id: id, generation: 1 }),
knowledge: opts.knowledge.as_deref(),
pin: match (&new_plan.pin, reevaluate) {
(Some(p), false) => PinWrite::Set(p.words()),
_ => PinWrite::Keep,
},
};
// 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]))?;
@@ -363,6 +398,9 @@ fn update_inner(db: &Db, store: &mut Store, id: CharacterId, server_id: &str, op
}
}
}
if !reevaluate {
super::project::remember(store, id, server_id, &new_plan)?;
}
let mut warnings = view.exported.warnings;
warnings.extend(super::profile::after_write(Some(db), store, id, server_id, opts, guid, &canonical, compatibility.as_ref())?);
Ok(UpdateOutcome {
@@ -461,5 +499,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, knowledge: 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, pin: PinWrite::Keep })?.counts)
}
+20 -2
View File
@@ -41,6 +41,19 @@ pub struct UpdateContext<'a> {
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 happens to the character's `coa.portable.pin` row.
pub pin: PinWrite,
}
/// What an update does to the realm's record of the progression the character was prepared for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PinWrite {
/// The row stays as it is.
Keep,
/// The character was prepared for this progression (policy, cap, signature words).
Set(Vec<u32>),
/// The character is not bound to a progression any more.
Clear,
}
/// What the script does, in numbers (and as the plan the journal records).
@@ -643,11 +656,16 @@ pub fn build_update(current: &PortableCharacter, merged: &PortableCharacter, ctx
// the markers: replaced, not added
let markers = [Val::text(IMPORT_MARKER_SOURCE), Val::text(ALLOC_MARKER_SOURCE)];
line(format!("DELETE FROM acore_characters.`character_settings` WHERE `guid` = @char AND `source` IN ({}, {});", markers[0].sql(), markers[1].sql()));
let pin_source = Val::text(super::policy::PIN_SOURCE);
let sources = if ctx.pin == PinWrite::Keep { format!("{}, {}", markers[0].sql(), markers[1].sql()) } else { format!("{}, {}, {}", markers[0].sql(), markers[1].sql(), pin_source.sql()) };
line(format!("DELETE FROM acore_characters.`character_settings` WHERE `guid` = @char AND `source` IN ({sources});"));
let mut m = Insert::new("character_settings", &["guid", "source", "data"]);
m.row(vec![Val::Expr("@char"), markers[0].clone(), Val::text(marker.clone())])?;
m.row(vec![Val::Expr("@char"), markers[1].clone(), Val::Expr("CONCAT(@item_base, ' ', @pet_base, ' ')")])?;
line(m.sql().expect("two rows"));
if let PinWrite::Set(words) = &ctx.pin {
m.row(vec![Val::Expr("@char"), pin_source.clone(), Val::text(words.iter().map(|w| format!("{w} ")).collect::<String>())])?;
}
line(m.sql().expect("at least two rows"));
if let Some(arm) = &ctx.session {
if !ctx.probe.has("coa_portable_session") {
return Err(PortableError::Invalid("this realm's core has no portable session support (coa_portable_session is missing)".into()));
@@ -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, knowledge: 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, pin: crate::portable::realm::update::PinWrite::Keep }).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(&current);
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, knowledge: 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, pin: crate::portable::realm::update::PinWrite::Keep };
let mut merged = current.clone();
merged.identity.gender ^= 1;
assert!(build_update(&current, &merged, &ctx).is_err(), "gender");
@@ -232,7 +232,7 @@ fn script_known(current: &PortableCharacter, merged: &PortableCharacter, known:
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()
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, pin: crate::portable::realm::update::PinWrite::Keep }).unwrap()
}
fn knows(ids: &[u32]) -> super::knowledge::RealmKnowledge {
@@ -298,7 +298,7 @@ fn hostile_or_broken_collection_messages_change_nothing() {
// 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)}});
let message = serde_json::json!({"protocol_version": PROTOCOL_VERSION, "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(_)));
}
@@ -101,6 +101,11 @@ impl FakeRealm {
/// The character arrives (an import): items and pets get local ids in plan order, like the offline importer does.
pub fn import(&mut self, store: &mut Store, character: CharacterId, server_id: &str, revision: u64, session: SessionId) -> Result<()> {
let model = store.load_snapshot(character, revision)?;
self.import_model(store, character, server_id, revision, session, model)
}
/// The same, for a character that is not the canonical one as it is (a working copy projected for this realm).
pub fn import_model(&mut self, store: &mut Store, character: CharacterId, server_id: &str, revision: u64, session: SessionId, model: PortableCharacter) -> Result<()> {
let items: Vec<PlannedItem> = model.items.iter().map(|i| PlannedItem { id: i.id, entry: i.entry.clone(), identity: item_identity(&i.entry, i.random_property_id) }).collect();
let pets: Vec<PlannedPet> = model.pets.iter().map(|p| PlannedPet { id: p.id, entry: p.entry.clone(), identity: pet_identity(&p.entry, p.pet_type, p.created_by_spell) }).collect();
let ticket = store.begin_import(character, server_id, revision, &items, &pets)?;
+78 -6
View File
@@ -4,7 +4,7 @@
use std::collections::{HashMap, HashSet};
use super::super::collection::IdSet;
use super::super::capabilities::RealmCapabilities;
use super::super::capabilities::{Progression, RealmCapabilities};
use super::super::error::{PortableError, Result};
use super::super::realm::collections::Applied;
use super::super::ids::{CharacterId, PortableItemId, PortablePetId, ProfileId, SessionId};
@@ -44,6 +44,11 @@ pub enum HostEvent {
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 },
/// The realm's progression (level cap or rules) is not the one this session started under: the session ends with a final checkpoint taken
/// **under the old pin**, and the working copy must be projected again before the next session is armed.
ProfileMoved { session: SessionId },
/// The realm's progression moved but the character is online under the old one (or could not be read): the session ends at its logout.
ProfileWaiting { session: SessionId, why: String },
}
pub struct HostService<'a> {
@@ -54,11 +59,13 @@ pub struct HostService<'a> {
last_checkpoint: HashMap<SessionId, u64>,
/// When the account collections of each session were last looked at.
last_collection: HashMap<SessionId, u64>,
/// The progression the realm reports now (from the last observed profile).
progression: Option<Progression>,
}
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(), last_collection: HashMap::new() }
Self { store, server_id: server_id.to_string(), config, last_checkpoint: HashMap::new(), last_collection: HashMap::new(), progression: None }
}
pub fn store(&self) -> &Store {
@@ -93,6 +100,19 @@ impl<'a> HostService<'a> {
let mut events = Vec::new();
for s in self.store.host_live_sessions(&self.server_id)? {
let Some(guid) = s.local_guid else { continue };
if self.moved(&s)? {
if !s.reproject {
match s.state {
HostState::Open => self.end_for_profile(bridge, &s, guid, &mut events)?,
HostState::Armed => {
self.store.host_mark_reproject(s.session_id)?;
events.push(HostEvent::ProfileMoved { session: s.session_id });
}
_ => {}
}
}
continue;
}
let Some(row) = bridge.session_row(guid)? else { continue };
if row.session_id != s.session_id {
if s.state == HostState::Open {
@@ -119,6 +139,44 @@ impl<'a> HostService<'a> {
Ok(events)
}
/// The realm's progression is not the one this session runs under.
fn moved(&self, s: &HostSession) -> Result<bool> {
let Some(current) = &self.progression else { return Ok(false) };
let pin = match &s.pin {
Some(pin) => Some(pin.clone()),
None => self.store.character_pin(s.character_id, &s.server_id)?,
};
Ok(pin.is_some_and(|p| p.progression_signature != current.progression_signature || p.max_player_level != current.max_player_level || p.policy_version != current.projection_policy_version))
}
/// End a session whose realm changed its progression: the realm's state is read as it is (the realm's core refuses the character at
/// login under the new progression, so nobody has played it) and sent as the **final checkpoint under the old pin**. The Owner merges it
/// as it merges any other; the next session is not armed until the working copy is projected again.
fn end_for_profile(&mut self, bridge: &mut dyn RealmBridge, s: &HostSession, guid: u32, events: &mut Vec<HostEvent>) -> Result<()> {
let (items, pets) = self.priors(s)?;
let read = match bridge.read(guid, &items, &pets) {
Ok(read) => read,
Err(e) => {
events.push(HostEvent::ProfileWaiting { session: s.session_id, why: e.to_string() });
return Ok(());
}
};
if read.online {
events.push(HostEvent::ProfileWaiting { session: s.session_id, why: "the character is online".into() });
return Ok(());
}
if read.session.as_ref().is_none_or(|r| r.session_id != s.session_id) {
return Ok(());
}
let sequence = self.store.host_begin_checkpoint(s.session_id)?;
let msg = PortableCheckpoint::new(s.session_id, s.character_id, &s.server_id, s.base_revision, sequence, true, &read.exported.model, s.pin.clone())?;
self.store.host_queue_checkpoint(s.session_id, &msg, &read.exported.observations, &read.exported.pet_observations)?;
self.store.host_mark_reproject(s.session_id)?;
events.push(HostEvent::CheckpointQueued { session: s.session_id, sequence, final_checkpoint: true });
events.push(HostEvent::ProfileMoved { session: s.session_id });
Ok(())
}
fn priors(&self, s: &HostSession) -> Result<(HashMap<u32, (PortableItemId, String)>, HashMap<u32, (PortablePetId, String)>)> {
Ok((self.store.active_item_lookup(s.character_id, &s.server_id)?, self.store.active_pet_lookup(s.character_id, &s.server_id)?))
}
@@ -131,7 +189,8 @@ impl<'a> HostService<'a> {
events.push(HostEvent::BaselineRetry { session: s.session_id, why: "the marker moved while the baseline was being read".into() });
return Ok(());
};
let msg = PortableSessionStarted::new(s.session_id, s.character_id, &s.server_id, s.base_revision, row.generation, &exported.model)?;
let progression = self.session_progression(s)?;
let msg = PortableSessionStarted::new(s.session_id, s.character_id, &s.server_id, s.base_revision, row.generation, &exported.model, progression)?;
self.store.host_queue_started(s.session_id, &msg, &exported.model, &exported.observations, &exported.pet_observations)?;
// the baseline is persisted (and queued): only now may the player move on
bridge.release(s.session_id)?;
@@ -169,13 +228,23 @@ impl<'a> HostService<'a> {
if final_checkpoint && row.state != RowState::Ended {
return Ok(());
}
let msg = PortableCheckpoint::new(s.session_id, s.character_id, &s.server_id, s.base_revision, sequence, final_checkpoint, &exported.model)?;
let msg = PortableCheckpoint::new(s.session_id, s.character_id, &s.server_id, s.base_revision, sequence, final_checkpoint, &exported.model, s.pin.clone())?;
self.store.host_queue_checkpoint(s.session_id, &msg, &exported.observations, &exported.pet_observations)?;
self.last_checkpoint.insert(s.session_id, now_secs);
events.push(HostEvent::CheckpointQueued { session: s.session_id, sequence, final_checkpoint });
Ok(())
}
/// What the session runs under: the projection of the character on this realm, else the realm's progression it was synchronised under.
fn session_progression(&self, s: &HostSession) -> Result<Option<SessionProgression>> {
if let Some(ctx) = self.store.projection_context(s.character_id, &s.server_id)? {
let progression = SessionProgression { pin: ctx.pin(), projection: Some(ctx) };
progression.validate()?;
return Ok(Some(progression));
}
Ok(self.store.character_pin(s.character_id, &s.server_id)?.map(|pin| SessionProgression { pin, projection: None }))
}
/// Messages waiting for delivery, in order.
pub fn outbox(&self) -> Result<Vec<OutboxMessage>> {
self.store.host_outbox_pending(&self.server_id)
@@ -186,7 +255,9 @@ impl<'a> HostService<'a> {
let session = self.store.host_session(ack.session_id)?;
let effect = self.store.host_receive_ack(ack)?;
if let (AckEffect::Finished { next_session, next_revision }, Some(old)) = (&effect, session) {
self.rearm(bridge, old.character_id, *next_session, *next_revision)?;
if !old.reproject {
self.rearm(bridge, old.character_id, *next_session, *next_revision)?;
}
}
Ok(effect)
}
@@ -201,7 +272,7 @@ impl<'a> HostService<'a> {
if current.as_ref().is_some_and(|r| r.session_id == s.session_id) {
continue;
}
if s.generation > 1 {
if s.generation > 1 && !s.reproject {
bridge.arm(guid, s.session_id, s.character_id, s.base_revision, s.generation)?;
n += 1;
}
@@ -313,6 +384,7 @@ impl<'a> HostService<'a> {
/// answers with what it holds); the characters whose profile is stale are returned for a re-evaluation (whatever their revision).
pub fn observe_profile(&mut self, caps: &RealmCapabilities, source: &str) -> Result<(ProfileChange, Vec<StaleMapping>)> {
let change = self.store.set_realm_profile(&self.server_id, caps, source)?;
self.progression = caps.progression.clone();
if change.changed() {
self.store.host_collection_reset(&self.server_id)?;
self.last_collection.clear();
@@ -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, None).unwrap();
let bytes = crate::portable::realm::online::job_bytes(ticket.import_id, ticket.nonce, ACCOUNT, record.revision, 10, &model, None, 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, 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();
refused(crate::portable::realm::online::job_bytes(ticket.import_id, [9, 9, 9, 9], ACCOUNT, 1, 10, &impossible, None, 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, 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, None).unwrap();
let last = tampered.len() - 3;
tampered[last] ^= 1;
refused(tampered, "a snapshot that does not match its hash");
@@ -478,7 +478,7 @@ fn the_core_reports_what_it_is_the_manager_evaluates_before_it_writes_and_the_co
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 good = crate::portable::realm::online::job_bytes(ticket.import_id, ticket.nonce, ACCOUNT, record.revision, 10, &model, None, None).unwrap();
let good = crate::portable::realm::online::job_bytes(ticket.import_id, ticket.nonce, ACCOUNT, record.revision, 10, &model, None, None, None).unwrap();
let text = String::from_utf8(good).unwrap();
assert!(text.starts_with("{\"job_format\":2,"), "{}", &text[..60]);
let chars = number(&r.b, "SELECT COUNT(*) FROM acore_characters.characters") + number(&r.b, "SELECT COUNT(*) FROM acore_characters.item_instance");
@@ -14,6 +14,8 @@ mod collection_tests;
#[cfg(test)]
mod profile_tests;
#[cfg(test)]
mod projection_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod live_session;
@@ -0,0 +1,276 @@
//! Runtime sessions of a character above the realm's level cap (Phase 8): the Owner and the Host as two stores, a simulated realm at
//! cap 60 between them. The core's decision is supplied (the real core is exercised by the live suite).
use super::bridge::*;
use super::fake::*;
use super::protocol::*;
use super::*;
use crate::portable::capabilities::*;
use crate::portable::ids::{CharacterId, SessionId};
use crate::portable::model::{PortableCharacter, Ruleset};
use crate::portable::projection::testing::*;
use crate::portable::projection::{settings, SuppliedDecision};
use crate::portable::realm::project::{plan_with, remember};
use crate::portable::store::Store;
const SERVER: &str = "realm-60";
const GUID: u32 = 777;
struct World {
owner: Store,
host: Store,
realm: FakeRealm,
id: CharacterId,
session: SessionId,
c0: PortableCharacter,
caps: RealmCapabilities,
}
fn caps(cap: u32, signature: &str) -> RealmCapabilities {
let content = ContentProfile {
ruleset: Ruleset::Coa,
character_formats: ContentProfile::manager_formats(),
online_import_job_formats: vec![2],
session_protocol: PROTOCOL_VERSION,
collection_protocol: PROTOCOL_VERSION,
features: [Feature::RuntimeSessions, Feature::LevelProjection].into_iter().collect(),
collection_kinds: Default::default(),
extensions: vec![],
client_catalog: Default::default(),
};
RealmCapabilities::build(None, content, Some(crate::portable::capabilities::Progression { max_player_level: cap, projection_protocol: 1, projection_policy_version: 1, progression_signature: signature.into(), scaling_enabled: true })).unwrap()
}
/// What the realm's core rewrites at its first load: the build record in its own order and padding.
fn rewrites_the_record(r: &mut FakeRealm) {
if let Some(v) = r.memory.settings.get("core.ascension_slot.0").cloned() {
let mut rec = settings::Record::parse(settings::SettingKind::Slot, &v).expect("a build record");
rec.entry_order.reverse();
let mut out = rec.write();
out.extend([0, 0, 0]);
r.memory.settings.insert("core.ascension_slot.0".into(), out);
}
}
fn world() -> World {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let canonical = canonical();
let id = owner.create_character(profile, canonical.clone(), "realm-80").unwrap();
let c0 = owner.load_current(id).unwrap();
let offer = OwnerService::new(&mut owner).offer(id, SERVER).unwrap();
let caps = caps(60, SIGNATURE);
host.set_realm_profile(SERVER, &caps, "live").unwrap();
let hold = hold_for(&c0);
let plan = plan_with(&c0, offer.canonical_revision, Some(&caps), Some(&SuppliedDecision(hold))).unwrap();
let host_profile = host.default_profile().unwrap();
let mut realm = FakeRealm::new(GUID);
realm.normalize = rewrites_the_record;
{
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
h.accept_offer(host_profile, &offer).unwrap();
realm.import_model(&mut host, id, SERVER, offer.canonical_revision, offer.session_id, plan.view.clone()).unwrap();
remember(&mut host, id, SERVER, &plan).unwrap();
HostService::new(&mut host, SERVER, HostConfig::default()).bind(offer.session_id, GUID).unwrap();
}
World { owner, host, realm, id, session: offer.session_id, c0, caps }
}
fn deliver(host: &mut HostService, owner: &mut OwnerService, realm: &mut FakeRealm) -> Vec<OwnerAck> {
let mut acks = Vec::new();
for m in host.outbox().unwrap() {
let ack = if m.started { owner.handle_started(&m.bytes) } else { owner.handle_checkpoint(&m.bytes) }.unwrap();
host.receive_ack(realm, &ack).unwrap();
acks.push(ack);
}
acks
}
fn checkpoint(host: &mut HostService, owner: &mut OwnerService, realm: &mut FakeRealm, now: u64) {
host.tick(realm, now).unwrap();
host.tick(realm, now + 1).unwrap();
deliver(host, owner, realm);
}
#[test]
fn a_session_of_a_level_eighty_on_a_cap_sixty_realm_keeps_the_canonical_character_whole() {
let World { mut owner, mut host, mut realm, id, session, c0, .. } = world();
assert_eq!(realm.db.progression.level, 60, "the realm was given the working copy");
assert!(realm.db.items.iter().all(|i| !hold_for(&c0).held_items.contains(&i.id)), "a held item never reaches the realm");
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
let started: PortableSessionStarted = from_json(&h.outbox().unwrap()[0].bytes).unwrap();
let progression = started.progression.clone().expect("the session carries its progression");
assert!(progression.pin.projected && progression.projection.is_some());
assert_eq!((progression.pin.max_player_level, progression.projection.as_ref().unwrap().canonical_level), (60, 80));
let acks = deliver(&mut h, &mut o, &mut realm);
assert_eq!(acks[0].outcome, AckOutcome::Applied);
assert_eq!(acks[0].pin, Some(progression.pin.clone()));
realm.play(|m| {
m.progression.money += 9_000;
m.progression.xp = 4_321;
m.reputation[0].standing += 100;
m.quests.rewarded.push(31_337);
m.settings.insert("core.ascension_build.61".into(), vec![2, 1001, 4001]);
});
realm.give_item(new_internal_item(9, 40, 88_001));
checkpoint(&mut h, &mut o, &mut realm, 100);
let c1 = o.store().load_current(id).unwrap();
assert_eq!((c1.progression.level, c1.progression.xp), (80, c0.progression.xp), "the realm's level and xp are not the canonical character's");
assert_eq!(c1.progression.money, c0.progression.money + 9_000);
assert!(c1.quests.rewarded.contains(&31_337) && c1.items.iter().any(|i| i.entry.id() == 88_001));
let hold = hold_for(&c0);
for held in &hold.held_items {
assert!(c1.items.iter().any(|i| i.id == *held), "the held item is still canonical");
}
for spell in &hold.held_spells {
assert!(c1.build.spells.iter().any(|(s, _)| s == spell), "the held ability is still canonical");
}
let slot = settings::Record::parse(settings::SettingKind::Slot, &c1.settings["core.ascension_slot.0"]).unwrap();
assert_eq!(slot.entries.keys().copied().collect::<Vec<_>>(), vec![100, 200, 300], "the realm's rewrite of the build record does not erase what it could not hold");
let build = settings::Record::parse(settings::SettingKind::Build, &c1.settings["core.ascension_build.61"]).unwrap();
assert_eq!(build.entries.keys().copied().collect::<Vec<_>>(), vec![100, 200, 300, 400], "a pick made at the cap arrives");
// the checkpoint repeated, and more of the same play: nothing is counted twice, the held state is still there
checkpoint(&mut h, &mut o, &mut realm, 200);
assert_eq!(o.store().load_current(id).unwrap(), c1);
realm.play(|m| m.progression.money += 1);
checkpoint(&mut h, &mut o, &mut realm, 300);
assert_eq!(o.store().load_current(id).unwrap().progression.money, c1.progression.money + 1);
// logout: the final checkpoint, the next session follows, and the projection is still the realm's
realm.logout();
h.tick(&mut realm, 400).unwrap();
let acks = deliver(&mut h, &mut o, &mut realm);
let last = acks.last().unwrap();
assert!(last.next_session.is_some() && last.canonical.is_some(), "{acks:?}");
let c2 = o.store().load_current(id).unwrap();
assert_eq!(c2.progression.level, 80);
assert_eq!(c2.items.len(), c1.items.len());
let ctx = h.store().projection_context(id, SERVER).unwrap().expect("the projection is still remembered");
assert_eq!(ctx.canonical_revision, o.store().character(id).unwrap().revision, "the context follows the acknowledged revision");
assert_eq!(o.session(session).unwrap().unwrap().0, "closed");
}
#[test]
fn a_checkpoint_under_another_pin_is_refused_and_changes_nothing() {
let World { mut owner, mut host, mut realm, id, session, .. } = world();
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
deliver(&mut h, &mut o, &mut realm);
realm.play(|m| m.progression.money += 5);
h.tick(&mut realm, 50).unwrap();
h.tick(&mut realm, 51).unwrap();
let pending = h.outbox().unwrap();
assert_eq!(pending.len(), 1);
let before = o.store().load_current(id).unwrap();
let mut forged: PortableCheckpoint = from_json(&pending[0].bytes).unwrap();
let mut other = forged.pin.clone().unwrap();
other.progression_signature = "ee".repeat(32);
forged.pin = Some(other);
let ack = o.handle_checkpoint(&to_json(&forged).unwrap()).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(ref why) if why.contains("progression")), "{ack:?}");
forged.pin = None;
let ack = o.handle_checkpoint(&to_json(&forged).unwrap()).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)), "a checkpoint with no pin under a pinned session");
assert_eq!(o.store().load_current(id).unwrap(), before, "nothing was merged");
assert_eq!(o.session(session).unwrap().unwrap().1, 0);
// the genuine one is accepted
let ack = o.handle_checkpoint(&pending[0].bytes).unwrap();
assert_eq!(ack.outcome, AckOutcome::Applied);
}
#[test]
fn a_session_started_without_its_projection_or_with_a_wrong_one_is_not_opened() {
let World { mut owner, mut host, mut realm, id, .. } = world();
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
let genuine = h.outbox().unwrap().remove(0).bytes;
let mut no_context: PortableSessionStarted = from_json(&genuine).unwrap();
no_context.progression.as_mut().unwrap().projection = None;
assert!(o.handle_started(&to_json(&no_context).unwrap()).unwrap().outcome != AckOutcome::Applied, "a projected pin needs its projection");
let mut wrong_level: PortableSessionStarted = from_json(&genuine).unwrap();
{
let p = wrong_level.progression.as_mut().unwrap();
let ctx = p.projection.as_mut().unwrap();
ctx.canonical_level = 70;
p.pin = ctx.pin();
}
let ack = o.handle_started(&to_json(&wrong_level).unwrap()).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(ref why) if why.contains("canonical level")), "{ack:?}");
assert_eq!(o.session(h.store().host_live_sessions(SERVER).unwrap()[0].session_id).unwrap().unwrap().0, "offered");
// an older protocol is not understood at all
let old = String::from_utf8(genuine.clone()).unwrap().replace("\"protocol_version\":2", "\"protocol_version\":1");
assert!(o.handle_started(old.as_bytes()).is_err());
assert_eq!(o.handle_started(&genuine).unwrap().outcome, AckOutcome::Applied);
assert_eq!(o.store().character(id).unwrap().revision, 1);
}
#[test]
fn a_realm_that_changes_its_cap_under_a_session_ends_it_under_the_old_pin_and_does_not_arm_the_next() {
let World { mut owner, mut host, mut realm, id, session, c0, .. } = world();
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
deliver(&mut h, &mut o, &mut realm);
realm.play(|m| m.progression.money += 700);
checkpoint(&mut h, &mut o, &mut realm, 100);
realm.play(|m| m.progression.money += 300);
// the realm restarts with another cap (a different progression signature); the player is gone
realm.crash();
let moved = caps(70, &"cd".repeat(32));
let (change, _) = h.observe_profile(&moved, "live").unwrap();
assert!(change.progression_changed() && !change.changed(), "only the progression moved, not the content");
let events = h.tick(&mut realm, 500).unwrap();
assert!(events.contains(&HostEvent::ProfileMoved { session }), "{events:?}");
assert!(events.contains(&HostEvent::CheckpointQueued { session, sequence: 2, final_checkpoint: true }), "{events:?}");
let started_pin = h.store().host_session(session).unwrap().unwrap().pin.unwrap();
assert_eq!(started_pin.max_player_level, 60, "the session ends under the pin it started under");
let acks = deliver(&mut h, &mut o, &mut realm);
let ack = acks.last().unwrap();
assert_eq!(ack.outcome, AckOutcome::Applied);
assert_eq!(ack.pin.as_ref().unwrap().max_player_level, 60);
let c1 = o.store().load_current(id).unwrap();
assert_eq!(c1.progression.level, 80, "merged as a projection of the old cap, never as the new one");
assert_eq!(c1.progression.money, c0.progression.money + 700 + 0, "what the realm had saved (the unsaved 300 died with the crash)");
let next = ack.next_session.as_ref().unwrap().session_id;
let next_row = h.store().host_session(next).unwrap().unwrap();
assert!(next_row.reproject, "the next session waits for the working copy to be projected again");
assert_eq!(h.rearm_pending(&mut realm).unwrap(), 0, "nothing is armed on the old working copy");
assert_eq!(realm.row.as_ref().unwrap().session_id, session, "the realm was not armed for the next session");
// later ticks do not end the session twice
let again = h.tick(&mut realm, 600).unwrap();
assert!(!again.iter().any(|e| matches!(e, HostEvent::CheckpointQueued { .. })), "{again:?}");
}
#[test]
fn a_character_online_under_the_old_profile_ends_at_its_logout() {
let World { mut owner, mut host, mut realm, session, .. } = world();
let mut h = HostService::new(&mut host, SERVER, HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
deliver(&mut h, &mut o, &mut realm);
h.observe_profile(&caps(70, &"cd".repeat(32)), "live").unwrap();
let events = h.tick(&mut realm, 10).unwrap();
assert!(events.iter().any(|e| matches!(e, HostEvent::ProfileWaiting { session: s, .. } if *s == session)), "{events:?}");
assert!(h.outbox().unwrap().is_empty(), "nothing is sent while the character is online");
}
@@ -10,9 +10,13 @@ use serde::{Deserialize, Serialize};
use super::super::error::{PortableError, Result};
use super::super::ids::{CharacterId, PortableItemId, PortablePetId, SessionId};
use super::super::model::{limits::MAX_COMPRESSED_BYTES, PortableCharacter};
use super::super::projection::{ProgressionPin, ProjectionContext};
use super::super::snapshot;
pub const PROTOCOL_VERSION: u32 = 1;
/// Version 2 (Phase 8): `PortableSessionStarted` carries the progression the session runs under, every `PortableCheckpoint` and `OwnerAck` its pin.
/// A version 1 peer and a version 2 peer read each other's messages as unsupported, and the realm's capability profile (`session_protocol`)
/// says so before any character is armed.
pub const PROTOCOL_VERSION: u32 = 2;
/// A message carries at most one compressed snapshot (base64: 4/3) plus a little structure.
pub const MAX_MESSAGE_BYTES: usize = MAX_COMPRESSED_BYTES * 4 / 3 + 64 * 1024;
/// The most item/pet ids an acknowledgement lists.
@@ -68,6 +72,32 @@ pub struct SessionOffer {
pub snapshot: Envelope,
}
/// The progression a session runs under: what the realm's cap and rules were when it started, and, when the character is above the cap,
/// the projection the working copy was made with. Nothing in a session may change it: a message under another pin is refused.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SessionProgression {
pub pin: ProgressionPin,
pub projection: Option<ProjectionContext>,
}
impl SessionProgression {
pub fn validate(&self) -> Result<()> {
self.pin.validate()?;
match (&self.projection, self.pin.projected) {
(Some(ctx), true) => {
ctx.validate()?;
if ctx.pin() != self.pin {
return Err(PortableError::Invalid("the projection is not the one the pin names".into()));
}
}
(None, false) => {}
_ => return Err(PortableError::Invalid("a projected pin needs its projection and a native one has none".into())),
}
Ok(())
}
}
/// Host -> Owner: the realm's own first load/save of the character was captured, before any gameplay.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -80,6 +110,8 @@ pub struct PortableSessionStarted {
pub baseline_generation: u32,
pub b0: Envelope,
pub content_hash: String,
/// The progression the session runs under; `None` when the Host does not know its realm's progression (no profile).
pub progression: Option<SessionProgression>,
}
/// Host -> Owner: the realm's state now. `sequence` is monotonic per session; `final_checkpoint` ends it.
@@ -95,6 +127,8 @@ pub struct PortableCheckpoint {
pub final_checkpoint: bool,
pub realm_snapshot: Envelope,
pub content_hash: String,
/// The pin the session started under (`None` as the start said).
pub pin: Option<ProgressionPin>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -142,6 +176,8 @@ pub struct OwnerAck {
pub canonical: Option<Envelope>,
/// Only on the acknowledgement of a final checkpoint: the session that follows.
pub next_session: Option<NextSession>,
/// The pin the Owner holds for this session (`None` before the start was accepted, or when the session has none).
pub pin: Option<ProgressionPin>,
}
pub fn to_json<T: Serialize>(message: &T) -> Result<Vec<u8>> {
@@ -167,16 +203,19 @@ pub fn from_json<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
}
impl PortableSessionStarted {
pub fn new(session_id: SessionId, character_id: CharacterId, server_id: &str, base_canonical_revision: u64, baseline_generation: u32, b0: &PortableCharacter) -> Result<Self> {
pub fn new(session_id: SessionId, character_id: CharacterId, server_id: &str, base_canonical_revision: u64, baseline_generation: u32, b0: &PortableCharacter, progression: Option<SessionProgression>) -> Result<Self> {
if let Some(p) = &progression {
p.validate()?;
}
let b0 = Envelope::seal(b0)?;
Ok(Self { protocol_version: PROTOCOL_VERSION, session_id, character_id, server_id: server_id.to_string(), base_canonical_revision, baseline_generation, content_hash: b0.content_hash.clone(), b0 })
Ok(Self { protocol_version: PROTOCOL_VERSION, session_id, character_id, server_id: server_id.to_string(), base_canonical_revision, baseline_generation, content_hash: b0.content_hash.clone(), b0, progression })
}
}
impl PortableCheckpoint {
pub fn new(session_id: SessionId, character_id: CharacterId, server_id: &str, base_canonical_revision: u64, sequence: u64, final_checkpoint: bool, b1: &PortableCharacter) -> Result<Self> {
pub fn new(session_id: SessionId, character_id: CharacterId, server_id: &str, base_canonical_revision: u64, sequence: u64, final_checkpoint: bool, b1: &PortableCharacter, pin: Option<ProgressionPin>) -> Result<Self> {
let realm_snapshot = Envelope::seal(b1)?;
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 })
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, pin })
}
}
@@ -398,7 +398,7 @@ fn messages_for_the_wrong_character_session_or_realm_and_malformed_ones_change_n
("a snapshot of another character", {
let mut other = geared_level_eighty();
other.character_id = other_character;
to_json(&PortableCheckpoint::new(session, id, SERVER, 10, 1, false, &other).unwrap()).unwrap()
to_json(&PortableCheckpoint::new(session, id, SERVER, 10, 1, false, &other, None).unwrap()).unwrap()
}),
("a snapshot that does not match its hash", tamper(&good, |v| {
let payload = v["realm_snapshot"]["payload"].as_str().unwrap().to_string();
@@ -456,7 +456,7 @@ fn checkpoints_out_of_order_or_with_reused_sequences_are_refused_safely() {
let reused = tamper(&two, |v| {
let mut m = geared_level_eighty();
m.progression.money += 123;
let other = PortableCheckpoint::new(session, id, SERVER, 10, 2, false, &m).unwrap();
let other = PortableCheckpoint::new(session, id, SERVER, 10, 2, false, &m, None).unwrap();
v["realm_snapshot"] = serde_json::to_value(&other.realm_snapshot).unwrap();
v["content_hash"] = other.content_hash.into();
});
+2 -1
View File
@@ -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"), include_str!("migrations/006_collections.sql"), include_str!("migrations/007_capabilities.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"), include_str!("migrations/007_capabilities.sql"), include_str!("migrations/008_projection.sql")];
pub const DEFAULT_HISTORY_KEEP: u32 = 20;
pub const MAX_HISTORY_KEEP: u32 = 1_000;
@@ -1042,6 +1042,7 @@ fn validate_observations(server_id: &str, observations: &[ItemObservation]) -> R
mod host;
mod profile;
mod projection;
mod journal;
mod owner;
mod sync;
+49 -11
View File
@@ -8,6 +8,7 @@ use rusqlite::{params, OptionalExtension};
use super::*;
use crate::portable::ids::{PortablePetId, SessionId};
use crate::portable::projection::ProgressionPin;
use crate::portable::session::protocol::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -44,6 +45,11 @@ pub struct HostSession {
pub acked_sequence: u64,
pub owned_items: Vec<PortableItemId>,
pub owned_pets: Vec<PortablePetId>,
/// The progression this session runs under (set when `B0` was taken; carried over to the next session).
pub pin: Option<ProgressionPin>,
/// The realm's progression profile changed under this session: its last checkpoint was taken under the old pin and the working copy
/// must be projected again before the realm is armed for this (next) session.
pub reproject: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -67,15 +73,16 @@ pub enum AckEffect {
}
fn read_host_session(conn: &Connection, session: SessionId) -> Result<Option<HostSession>> {
type Raw = (String, String, Option<i64>, i64, i64, String, i64, Option<i64>, i64, String, String);
type Raw = (String, String, Option<i64>, i64, i64, String, i64, Option<i64>, i64, String, String, Option<String>, i64);
let raw: Option<Raw> = conn
.query_row(
"SELECT character_id, server_id, local_guid, base_revision, generation, state, next_sequence, pending_sequence, acked_sequence, owned_items, owned_pets FROM host_session WHERE session_id = ?1",
"SELECT character_id, server_id, local_guid, base_revision, generation, state, next_sequence, pending_sequence, acked_sequence, owned_items, owned_pets, pin, reproject FROM host_session WHERE session_id = ?1",
[session.to_string()],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?, r.get(10)?)),
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?, r.get(10)?, r.get(11)?, r.get(12)?)),
)
.optional()?;
let Some((character, server_id, guid, base, generation, state, next, pending, acked, items, pets)) = raw else { return Ok(None) };
let Some((character, server_id, guid, base, generation, state, next, pending, acked, items, pets, pin, reproject)) = raw else { return Ok(None) };
let pin: Option<ProgressionPin> = pin.map(|j| serde_json::from_str(&j).map_err(|e| PortableError::CorruptSnapshot(format!("a stored session pin is not valid: {e}")))).transpose()?;
Ok(Some(HostSession {
session_id: session,
character_id: character.parse()?,
@@ -89,17 +96,20 @@ fn read_host_session(conn: &Connection, session: SessionId) -> Result<Option<Hos
acked_sequence: acked as u64,
owned_items: serde_json::from_str(&items)?,
owned_pets: serde_json::from_str(&pets)?,
pin,
reproject: reproject != 0,
}))
}
fn insert_host_session(tx: &Transaction<'_>, session: SessionId, id: CharacterId, server_id: &str, guid: Option<u32>, base: u64, generation: u32, model: &PortableCharacter) -> Result<()> {
#[allow(clippy::too_many_arguments)]
fn insert_host_session(tx: &Transaction<'_>, session: SessionId, id: CharacterId, server_id: &str, guid: Option<u32>, base: u64, generation: u32, model: &PortableCharacter, pin: Option<&ProgressionPin>, reproject: bool) -> Result<()> {
let items: Vec<PortableItemId> = model.items.iter().map(|i| i.id).collect();
let pets: Vec<PortablePetId> = model.pets.iter().map(|p| p.id).collect();
let at = now();
tx.execute(
"INSERT INTO host_session(session_id, character_id, server_id, local_guid, base_revision, generation, state, next_sequence, acked_sequence, owned_items, owned_pets, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'armed', 1, 0, ?7, ?8, ?9, ?9)",
params![session.to_string(), id.to_string(), server_id, guid, base as i64, generation, serde_json::to_string(&items)?, serde_json::to_string(&pets)?, at],
"INSERT INTO host_session(session_id, character_id, server_id, local_guid, base_revision, generation, state, next_sequence, acked_sequence, owned_items, owned_pets, pin, reproject, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'armed', 1, 0, ?7, ?8, ?10, ?11, ?9, ?9)",
params![session.to_string(), id.to_string(), server_id, guid, base as i64, generation, serde_json::to_string(&items)?, serde_json::to_string(&pets)?, at, pin.map(serde_json::to_string).transpose()?, reproject as i64],
)?;
Ok(())
}
@@ -176,7 +186,7 @@ impl Store {
if let Some(existing) = read_host_session(&tx, offer.session_id)? {
return Ok(existing);
}
insert_host_session(&tx, offer.session_id, offer.character_id, &offer.server_id, None, offer.canonical_revision, 1, model)?;
insert_host_session(&tx, offer.session_id, offer.character_id, &offer.server_id, None, offer.canonical_revision, 1, model, None, false)?;
tx.commit()?;
Ok(read_host_session(&self.conn, offer.session_id)?.expect("just inserted"))
}
@@ -226,7 +236,8 @@ impl Store {
capture_baseline_in_tx(&tx, s.character_id, &s.server_id, &BaselineInput { b0, items, pets })?;
let bytes = to_json(msg)?;
tx.execute("INSERT INTO host_outbox(session_id, sequence, kind, message, state, created_at) VALUES (?1, 0, 'started', ?2, 'pending', ?3)", params![session.to_string(), bytes, now()])?;
tx.execute("UPDATE host_session SET state = 'open', generation = ?2, updated_at = ?3 WHERE session_id = ?1", params![session.to_string(), msg.baseline_generation, now()])?;
let pin = msg.progression.as_ref().map(|p| serde_json::to_string(&p.pin)).transpose()?;
tx.execute("UPDATE host_session SET state = 'open', generation = ?2, pin = ?4, updated_at = ?3 WHERE session_id = ?1", params![session.to_string(), msg.baseline_generation, now(), pin])?;
tx.commit()?;
Ok(())
}
@@ -239,6 +250,9 @@ impl Store {
if s.state != HostState::Open || s.pending_sequence != Some(msg.sequence) {
return Err(PortableError::Invalid("this checkpoint was not reserved".into()));
}
if msg.pin != s.pin {
return Err(PortableError::ProgressionChanged("the checkpoint is not under the pin the session started under".into()));
}
let baseline = read_open_baseline(&tx, s.character_id, &s.server_id)?.ok_or(PortableError::NoBaseline)?;
let (c0_items, b0_items): (std::collections::HashSet<_>, std::collections::HashSet<_>) = (baseline.c0.items.iter().map(|i| i.id).collect(), baseline.b0.items.iter().map(|i| i.id).collect());
let (c0_pets, b0_pets): (std::collections::HashSet<_>, std::collections::HashSet<_>) = (baseline.c0.pets.iter().map(|p| p.id).collect(), baseline.b0.pets.iter().map(|p| p.id).collect());
@@ -259,6 +273,23 @@ impl Store {
Ok(())
}
/// The realm's progression profile changed under this session: when its final checkpoint is acknowledged, the next session must not be
/// armed before the working copy is projected again.
pub fn host_mark_reproject(&mut self, session: SessionId) -> Result<()> {
let n = self.conn.execute("UPDATE host_session SET reproject = 1, updated_at = ?2 WHERE session_id = ?1 AND state <> 'closed'", params![session.to_string(), now()])?;
if n == 0 {
return Err(PortableError::Invalid(format!("session {session} is not live")));
}
Ok(())
}
/// The working copy was projected again under the new profile: the session may be armed.
pub fn host_clear_reproject(&mut self, session: SessionId, pin: Option<&ProgressionPin>) -> Result<()> {
let json = pin.map(serde_json::to_string).transpose()?;
self.conn.execute("UPDATE host_session SET reproject = 0, pin = ?3, updated_at = ?2 WHERE session_id = ?1", params![session.to_string(), now(), json])?;
Ok(())
}
/// The bytes of one queued message, acknowledged or not.
pub fn host_message(&self, session: SessionId, sequence: u64) -> Result<Option<Vec<u8>>> {
Ok(self.conn.query_row("SELECT message FROM host_outbox WHERE session_id = ?1 AND sequence = ?2", params![session.to_string(), sequence as i64], |r| r.get(0)).optional()?)
@@ -292,6 +323,9 @@ impl Store {
Some(_) => {}
}
let at = now();
if ack.outcome.accepted() && ack.pin != s.pin {
return Err(PortableError::ProgressionChanged("the acknowledgement is under another progression profile than the session".into()));
}
if !ack.outcome.accepted() {
tx.execute("UPDATE host_outbox SET state = 'acked' WHERE session_id = ?1 AND sequence = ?2", params![ack.session_id.to_string(), ack.sequence as i64])?;
if matches!(ack.outcome, AckOutcome::StaleSession) {
@@ -325,7 +359,11 @@ impl Store {
set_synced_in_tx(&tx, s.character_id, &s.server_id, &encoded)?;
tx.execute("UPDATE realm_baseline SET state = 'closed', updated_at = ?3 WHERE character_id = ?1 AND server_id = ?2 AND state = 'open'", params![s.character_id.to_string(), s.server_id, at])?;
tx.execute("UPDATE host_session SET state = 'closed', updated_at = ?2 WHERE session_id = ?1", params![ack.session_id.to_string(), at])?;
insert_host_session(&tx, next.session_id, s.character_id, &s.server_id, s.local_guid, next.canonical_revision, s.generation + 1, &model)?;
insert_host_session(&tx, next.session_id, s.character_id, &s.server_id, s.local_guid, next.canonical_revision, s.generation + 1, &model, s.pin.as_ref(), s.reproject)?;
tx.execute(
"UPDATE realm_projection SET canonical_revision = ?3, context = json_set(context, '$.canonical_revision', ?3), updated_at = ?4 WHERE character_id = ?1 AND server_id = ?2",
params![s.character_id.to_string(), s.server_id, next.canonical_revision as i64, at],
)?;
tx.commit()?;
Ok(AckEffect::Finished { next_session: next.session_id, next_revision: next.canonical_revision })
}
+45 -12
View File
@@ -8,7 +8,8 @@ use rusqlite::{params, OptionalExtension};
use super::*;
use crate::portable::ids::SessionId;
use crate::portable::merge::{merge3, Mode};
use crate::portable::merge::{merge3_with, MergeProjection, Mode};
use crate::portable::projection::ProgressionPin;
use crate::portable::session::protocol::*;
struct OwnerRow {
@@ -24,18 +25,26 @@ struct OwnerRow {
b0_payload: Option<Vec<u8>>,
head_revision: u64,
last_sequence: u64,
progression: Option<SessionProgression>,
}
impl OwnerRow {
fn pin(&self) -> Option<ProgressionPin> {
self.progression.as_ref().map(|p| p.pin.clone())
}
}
fn read_owner_row(conn: &Connection, session: SessionId) -> Result<Option<OwnerRow>> {
type Raw = (String, String, String, i64, Vec<u8>, Vec<u8>, Option<i64>, Option<Vec<u8>>, Option<Vec<u8>>, i64, i64);
type Raw = (String, String, String, i64, Vec<u8>, Vec<u8>, Option<i64>, Option<Vec<u8>>, Option<Vec<u8>>, i64, i64, Option<String>);
let raw: Option<Raw> = conn
.query_row(
"SELECT character_id, server_id, state, c0_revision, c0_hash, c0_payload, baseline_generation, b0_hash, b0_payload, head_revision, last_sequence FROM owner_session WHERE session_id = ?1",
"SELECT character_id, server_id, state, c0_revision, c0_hash, c0_payload, baseline_generation, b0_hash, b0_payload, head_revision, last_sequence, progression FROM owner_session WHERE session_id = ?1",
[session.to_string()],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?, r.get(10)?)),
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?, r.get(10)?, r.get(11)?)),
)
.optional()?;
let Some((character, server_id, state, c0_revision, c0_hash, c0_payload, generation, b0_hash, b0_payload, head, last)) = raw else { return Ok(None) };
let Some((character, server_id, state, c0_revision, c0_hash, c0_payload, generation, b0_hash, b0_payload, head, last, progression)) = raw else { return Ok(None) };
let progression: Option<SessionProgression> = progression.map(|j| serde_json::from_str(&j).map_err(|e| PortableError::CorruptSnapshot(format!("a stored session progression is not valid: {e}")))).transpose()?;
Ok(Some(OwnerRow {
session_id: session,
character_id: character.parse()?,
@@ -49,6 +58,7 @@ fn read_owner_row(conn: &Connection, session: SessionId) -> Result<Option<OwnerR
b0_payload,
head_revision: head as u64,
last_sequence: last as u64,
progression,
}))
}
@@ -57,7 +67,7 @@ fn head_hash(conn: &Connection, id: CharacterId, revision: u64) -> Result<[u8; 3
}
fn ack(session: SessionId, sequence: u64, outcome: AckOutcome, revision: u64, hash: [u8; 32]) -> OwnerAck {
OwnerAck { protocol_version: PROTOCOL_VERSION, session_id: session, sequence, outcome, canonical_revision: revision, canonical_hash: hex::encode(hash), owned_items: vec![], owned_pets: vec![], canonical: None, next_session: None }
OwnerAck { protocol_version: PROTOCOL_VERSION, session_id: session, sequence, outcome, canonical_revision: revision, canonical_hash: hex::encode(hash), owned_items: vec![], owned_pets: vec![], canonical: None, next_session: None, pin: None }
}
fn owned_ids(model: &PortableCharacter) -> (Vec<PortableItemId>, Vec<crate::portable::ids::PortablePetId>) {
@@ -135,8 +145,10 @@ impl Store {
};
match row.state.as_str() {
"open" => {
return Ok(if row.b0_hash == Some(b0_hash) && row.generation == Some(msg.baseline_generation) {
ack(msg.session_id, 0, AckOutcome::Duplicate, row.head_revision, current_hash)
return Ok(if row.b0_hash == Some(b0_hash) && row.generation == Some(msg.baseline_generation) && row.progression == msg.progression {
let mut a = ack(msg.session_id, 0, AckOutcome::Duplicate, row.head_revision, current_hash);
a.pin = row.pin();
a
} else {
reject("this session already has a different baseline")
})
@@ -152,12 +164,27 @@ impl Store {
if b0.character_id != row.character_id || b0.ruleset != c0.ruleset || b0.content_namespace != c0.content_namespace {
return Ok(reject("the baseline is another character or ruleset"));
}
if let Some(p) = &msg.progression {
if let Err(e) = p.validate() {
return Ok(reject(&format!("the progression of the session is not valid: {e}")));
}
if let Some(ctx) = &p.projection {
if ctx.canonical_level != c0.progression.level as u32 || ctx.canonical_revision != row.c0_revision {
return Ok(reject("the projection was made for another canonical level or revision than this session's"));
}
} else if p.pin.projected {
return Ok(reject("a projected session must carry its projection"));
}
}
let progression_json = msg.progression.as_ref().map(serde_json::to_string).transpose()?;
tx.execute(
"UPDATE owner_session SET state = 'open', baseline_generation = ?2, b0_hash = ?3, b0_payload = ?4, updated_at = ?5 WHERE session_id = ?1",
params![msg.session_id.to_string(), msg.baseline_generation, b0_hash.as_slice(), msg.b0.bytes()?, now()],
"UPDATE owner_session SET state = 'open', baseline_generation = ?2, b0_hash = ?3, b0_payload = ?4, progression = ?6, updated_at = ?5 WHERE session_id = ?1",
params![msg.session_id.to_string(), msg.baseline_generation, b0_hash.as_slice(), msg.b0.bytes()?, now(), progression_json],
)?;
tx.commit()?;
Ok(ack(msg.session_id, 0, AckOutcome::Applied, row.head_revision, current_hash))
let mut a = ack(msg.session_id, 0, AckOutcome::Applied, row.head_revision, current_hash);
a.pin = msg.progression.as_ref().map(|p| p.pin.clone());
Ok(a)
}
/// Apply one checkpoint of the realm: `merge3(C0, B0, B1)`.
@@ -196,6 +223,7 @@ impl Store {
}
let revision = revision as u64;
let mut a = ack(msg.session_id, msg.sequence, AckOutcome::Duplicate, revision, head_hash(&tx, row.character_id, revision)?);
a.pin = row.pin();
if let Ok((model, _)) = read_snapshot_row(&tx, row.character_id, revision) {
(a.owned_items, a.owned_pets) = owned_ids(&model);
if was_final == 1 {
@@ -215,6 +243,9 @@ impl Store {
if msg.sequence < row.last_sequence {
return Ok(outcome(AckOutcome::StaleSequence));
}
if msg.pin != row.pin() {
return Ok(reject("the checkpoint was taken under another progression profile than the session started under"));
}
if record.revision != row.head_revision {
tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![msg.session_id.to_string(), now()])?;
tx.commit()?;
@@ -229,7 +260,8 @@ impl Store {
if b1.character_id != row.character_id || b1.ruleset != c0.ruleset || b1.content_namespace != c0.content_namespace {
return Ok(reject("the snapshot is another character or ruleset"));
}
let merged = match merge3(&c0, &b0, &b1, Mode::Lenient) {
let projection = row.progression.as_ref().and_then(|p| p.projection.as_ref()).map(|ctx| MergeProjection { freeze_progression: true, blocked: ctx.hold.blocked_settings.iter().cloned().collect() });
let merged = match merge3_with(&c0, &b0, &b1, Mode::Lenient, projection.as_ref()) {
Ok(m) => m.model,
Err(e) => return Ok(reject(&format!("the checkpoint cannot be merged: {e}"))),
};
@@ -251,6 +283,7 @@ impl Store {
};
let mut a = ack(msg.session_id, msg.sequence, AckOutcome::Applied, revision, encoded.content_hash);
a.pin = row.pin();
(a.owned_items, a.owned_pets) = owned_ids(&merged);
let mut next_id = None;
if msg.final_checkpoint {
+12 -2
View File
@@ -13,12 +13,20 @@ use crate::portable::capabilities::RealmCapabilities;
pub struct ProfileChange {
pub previous: Option<String>,
pub current: String,
/// The progression signature the realm had before, and now (`None`: not known).
pub previous_progression: Option<String>,
pub current_progression: Option<String>,
}
impl ProfileChange {
pub fn changed(&self) -> bool {
self.previous.as_deref() != Some(self.current.as_str())
}
/// The realm's level cap or progression rules are not the ones it had when it was last looked at.
pub fn progression_changed(&self) -> bool {
self.previous.is_some() && self.previous_progression != self.current_progression
}
}
/// A character whose synchronised profile is not the realm's current one.
@@ -40,14 +48,16 @@ impl Store {
caps.validate()?;
let json = String::from_utf8(caps.to_json()?).map_err(|_| PortableError::Invalid("the profile is not UTF-8".into()))?;
let tx = self.write_tx()?;
let previous: Option<String> = tx.query_row("SELECT content_profile_hash FROM realm_profile WHERE server_id = ?1", [server_id], |r| r.get(0)).optional()?;
let previous_row: Option<(String, String)> = tx.query_row("SELECT content_profile_hash, profile FROM realm_profile WHERE server_id = ?1", [server_id], |r| Ok((r.get(0)?, r.get(1)?))).optional()?;
let previous = previous_row.as_ref().map(|(h, _)| h.clone());
let previous_progression = previous_row.and_then(|(_, json)| RealmCapabilities::from_json(json.as_bytes()).ok()).and_then(|c| c.progression).map(|p| p.progression_signature);
tx.execute(
"INSERT INTO realm_profile(server_id, content_profile_hash, profile, source, fetched_at) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(server_id) DO UPDATE SET content_profile_hash = excluded.content_profile_hash, profile = excluded.profile, source = excluded.source, fetched_at = excluded.fetched_at",
params![server_id, caps.content_profile_hash, json, source, now()],
)?;
tx.commit()?;
Ok(ProfileChange { previous, current: caps.content_profile_hash.clone() })
Ok(ProfileChange { previous, current: caps.content_profile_hash.clone(), previous_progression, current_progression: caps.progression.as_ref().map(|p| p.progression_signature.clone()) })
}
pub fn realm_profile(&self, server_id: &str) -> Result<Option<RealmCapabilities>> {
@@ -0,0 +1,83 @@
//! What the Manager remembers of level-cap projections (Phase 8): the context of each projected character on each realm, and the
//! progression signature each character was last synchronised under.
use rusqlite::{params, OptionalExtension};
use super::*;
use crate::portable::projection::{ProgressionPin, ProjectionContext};
impl Store {
/// Remember (replace) the projection of a character on a realm. The character must be bound to the realm.
pub fn set_projection_context(&mut self, id: CharacterId, server_id: &str, ctx: &ProjectionContext) -> Result<()> {
check_server_id(server_id)?;
ctx.validate()?;
let json = serde_json::to_string(ctx)?;
let tx = self.write_tx()?;
let bound: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM character_server_mapping WHERE character_id = ?1 AND server_id = ?2)", params![id.to_string(), server_id], |r| r.get(0))?;
if !bound {
return Err(PortableError::Invalid(format!("character {id} is not on realm {server_id}")));
}
tx.execute(
"INSERT INTO realm_projection(character_id, server_id, canonical_level, projected_level, canonical_revision, content_profile_hash, progression_signature, policy_version, context, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
ON CONFLICT(character_id, server_id) DO UPDATE SET canonical_level = excluded.canonical_level, projected_level = excluded.projected_level, canonical_revision = excluded.canonical_revision,
content_profile_hash = excluded.content_profile_hash, progression_signature = excluded.progression_signature, policy_version = excluded.policy_version, context = excluded.context, updated_at = excluded.updated_at",
params![id.to_string(), server_id, ctx.canonical_level, ctx.projected_level, ctx.canonical_revision as i64, ctx.content_profile_hash, ctx.progression_signature, ctx.projection_policy_version, json, now()],
)?;
tx.execute("UPDATE character_server_mapping SET progression_pin = ?3 WHERE character_id = ?1 AND server_id = ?2", params![id.to_string(), server_id, serde_json::to_string(&ctx.pin())?])?;
tx.commit()?;
Ok(())
}
pub fn projection_context(&self, id: CharacterId, server_id: &str) -> Result<Option<ProjectionContext>> {
let json: Option<String> = self.conn.query_row("SELECT context FROM realm_projection WHERE character_id = ?1 AND server_id = ?2", params![id.to_string(), server_id], |r| r.get(0)).optional()?;
json.map(|j| {
let ctx: ProjectionContext = serde_json::from_str(&j).map_err(|e| PortableError::CorruptSnapshot(format!("a stored projection context is not valid: {e}")))?;
ctx.validate()?;
Ok(ctx)
})
.transpose()
}
/// The character is not projected on this realm (any more).
pub fn clear_projection_context(&mut self, id: CharacterId, server_id: &str) -> Result<bool> {
Ok(self.conn.execute("DELETE FROM realm_projection WHERE character_id = ?1 AND server_id = ?2", params![id.to_string(), server_id])? > 0)
}
/// The working copy was brought to a newer canonical revision (an acknowledged checkpoint): the decision stays, the revision moves.
pub fn advance_projection_revision(&mut self, id: CharacterId, server_id: &str, revision: u64) -> Result<()> {
self.conn.execute(
"UPDATE realm_projection SET canonical_revision = ?3, context = json_set(context, '$.canonical_revision', ?3), updated_at = ?4 WHERE character_id = ?1 AND server_id = ?2",
params![id.to_string(), server_id, revision as i64, now()],
)?;
Ok(())
}
/// Record the pin a character was synchronised under on a realm (`None`: unknown, a realm that did not report its progression).
pub fn set_mapping_pin(&mut self, id: CharacterId, server_id: &str, pin: Option<&ProgressionPin>) -> Result<()> {
if let Some(p) = pin {
p.validate()?;
}
let json = pin.map(serde_json::to_string).transpose()?;
let n = self.conn.execute("UPDATE character_server_mapping SET progression_pin = ?3 WHERE character_id = ?1 AND server_id = ?2", params![id.to_string(), server_id, json])?;
if n == 0 {
return Err(PortableError::Invalid(format!("character {id} is not on realm {server_id}")));
}
Ok(())
}
/// The pin a character on a realm was last synchronised under (projected or native).
pub fn character_pin(&self, id: CharacterId, server_id: &str) -> Result<Option<ProgressionPin>> {
let json: Option<String> = self
.conn
.query_row("SELECT progression_pin FROM character_server_mapping WHERE character_id = ?1 AND server_id = ?2", params![id.to_string(), server_id], |r| r.get::<_, Option<String>>(0))
.optional()?
.flatten();
json.map(|j| {
let pin: ProgressionPin = serde_json::from_str(&j).map_err(|e| PortableError::CorruptSnapshot(format!("a stored progression pin is not valid: {e}")))?;
pin.validate()?;
Ok(pin)
})
.transpose()
}
}
+12
View File
@@ -118,6 +118,18 @@ impl Ra {
}
}
/// `portable project <job_id>`: the core decides what a projection of the job file's character at its level cap holds, and writes the
/// decision to the job's result file. Only the id travels.
pub fn portable_project(&mut self, job_id: crate::portable::ImportId) -> Result<String> {
let out = self.command(&format!("portable project {job_id}"))?;
let first = out.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("").to_string();
if first.starts_with("OK") {
Ok(first)
} else {
Err(Error::Invalid(format!("The server did not answer the projection query: {first}")))
}
}
/// `portable capabilities`: the realm's core says what it is and what portable features it has. An older core does not know the command.
pub fn portable_capabilities(&mut self) -> Result<crate::portable::capabilities::CoreReport> {
let out = self.command("portable capabilities")?;