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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
use core::{fmt, iter::DoubleEndedIterator};
use buggy::Bug;
use tracing::error;
use crate::{
Address, CmdId, Command, GraphId, LocatedAddress, PeerCache, Perspective as _, Policy,
PolicyError, PolicyStore, Sink, Storage as _, StorageError, StorageProvider, TraversalBuffer,
policy::ActionPlacement, storage::Spill,
};
pub(crate) mod braiding; // exposed for `buffers.rs` (StrandHeap)
mod buffers;
pub(crate) mod convergence_map; // exposed for `buffers.rs` (ConvergenceStorage)
mod session;
mod transaction;
pub(crate) use buffers::BraidBuffer;
pub use buffers::RuntimeBuffers;
pub use self::{session::Session, transaction::Transaction};
/// An error returned by the runtime client.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ClientError {
#[error("no such parent: {0}")]
NoSuchParent(CmdId),
#[error("policy error: {0}")]
PolicyError(PolicyError),
#[error("storage error: {0}")]
StorageError(#[from] StorageError),
#[error("init error")]
InitError,
#[error("not authorized")]
NotAuthorized,
#[error("could not deserialize session command")]
SessionDeserialize,
/// Attempted to braid two parallel finalize commands together.
///
/// Policy must be designed such that two parallel finalize commands are never produced.
///
/// Currently, this is practically an unrecoverable error. You must wipe all graphs containing
/// the "bad" finalize command and resync from the "good" clients. Otherwise, your network will
/// split into two separate graph states which can never successfully sync.
#[error("found parallel finalize commands during braid")]
ParallelFinalize,
#[error("concurrent transaction usage")]
ConcurrentTransaction,
#[error(transparent)]
Bug(#[from] Bug),
}
impl From<PolicyError> for ClientError {
fn from(error: PolicyError) -> Self {
match error {
PolicyError::Check => Self::NotAuthorized,
_ => Self::PolicyError(error),
}
}
}
/// Keeps track of client graph state.
///
/// - `PS` should be an implementation of [`PolicyStore`].
/// - `SP` should be an implementation of [`StorageProvider`].
pub struct ClientState<PS, SP> {
policy_store: PS,
provider: SP,
}
// Manual Debug impl to exclude `buffers` (large, not useful in debug output).
impl<PS: fmt::Debug, SP: fmt::Debug> fmt::Debug for ClientState<PS, SP> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientState")
.field("policy_store", &self.policy_store)
.field("provider", &self.provider)
.finish_non_exhaustive()
}
}
impl<PS, SP> ClientState<PS, SP> {
/// Creates a `ClientState`.
pub const fn new(policy_store: PS, provider: SP) -> Self {
Self {
policy_store,
provider,
}
}
/// Provide access to the [`StorageProvider`].
pub fn provider(&mut self) -> &mut SP {
&mut self.provider
}
}
impl<PS, SP> ClientState<PS, SP>
where
PS: PolicyStore,
SP: StorageProvider,
{
/// Create a new graph (AKA Team). This graph will start with the initial policy
/// provided which must be compatible with the policy store PS. The `payload` is the initial
/// init message that will bootstrap the graph facts. Effects produced when processing
/// the payload are emitted to the sink.
pub fn new_graph(
&mut self,
policy_data: &[u8],
action: <PS::Policy as Policy>::Action<'_>,
sink: &mut impl Sink<PS::Effect>,
) -> Result<GraphId, ClientError> {
let policy_id = self.policy_store.add_policy(policy_data)?;
let policy = self.policy_store.get_policy(policy_id)?;
let mut perspective = self.provider.new_perspective(policy_id);
sink.begin();
policy
.call_action(action, &mut perspective, sink, ActionPlacement::OnGraph)
.inspect_err(|_| sink.rollback())?;
sink.commit();
let (graph_id, _) = self.provider.new_storage(perspective)?;
Ok(graph_id)
}
/// Remove a graph (AKA Team). The graph commands will be removed from storage.
pub fn remove_graph(&mut self, graph_id: GraphId) -> Result<(), ClientError> {
self.provider.remove_storage(graph_id)?;
Ok(())
}
/// Commit the [`Transaction`] to storage, after merging all temporary heads.
///
/// `make_spill` is called whenever an internal braid or convergence map
/// needs byte-addressable overflow storage. It is typically
/// `|| LibcSpill::new(&dir)` for production callers or `MemSpill::new`
/// for tests.
///
/// Returns whether any new commands were added.
pub fn commit<F, MS>(
&mut self,
trx: Transaction<SP, PS>,
sink: &mut impl Sink<PS::Effect>,
buffers: &mut RuntimeBuffers<SP::Segment>,
make_spill: MS,
) -> Result<bool, ClientError>
where
F: Spill,
MS: Fn() -> Result<F, StorageError>,
{
trx.commit::<F, MS>(
&mut self.provider,
&mut self.policy_store,
sink,
buffers,
&make_spill,
)
}
/// Add commands to the transaction, writing the results to
/// `sink`.
///
/// `make_spill` is called whenever an internal braid or convergence map
/// needs byte-addressable overflow storage. See [`Self::commit`].
///
/// Returns the number of commands that were added.
pub fn add_commands<F, MS>(
&mut self,
trx: &mut Transaction<SP, PS>,
sink: &mut impl Sink<PS::Effect>,
commands: &[impl Command],
buffers: &mut RuntimeBuffers<SP::Segment>,
make_spill: MS,
) -> Result<usize, ClientError>
where
F: Spill,
MS: Fn() -> Result<F, StorageError>,
{
trx.add_commands::<F, MS>(
commands,
&mut self.provider,
&mut self.policy_store,
sink,
buffers,
&make_spill,
)
}
pub fn update_heads<I>(
&mut self,
graph_id: GraphId,
addrs: I,
request_heads: &mut PeerCache,
buffer: &mut TraversalBuffer,
) -> Result<(), ClientError>
where
I: IntoIterator<Item = Address>,
I::IntoIter: DoubleEndedIterator,
{
let storage = self.provider.get_storage(graph_id)?;
// Commands in sync messages are always ancestor-first (lower max_cut to higher max_cut).
// Reverse the iterator to process highest max_cut first, which allows us to skip ancestors
// since if a command is an ancestor of one we've already added, we don't need to add it.
for address in addrs.into_iter().rev() {
if let Some(loc) = storage.get_location(address, buffer)? {
request_heads.add_command(
storage,
LocatedAddress {
id: address.id,
segment: loc.segment,
max_cut: address.max_cut,
},
buffer,
)?;
} else {
error!(
"UPDATE_HEADS: Address {:?} does NOT exist in storage, skipping (should not happen if command was successfully added)",
address
);
}
}
Ok(())
}
/// Returns the address of the head of the graph.
pub fn head_address(&mut self, graph_id: GraphId) -> Result<Address, ClientError> {
let storage = self.provider.get_storage(graph_id)?;
let address = storage.get_head_address()?;
Ok(address)
}
/// Performs an `action`, writing the results to `sink`.
pub fn action(
&mut self,
graph_id: GraphId,
sink: &mut impl Sink<PS::Effect>,
action: <PS::Policy as Policy>::Action<'_>,
) -> Result<(), ClientError> {
let storage = self.provider.get_storage(graph_id)?;
let head = storage.get_head()?;
let mut perspective = storage.get_linear_perspective(head)?;
let policy_id = perspective.policy();
let policy = self.policy_store.get_policy(policy_id)?;
// No need to checkpoint the perspective since it is only for this action.
// Must checkpoint once we add action transactions.
sink.begin();
match policy.call_action(action, &mut perspective, sink, ActionPlacement::OnGraph) {
Ok(()) => {
let segment = storage.write(perspective)?;
storage.commit(segment)?;
sink.commit();
Ok(())
}
Err(e) => {
sink.rollback();
Err(e.into())
}
}
}
}
impl<PS, SP> ClientState<PS, SP>
where
SP: StorageProvider,
{
/// Create a new [`Transaction`], used to receive [`Command`]s when syncing.
pub fn transaction(&mut self, graph_id: GraphId) -> Transaction<SP, PS> {
Transaction::new(graph_id)
}
/// Create an ephemeral [`Session`] associated with this client.
pub fn session(&mut self, graph_id: GraphId) -> Result<Session<SP, PS>, ClientError> {
Session::new(&mut self.provider, graph_id)
}
/// Checks if a command with the given address exists in the specified graph.
///
/// Returns `true` if the command exists, `false` if it doesn't exist or the graph doesn't exist.
/// This method is used to determine if we need to sync when a hello message is received.
pub fn command_exists(
&mut self,
graph_id: GraphId,
address: Address,
buffer: &mut TraversalBuffer,
) -> bool {
let Ok(storage) = self.provider.get_storage(graph_id) else {
// Graph doesn't exist
return false;
};
storage
.get_location(address, buffer)
.unwrap_or(None)
.is_some()
}
}