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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! Replication apply (D315 PR 3, ICR 0114): what a replica applies, taken from the primary's
//! feed with the primary's ids. Behind `__unstable-replication`, hidden: not part of the API.
use std::collections::HashSet;
use pigeonhole_engine::{CatalogEvent, FamilyId, TableId, WriteBatch};
use pigeonhole_format::Kind;
use crate::feed::StreamPosition;
use crate::{ChangeKind, Error, ErrorCode, FeedEvent, FeedToken, Pigeonhole, Result};
/// One event of a primary's feed, as a replica applies it ([`Feed::replicated`]): a commit's
/// changes with the primary's table and family ids, or a catalog change with its ids; the
/// feed's position before and after it, so the runs a replica applies chain; and the feed's
/// token right after it, to store with what it applied. Not part of the stable API.
///
/// [`Feed::replicated`]: crate::Feed::replicated
#[derive(Debug, Clone, PartialEq)]
pub struct ReplicatedEvent {
pub(crate) before: StreamPosition,
pub(crate) after: StreamPosition,
pub(crate) token: FeedToken,
pub(crate) body: Body,
}
/// What a [`ReplicatedEvent`] holds.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Body {
Commit {
seqno: u64,
ts: u64,
changes: Vec<ReplicatedChange>,
},
Catalog(CatalogEvent),
}
/// One change of a replicated commit, as the primary logged it.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ReplicatedChange {
pub(crate) table: TableId,
pub(crate) family: FamilyId,
pub(crate) kind: ChangeKind,
pub(crate) row: Vec<u8>,
pub(crate) qualifier: Vec<u8>,
pub(crate) ts: u64,
/// The stored value, its tag byte first; empty for deletes.
pub(crate) stored: Vec<u8>,
}
impl ReplicatedEvent {
pub(crate) fn new(
event: &FeedEvent,
(before, after): (StreamPosition, StreamPosition),
token: FeedToken,
) -> Self {
let body = match event {
FeedEvent::Commit(c) => Body::Commit {
seqno: c.seqno(),
ts: c.timestamp(),
changes: c
.changes()
.iter()
.map(|ch| {
let (table, family) = ch.ids();
ReplicatedChange {
table,
family,
kind: ch.kind(),
row: ch.row().to_vec(),
qualifier: ch.qualifier().to_vec(),
ts: ch.timestamp(),
stored: ch.stored().to_vec(),
}
})
.collect(),
},
FeedEvent::Catalog(change) => Body::Catalog(change.raw().clone()),
};
Self {
before,
after,
token,
body,
}
}
/// Whether it is a catalog change (applied with `apply_catalog`, between runs of commits).
pub fn is_catalog(&self) -> bool {
matches!(self.body, Body::Catalog(_))
}
/// The primary feed's token right after this event: what a replica stores with it.
pub fn token(&self) -> &FeedToken {
&self.token
}
/// The primary's commit seqno the feed stood at after this event: what a replica that
/// applied it has applied through (#1436's lag).
pub fn primary_seqno(&self) -> u64 {
self.after.seqno
}
/// The event's bytes, for a replica in another process (#1436: `phdb serve`'s
/// `Replication.Follow`): versioned, opaque to the transport. [`decode`](Self::decode)
/// reads them back.
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
out.push(EVENT_VERSION);
for v in [
self.before.seqno,
self.before.catalog,
self.after.seqno,
self.after.catalog,
] {
out.extend_from_slice(&v.to_le_bytes());
}
put_bytes(&mut out, self.token.as_bytes());
match &self.body {
Body::Commit { seqno, ts, changes } => {
out.push(0);
out.extend_from_slice(&seqno.to_le_bytes());
out.extend_from_slice(&ts.to_le_bytes());
out.extend_from_slice(&(changes.len() as u32).to_le_bytes());
for c in changes {
out.extend_from_slice(&c.table.0.to_le_bytes());
out.extend_from_slice(&c.family.0.to_le_bytes());
out.push(logged_kind(c.kind) as u8);
out.extend_from_slice(&c.ts.to_le_bytes());
put_bytes(&mut out, &c.row);
put_bytes(&mut out, &c.qualifier);
put_bytes(&mut out, &c.stored);
}
}
Body::Catalog(ev) => {
out.push(1);
for v in [ev.seqno_ceiling, ev.timestamp, ev.sequence] {
out.extend_from_slice(&v.to_le_bytes());
}
let mut edits = Vec::new();
for e in &ev.edits {
e.encode(&mut edits);
}
out.extend_from_slice(&(ev.edits.len() as u32).to_le_bytes());
put_bytes(&mut out, &edits);
out.extend_from_slice(&(ev.names.len() as u32).to_le_bytes());
for (table, name) in &ev.names {
out.extend_from_slice(&table.0.to_le_bytes());
put_bytes(&mut out, name.as_bytes());
}
}
}
out
}
/// An event [`encode`](Self::encode) wrote. `InvalidArgument` for anything else, or for a
/// newer encoding.
pub fn decode(bytes: &[u8]) -> Result<Self> {
let mut r = Reader(bytes);
if r.u8()? != EVENT_VERSION {
return Err(invalid("not a replicated event of this version".to_owned()));
}
let before = StreamPosition {
seqno: r.u64()?,
catalog: r.u64()?,
};
let after = StreamPosition {
seqno: r.u64()?,
catalog: r.u64()?,
};
let token = FeedToken::from_bytes(r.bytes()?);
let body = match r.u8()? {
0 => {
let (seqno, ts) = (r.u64()?, r.u64()?);
let n = r.u32()?;
let mut changes = Vec::with_capacity(n.min(1 << 16) as usize);
for _ in 0..n {
let table = TableId(r.u32()?);
let family = FamilyId(r.u32()?);
let kind = Kind::from_u8(r.u8()?)
.map_err(|_| invalid("a replicated change's kind".to_owned()))?;
let ts = r.u64()?;
changes.push(ReplicatedChange {
table,
family,
kind: ChangeKind::of(kind),
row: r.bytes()?.to_vec(),
qualifier: r.bytes()?.to_vec(),
ts,
stored: r.bytes()?.to_vec(),
});
}
Body::Commit { seqno, ts, changes }
}
1 => {
let mut ev = CatalogEvent::default();
ev.seqno_ceiling = r.u64()?;
ev.timestamp = r.u64()?;
ev.sequence = r.u64()?;
let n = r.u32()?;
let mut edits = r.bytes()?;
for _ in 0..n {
let (e, used) = pigeonhole_format::manifest::Edit::decode(edits)
.map_err(|_| invalid("a replicated catalog edit".to_owned()))?;
ev.edits.push(e);
edits = &edits[used..];
}
for _ in 0..r.u32()? {
let table = TableId(r.u32()?);
let name = std::str::from_utf8(r.bytes()?)
.map_err(|_| invalid("a replicated table name".to_owned()))?;
ev.names.push((table, name.to_owned()));
}
Body::Catalog(ev)
}
_ => return Err(invalid("a replicated event's body".to_owned())),
};
if !r.0.is_empty() {
return Err(invalid(
"trailing bytes after a replicated event".to_owned(),
));
}
Ok(Self {
before,
after,
token,
body,
})
}
}
/// [`ReplicatedEvent::encode`]'s version.
const EVENT_VERSION: u8 = 1;
fn put_bytes(out: &mut Vec<u8>, b: &[u8]) {
out.extend_from_slice(&(b.len() as u32).to_le_bytes());
out.extend_from_slice(b);
}
/// Reads [`ReplicatedEvent::encode`]'s fields.
struct Reader<'a>(&'a [u8]);
impl<'a> Reader<'a> {
fn take<const N: usize>(&mut self) -> Result<[u8; N]> {
let (head, rest) = self
.0
.split_first_chunk::<N>()
.ok_or_else(|| invalid("a truncated replicated event".to_owned()))?;
self.0 = rest;
Ok(*head)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take::<1>()?[0])
}
fn u32(&mut self) -> Result<u32> {
Ok(u32::from_le_bytes(self.take()?))
}
fn u64(&mut self) -> Result<u64> {
Ok(u64::from_le_bytes(self.take()?))
}
fn bytes(&mut self) -> Result<&'a [u8]> {
let n = self.u32()? as usize;
if self.0.len() < n {
return Err(invalid("a truncated replicated event".to_owned()));
}
let (b, rest) = self.0.split_at(n);
self.0 = rest;
Ok(b)
}
}
/// What a replica stores with each apply (D315 PR 3), in its state cell: the primary feed's
/// position after the last event applied, and the token right after it (none until the first
/// event is applied: the first apply records where it starts before it applies anything,
/// so a crash in its middle resumes there).
#[derive(Debug, Clone, PartialEq)]
struct State {
/// The primary's database id (simp724 on #1436): a replica follows only this database.
/// Zero in a version 1 cell, written before it was recorded.
primary: [u8; 16],
after: StreamPosition,
token: Option<FeedToken>,
}
/// The state cell's encoding version.
const STATE_VERSION: u8 = 2;
impl State {
fn encode(&self) -> Vec<u8> {
let mut out =
Vec::with_capacity(18 + self.token.as_ref().map_or(0, |t| t.as_bytes().len()));
out.push(STATE_VERSION);
out.extend_from_slice(&self.primary);
out.extend_from_slice(&self.after.seqno.to_le_bytes());
out.extend_from_slice(&self.after.catalog.to_le_bytes());
match &self.token {
Some(t) => {
out.push(1);
out.extend_from_slice(t.as_bytes());
}
None => out.push(0),
}
out
}
fn decode(bytes: &[u8]) -> Result<Self> {
let bad = || Error::new(ErrorCode::Corruption, "a replica's state cell is malformed");
let (&[version], rest) = bytes.split_first_chunk::<1>().ok_or_else(bad)?;
// Version 1 had no primary id (D315 PR 3, before #1436's bootstrap).
let (primary, rest) = match version {
1 => ([0; 16], rest),
2 => {
let (id, rest) = rest.split_first_chunk::<16>().ok_or_else(bad)?;
(*id, rest)
}
_ => return Err(bad()),
};
let (seqno, rest) = rest.split_first_chunk::<8>().ok_or_else(bad)?;
let (catalog, rest) = rest.split_first_chunk::<8>().ok_or_else(bad)?;
let (&[has_token], token) = rest.split_first_chunk::<1>().ok_or_else(bad)?;
Ok(Self {
primary,
after: StreamPosition {
seqno: u64::from_le_bytes(*seqno),
catalog: u64::from_le_bytes(*catalog),
},
token: match has_token {
0 if token.is_empty() => None,
1 => Some(FeedToken::from_bytes(token)),
_ => return Err(bad()),
},
})
}
}
/// A cell at one timestamp, as one commit may write it once: table, family, row, qualifier
/// and timestamp.
type Cell<'a> = (TableId, FamilyId, &'a [u8], &'a [u8], u64);
/// The engine kind of a change.
fn logged_kind(kind: ChangeKind) -> Kind {
match kind {
ChangeKind::Put => Kind::Put,
ChangeKind::Merge => Kind::Merge,
ChangeKind::DeleteCell => Kind::CellDelete,
ChangeKind::DeleteColumn => Kind::ColumnDelete,
ChangeKind::DeleteFamily => Kind::FamilyDelete,
}
}
/// The primary database a token belongs to (zeros for a token that isn't a feed of every
/// table's, which a replicated event never carries).
fn primary_of(token: &FeedToken) -> [u8; 16] {
pigeonhole_engine::all_tables_token_position(token.as_bytes()).map_or([0; 16], |(id, _, _)| id)
}
fn invalid(message: String) -> Error {
Error::new(ErrorCode::InvalidArgument, message)
}
impl Pigeonhole {
/// Makes this database, a bootstrap copy of a primary (its [`backup_at`](Self::backup_at)
/// of a snapshot), a replica that follows the primary from `token`: the token of a feed of
/// every table opened `from_snapshot` on that same snapshot (#1436, ICR 0125). The first
/// [`apply_replicated`](Self::apply_replicated) chains on it. Refused on a replica, and on
/// a promoted one. Not part of the stable API.
#[doc(hidden)]
pub fn begin_replication(&self, token: &FeedToken) -> Result<()> {
let (primary, seqno, catalog) =
pigeonhole_engine::all_tables_token_position(token.as_bytes())?;
let state = State {
primary,
after: StreamPosition { seqno, catalog },
token: Some(token.clone()),
};
self.engine().begin_replication(&state.encode(), true)?;
Ok(())
}
/// Replaces this database's file with the one at `side` (#1436: a replica's
/// re-bootstrap swaps a fresh copy of its primary in), as a recovery swaps engines
/// (D265): every handle and clone then reads the new file, and operations in flight on
/// the old engine fail with `Closed` or retry on the new one. The path is never left
/// unlocked (simp724's sequence):
/// 1. `side` is opened and locked (writer byte and presence) first, and must have been
/// closed cleanly (`InvalidArgument` otherwise): its own WAL isn't replayed after the
/// rename, so a commit only it held would be lost;
/// 2. the current engine closes, keeping its locks;
/// 3. the old copy's WAL and sidecar files are removed;
/// 4. `side` is renamed over the path, and `side`'s own WAL and sidecar files (from an
/// open of it under its own name, all checkpointed) are removed;
/// 5. the old locks are released, and the old file's shm region removed unless a reader
/// process is still attached to it;
/// 6. the new engine opens on `side`'s locks and is swapped in.
///
/// Refused while an automatic recovery runs. If a step after 2 fails, the handle is
/// left closed (`Closed`): reopen the path. Not part of the stable API.
#[doc(hidden)]
pub fn replace_with(&self, side: impl AsRef<std::path::Path>) -> Result<()> {
let db = &self.db;
db.check_open()?;
if db.supervision().is_some_and(|s| s.recovering()) {
return Err(Error::new(
ErrorCode::Busy,
"a recovery is running: replace the file after it",
));
}
let options = db.reopen_options()?;
let path = db.path().to_path_buf();
let vfs = std::sync::Arc::clone(&options.vfs);
let side = side.as_ref();
let adopted = pigeonhole_engine::Handover::adopt(&vfs, side, &path, options.allow_fuse)?;
let old = db.engine_arc();
let (_closed, held) = old.close_for_reopen();
pigeonhole_engine::remove_side_files(&vfs, &path)?;
let io = |e| Error::from(pigeonhole_engine::Error::Io(e));
vfs.rename(side, &path).map_err(io)?;
let dir = match path.parent() {
Some(d) if !d.as_os_str().is_empty() => d,
_ => std::path::Path::new("."),
};
vfs.sync_dir(dir).map_err(io)?;
// The side file's own WAL streams and sidecar, from an open of it under its own name
// (the bootstrap's `begin_replication`): checkpointed by its clean close, which
// `adopt` checked, so nothing in them is needed (simp724's A1 on #1583).
pigeonhole_engine::remove_side_files(&vfs, side)?;
// The old file is gone from the path: its shm region goes too, unless a reader
// process is still attached to it (simp724's A3 on #1583).
if let Some(held) = held {
old.retire(held)?;
}
let engine =
pigeonhole_engine::Engine::open_with(&path, options, adopted).map_err(|(e, _)| e)?;
drop(db.swap_engine(engine));
drop(old);
Ok(())
}
/// Turns this replica into a primary at the last event it applied (#1436, ICR 0125):
/// returns the primary's token stored with that event (`None` if it applied none). It then
/// takes writes, and its own feed goes on; an apply after it is refused. Stop following
/// the old primary first, and stop the old primary's writers: nothing fences it. If it fails after
/// dropping the state (its bit's commit failed), the database is already no replica: reopen
/// it to finish. Not part of the stable API.
#[doc(hidden)]
pub fn promote(&self) -> Result<Option<FeedToken>> {
let token = self.replicated_token()?;
self.engine().promote()?;
Ok(token)
}
/// The primary feed's token a replica stored with the last event it applied (D315 PR 3):
/// resume the primary's feed from it ([`FeedBuilder::resume`](crate::FeedBuilder::resume))
/// to go on from there. `None` before the first event is applied. Not part of the stable
/// API.
#[doc(hidden)]
pub fn replicated_token(&self) -> Result<Option<FeedToken>> {
Ok(self.replication_state()?.and_then(|s| s.token))
}
/// The durable feed's frontier: every commit at or below it is durable at its level and in
/// its stream file, so a feed that isn't `visible` can deliver it (#1436: what a primary
/// tells its replicas they can have, cli692's F5 on #1583). An atomic read. Not part of
/// the stable API.
#[doc(hidden)]
pub fn replication_frontier(&self) -> u64 {
self.engine().feed_frontier(true)
}
/// The primary's commit seqno a replica applied through (#1436's lag): `None` on a
/// database that isn't a replica. Not part of the stable API.
#[doc(hidden)]
pub fn replicated_seqno(&self) -> Result<Option<u64>> {
Ok(self.replication_state()?.map(|s| s.after.seqno))
}
fn replication_state(&self) -> Result<Option<State>> {
self.engine()
.replication_state()?
.map(|b| State::decode(&b))
.transpose()
}
/// Where an apply starting at `before` stands: the stored state, which must end there
/// (`run[0].before == stored.after`: anything else is a gap or an overlap). The first
/// apply, with none stored, needs a database with no tables of its own, and records
/// `before` as where it starts.
fn chain(&self, before: StreamPosition, primary: [u8; 16]) -> Result<()> {
match self.replication_state()? {
// Another database's history (#1436): a replica follows only its primary.
Some(s) if s.primary != [0; 16] && s.primary != primary => Err(invalid(
"the events are another database's than the replica's primary".to_owned(),
)),
Some(s) if s.after == before => Ok(()),
Some(s) => Err(invalid(format!(
"a replicated run must start where the last apply ended: it starts at \
{before:?}, the last apply ended at {:?} (a gap or an overlap)",
s.after
))),
None => {
if !self.engine().tables().is_empty() {
return Err(invalid(
"a replica's first apply needs a database with no tables of its own"
.to_owned(),
));
}
let start = State {
primary,
after: before,
token: None,
};
self.engine().begin_replication(&start.encode(), false)?;
Ok(())
}
}
}
/// Applies a run of a primary's commits (D315 PR 3), in order, with `token` (the last
/// event's, [`ReplicatedEvent::token`]) stored in the same commit as the run's last change,
/// so what a replica applied and the token it resumes from never part. The run must start
/// where the last apply ended and each event where the one before it ended; it holds
/// commits only (a catalog change goes through [`apply_catalog`](Self::apply_catalog)).
///
/// One atomic `GroupSync` commit, unless two of the run's commits write the same cell
/// at the same timestamp (one commit can't hold both), or the run is larger than a
/// commit should carry (a quarter of one shard's memtable share, at least 64 KiB): it
/// then splits there, between primary commits, each part committed with the token of its
/// own last event, so a crash between parts resumes after the last one committed. Refused with `InvalidArgument`: an empty run, a catalog
/// change in it, a gap or an overlap, or a `token` that isn't the last event's. Not part
/// of the stable API.
#[doc(hidden)]
pub fn apply_replicated(&self, run: &[ReplicatedEvent], token: &FeedToken) -> Result<()> {
let (Some(first), Some(last)) = (run.first(), run.last()) else {
return Err(invalid("an empty replicated run".to_owned()));
};
if run.iter().any(ReplicatedEvent::is_catalog) {
return Err(invalid(
"a catalog change in a replicated run: apply it with apply_catalog".to_owned(),
));
}
if let Some(w) = run.windows(2).find(|w| w[1].before != w[0].after) {
return Err(invalid(format!(
"a replicated run's events must chain: one ends at {:?}, the next starts at {:?}",
w[0].after, w[1].before
)));
}
if last.token != *token {
return Err(invalid(
"the token to store must be the run's last event's".to_owned(),
));
}
self.chain(first.before, primary_of(&first.token))?;
let mut batch = WriteBatch::new();
let mut cells: HashSet<Cell<'_>> = HashSet::new();
let mut max_ts = 0;
let mut part_end: Option<&ReplicatedEvent> = None;
let cap = self.engine().max_replicated_part_bytes();
let mut part_bytes = 0;
for event in run {
let Body::Commit { changes, .. } = &event.body else {
unreachable!("checked above");
};
let bytes: usize = changes
.iter()
.map(|c| c.row.len() + c.qualifier.len() + c.stored.len() + 32)
.sum();
// A cell and timestamp this part already writes, or a part this event would take
// past the byte cap (simp724's S1): commit the part first. One event is never
// split: a primary commit applies whole.
if let Some(end) = part_end
&& (part_bytes + bytes > cap
|| changes.iter().any(|c| {
cells.contains(&(c.table, c.family, &c.row[..], &c.qualifier[..], c.ts))
}))
{
self.commit_part(std::mem::take(&mut batch), end, max_ts)?;
cells.clear();
max_ts = 0;
part_bytes = 0;
}
part_bytes += bytes;
for c in changes {
batch.push_logged(
c.table,
c.family,
logged_kind(c.kind),
&c.row,
&c.qualifier,
c.ts,
&c.stored,
)?;
cells.insert((c.table, c.family, &c.row[..], &c.qualifier[..], c.ts));
max_ts = max_ts.max(c.ts);
}
part_end = Some(event);
}
let end = part_end.expect("a non-empty run");
if batch.is_empty() {
// Commits with nothing this database stores (every change was another's): only
// the state moves.
let state = State {
primary: primary_of(&end.token),
after: end.after,
token: Some(end.token.clone()),
};
self.engine().store_replication_state(&state.encode())?;
return Ok(());
}
self.commit_part(batch, end, max_ts)
}
fn commit_part(&self, batch: WriteBatch, end: &ReplicatedEvent, max_ts: u64) -> Result<()> {
let state = State {
primary: primary_of(&end.token),
after: end.after,
token: Some(end.token.clone()),
};
self.engine()
.apply_replicated(batch, &state.encode(), max_ts)?;
Ok(())
}
/// Applies a catalog change of a primary's feed (D315 PR 3), with the primary's ids,
/// between runs of commits, then stores `token` (the event's). It must start where the
/// last apply ended. The change and the token are two commits (the manifest's, then the
/// state cell's): after a crash between them the change is applied again, and one already
/// applied as it stands is passed over. Not part of the stable API.
#[doc(hidden)]
pub fn apply_catalog(&self, event: &ReplicatedEvent, token: &FeedToken) -> Result<()> {
let Body::Catalog(change) = &event.body else {
return Err(invalid(
"apply_catalog takes a catalog change: apply commits with apply_replicated"
.to_owned(),
));
};
if event.token != *token {
return Err(invalid("the token to store must be the event's".to_owned()));
}
self.chain(event.before, primary_of(&event.token))?;
self.engine().apply_catalog(&change.edits)?;
let state = State {
primary: primary_of(&event.token),
after: event.after,
token: Some(event.token.clone()),
};
self.engine().store_replication_state(&state.encode())?;
Ok(())
}
}