1use crate::{Context, Error, Host, Result, core};
2use serde::Serialize;
3use std::{marker::PhantomData, rc::Rc};
4
5type Validator<T> = Rc<dyn Fn(&T) -> Result<()>>;
6
7pub struct State<T> {
9 host: Host,
10 object: core::Id,
11 validate: Validator<T>,
12 marker: PhantomData<T>,
13}
14impl<T> Clone for State<T> {
15 fn clone(&self) -> Self {
17 Self {
18 host: self.host.clone(),
19 object: self.object,
20 validate: self.validate.clone(),
21 marker: PhantomData,
22 }
23 }
24}
25impl<T: Serialize + 'static> State<T> {
26 pub(crate) fn new(
28 host: Host,
29 object: core::Id,
30 initial: T,
31 version: u32,
32 validate: impl Fn(&T) -> Result<()> + 'static,
33 ) -> Result<Self> {
34 validate(&initial)?;
35 if let Ok(snapshot) = host.kernel().snapshot(object) {
36 if snapshot.version != version {
37 return Err(Error::invalid(
38 core::Reason::StateVersion,
39 "native state version changes require a migration adapter",
40 ));
41 }
42 validate(host.value::<T>(snapshot.value)?.as_ref())?;
43 } else {
44 let value = host.store(initial, true)?;
45 if let Err(error) = host.kernel().initialize_state(object, value, version) {
46 host.drop_value(value);
47 return Err(error);
48 }
49 }
50 Ok(Self {
51 host,
52 object,
53 validate: Rc::new(validate),
54 marker: PhantomData,
55 })
56 }
57
58 pub fn value(&self) -> Result<Rc<T>> {
60 self.host
61 .value(self.host.kernel().snapshot(self.object)?.value)
62 }
63
64 pub fn snapshot(&self) -> Result<core::Snapshot> {
66 self.host.kernel().snapshot(self.object)
67 }
68
69 pub(crate) fn validate_current(&self) -> Result<()> {
71 (self.validate)(self.value()?.as_ref())
72 }
73
74 pub fn update(&self, context: &Context, change: impl FnOnce(&T) -> Result<T>) -> Result<Rc<T>> {
76 let call = context.invocation()?;
77 if !self.host.same(&context.host) || call.object != self.object {
78 return Err(Error::new(
79 core::Code::Forbidden,
80 "state_owner",
81 "context does not own this state",
82 ));
83 }
84 context.check()?;
85 let previous = self.host.kernel().snapshot(self.object)?;
86 let current = self.host.value::<T>(previous.value)?;
87 let candidate = change(¤t)?;
88 (self.validate)(&candidate)?;
89 context.check()?;
90 let value = self.host.store(candidate, true)?;
91 if let Err(error) =
92 self.host
93 .kernel()
94 .adopt_state(call.id, self.object, previous.revision, value)
95 {
96 self.host.drop_value(value);
97 return Err(error);
98 }
99 let result = self.host.value(value);
100 self.host.publish_state(self.object);
101 self.host.flush();
102 result
103 }
104}
105
106impl<T: 'static> State<T> {
107 pub fn readable(&self) -> crate::Readable<T> {
109 crate::Readable::new(self.host.clone(), self.object, None)
110 }
111}