- OCaml 90%
- C 10%
wal #
Write-ahead logs for OCaml, in LevelDB's log format.
If a store acknowledges a write before the write reaches the disk, a crash loses it. If a store rewrites its data files in place, a crash can leave them half updated. A write-ahead log (WAL) fixes both problems. Each change is appended to a sequential file and synced before the store acknowledges it, and after a crash the store replays that file.
This library writes its logs in LevelDB's format. A log file is a sequence of
32 KB blocks. Every physical record in it carries a CRC32C checksum, and a
record too long for the space left in its block is split into fragments that
the reader puts back together. CRC32C is the 32-bit CRC over the Castagnoli
polynomial 0x1EDC6F41. It catches more error patterns than the Ethernet
CRC-32, and x86 and arm64 both have an instruction for it.
A torn tail and a damaged block both fail their CRC, and the reader tells them apart by where the failure sits. When the failing bytes are at the end of the log with no valid record after them, they are a torn tail, the part of the last append that had not reached the disk at the crash. That append was never acknowledged, and the reader drops it without comment. When valid records follow the failure, the damaged record held acknowledged data, and the reader reports a gap at that point. The length field sits outside the CRC, so after a checksum failure the reader can only trust the next block boundary, and one damaged record loses the rest of its 32 KB block.
Wal.Segmented writes one stream of records across a directory of numbered
files. Retention then deletes whole files, which keeps the log's size on disk
bounded. The library uses Eio for I/O.
Installation #
$ opam install wal
The package may not be in the public opam-repository yet. If opam cannot
find it, add the overlay repository first:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install wal
Usage #
Writing records #
let run () =
Eio_main.run @@ fun env ->
Eio.Switch.run @@ fun sw ->
let fs = Eio.Stdenv.fs env in
let log = Wal.v ~sw Eio.Path.(fs / "mylog.wal") in
Wal.append log "key1=value1";
Wal.append log "key2=value2";
Wal.sync log; (* Durably persist *)
Wal.close log
Reading records #
let run () =
Eio_main.run @@ fun env ->
let fs = Eio.Stdenv.fs env in
let records = Wal.read_all Eio.Path.(fs / "mylog.wal") in
List.iter (fun data -> print_endline data) records
Reading records with gaps #
Wal.fold also tells you where damage on disk lost records. Every record
after a Gap was written after some records that are now gone. A consumer
whose records only make sense together, such as a transaction that must apply
whole or not at all, should stop at the first gap.
let run () =
Eio_main.run @@ fun env ->
let fs = Eio.Stdenv.fs env in
let sum =
Wal.fold Eio.Path.(fs / "mylog.wal")
~init:0
~f:(fun acc -> function
| Wal.Record data -> acc + int_of_string data
| Wal.Gap -> acc)
in
Printf.printf "sum = %d\n" sum
Segmented logs #
A single log file keeps growing. Wal.Segmented writes the same records into a
directory of numbered logs and starts a new one every roll_bytes. To drop old
records, retention deletes whole files and never rewrites a record. Each
segment is named after the sequence of its first record. A sequence is a
record's position in the whole log, and it stays the same across rolls,
retention and reopening.
let run () =
Eio_main.run @@ fun env ->
let fs = Eio.Stdenv.fs env in
Eio.Switch.run @@ fun sw ->
let dir = Eio.Path.(fs / "events") in
let log = Wal.Segmented.v ~sw ~roll_bytes:(4 * 1024 * 1024) dir in
Wal.Segmented.append log "an event";
Wal.Segmented.sync log;
(* Drop the segments below a watermark, and stay under 64 MB whatever the
watermark says. *)
let dropped =
Wal.Segmented.retain log
~keep:(fun seq -> Wal.Segmented.compare_seq seq 1_000 >= 0)
~ceiling_bytes:(64 * 1024 * 1024)
in
Printf.printf "the log now starts at %d\n" dropped.log_start
Reading a segmented log looks like reading a single one, given the directory:
let replay () =
Eio_main.run @@ fun env ->
let fs = Eio.Stdenv.fs env in
List.iter print_endline (Wal.Segmented.read_all Eio.Path.(fs / "events"))
A consumer that stopped at some sequence can resume there without replaying
what it has already seen. fold passes each record its sequence, and ~from
skips every segment whose name shows it holds nothing past that point:
let resume ~cursor =
Eio_main.run @@ fun env ->
let fs = Eio.Stdenv.fs env in
Wal.Segmented.fold ~from:cursor Eio.Path.(fs / "events")
~init:cursor
~f:(fun last seq -> function
| Wal.Record event ->
print_endline event;
seq
| Wal.Gap -> last)
Record format #
Each physical record has a seven-byte header:
+----------+----------+----------+--- ... ---+
| CRC (4B) | Len (2B) | Type (1B)| Data |
+----------+----------+----------+--- ... ---+
- CRC: CRC32C checksum of Type + Data
- Len: Length of Data in bytes (max 65535)
- Type: Record type (Full, First, Middle, Last)
- Data: Payload bytes
When a record does not fit in what is left of the current 32 KB block, it is split into physical records of type First, Middle and Last, each with its own CRC. Because the CRC does not cover the length field, the reader cannot trust any offset inside a block after a damaged record. It skips to the next block boundary, and the rest of that block is lost.
API #
Wal.vcreates or opens a log,Wal.appendadds a record,Wal.syncmakes the appended records durable andWal.closesyncs and closes.Wal.read_allandWal.foldread a log;foldalso reports gaps.Wal.sizeis the bytes the log occupies once pending records are flushed.Wal.is_logsays whether a file starts with a record this writer could have written.Wal.Segmented.vandWal.Segmented.appendcreate and extend a segmented log, rolling to a new segment atroll_bytes.Wal.Segmented.size,segmentsandlog_startobserve its footprint, andretaindeletes the segments below a watermark and a size ceiling.Wal.Segmented.read_allandfoldread every segment, oldest first;foldnumbers each record and resumes from a sequence with~from.
Related work #
- The LevelDB log format is the format this library writes.
- RocksDB's WAL extends the same format.
- Kafka's log retention
(
segment.bytesand the log start offset) is the model forWal.Segmented.
License #
ISC. See LICENSE.md.