This repository has been archived by the owner on Feb 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 269
/
state.rs
273 lines (238 loc) · 7.89 KB
/
state.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
use crate::{
dht::pending_validations::ValidatingWorkflow,
nucleus::{actions::initialize::Initialization, HdkFnCall, HdkFnCallResult, ZomeFnCall},
};
use holochain_core_types::{dna::Dna, error::HolochainError};
use crate::state::StateWrapper;
use holochain_json_api::{
error::{JsonError, JsonResult},
json::JsonString,
};
use holochain_persistence_api::cas::content::{Address, AddressableContent, Content};
use im::{HashMap, HashSet};
use serde::{
de::{Error, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use std::{collections::VecDeque, convert::TryFrom, fmt};
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, DefaultJson)]
pub enum NucleusStatus {
New,
Initializing,
Initialized(Initialization),
InitializationFailed(String),
}
impl Default for NucleusStatus {
fn default() -> Self {
NucleusStatus::New
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PendingValidationKey {
pub address: Address,
pub workflow: ValidatingWorkflow,
}
impl Serialize for PendingValidationKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let workflow_string: String = self.workflow.to_owned().into();
serializer.serialize_str(&format!("{}__{}", self.address, workflow_string))
}
}
struct PendingValidationKeyStringVisitor;
impl<'de> Visitor<'de> for PendingValidationKeyStringVisitor {
type Value = PendingValidationKey;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a PendingValidtionKey in the format '<address>__<workflow>'")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
let parts: Vec<String> = value.split("__").map(|s| s.to_string()).collect();
let address = parts
.first()
.ok_or_else(|| Error::custom("No address found"))?
.to_owned();
let workflow = parts
.last()
.ok_or_else(|| Error::custom("No workflow found"))?
.to_owned();
Ok(PendingValidationKey::new(
address.into(),
ValidatingWorkflow::try_from(workflow).map_err(|e| Error::custom(e.to_string()))?,
))
}
}
impl<'de> Deserialize<'de> for PendingValidationKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(PendingValidationKeyStringVisitor)
}
}
impl PendingValidationKey {
pub fn new(address: Address, workflow: ValidatingWorkflow) -> Self {
PendingValidationKey { address, workflow }
}
}
/// The state-slice for the Nucleus.
/// Holds the dynamic parts of the DNA, i.e. zome calls and validation requests.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct NucleusState {
// Persisted fields:
pub status: NucleusStatus,
// Transient fields:
pub dna: Option<Dna>, //DNA is transient here because it is stored in the chain and gets
//read from there when loading an instance/chain.
pub queued_zome_calls: VecDeque<ZomeFnCall>,
pub running_zome_calls: HashSet<ZomeFnCall>,
pub hdk_function_calls: HashMap<ZomeFnCall, ZomeFnCallState>,
// @TODO eventually drop stale calls
// @see https://github.com/holochain/holochain-rust/issues/166
// @TODO should this use the standard ActionWrapper/ActionResponse format?
// @see https://github.com/holochain/holochain-rust/issues/196
pub zome_call_results: HashMap<ZomeFnCall, Result<JsonString, HolochainError>>,
}
impl NucleusState {
pub fn new() -> Self {
NucleusState {
dna: None,
status: NucleusStatus::New,
queued_zome_calls: VecDeque::new(),
running_zome_calls: HashSet::new(),
zome_call_results: HashMap::new(),
hdk_function_calls: HashMap::new(),
}
}
pub fn zome_call_result(
&self,
zome_call: &ZomeFnCall,
) -> Option<Result<JsonString, HolochainError>> {
self.zome_call_results.get(zome_call).cloned()
}
pub fn has_initialized(&self) -> bool {
match self.status {
NucleusStatus::Initialized(_) => true,
_ => false,
}
}
pub fn initialization(&self) -> Option<Initialization> {
match self.status {
NucleusStatus::Initialized(ref init) => Some(init.clone()),
_ => None,
}
}
pub fn has_initialization_failed(&self) -> bool {
match self.status {
NucleusStatus::InitializationFailed(_) => true,
_ => false,
}
}
// Getters
pub fn dna(&self) -> Option<Dna> {
self.dna.clone()
}
pub fn status(&self) -> NucleusStatus {
self.status.clone()
}
}
#[derive(Clone, Debug, Deserialize, Serialize, DefaultJson)]
pub struct NucleusStateSnapshot {
pub status: NucleusStatus,
}
impl From<&StateWrapper> for NucleusStateSnapshot {
fn from(state: &StateWrapper) -> Self {
NucleusStateSnapshot {
status: state.nucleus().status(),
}
}
}
impl From<NucleusStateSnapshot> for NucleusState {
fn from(snapshot: NucleusStateSnapshot) -> Self {
NucleusState {
dna: None,
status: snapshot.status,
queued_zome_calls: VecDeque::new(),
running_zome_calls: HashSet::new(),
zome_call_results: HashMap::new(),
hdk_function_calls: HashMap::new(),
}
}
}
pub static NUCLEUS_SNAPSHOT_ADDRESS: &str = "NucleusState";
impl AddressableContent for NucleusStateSnapshot {
fn address(&self) -> Address {
NUCLEUS_SNAPSHOT_ADDRESS.into()
}
fn content(&self) -> Content {
self.to_owned().into()
}
fn try_from_content(content: &Content) -> JsonResult<Self> {
Self::try_from(content.to_owned())
}
}
#[derive(Clone, Default, Debug, PartialEq, Serialize)]
pub struct ZomeFnCallState {
hdk_fn_invocations: Vec<(HdkFnCall, Option<HdkFnCallResult>)>,
}
impl ZomeFnCallState {
pub fn begin_hdk_call(&mut self, call: HdkFnCall) {
self.hdk_fn_invocations.push((call, None))
}
pub fn end_hdk_call(
&mut self,
call: HdkFnCall,
result: HdkFnCallResult,
) -> Result<(), HolochainError> {
if let Some((current_call, current_result)) = self.hdk_fn_invocations.pop() {
if call != current_call {
Err(HolochainError::new(
"HDK call other than the current call was ended.",
))
} else if current_result.is_some() {
Err(HolochainError::new(
"Ending and HDK which was already ended.",
))
} else {
self.hdk_fn_invocations.push((call, Some(result)));
Ok(())
}
} else {
Err(HolochainError::new(
"Attempted to end HDK call, but none was started!",
))
}
}
}
#[cfg(test)]
pub mod tests {
use super::{HdkFnCall, NucleusState, ZomeFnCallState};
use crate::nucleus::ribosome::api::ZomeApiFunction;
/// dummy nucleus state
pub fn test_nucleus_state() -> NucleusState {
NucleusState::new()
}
#[test]
fn test_zome_fn_call_state() {
let mut state = ZomeFnCallState::default();
let call1 = HdkFnCall {
function: ZomeApiFunction::Call,
parameters: "params1".into(),
};
let call2 = HdkFnCall {
function: ZomeApiFunction::Call,
parameters: "params2".into(),
};
state.begin_hdk_call(call1.clone());
state.end_hdk_call(call1, Ok("result".into())).unwrap();
state.begin_hdk_call(call2.clone());
state
.end_hdk_call(call2, Err("call failed for reasons".into()))
.unwrap();
assert_eq!(state.hdk_fn_invocations.len(), 2);
}
}