aboutsummaryrefslogtreecommitdiffstats
path: root/src/remake/switch.rs
blob: 91591c2c2fe403a828ac6dbd47162d895513d56a (plain)
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Switching this node to a committed epoch.
//!
//! The worker watches the remake records. When a remake of the local epoch is
//! committed, it waits one keepalive interval (so the commit record can reach peers
//! through ordinary sync before this node stops syncing the old epoch), then:
//!
//! 1. clones the live document under the read lock;
//! 2. without any lock: takes the coordinator's prebuilt snapshot or builds it, checks
//!    that its hash is the committed epoch ID, and replays the clone's changes since
//!    the base into it;
//! 3. under the write lock: replays whatever arrived since the clone, swaps document and
//!    epoch, and hands back the old document;
//! 4. archives the old document according to the policy.
//!
//! The write lock is held only for step 3, which is proportional to the changes made
//! during steps 1-2.
//!
//! A node whose build doesn't match the committed epoch, or that never saw the commit,
//! rejoins the new epoch from peers instead (`catchup`).

use std::time::Duration;

use tokio::sync::broadcast;
use tracing::{error, info, warn};

use super::Host;
use super::catchup;
use super::content;
use super::coordinator;
use super::delta::{self, ReplayStats};
use super::kind::Translator;
use super::local::LocalStatus;
use super::quarantine;
use super::records::{self, EpochRecord, Record};
use super::snapshot;
use super::vote;
use crate::document::meta::{self, REMAKES};
use crate::document::replica::Epoch;
use crate::document::store;
use crate::document::store::paths_related;
use crate::document::{ActorId, ChangeHash, Document};
use crate::locks::MutexExt;

/// How often the worker looks while something waits on time: a remake of this epoch
/// open or committed, a rejoin, a catch-up, a member on another epoch. Otherwise it
/// waits for what wakes it (`look_again`).
const TICK: Duration = Duration::from_secs(1);

pub(crate) async fn run_worker<H: Host>(host: H) {
    info!("Starting remake worker");

    let records_dir = meta::path(&[REMAKES]);
    let mut changes = host.subscribe_changes();
    let mut changes_closed = false;
    // What it finds at its start: a remake committed while the node was down.
    let mut again = Some(tokio::time::Instant::now());

    loop {
        // React promptly to changes of the records, and to a peer saying another
        // epoch; a timer only while something waits on time (`look_again`).
        // A vote waiting for its random delay (`vote`) is cast when due, not at the next
        // tick: with a short voting period, a second can make it too late.
        let vote_wait = host.remake().vote_wait(host.now_millis());
        let should_check = tokio::select! {
            () = tokio::time::sleep_until(again.unwrap_or_else(tokio::time::Instant::now)), if again.is_some() => true,
            // A peer said another epoch: looked at within `TICK`, not at once, as its
            // message is still being taken, and others saying the same are on their way.
            () = host.remake_woken() => {
                let soon = tokio::time::Instant::now() + TICK;
                again = Some(again.map_or(soon, |at| at.min(soon)));
                false
            }
            _ = tokio::time::sleep(vote_wait.unwrap_or_default()), if vote_wait.is_some() => true,
            received = changes.recv(), if !changes_closed => match received {
                Ok(set) => set.paths.iter().any(|path| paths_related(path, &records_dir)),
                Err(broadcast::error::RecvError::Lagged(_)) => true,
                Err(broadcast::error::RecvError::Closed) => {
                    warn!("Change events closed; remake worker continues on its timer only");
                    changes_closed = true;
                    again.is_none()
                }
            }
        };

        if should_check {
            check(&host).await;
            let wait = look_again(&host).await;
            let wait = if changes_closed {
                wait.or(Some(TICK))
            } else {
                wait
            };
            again = wait.map(|wait| tokio::time::Instant::now() + wait);
        }
    }
}

/// How long until the worker looks again by itself (`check`); none while nothing it
/// does waits on time, and what changes that wakes it: a change of the remake
/// records, a peer saying another epoch than this node's (`Host::remake_woken`), a
/// vote due.
async fn look_again<H: Host>(host: &H) -> Option<Duration> {
    #[cfg(feature = "federation")]
    if host.holding().of_a_set() {
        return None;
    }
    let remake = host.remake();
    // A rejoin runs against its timeout, a catch-up against its retries.
    if remake.is_rejoining() || remake.fetching_snapshot() || remake.catch_up().is_some() {
        return Some(TICK);
    }
    let local = host.current_epoch();
    let (now, grace) = (host.now_millis(), host.dormant_after().as_millis() as u64);
    // A remake of this epoch still voted on, to expire, or committed and to switch to.
    let local_record = EpochRecord::from(local);
    let open = host
        .read_doc(move |doc| {
            records::load_all(doc).iter().any(|(_, record)| {
                record.proposal.from_epoch == local_record && record.phase(now, grace).is_open()
            })
        })
        .await;
    if open {
        return Some(TICK);
    }
    // A member on another epoch than ours, not an earlier one: to be followed once
    // enough say so, or once it is ready (`catchup::check`).
    let elsewhere = host.peer_summaries().await.into_iter().any(|peer| {
        peer.active
            && peer.member
            && peer
                .epoch
                .is_some_and(|epoch| epoch != local && epoch.generation >= local.generation)
    });
    if elsewhere {
        return Some(TICK);
    }
    // What it keeps for a time: archived documents, a remake's content.
    remake.next_expiry(now)
}

async fn check<H: Host>(host: &H) {
    // A set of events has no epochs: the document a node holds beside one stays as
    // it is, whatever epoch its peers of both kinds say.
    #[cfg(feature = "federation")]
    if host.holding().of_a_set() {
        return;
    }
    let local = host.current_epoch();
    host.remake()
        .prune_archive(local.generation, host.now_millis());

    // While rejoining, the document is being filled from peers: its records are not
    // complete enough to act on.
    if host.remake().is_rejoining() {
        return catchup::check(host).await;
    }

    vote::cast(host).await;

    let all = host.read_doc(records::load_all).await;
    content::prune(
        host,
        &all,
        host.now_millis(),
        host.dormant_after().as_millis() as u64,
    );
    let local_record = EpochRecord::from(local);
    if host.is_node_ready().await {
        coordinator::resume(host, &local_record, &all);
    }

    let committed: Vec<(String, Record)> = all
        .into_iter()
        .filter(|(_, record)| {
            record.proposal.from_epoch == local_record && record.committed_epoch().is_some()
        })
        .collect();

    let (id, record) = match committed.as_slice() {
        // Nothing committed here; maybe peers moved on without us.
        [] => return catchup::check(host).await,
        [(id, record)] if record.contested => {
            error!(remake = %id, "Decisions on this remake disagree; not switching on my own");
            return catchup::check(host).await;
        }
        [(id, record)] => (id.clone(), record.clone()),
        // Holding a store, of two epochs decided for one, the lower ID (`docs/store.md`,
        // Remakes).
        #[cfg(feature = "federation")]
        several
            if host
                .read_doc(|doc| {
                    matches!(
                        crate::access::policy::of(doc),
                        crate::access::policy::Policy::Store(_)
                    )
                })
                .await =>
        {
            let lowest = several
                .iter()
                .filter(|(_, record)| !record.contested)
                .min_by_key(|(_, record)| record.committed_epoch().map(|epoch| epoch.id));
            let Some((id, record)) = lowest else {
                error!("Decisions on these remakes disagree; not switching on my own");
                return catchup::check(host).await;
            };
            (id.clone(), record.clone())
        }
        several => {
            // Majority voting prevents this; never guess which one is right. Peers
            // that did switch can still be followed.
            let ids: Vec<&str> = several.iter().map(|(id, _)| id.as_str()).collect();
            error!(remakes = ?ids, "Several remakes committed for this epoch; not switching on my own");
            return catchup::check(host).await;
        }
    };

    if host
        .remake()
        .status(&id)
        .is_some_and(|status| status.error.is_some())
    {
        // Our own switch failed (reported in the remake's status): fetch the epoch
        // from a peer that made it.
        return catchup::check(host).await;
    }

    // As proposed, or one keepalive interval.
    let switch_delay = record
        .proposal
        .switch_delay_ms
        .map(Duration::from_millis)
        .unwrap_or(host.dormant_after() / 4);
    if host.remake().first_seen(&id).elapsed() < switch_delay {
        return;
    }

    match switch(host, &id, &record).await {
        Ok((stats, quarantine)) => {
            host.remake().set_status(
                &id,
                LocalStatus {
                    switched_at: Some(host.now_millis()),
                    replayed_paths: Some(stats.replayed),
                    failed_paths: Some(stats.failed),
                    quarantine,
                    error: None,
                },
            );
        }
        Err(reason) => {
            error!(remake = %id, reason = %reason, "Epoch switch failed");
            host.remake().set_status(
                &id,
                LocalStatus {
                    error: Some(reason),
                    ..LocalStatus::default()
                },
            );
        }
    }
}

/// Returns the replay numbers and the quarantine entry for writes the remake had no
/// place for, if any.
async fn switch<H: Host>(
    host: &H,
    id: &str,
    record: &Record,
) -> Result<(ReplayStats, Option<String>), String> {
    let (Some(expected), Some(mut request)) =
        (record.committed_epoch(), record.snapshot_request(id))
    else {
        return Err("unreadable remake record".to_owned());
    };
    // Voters fetched it already; a node that didn't vote fetches it now. Without it the
    // switch fails, and the node rejoins (downloading the snapshot instead).
    if let Some(reference) = &record.proposal.content {
        request.content = Some(content::ensure(host, reference).await?);
    }
    #[cfg(feature = "federation")]
    {
        request.held = super::snapshot::Held(Some(host.holding()));
    }
    let translator = request
        .translator()
        .ok_or_else(|| format!("unknown remake kind {:?}", request.kind))?;
    // A strict remake of a swarm strict already, committed by a majority of members
    // anyway: not followed (`vote::strict_taken`, `catchup`).
    if request.kind == "strict"
        && host
            .read_doc(|doc| crate::access::policy::of(doc).strict())
            .await
    {
        return Err(
            "a strict remake of a swarm strict already: its registry changes by its users' signatures; not followed"
                .to_owned(),
        );
    }
    let late_translator = translator.clone();
    let superseded = host.superseded();
    let previous = request.previous;
    let base = request.base_heads.clone();
    let retention = record.proposal.policy.archive_retention.clone();
    // Only the coordinator carries the record into the new epoch: one writer, so the
    // nodes don't all write the same path concurrently right after switching (a merge
    // conflict, plus one change per node to sync). The epoch metadata in the snapshot
    // keeps the essentials on every node anyway, and names the coordinator: the rules
    // take the record from it only (`access::rules`).
    let carry_record = record.proposal.coordinator == host.node_id();
    let record_path = records::record_path(id, "");

    info!(remake = %id, from = %previous, to = %expected, "Switching epoch");

    // 1. Consistent copy, under the read lock only.
    let copy = host.read_doc(|doc| doc.clone()).await;
    let prebuilt = host
        .remake()
        .take_prebuilt(id)
        .filter(|snapshot| snapshot.epoch == expected);

    let actor = ActorId::random();
    host.own_writers().add(actor.clone());
    let new_actor = actor.clone();
    let node = host.node_id();

    // 2. Build (or reuse), verify and replay without holding any lock.
    let (new_doc, copy_heads, mut stats) = tokio::task::spawn_blocking(
        move || -> Result<(Document, Vec<ChangeHash>, ReplayStats), String> {
            let copy = copy;
            let snapshot = match prebuilt {
                Some(snapshot) => snapshot,
                None => snapshot::build(&copy, &request.params())
                    .map_err(|error| format!("snapshot build failed: {error}"))?,
            };
            if snapshot.epoch != expected {
                return Err(format!(
                    "built snapshot {} does not match the committed epoch {expected}",
                    snapshot.epoch
                ));
            }

            // A fresh actor: this node's writes in the new epoch, made by it.
            let mut doc = snapshot.doc.with_actor(actor);
            crate::document::replica::authored(&mut doc, &node);

            let heads = copy.get_heads();

            // Keep this remake's record visible in the new epoch, for its history.
            if carry_record {
                let mut transaction = doc.transaction();
                if let Err(error) = store::copy_path(&copy, &mut transaction, &record_path) {
                    warn!(error = %error, "Could not carry the remake record into the new epoch");
                }
                transaction.commit();
            }

            // Each write at the time it was made, so later replays judge by it.
            let stats = delta::replay_newest(
                &copy,
                &base,
                &heads,
                &mut doc,
                expected,
                &node,
                &translator,
                superseded,
            );
            Ok((doc, heads, stats))
        },
    )
    .await
    .map_err(|error| format!("switch task failed: {error}"))??;

    // 3. Swap, replaying what arrived since the copy.
    let (old, late) = swap_in(host, expected, new_doc, copy_heads, late_translator).await?;
    stats.absorb(late);
    host.own_writers().reset(new_actor);

    // 4. Writes the remake had no place for wait for an operator (the old document
    //    holds them); the old document is kept as configured either way.
    let quarantine = quarantine::add(
        host,
        previous,
        expected,
        &old,
        std::mem::take(&mut stats.quarantined),
    );
    // Holding a store: what the old document holds that the new one's store takes goes
    // again (`Holding::left`).
    #[cfg(feature = "federation")]
    let old = {
        let holding = host.holding();
        host.read_doc(move |doc| {
            holding.left(doc, &old);
            old
        })
        .await
    };
    host.remake().archive(
        previous,
        old,
        retention,
        expected.generation,
        host.now_millis(),
    );

    info!(
        remake = %id,
        epoch = %expected,
        replayed = stats.replayed,
        failed = stats.failed,
        dropped = stats.dropped,
        superseded = stats.superseded,
        quarantine = ?quarantine,
        "Switched to the new epoch"
    );
    Ok((stats, quarantine))
}

/// Under the write lock: replays into `new_doc` whatever the live document received
/// since `copy_heads` (the heads of the copy `new_doc` was prepared from), then swaps it
/// in as `target`. Returns the old document.
pub(super) async fn swap_in<H: Host>(
    host: &H,
    target: Epoch,
    new_doc: Document,
    copy_heads: Vec<ChangeHash>,
    translator: Translator,
) -> Result<(Document, ReplayStats), String> {
    let superseded = host.superseded();
    let node = host.node_id();
    // The closure runs on the blocking pool; its replay numbers come back through this.
    let late_stats = std::sync::Arc::new(std::sync::Mutex::new(ReplayStats::default()));
    let late_out = std::sync::Arc::clone(&late_stats);
    let old = host
        .switch_epoch(target, move |live| {
            // Only one worker switches, but be sure the copy still describes the live document.
            if !crate::document::changes::missing(live, &copy_heads).is_empty() {
                return Err("the document was replaced while preparing the switch".to_owned());
            }
            let mut new_doc = new_doc;
            let live_heads = live.get_heads();
            let late = delta::replay_newest(
                live,
                &copy_heads,
                &live_heads,
                &mut new_doc,
                target,
                &node,
                &translator,
                superseded,
            );
            if late.replayed + late.failed > 0 {
                info!(
                    replayed = late.replayed,
                    failed = late.failed,
                    "Replayed late changes"
                );
            }
            *late_out.lock_or_recover() = late;
            Ok(new_doc)
        })
        .await?;
    let late = std::mem::take(&mut *late_stats.lock_or_recover());
    Ok((old, late))
}