| index eceac45..c1cbace 100644 |
| --- a/internal/docs/logepoch.go |
| +++ b/internal/docs/logepoch.go |
| @@ -59,29 +59,42 @@ func newLogEpoch() (string, error) { |
| // serves. |
| func loadLogEpoch(ctx context.Context, db *gorm.DB, dbPath string) (string, error) { |
| sidecar := dbPath + ".log-epoch" |
| - var row logEpochRow |
| - err := db.WithContext(ctx).Where("id = 1").Limit(1).Find(&row).Error |
| - if err != nil { |
| - return "", fmt.Errorf("docs: read log epoch: %w", err) |
| - } |
| - keep := false |
| - if row.ID == 1 { |
| - if raw, err := os.ReadFile(sidecar); err == nil { |
| - epoch, boot, ok := strings.Cut(strings.TrimSpace(string(raw)), " ") |
| - n, err := strconv.ParseInt(boot, 10, 64) |
| - keep = ok && err == nil && epoch == row.Epoch && n == row.Boot |
| + var fileEpoch string |
| + fileBoot := int64(-1) |
| + if raw, err := os.ReadFile(sidecar); err == nil { |
| + epoch, boot, ok := strings.Cut(strings.TrimSpace(string(raw)), " ") |
| + if n, err := strconv.ParseInt(boot, 10, 64); ok && err == nil { |
| + fileEpoch, fileBoot = epoch, n |
| } |
| } |
| - if !keep { |
| - epoch, err := newLogEpoch() |
| - if err != nil { |
| - return "", fmt.Errorf("docs: draw log epoch: %w", err) |
| + // Read, compare and bump in one write transaction, so two starts close |
| + // together are serialised on the database (#175 finding 6). The file is |
| + // written after the commit, so a start can land between another start's |
| + // commit and its file write and see the file exactly one boot behind, |
| + // with the same epoch: that is a neighbour, not a restore, and keeps it. |
| + // A database older than the file (a restore from before the last start) |
| + // has a lower boot and rotates. |
| + var row logEpochRow |
| + err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + if err := tx.Where("id = 1").Limit(1).Find(&row).Error; err != nil { |
| + return fmt.Errorf("docs: read log epoch: %w", err) |
| } |
| - row = logEpochRow{ID: 1, Epoch: epoch, Boot: row.Boot} |
| - } |
| - row.Boot++ |
| - if err := db.WithContext(ctx).Save(&row).Error; err != nil { |
| - return "", fmt.Errorf("docs: write log epoch: %w", err) |
| + keep := row.ID == 1 && fileEpoch == row.Epoch && (fileBoot == row.Boot || fileBoot == row.Boot-1) |
| + if !keep { |
| + epoch, err := newLogEpoch() |
| + if err != nil { |
| + return fmt.Errorf("docs: draw log epoch: %w", err) |
| + } |
| + row = logEpochRow{ID: 1, Epoch: epoch, Boot: row.Boot} |
| + } |
| + row.Boot++ |
| + if err := tx.Save(&row).Error; err != nil { |
| + return fmt.Errorf("docs: write log epoch: %w", err) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + return "", err |
| } |
| tmp, err := os.CreateTemp(filepath.Dir(sidecar), ".log-epoch-*") |
| if err != nil { |