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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
|
//! Passing an Automerge document on to a peer (`docs/document.md`, Passing on): what goes
//! to it next (`next`), by the session with it (`sync::SyncSession`), as the wire
//! carries it now. Whom a node syncs with and when, along whose tree, and what is counted
//! of it, is the swarm's (`swarm::sync`).
use tokio::time::Instant;
use tracing::{debug, info};
use super::ChangeHash;
use super::replica::Replica;
use super::signatures;
use super::sync::{Received, SyncSession};
use crate::swarm::throughput::SyncBytes;
use crate::transport::{DeltaSignatures, DeltaSpec, SyncBody, SyncPayload};
/// What goes to a peer next.
pub(crate) struct Outgoing {
pub(crate) body: SyncBody,
/// The sender takes it as delivered (`SyncSession::assume_delivered`): it had
/// everything the peer had, and awaits no answer.
pub(crate) delivered: bool,
/// The signatures of the changes it carries, packed (`signatures::pack`).
pub(crate) signatures: Vec<u8>,
/// Where taken as delivered, the bytes it carries of the document.
pub(crate) delivered_bytes: Option<usize>,
}
/// How large a message to a peer may be before what it would carry is offered as a blob
/// (`threshold`), and what lowered that, to say so: the throughput measured to the peer
/// (`rate`), a message that failed whole to it lately (`failed`).
pub(crate) struct Whole {
pub(crate) threshold: usize,
pub(crate) rate: Option<f64>,
pub(crate) failed: Option<usize>,
}
/// The next message for the peer `session` is with, of the document `replica` holds, if
/// there is anything to say: changes as they are, where it passes a writer's on along
/// its tree (`pushing`) to a peer level with it; else a sync message; or, where that is
/// larger than `whole` allows, an offer of the changes as a blob, whose signatures `keep`
/// keeps to serve. Under the locks the message's epoch is read under.
pub(crate) fn next(
session: &mut SyncSession,
replica: &Replica,
pushing: bool,
whole: &Whole,
bytes_before: SyncBytes,
keep: impl FnOnce(Vec<u8>) -> DeltaSignatures,
) -> Option<Outgoing> {
let delta_threshold = whole.threshold;
// To a peer that had nothing we lack, with nothing awaited: taken as delivered
// (`SyncSession::assume_delivered`).
let level = session.reply.is_none() && session.have_all_theirs(&replica.doc);
// The same delta as last time, the peer's heads and ours unchanged (it didn't answer
// in time): offered again without generating the message it replaces, which may take
// seconds when large.
let again = session.offer_again(
&replica.doc,
replica.heads(),
delta_threshold,
Instant::now(),
);
// Along a tree, taken as delivered: the changes as they are (`SyncSession::push`).
// Only those too small to deflate: larger ones go as a message, deflated
// (`compress`).
let pushed = (level && pushing && again.is_none())
.then(|| {
session.push(
&replica.doc,
delta_threshold.min(crate::compress::WORTH_FROM - 1),
)
})
.flatten();
// A message's signatures, where finding them was part of deciding it.
let mut carried_signatures = None;
let mut body = if let Some((heads, changes)) = pushed {
Some(SyncBody::Changes {
heads,
changes: changes
.into_iter()
.map(serde_bytes::ByteBuf::from)
.collect(),
})
} else if let Some(from) = again {
let spec = DeltaSpec::new(from, replica.heads().to_vec());
debug!(
from = spec.from.len(),
to = spec.to.len(),
"Offering the same changes as a blob again"
);
Some(SyncBody::Delta(spec))
} else {
let message = session.generate(&replica.doc, Instant::now(), bytes_before);
message.and_then(|payload| {
// Its signatures count towards its size: a whole document pulled carries one
// per writer.
let signatures = replica
.signatures
.for_changes(&replica.doc, session.carried());
if payload.0.len() + signatures.len() * signatures::PACKED <= delta_threshold {
carried_signatures = Some(signatures);
return Some(SyncBody::Message(payload));
}
// Too large for one message: all or nothing, and on a slow link within the
// transport's delivery limit. The peer fetches it in chunks.
let from = session.withdraw_for_delta(&replica.doc, Instant::now());
let spec = DeltaSpec::new(from, replica.heads().to_vec());
if spec.to.iter().all(|head| spec.from.contains(head)) {
// It has our heads: nothing to offer (Automerge thought it lacked what it
// has, as from a view of it that was old).
debug!(
message_bytes = payload.0.len(),
"Sync message too large, but the peer has our heads; not sent"
);
session.nothing_to_send();
return None;
}
// And why it is too large here: the threshold, lowered by the throughput
// measured to the peer or a message that failed whole to it lately
// (`Blobs::delta_threshold_for`).
info!(
message_bytes = payload.0.len(),
threshold = delta_threshold,
throughput = ?whole.rate.map(|rate| rate as u64),
failed_whole = ?whole.failed,
from = spec.from.len(),
to = spec.to.len(),
"Sync message too large; offering the changes as a blob"
);
session.offered(&spec.from, &spec.to, payload.0.len());
Some(SyncBody::Delta(spec))
})
};
let delivered = level && matches!(body, Some(SyncBody::Message(_) | SyncBody::Changes { .. }));
let mut delivered_bytes = None;
if delivered {
session.assume_delivered(replica.heads());
delivered_bytes = match &body {
Some(SyncBody::Message(payload)) => Some(payload.0.len()),
Some(SyncBody::Changes { changes, .. }) => {
Some(changes.iter().map(|change| change.len()).sum())
}
_ => None,
};
}
// With changes, the signatures of those it carries: they go where changes go, along
// the trees, so a peer that got these changes elsewhere got the signatures with
// them; and changes sent again go vouched for as the first time. A delta's, of each
// writer with changes in it its latest, go as a blob of their own, from this node
// (`keep`): the peer fetches them with the delta. A message carrying no changes takes
// none.
let signatures = match &mut body {
Some(SyncBody::Delta(spec)) => {
let signatures = replica.signatures.for_delta(&replica.doc, &spec.from);
spec.signatures = (!signatures.is_empty()).then(|| keep(signatures::pack(&signatures)));
Vec::new()
}
Some(_) => carried_signatures.unwrap_or_else(|| {
replica
.signatures
.for_changes(&replica.doc, session.carried())
}),
None => Vec::new(),
};
Some(Outgoing {
body: body?,
delivered,
signatures: signatures::pack(&signatures),
delivered_bytes,
})
}
/// `body` with a large sync message deflated, if it shrinks (`compress`): and from how
/// many bytes to how many. Not under a lock: it takes a while.
pub(crate) fn deflated(body: SyncBody) -> (SyncBody, Option<(usize, usize)>) {
match body {
SyncBody::Message(payload) => match crate::compress::deflate(&payload.0) {
Some(deflated) => {
let sizes = (payload.0.len(), deflated.len());
(
SyncBody::Deflated(SyncPayload(deflated.into())),
Some(sizes),
)
}
None => (SyncBody::Message(payload), None),
},
other => (other, None),
}
}
/// How many bytes of the document `body` carries itself: none for an offer of a blob.
pub(crate) fn carried_bytes(body: &SyncBody) -> Option<usize> {
match body {
SyncBody::Message(payload) | SyncBody::Deflated(payload) => Some(payload.0.len()),
SyncBody::Changes { changes, .. } => Some(changes.iter().map(|change| change.len()).sum()),
SyncBody::Delta(_) => None,
}
}
/// A message as it came, read: its bytes of the document, and what it says. Not under a
/// lock: inflating and decoding a large one takes a while. No larger than any sender
/// should send, deflated or not.
pub(crate) fn received(
message: SyncPayload,
deflated: bool,
pushed: Option<(Vec<ChangeHash>, Vec<Vec<u8>>, usize)>,
) -> anyhow::Result<(usize, Received)> {
use anyhow::Context;
let message = if deflated {
SyncPayload(
crate::compress::inflate(&message.0, crate::swarm::blob::MAX_SYNC_MESSAGE)
.context("Inflating a sync message")?
.into(),
)
} else {
message
};
Ok(match pushed {
Some((heads, changes, len)) => (
len,
Received::pushed(heads, changes).context("Pushed changes that don't decode")?,
),
None => (message.0.len(), super::sync::decode(&message)?),
})
}
/// What taking a message did (`take`).
pub(crate) struct Taken {
/// The document's heads before, and those the peer said it has.
pub(crate) heads_before: Vec<ChangeHash>,
pub(crate) said: Vec<ChangeHash>,
/// It carried changes, all of them refused before (`screen::Outcome`).
pub(crate) refused_again: bool,
/// The changes that broke a rule, of those refused.
pub(crate) roots: Vec<ChangeHash>,
/// Changes it carried forged under another node's actor.
pub(crate) forged: usize,
/// The fresh actor this node writes as from now on, where it carried a change of
/// this node's actor that the node didn't make.
pub(crate) fresh_actor: Option<super::ActorId>,
}
/// Takes `message`, from the peer `session` is with, into the document `replica` holds:
/// the changes it carries judged first, each as the policy it was written under has it
/// (`screen`), whether this document has one yet or not, and vouched for by the
/// `signatures` it came with too, where that policy requires them; then the rest of it
/// given to the session. What it did so far, where that failed too: a fresh actor is the
/// node's from then on.
pub(crate) fn take(
session: &mut SyncSession,
replica: &mut Replica,
mut message: Received,
mut signatures: Vec<(ChangeHash, [u8; 64])>,
screening: &std::sync::Mutex<super::screen::Screening>,
) -> (Taken, anyhow::Result<()>) {
use crate::locks::MutexExt;
let heads_before = replica.heads().to_vec();
let said = message.heads().to_vec();
let (epoch, epoch_seq) = (replica.epoch, replica.epoch_seq);
let mut outcome = super::screen::Outcome::default();
let result = replica.logged_signed(|doc, known, log| {
let result = (|| {
let bytes = message.take_changes();
known.offer(doc, std::mem::take(&mut signatures));
outcome = super::screen::apply_bytes(
doc,
epoch,
epoch_seq,
&bytes,
screening,
Some(&mut *known),
log,
)?;
session.lacks(screening.lock_or_recover().waiting.lacking(doc));
session.receive_logged(doc, message, log)
})();
(result, true)
});
let taken = Taken {
heads_before,
said,
refused_again: outcome.refused_again,
roots: outcome.roots,
forged: outcome.forged,
fresh_actor: outcome.fresh_actor,
};
(taken, result)
}
/// Where a document and the session with a peer stand once a message was taken
/// (`settle`).
pub(crate) struct Settled {
/// What was asked for again that the peer is known to have elsewhere
/// (`SyncSession::resend_if_needed`).
pub(crate) asked: (usize, usize),
/// How many heads the document has now, and whether they changed.
pub(crate) heads: usize,
pub(crate) changed: bool,
/// The message was taken as delivered, and the peer is behind: the answer brings it
/// what it lacks.
pub(crate) answering_behind: bool,
/// How many of the changes it brought are new to the session.
pub(crate) new: Option<usize>,
/// It carried changes and the heads stayed: whether what it brought waits for
/// predecessors (the peer's heads aren't the document's yet), or had come before.
pub(crate) waits: Option<bool>,
/// Whose the changes it brought are, whether any is nobody's, and when each was made.
pub(crate) authors: Vec<(String, Vec<ChangeHash>)>,
pub(crate) unauthored: bool,
pub(crate) times: Vec<i64>,
/// Where asked: whether the document holds all the peer said it has.
pub(crate) level: bool,
}
/// Settles the session with `peer` after a message was taken (`taken`): what the peer
/// still lacks asked for again, the signatures waiting for what came offered, and, where
/// the message was taken as `delivered`, whether an answer is due at all.
pub(crate) fn settle(
session: &mut SyncSession,
replica: &mut Replica,
peer: &str,
taken: &Taken,
carried: bool,
delivered: bool,
level: bool,
) -> Settled {
let heads_before = &taken.heads_before;
let asked = session.resend_if_needed(&replica.doc, peer, Instant::now());
replica.refresh_heads();
// The signatures waiting for what it brought (those it sent, offered before).
if replica.heads() != heads_before.as_slice() {
let replica = &mut *replica;
replica.signatures.offer(&replica.doc, Vec::new());
}
let heads_after = replica.heads().to_vec();
let mut answering_behind = false;
if delivered {
// Level with the sender now, which takes the message as delivered: nothing to
// answer (`SyncSession::answered_as_delivered`). Unless it is behind us: then the
// answer brings it what it lacks.
let behind = session.peer_behind(&replica.doc, &heads_after);
let answered = session.answered_as_delivered(&replica.doc, &heads_after);
answering_behind = behind && !answered;
}
let changed = heads_after != *heads_before;
// What it brought, walked once.
let since = changed.then(|| super::changes::since(&replica.doc, heads_before));
// They came from it: none goes back (`SyncSession::came_from_peer`).
let new = since
.as_ref()
.map(|since| session.these_came_from_peer(&since.hashes));
// Its heads not ours yet: what it brought waits for predecessors, which isn't having
// come twice.
let waits =
(carried && !changed).then(|| !super::changes::holds_all(&replica.doc, &taken.said));
let (authors, unauthored, times) = match since {
Some(since) => (since.authors, since.unauthored, since.times),
None => (Vec::new(), false, Vec::new()),
};
Settled {
asked,
heads: heads_after.len(),
changed,
answering_behind,
new,
waits,
authors,
unauthored,
times,
level: level && session.have_all_theirs(&replica.doc),
}
}
|