Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion engine/engine_mock_storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -700,4 +700,5 @@ func (m *mockStorage) GetAllSignatures(ctx context.Context) (map[string]string,
func (m *mockStorage) WithTx(ctx context.Context, fn func(storage.Storage) error) error {
return fn(m)
}
func (m *mockStorage) Close() error { return nil }
func (m *mockStorage) Backup(ctx context.Context, backupPath string) error { return nil }
func (m *mockStorage) Close() error { return nil }
45 changes: 45 additions & 0 deletions storage/backup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package storage

import (
"context"
"fmt"
"os"
"path/filepath"
"time"
)

// Backup creates a consistent snapshot of the database at backupPath using
// SQLite's VACUUM INTO, which reads the live database without blocking
// writers for more than a moment and produces a compact, standalone file.
// The backup is written atomically (temp file + rename) and its permissions
// are restricted to owner-only, matching the main database file.
func (s *Store) Backup(ctx context.Context, backupPath string) error {
if backupPath == "" {
return fmt.Errorf("backup path must not be empty")
}

dir := filepath.Dir(backupPath)
if err := os.MkdirAll(dir, 0o700); err != nil {
return fmt.Errorf("create backup directory: %w", err)
}

tq, cancel := s.withTimeout(ctx)
defer cancel()

// VACUUM INTO cannot target an existing file, so write to a temp file
// in the same directory and rename it into place.
tmp := backupPath + fmt.Sprintf(".%d.tmp", time.Now().UnixNano())
if _, err := s.q().ExecContext(tq, `VACUUM INTO ?`, tmp); err != nil {
_ = os.Remove(tmp) // best-effort cleanup of any partial file
return fmt.Errorf("backup database: %w", err)
}
if err := os.Chmod(tmp, 0o600); err != nil {
_ = os.Remove(tmp)
return fmt.Errorf("restrict backup file permissions: %w", err)
}
if err := os.Rename(tmp, backupPath); err != nil {
_ = os.Remove(tmp)
return fmt.Errorf("finalize backup: %w", err)
}
return nil
}
74 changes: 74 additions & 0 deletions storage/backup_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package storage

import (
"context"
"os"
"path/filepath"
"testing"
)

func TestBackup(t *testing.T) {
s, cleanup := setupStore(t)
defer cleanup()
ctx := context.Background()

// Seed some data so the backup is non-trivial.
if err := s.CreateNode(ctx, &Node{
ID: "backup-node", Type: "convention", Content: "backup me",
ContentHash: "h-backup", Scope: "project", Project: "test",
}); err != nil {
t.Fatal(err)
}

backupPath := filepath.Join(t.TempDir(), "sub", "backup.db")
if err := s.Backup(ctx, backupPath); err != nil {
t.Fatalf("Backup: %v", err)
}

fi, err := os.Stat(backupPath)
if err != nil {
t.Fatalf("backup file not created: %v", err)
}
if fi.Size() == 0 {
t.Error("backup file is empty")
}
// Owner-only permissions (mask umask for strictness).
if perm := fi.Mode().Perm() & 0o777; perm != 0o600 {
t.Errorf("backup permissions = %o, want 600", perm)
}

// The backup must be a standalone, consistent database: opening it and
// reading the seeded node should work.
restore, err := NewStore(backupPath)
if err != nil {
t.Fatalf("open backup: %v", err)
}
defer restore.Close()
n, err := restore.GetNode(ctx, "backup-node")
if err != nil {
t.Fatalf("GetNode from backup: %v", err)
}
if n.Content != "backup me" {
t.Errorf("backup content = %q, want %q", n.Content, "backup me")
}
}

func TestBackupEmptyPath(t *testing.T) {
s, cleanup := setupStore(t)
defer cleanup()
if err := s.Backup(context.Background(), ""); err == nil {
t.Error("expected error for empty backup path")
}
}

func TestBackupInsideTx(t *testing.T) {
s, cleanup := setupStore(t)
defer cleanup()
ctx := context.Background()
err := s.WithTx(ctx, func(tx Storage) error {
return tx.Backup(ctx, filepath.Join(t.TempDir(), "nope.db"))
})
if err == nil {
t.Error("expected error backing up inside a transaction")
}
}
4 changes: 4 additions & 0 deletions storage/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,9 @@ type Storage interface {
// Transactions
WithTx(ctx context.Context, fn func(Storage) error) error

// Backup writes a consistent, compact snapshot of the database to
// backupPath (atomic temp-file + rename, owner-only permissions).
Backup(ctx context.Context, backupPath string) error

Close() error
}
4 changes: 4 additions & 0 deletions storage/interface_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,10 @@ func (m *mockStorage) WithTx(ctx context.Context, fn func(Storage) error) error
return fn(m)
}

func (m *mockStorage) Backup(ctx context.Context, backupPath string) error {
return nil
}

func (m *mockStorage) Close() error {
return nil
}
Expand Down
14 changes: 14 additions & 0 deletions storage/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
"os"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -974,6 +975,19 @@ func (m *MockStorage) WithTx(_ context.Context, fn func(Storage) error) error {
return fn(m)
}

// ───────────────────── Backup ─────────────────────

// Backup writes an empty file at backupPath to simulate a snapshot.
func (m *MockStorage) Backup(_ context.Context, backupPath string) error {
if err := m.err(); err != nil {
return err
}
if backupPath == "" {
return fmt.Errorf("backup path must not be empty")
}
return os.WriteFile(backupPath, nil, 0o600)
}

// ───────────────────── Close ─────────────────────

func (m *MockStorage) Close() error {
Expand Down
8 changes: 7 additions & 1 deletion storage/sqlite_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,13 @@ func (t *txStore) GetAllSignatures(ctx context.Context) (map[string]string, erro

func (t *txStore) FlushAccessLog(ctx context.Context) (int, error) { return flushAccessLogQ(ctx, t.tx) }
func (t *txStore) WithTx(ctx context.Context, fn func(Storage) error) error { return fn(t) }
func (t *txStore) Close() error { return nil }

// Backup cannot run inside a transaction: callers must back up through a
// non-transactional Store handle.
func (t *txStore) Backup(ctx context.Context, backupPath string) error {
return fmt.Errorf("backup is not supported inside a transaction")
}
func (t *txStore) Close() error { return nil }

// RollbackToVersion restores a node's content to a specific version.
// All operations run inside a single transaction to prevent concurrent
Expand Down
Loading