oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3// The log epoch (live-push spec §3.1). A client that holds a cursor into a
4// log that has since been rewound must resync from the start: a log
5// restored to 90 that has taken twenty commits since shows a client at 100
6// a current seq of 110, and without this it would skip the new 91-100.
7//
8// The spec asks for rotation "at startup whenever the process did not find
9// its own clean-shutdown marker". Built literally, that would rotate the
10// epoch at every deploy that overlaps generations (CARLOS_SWAP=overlap,
11// carlos/platform's zero-downtime spec): the new process starts before the
12// old one has drained and written its marker. So the marker is a boot
13// counter instead, held in the database (docs_log_epoch) and in a file
14// beside it (<db>.log-epoch), compared at every start:
15//
16// - equal: the database is the one the last start left; bump both, keep
17// the epoch. An ordinary deploy, overlapped or not, and a process
18// crash (which loses no committed row) keep it.
19// - the file missing (a new box or disk, a restore onto one), or naming
20// another epoch or boot (a database restored from a copy taken before
21// the last start): rotate.
22//
23// What neither scheme catches: a restore from a copy taken after the last
24// start, onto the same disk. The seq check (hello's seq below the
25// client's cursor) still covers a log that is behind; a restore runbook
26// can delete the file to force a rotation. Any operation that rewinds a
27// log (none exists yet; version restore will) must call rotateLogEpoch.
28
29import (
30 "context"
31 "crypto/rand"
32 "encoding/hex"
33 "fmt"
34 "os"
35 "path/filepath"
36 "strconv"
37 "strings"
38
39 "gorm.io/gorm"
40)
41
42type logEpochRow struct {
43 ID int64 `gorm:"primaryKey"`
44 Epoch string
45 Boot int64
46}
47
48func (logEpochRow) TableName() string { return "docs_log_epoch" }
49
50func newLogEpoch() (string, error) {
51 b := make([]byte, 12)
52 if _, err := rand.Read(b); err != nil {
53 return "", err
54 }
55 return hex.EncodeToString(b), nil
56}
57
58// loadLogEpoch runs once at startup and returns the epoch this process
59// serves.
60func loadLogEpoch(ctx context.Context, db *gorm.DB, dbPath string) (string, error) {
61 sidecar := dbPath + ".log-epoch"
62 var fileEpoch string
63 fileBoot := int64(-1)
64 if raw, err := os.ReadFile(sidecar); err == nil {
65 epoch, boot, ok := strings.Cut(strings.TrimSpace(string(raw)), " ")
66 if n, err := strconv.ParseInt(boot, 10, 64); ok && err == nil {
67 fileEpoch, fileBoot = epoch, n
68 }
69 }
70 // Read, compare and bump in one write transaction, so two starts close
71 // together are serialised on the database (#175 finding 6). The file is
72 // written after the commit, so a start can land between another start's
73 // commit and its file write and see the file exactly one boot behind,
74 // with the same epoch: that is a neighbour, not a restore, and keeps it.
75 // A database older than the file (a restore from before the last start)
76 // has a lower boot and rotates.
77 var row logEpochRow
78 err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
79 // The first statement writes, so the transaction takes SQLite's
80 // write lock before it reads anything. rastrillo's transactions are
81 // deferred: one that read first and wrote later would fail with
82 // SQLITE_BUSY_SNAPSHOT, which busy_timeout does not retry, whenever
83 // another start (an overlapped deploy) committed in between; the
84 // write lock is waited for instead (#175 approval finding 1). It
85 // also makes the row exist: an empty epoch is a database no start
86 // has stamped yet.
87 if err := tx.Exec("INSERT INTO docs_log_epoch (id, epoch, boot) VALUES (1, '', 0) ON CONFLICT(id) DO NOTHING").Error; err != nil {
88 return fmt.Errorf("docs: claim log epoch: %w", err)
89 }
90 if err := tx.Where("id = 1").Limit(1).Find(&row).Error; err != nil {
91 return fmt.Errorf("docs: read log epoch: %w", err)
92 }
93 keep := row.Epoch != "" && fileEpoch == row.Epoch && (fileBoot == row.Boot || fileBoot == row.Boot-1)
94 if !keep {
95 epoch, err := newLogEpoch()
96 if err != nil {
97 return fmt.Errorf("docs: draw log epoch: %w", err)
98 }
99 row = logEpochRow{ID: 1, Epoch: epoch, Boot: row.Boot}
100 }
101 row.Boot++
102 if err := tx.Save(&row).Error; err != nil {
103 return fmt.Errorf("docs: write log epoch: %w", err)
104 }
105 return nil
106 })
107 if err != nil {
108 return "", err
109 }
110 tmp, err := os.CreateTemp(filepath.Dir(sidecar), ".log-epoch-*")
111 if err != nil {
112 return "", fmt.Errorf("docs: write %s: %w", sidecar, err)
113 }
114 if _, err := fmt.Fprintf(tmp, "%s %d\n", row.Epoch, row.Boot); err != nil {
115 tmp.Close()
116 os.Remove(tmp.Name())
117 return "", err
118 }
119 if err := tmp.Close(); err != nil {
120 os.Remove(tmp.Name())
121 return "", err
122 }
123 if err := os.Rename(tmp.Name(), sidecar); err != nil {
124 os.Remove(tmp.Name())
125 return "", fmt.Errorf("docs: write %s: %w", sidecar, err)
126 }
127 return row.Epoch, nil
128}
129