Some data is best kept as the list of everything that happened: a
task manager's edits, a replay of a game, an audit trail. You only ever
add to the end, you rebuild the current state by reading it back, and
history and undo come with it. The durable module writes
such a log for you: each entry is a durable value, so it
keeps decimal, money, datetime
and enums exactly, it checks every entry against a record type on the
way in and on the way out, and a migrate upgrades old
entries as it does a save. The file is in one documented format, so a
crash in the middle of a write is found and cut off, not misread.
durable.append(f, values, version, T)writes a batch of entries to the end of a file in one write.durable.read_stream(f)anddurable.next(stream, T)read them back one at a time, however long the log is.- An optional hash chain links each entry to the one before it, so a changed, removed or reordered entry is noticed.
The file functions need the fs capability
(--allow-fs); the same format also works on a
bytes value, with no capability at all.
#Write and read a log
import durable
import fs
enum Change { Add(string), Done, Rename(string) }
record Entry { seq: int where seq >= 1, task: int, change: Change }
-- write: one batch, one write, on the disk before it returns
let f = fs.open("tasks.log", { mode = "append" })?
let batch = [
{ seq = 1, task = 7, change = Change.Add("buy milk") },
{ seq = 2, task = 7, change = Change.Rename("buy oat milk") },
{ seq = 3, task = 7, change = Change.Done },
]
print(durable.append(f, batch, 1, Entry, { sync = true }))
fs.close(f)
-- read: one entry at a time, however long the log is
let r = fs.open("tasks.log")?
let log = durable.read_stream(r)
let item = durable.next(log, Entry)
while item != nil do
match item
Ok(e) -> print(`{log.offset}: #{e.seq} task {e.task} {e.change}`)
Error(e) -> print(`{e.kind} at {e.offset}: {e.message}`)
end
item = durable.next(log, Entry)
end
fs.close(r)
$ scua --allow-fs tasks_log.scua
Ok({frames = 3, bytes = 220, offset = 8, head = nil})
8: #1 task 7 Change.Add(buy milk)
79: #2 task 7 Change.Rename(buy oat milk)
157: #3 task 7 Change.Done
durable.append(f, values, version, T, opts?)takes an array, so a batch of entries (all the changes one request made, or everything that arrived in the last few milliseconds) costs one write and onesync. It checks every value againstTbefore it encodes anything, and a value that does not fit is anErrornaming it (values[2].seq violates Entry's where rule) with nothing written: a batch lands whole or not at all. LeaveTout to write values as they are.versionis your schema version, stamped on every entry asdurable.encodestamps it.{ sync = true }returns only afterfs.sync: the entries are on the disk, so a power cut cannot lose them. On macOS that isF_FULLFSYNC, often a few milliseconds, which is why it is worth batching.- The file is opened with
{ mode = "append" }, which creates it the first time. At the start of an empty fileappendwrites the log's 8-byte header first, so the first entry starts at offset 8. - The result says how many entries were written, how many bytes that
came to, and the
offsetwhere the first of them starts. durable.read_stream(f, opts?)makes a stream over an open read handle, anddurable.next(stream, T)gives the next entry:Ok(entry), anError, ornilwhen the log ends. WithTeach entry is converted asdurable.decode(blob, T)converts a save: defaults filled,migraterun,whererules checked. An entry that does not fit is that entry'sError, and the stream goes on to the next one.- After each
next,log.offsetis where that entry starts in the file,log.positionis where the next one does, andlog.framescounts the entries read so far.
nil is outside the Result on purpose: a saved
nil is a value, so Ok(nil) is an entry holding
nil, and only nil means the end. A stream that
reached the end of a file that is still growing gives the new entries on
a later next.
Only one program should append to a log at a time. Two writers would
interleave their batches; take a fs.lock
first if more than one program might.
#Pick up where you left off
durable.read_stream(f, { from_offset = n }) starts at an
entry's offset, one an append returned or a stream's
offset or position. Keep the last
position with a snapshot of your state, and on the next
start read only what came after it.
#A hash chain
Pass chain to the first append and the log
is chained: after each entry the file holds
sha256(previous hash ‖ entry), and append
returns the new hash as head. Pass that head
as chain to the next append. To start a new
chain, pass 32 zero bytes,
bytes.from_hex(str.repeat("00", 32))?, or the last
head of the log this one continues, so a log split into
several files still forms one chain.
The reader checks every link and keeps the head as it goes
(log.head). An entry that was changed, removed or moved is
an Error with kind = "chain_broken", and the
stream goes on from the hash the file stores, so one changed entry is
the only one reported. If you keep the head somewhere else as well,
comparing it with log.head at the end also catches entries
cut from the end.
The chain is chosen when the log is created: a log is chained throughout or not at all. Every entry already carries a checksum that catches accidental damage, so a log without a chain is not unprotected; the chain is for noticing deliberate changes and keeping the order.
#After a crash
A crash or a power cut in the middle of an append can
leave the file ending part-way through an entry. The reader reports that
once, as Error({ kind = "torn_tail", offset, length }), and
then gives nil. Every whole entry before it reads normally.
To carry on, cut the file at offset with
fs.truncate and append from the head the reader kept:
import durable
import fs
import bytes
import str
record Entry { seq: int, note: string }
let genesis = bytes.from_hex(str.repeat("00", 32))? -- the head a new chain starts from
-- A log of two entries, then a crash: the third write was cut off after 10 bytes.
let w = fs.open("ops.log", { mode = "append" })?
let early = durable.append(w, [{ seq = 1, note = "a" }, { seq = 2, note = "b" }], 1, Entry, { chain = genesis })?
let third = durable.encode_log([{ seq = 3, note = "c" }], 1, Entry, { chain = early.head })?
fs.write_chunk(w, third.bytes, { from = 0, to = 10 })?
fs.close(w)
-- Start-up: read to the end, keeping the head. A torn tail is reported once, with its offset.
fn replay(path) -> any
let r = fs.open(path)?
let log = durable.read_stream(r)
let cut = nil
let item = durable.next(log, Entry)
while item != nil do
match item
Ok(e) -> print(`replay #{e.seq} {e.note}`)
Error(e) -> if e.kind == "torn_tail" then cut = e.offset else print(`{e.kind}: {e.message}`) end
end
item = durable.next(log, Entry)
end
fs.close(r)
return Ok({ head = log.head, cut = cut })
end
let state = replay("ops.log")?
print(`torn tail at {state.cut}`)
-- Cut it off, and carry on from the head the reader kept.
let a = fs.open("ops.log", { mode = "append" })?
if state.cut != nil then fs.truncate(a, state.cut)? end
let more = durable.append(a, [{ seq = 3, note = "c" }], 1, Entry, { chain = state.head })?
print(`appended {more.frames} at {more.offset}`)
fs.close(a)
let again = replay("ops.log")?
print(again.cut, again.head == third.head)
$ scua --allow-fs recover.scua
replay #1 a
replay #2 b
torn tail at 178
appended 1 at 178
replay #1 a
replay #2 b
replay #3 c
nil true
length is how many bytes the cut drops. A crash can tear
only the last write, so if length is larger than the
batches you write, something else damaged the file; look before you
cut.
An append whose write fails part-way says so:
Error({ kind, message, wrote, offset }), where
wrote bytes landed at offset.
fs.truncate(f, e.offset) puts the file back as it was, and
the same batch can be appended again.
#What the reader reports
kind |
What it means | Then |
|---|---|---|
torn_tail |
the log ends in an entry cut short; offset and
length say where and how much |
nil |
chain_broken |
this entry does not link to the one before it | the next entry |
decode |
this entry's bytes do not decode (its checksum failed, or it holds an enum variant this program no longer declares) | the next entry |
corrupt |
a length no writer writes: zero, or larger than
max_frame with more bytes after it |
nil |
not_a_log, newer_format |
the file is not a log, or a newer SCUA wrote it | nil |
the fs kinds |
a read failed | the same entry again |
An entry that does not fit T is the same
Error durable.decode(blob, T) gives, with
message and path. Every Error
from the reader has kind, message and
offset, and those about one entry have frame,
its number counted from where the stream started.
One entry is at most max_frame bytes, 16 MiB unless you
pass { max_frame = n } to append and to
read_stream. The reader never allocates more than one entry
at a time, so a damaged length cannot make it ask for gigabytes.
#Changing what an entry holds
Entries are durable values, so the rules in Evolve your saved data safely apply.
Give a new field a default, or bump version and add a
migrate to the record: entries written before and after the
change sit in one log and all read back as the current record. Enum
variants are saved by name, payloads included, so reordering an enum is
safe; a variant that is renamed or removed, or whose payload changes
shape, is that entry's decode Error, naming it.
#Without a file
durable.encode_log(values, version, T?, opts?) gives the
same bytes append would write, as a bytes
value: { header = true } puts the header in front to start
a new log, and chain works as for append.
durable.read_stream reads a bytes value as
well as a file. Neither needs a capability, so a sandboxed script can
build a log, and a server can send one over a socket.
import durable
import bytes
enum Move { Step(int, int), Wait }
record Turn { n: int, move: Move }
-- No file: the same format as bytes, to send or to keep inside another value
let one = durable.encode_log([{ n = 1, move = Move.Step(0, 1) }], 1, Turn, { header = true })?
let two = durable.encode_log([{ n = 2, move = Move.Wait }, { n = 3, move = Move.Step(1, 1) }], 1, Turn)?
let all = bytes.concat(one.bytes, two.bytes)
print(`{len(all)} bytes, {one.frames + two.frames} turns`)
let turns = durable.read_stream(all)
let t = durable.next(turns, Turn)
while t != nil do
print(t?.n, t?.move)
t = durable.next(turns, Turn)
end
$ scua bytes_log.scua
162 bytes, 3 turns
1 Move.Step([0, 1])
2 Move.Wait
3 Move.Step([1, 1])
#The format
For a program in another language that reads or writes these files:
- The header, once at the start: the 4 bytes
SCUL, a version byte (1), a flags byte (bit 0 set when the log is chained), two zero bytes, and in a chained log the 32 bytes the chain starts from. - Each entry: its length as a 4-byte little-endian
number, then that many bytes, which are exactly what
durable.encode(value, version)returns, then in a chained log the 32-byte SHA-256 of the previous hash followed by those bytes.
The schema version is inside each entry's bytes, where
durable.version reads it without decoding the rest.
#Related
- Evolve your saved data safely:
the
durableformat,migrate, and what can be saved. - Read and write files: file
handles,
fs.syncandfs.truncate.