Skip to main content

store_io_engine/
receipt.rs

1//! Positions, write tickets and durability receipts.
2//!
3//! These are the values a caller cannot forge: every constructor is private
4//! to this crate. A position comes only from a region (checked against its
5//! bounds and alignment), a ticket only from a submitted write, and a receipt
6//! only from a completed durable write or a successful barrier.
7//!
8//! A ticket records the first device flush that can cover its write: the
9//! flush issued after the write completed. A receipt records the flush its
10//! barrier waited for. The receipt proves the ticket's write durable exactly
11//! when the ticket's flush number is not later than the receipt's, which is
12//! the join rule the flush domain enforces.
13//!
14//! # Compile-time guarantees
15//!
16//! The valid forms compile:
17//!
18//! ```
19//! # use std::path::Path;
20//! # use store_io_engine::{Store, StoreOptions};
21//! # use store_io_sim::{SimConfig, SimPlatform};
22//! # let store = Store::create(SimPlatform::new(SimConfig::volatile(1)), Path::new("/db"), StoreOptions::default()).unwrap();
23//! # let pages = store.provision_page_region("p", 1 << 20).unwrap();
24//! # let wal = store.provision_append_region("w", 1 << 20).unwrap();
25//! let pos = pages.pos(4096)?;                       // a checked position
26//! let ticket = pages.write(pos, &[0u8; 4096])?;     // a ticket per write
27//! let receipt = pages.sync_through(&ticket)?;       // a receipt per barrier
28//! assert!(receipt.covers(&ticket));
29//! let appended = wal.append(b"x")?;
30//! let _durable = wal.sync_through(&appended)?;
31//! # Ok::<(), store_io_core::error::Error>(())
32//! ```
33//!
34//! An integer is never a position:
35//!
36//! ```compile_fail,E0308
37//! # use std::path::Path;
38//! # use store_io_engine::{Store, StoreOptions};
39//! # use store_io_sim::{SimConfig, SimPlatform};
40//! # let store = Store::create(SimPlatform::new(SimConfig::volatile(1)), Path::new("/db"), StoreOptions::default()).unwrap();
41//! # let pages = store.provision_page_region("p", 1 << 20).unwrap();
42//! let _ticket = pages.write(4096, &[0u8; 4096]);
43//! ```
44//!
45//! A position cannot be built by hand:
46//!
47//! ```compile_fail,E0451
48//! # use store_io_engine::RegionPos;
49//! let _pos = RegionPos { offset: 4096 };
50//! ```
51//!
52//! A receipt cannot be forged:
53//!
54//! ```compile_fail,E0451
55//! # use store_io_engine::DurableReceipt;
56//! let _receipt = DurableReceipt { through: u64::MAX };
57//! ```
58//!
59//! A ticket is not a position, and a receipt is not a ticket:
60//!
61//! ```compile_fail,E0308
62//! # use std::path::Path;
63//! # use store_io_engine::{Store, StoreOptions};
64//! # use store_io_sim::{SimConfig, SimPlatform};
65//! # let store = Store::create(SimPlatform::new(SimConfig::volatile(1)), Path::new("/db"), StoreOptions::default()).unwrap();
66//! # let pages = store.provision_page_region("p", 1 << 20).unwrap();
67//! let ticket = pages.write(pages.pos(0).unwrap(), &[0u8; 4096]).unwrap();
68//! let _again = pages.write(ticket, &[0u8; 4096]);
69//! ```
70//!
71//! ```compile_fail,E0308
72//! # use std::path::Path;
73//! # use store_io_engine::{Store, StoreOptions};
74//! # use store_io_sim::{SimConfig, SimPlatform};
75//! # let store = Store::create(SimPlatform::new(SimConfig::volatile(1)), Path::new("/db"), StoreOptions::default()).unwrap();
76//! # let wal = store.provision_append_region("w", 1 << 20).unwrap();
77//! let (_pos, receipt) = wal.append_durable(b"x").unwrap();
78//! let _again = wal.sync_through(&receipt);
79//! ```
80//!
81//! A ticket stands for one write and cannot be copied:
82//!
83//! ```compile_fail,E0599
84//! # use std::path::Path;
85//! # use store_io_engine::{Store, StoreOptions};
86//! # use store_io_sim::{SimConfig, SimPlatform};
87//! # let store = Store::create(SimPlatform::new(SimConfig::volatile(1)), Path::new("/db"), StoreOptions::default()).unwrap();
88//! # let wal = store.provision_append_region("w", 1 << 20).unwrap();
89//! let ticket = wal.append(b"x").unwrap();
90//! let _copy = ticket.clone();
91//! ```
92//!
93//! Dropping a ticket unused is flagged (here made an error):
94//!
95//! ```compile_fail
96//! #![deny(unused_must_use)]
97//! # use std::path::Path;
98//! # use store_io_engine::{Store, StoreOptions};
99//! # use store_io_sim::{SimConfig, SimPlatform};
100//! # fn main() -> Result<(), store_io_core::error::Error> {
101//! # let store = Store::create(SimPlatform::new(SimConfig::volatile(1)), Path::new("/db"), StoreOptions::default())?;
102//! # let wal = store.provision_append_region("w", 1 << 20)?;
103//! wal.append(b"x")?;
104//! # Ok(())
105//! # }
106//! ```
107
108use core::fmt;
109
110use store_io_core::class::{DurabilityClass, ReceiptLabel};
111use store_io_core::id::{Generation, RegionId, VolumeId};
112
113/// A byte position inside one generation of one region.
114///
115/// Created by [`crate::PageRegion::pos`] or returned by appends. A position
116/// from another region, or from a generation that has since been recycled,
117/// is rejected before any I/O.
118#[derive(Clone, Copy, PartialEq, Eq, Hash)]
119pub struct RegionPos {
120    pub(crate) volume: VolumeId,
121    pub(crate) region: RegionId,
122    pub(crate) generation: Generation,
123    pub(crate) offset: u64,
124}
125
126impl RegionPos {
127    /// Byte offset within the region's data area.
128    #[must_use]
129    pub fn offset(&self) -> u64 {
130        self.offset
131    }
132
133    /// The region.
134    #[must_use]
135    pub fn region(&self) -> RegionId {
136        self.region
137    }
138
139    /// The region generation the position belongs to.
140    #[must_use]
141    pub fn generation(&self) -> Generation {
142        self.generation
143    }
144}
145
146impl fmt::Debug for RegionPos {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        write!(
149            f,
150            "RegionPos({}/{}+{})",
151            self.region, self.generation, self.offset
152        )
153    }
154}
155
156/// Proof that a write was submitted and completed. Barrier it to make it
157/// durable. Not `Clone`: one ticket per write.
158#[must_use = "a write ticket is how you make the write durable; drop it only if durability does not matter"]
159#[derive(PartialEq, Eq)]
160pub struct WriteTicket {
161    pub(crate) volume: VolumeId,
162    pub(crate) region: RegionId,
163    pub(crate) generation: Generation,
164    pub(crate) start: u64,
165    pub(crate) end: u64,
166    /// The first flush issued after the write completed.
167    pub(crate) need: u64,
168    /// The open store that issued it.
169    pub(crate) epoch: u64,
170    /// The write is to an append region (receipts built from the ticket
171    /// carry it on).
172    pub(crate) append: bool,
173}
174
175impl WriteTicket {
176    /// Where the write starts.
177    #[must_use]
178    pub fn pos(&self) -> RegionPos {
179        RegionPos {
180            volume: self.volume,
181            region: self.region,
182            generation: self.generation,
183            offset: self.start,
184        }
185    }
186
187    /// One past the last byte written (block-aligned for appends).
188    #[must_use]
189    pub fn end(&self) -> u64 {
190        self.end
191    }
192}
193
194impl fmt::Debug for WriteTicket {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        write!(
197            f,
198            "WriteTicket({}/{} {}..{})",
199            self.region, self.generation, self.start, self.end
200        )
201    }
202}
203
204/// Unforgeable proof that bytes are durable.
205///
206/// Its existence means every byte it covers is durable at [`Self::class`] on
207/// this device, under the device's documented fault model. The label says
208/// why that class is trusted.
209#[must_use]
210#[derive(Clone, Copy, PartialEq, Eq)]
211pub struct DurableReceipt {
212    pub(crate) volume: VolumeId,
213    pub(crate) region: RegionId,
214    pub(crate) generation: Generation,
215    pub(crate) class: DurabilityClass,
216    pub(crate) label: ReceiptLabel,
217    pub(crate) start: u64,
218    pub(crate) through: u64,
219    pub(crate) untorn: bool,
220    /// The flush the barrier waited for (`u64::MAX` when every completed
221    /// write is durable at completion; 0 when no barrier ran).
222    pub(crate) need: u64,
223    /// `through` is a contiguous durable prefix of an append region.
224    pub(crate) prefix: bool,
225    /// A data flush issued after the covered writes completed succeeded.
226    pub(crate) synced: bool,
227    /// The open store that issued it.
228    pub(crate) epoch: u64,
229    /// The covered bytes are an append region's, so a dependent write may
230    /// name the receipt only if it is a prefix (`NotPrefix`), whichever
231    /// store it comes from. Never visible to callers.
232    pub(crate) append: bool,
233}
234
235impl DurableReceipt {
236    /// The volume.
237    #[must_use]
238    pub fn volume(&self) -> VolumeId {
239        self.volume
240    }
241
242    /// The region.
243    #[must_use]
244    pub fn region(&self) -> RegionId {
245        self.region
246    }
247
248    /// The region generation.
249    #[must_use]
250    pub fn generation(&self) -> Generation {
251        self.generation
252    }
253
254    /// The durability class the bytes are durable at.
255    #[must_use]
256    pub fn class(&self) -> DurabilityClass {
257        self.class
258    }
259
260    /// Why the class is trusted.
261    #[must_use]
262    pub fn label(&self) -> ReceiptLabel {
263        self.label
264    }
265
266    /// For a prefix receipt ([`Self::is_prefix`]: an append region's
267    /// `sync_through`, or a durable submitter append whose region was
268    /// complete up to it): every byte of the region before this offset is
269    /// durable. Otherwise (page regions, slots, and a submitter receipt for
270    /// one append whose region was not yet complete before it): the end of
271    /// the covered write; earlier bytes may not be durable.
272    #[must_use]
273    pub fn durable_through(&self) -> u64 {
274        self.through
275    }
276
277    /// Whether this is a prefix receipt: every byte of the region before
278    /// [`Self::durable_through`] is durable (see there).
279    #[must_use]
280    pub fn is_prefix(&self) -> bool {
281        self.prefix
282    }
283
284    /// Whether a data sync issued after the covered writes completed has
285    /// succeeded (D-102): always on a flush-required store; on a power-safe
286    /// store (writes durable at completion, no flush needed) for a region
287    /// forcing data sync. False means none is guaranteed, not that none
288    /// happened. Such a receipt covers ([`Self::covers`]) the tickets of
289    /// writes completed before its flush, not later ones (an unforced
290    /// power-safe receipt covers every write of its region, generation and
291    /// open).
292    #[must_use]
293    pub fn data_synced(&self) -> bool {
294        self.synced
295    }
296
297    /// Whether the covered write was accepted as atomic (never torn).
298    #[must_use]
299    pub fn untorn(&self) -> bool {
300        self.untorn
301    }
302
303    /// Whether this receipt proves the ticket's write durable: the write
304    /// completed before the receipt's flush was issued, or (append regions)
305    /// it lies inside the durable prefix. Tickets and receipts from different
306    /// opens of a store never match: a reopened store vouches only for its
307    /// own writes.
308    #[must_use]
309    pub fn covers(&self, t: &WriteTicket) -> bool {
310        self.epoch == t.epoch
311            && self.volume == t.volume
312            && self.region == t.region
313            && self.generation == t.generation
314            && (t.need <= self.need || (self.prefix && t.end <= self.through))
315    }
316}
317
318impl fmt::Debug for DurableReceipt {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        write!(
321            f,
322            "DurableReceipt({}/{} {}..{} {} {})",
323            self.region, self.generation, self.start, self.through, self.class, self.label
324        )
325    }
326}