Skip to main content

tembra_core/
state.rs

1use crate::Reason;
2use crate::{
3    Code, Error, Host, Id, Result, Version,
4    host::{conflict, gone},
5};
6
7/// Immutable metadata. Values remain owned by their language adapter.
8#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
9pub struct Snapshot {
10    pub value: Id,
11    pub revision: u64,
12    pub version: Version,
13}
14
15/// A private candidate tied to the exact invocation, object, revision and issuing host.
16pub struct PreparedState {
17    host: Host,
18    call: Id,
19    object: Id,
20    expected: u64,
21    value: Id,
22}
23
24impl Host {
25    /// Attach initial state once while the object is loading.
26    pub fn initialize_state(&self, object: Id, value: Id, version: Version) -> Result<Snapshot> {
27        if value == 0 || !crate::valid_version(version) {
28            return Err(Error::invalid(
29                Reason::State,
30                "value and state version must be nonzero",
31            ));
32        }
33        let mut inner = self.inner.borrow_mut();
34        let object = inner
35            .objects
36            .get_mut(&object)
37            .ok_or_else(|| gone(Reason::Object))?;
38        if object.phase != crate::Status::Loading || object.state.is_some() {
39            return Err(conflict(Reason::StateInitialized));
40        }
41        let snapshot = Snapshot {
42            value,
43            version,
44            revision: 0,
45        };
46        object.state = Some(snapshot);
47        Ok(snapshot)
48    }
49
50    /// Read state metadata without decoding the adapter-owned value.
51    pub fn snapshot(&self, object: Id) -> Result<Snapshot> {
52        self.inner
53            .borrow()
54            .objects
55            .get(&object)
56            .and_then(|o| o.state)
57            .ok_or_else(|| gone(Reason::State))
58    }
59
60    /// Captures the revision before adapter code prepares and validates a candidate.
61    pub fn prepare_state(
62        &self,
63        call: Id,
64        object: Id,
65        expected: u64,
66        value: Id,
67    ) -> Result<PreparedState> {
68        self.check_state_call(call, object)?;
69        let snapshot = self.snapshot(object)?;
70        if snapshot.revision != expected {
71            return Err(conflict(Reason::StateRevision));
72        }
73        if value == 0 {
74            return Err(Error::invalid(
75                Reason::Value,
76                "zero is not a value identity",
77            ));
78        }
79        Ok(PreparedState {
80            host: self.clone(),
81            call,
82            object,
83            expected,
84            value,
85        })
86    }
87
88    /// Check and adopt a candidate against its expected revision.
89    pub fn adopt_state(&self, call: Id, object: Id, expected: u64, value: Id) -> Result<Snapshot> {
90        self.prepare_state(call, object, expected, value)?.adopt()
91    }
92
93    /// Require a live owner call at the object's accepted version.
94    fn check_state_call(&self, call: Id, object: Id) -> Result<()> {
95        let inner = self.inner.borrow();
96        let call = inner.calls.get(&call).ok_or_else(|| gone(Reason::Call))?;
97        inner.check_root(call.root)?;
98        if call.object != object {
99            return Err(Error::new(
100                Code::Forbidden,
101                Reason::StateOwner,
102                "only an entered owner invocation may mutate state",
103            ));
104        }
105        let record = inner
106            .objects
107            .get(&object)
108            .ok_or_else(|| gone(Reason::Object))?;
109        if call.code_version < record.min_version {
110            return Err(conflict(Reason::UpgradeConflict));
111        }
112        Ok(())
113    }
114}
115
116impl PreparedState {
117    /// Atomically adopts a previously adapter-validated value.
118    ///
119    /// # Guarantees
120    /// Failure does not change the snapshot or emit a notification. Validation belongs to the
121    /// orb; this method checks ownership, scope, execution version and optimistic revision.
122    pub fn adopt(self) -> Result<Snapshot> {
123        self.host.check_state_call(self.call, self.object)?;
124        let mut inner = self.host.inner.borrow_mut();
125        let object = inner
126            .objects
127            .get_mut(&self.object)
128            .ok_or_else(|| gone(Reason::Object))?;
129        let previous = object.state.ok_or_else(|| gone(Reason::State))?;
130        if previous.revision != self.expected {
131            return Err(conflict(Reason::StateRevision));
132        }
133        if previous.value == self.value {
134            return Ok(previous);
135        }
136        let revision = previous
137            .revision
138            .checked_add(1)
139            .ok_or_else(|| conflict(Reason::RevisionExhausted))?;
140        let snapshot = Snapshot {
141            value: self.value,
142            revision,
143            version: previous.version,
144        };
145        object.state = Some(snapshot);
146        inner
147            .actions
148            .push_back(crate::Action::DropValue(previous.value));
149        inner.actions.push_back(crate::Action::StateChanged {
150            object: self.object,
151            revision,
152        });
153        Ok(snapshot)
154    }
155}