backup

package
v0.0.0-...-8acab51 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DiscoverSQLiteDatabasePaths

func DiscoverSQLiteDatabasePaths(dataDir string) ([]string, error)

DiscoverSQLiteDatabasePaths returns managed SQLite database files in the data directory.

Only top-level files are considered so startup auto-recovery stays scoped to the application's own databases and does not traverse user workspace content.

Types

type AutoRecoveryResult

type AutoRecoveryResult struct {
	// Recovered indicates if recovery was performed
	Recovered bool `json:"recovered"`
	// RepairedDatabases lists databases salvaged in place without backup rollback.
	RepairedDatabases []string `json:"repaired_databases,omitempty"`
	// RepairDetails describes how each repaired database was salvaged.
	RepairDetails map[string]DatabaseRepairDetail `json:"repair_details,omitempty"`
	// BackupID is the ID of the backup used for recovery
	BackupID string `json:"backup_id,omitempty"`
	// BackupTime is the timestamp of the backup used
	BackupTime time.Time `json:"backup_time,omitempty"`
	// Error contains any error message
	Error string `json:"error,omitempty"`
	// FilesRecovered is the number of files recovered
	FilesRecovered int `json:"files_recovered,omitempty"`
	// DatabasesChecked lists the databases that were checked
	DatabasesChecked []string `json:"databases_checked,omitempty"`
	// CorruptedDatabases lists the databases that were found corrupted
	CorruptedDatabases []string `json:"corrupted_databases,omitempty"`
}

AutoRecoveryResult contains information about an auto-recovery operation.

type BackupInfo

type BackupInfo struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	SizeBytes int64     `json:"size_bytes"`
	Path      string    `json:"path"`
	Type      string    `json:"type"` // full, config, data
	// CreatedBy indicates who created this backup: manual, auto, checkpoint.
	CreatedBy string   `json:"created_by,omitempty"`
	Checksum  string   `json:"checksum"`
	Version   string   `json:"version"`
	Files     []string `json:"files"`
	// IsCheckpoint marks backups created automatically before restore.
	IsCheckpoint bool `json:"is_checkpoint,omitempty"`
	// CheckpointReason indicates why the checkpoint was created.
	CheckpointReason string `json:"checkpoint_reason,omitempty"`
}

BackupInfo contains metadata about a backup

type BackupSource

type BackupSource string
const (
	BackupSourceManual     BackupSource = "manual"
	BackupSourceAuto       BackupSource = "auto"
	BackupSourceCheckpoint BackupSource = "checkpoint"
)

type BackupType

type BackupType string

BackupType represents the type of backup

const (
	BackupTypeFull   BackupType = "full"
	BackupTypeConfig BackupType = "config"
	BackupTypeData   BackupType = "data"
)

type CompatibilityResult

type CompatibilityResult struct {
	BackupVersion     string   `json:"backup_version"`
	CurrentVersion    string   `json:"current_version"`
	Compatible        bool     `json:"compatible"`
	RequiresMigration bool     `json:"requires_migration"`
	MigrationsNeeded  int      `json:"migrations_needed"`
	MigrationVersions []string `json:"migration_versions,omitempty"`
	Message           string   `json:"message"`
}

CompatibilityResult contains the result of a compatibility check.

type Config

type Config struct {
	Enabled            bool          `yaml:"enabled"`
	Schedule           string        `yaml:"schedule"` // cron expression
	RetentionDays      int           `yaml:"retention_days"`
	Path               string        `yaml:"path"`
	SkillsPath         string        `yaml:"skills_path"`
	AutoBackup         bool          `yaml:"auto_backup"`
	AutoBackupInterval time.Duration `yaml:"auto_backup_interval"`
	AutoBackupOnChange bool          `yaml:"auto_backup_on_change"`
	ChangePollInterval time.Duration `yaml:"change_poll_interval"`
	ChangeDebounce     time.Duration `yaml:"change_debounce"`
}

Config holds backup configuration

type CreateRequest

type CreateRequest struct {
	Type string `json:"type"` // full, config, data
}

CreateRequest represents a backup creation request

type DatabaseRepairDetail

type DatabaseRepairDetail struct {
	Method        string `json:"method"`
	PartialImport bool   `json:"partial_import,omitempty"`
	Warning       string `json:"warning,omitempty"`
}

DatabaseRepairDetail describes how a database was salvaged in place.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler handles backup-related API endpoints

func NewHandler

func NewHandler(manager *Manager) *Handler

NewHandler creates a new backup handler

func (*Handler) CancelPendingRestore

func (h *Handler) CancelPendingRestore(c echo.Context) error

CancelPendingRestore cancels a pending restore operation

func (*Handler) Create

func (h *Handler) Create(c echo.Context) error

Create creates a new backup

func (*Handler) Delete

func (h *Handler) Delete(c echo.Context) error

Delete removes a backup

func (*Handler) Get

func (h *Handler) Get(c echo.Context) error

Get returns a specific backup by ID

func (*Handler) GetPendingRestore

func (h *Handler) GetPendingRestore(c echo.Context) error

GetPendingRestore returns the pending restore info if any

func (*Handler) GetProgress

func (h *Handler) GetProgress(c echo.Context) error

GetProgress returns the current backup/restore progress

func (*Handler) List

func (h *Handler) List(c echo.Context) error

List returns all available backups

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers backup routes on the given group

func (*Handler) Repair

func (h *Handler) Repair(c echo.Context) error

Repair recalculates and updates the checksum for a backup

func (*Handler) Restore

func (h *Handler) Restore(c echo.Context) error

Restore restores from a backup

func (*Handler) SetRestartFunc

func (h *Handler) SetRestartFunc(fn func() error)

SetRestartFunc sets the restart callback used for auto-restart after staged restore.

func (*Handler) StageRestore

func (h *Handler) StageRestore(c echo.Context) error

StageRestore stages a backup for restore on next restart. This is the recommended approach for hot recovery to avoid database lock issues.

func (*Handler) Verify

func (h *Handler) Verify(c echo.Context) error

Verify checks the integrity of a backup

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager handles backup and restore operations

func NewManager

func NewManager(cfg Config, dataDir, configDir string) (*Manager, error)

NewManager creates a new backup manager

func (*Manager) ApplyPendingRestore

func (m *Manager) ApplyPendingRestore(ctx context.Context) (*RestoreResult, error)

ApplyPendingRestore applies a pending restore operation. This should be called during startup BEFORE opening any databases.

func (*Manager) CancelPendingRestore

func (m *Manager) CancelPendingRestore() error

CancelPendingRestore cancels a pending restore operation

func (*Manager) CheckAndAutoRecover

func (m *Manager) CheckAndAutoRecover(ctx context.Context, dbPaths []string) (*AutoRecoveryResult, error)

CheckAndAutoRecover checks database integrity and automatically recovers from backup if corrupted. This should be called during application startup before opening databases.

func (*Manager) CheckDatabaseHealth

func (m *Manager) CheckDatabaseHealth(ctx context.Context) ([]string, error)

CheckDatabaseHealth checks the health of all databases in the data directory. Returns a list of corrupted database paths.

func (*Manager) Cleanup

func (m *Manager) Cleanup() (int, error)

Cleanup removes backups older than retention period

func (*Manager) CleanupAutoBackupsKeepLatest

func (m *Manager) CleanupAutoBackupsKeepLatest() (int, error)

CleanupAutoBackupsKeepLatest keeps only the newest auto backup and removes older auto backups.

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, backupType BackupType) (*BackupInfo, error)

Create creates a new backup

func (*Manager) CreateCheckpoint

func (m *Manager) CreateCheckpoint(ctx context.Context, reason string) (*BackupInfo, error)

CreateCheckpoint creates a full backup checkpoint of the current state.

func (*Manager) Delete

func (m *Manager) Delete(id string) error

Delete removes a backup

func (*Manager) Get

func (m *Manager) Get(id string) (*BackupInfo, error)

Get returns a specific backup by ID

func (*Manager) GetLatestBackup

func (m *Manager) GetLatestBackup() *BackupInfo

GetLatestBackup returns the most recent backup, or nil if no backups exist.

func (*Manager) GetPendingRestore

func (m *Manager) GetPendingRestore() (*PendingRestore, error)

GetPendingRestore returns the pending restore info if any

func (*Manager) GetProgress

func (m *Manager) GetProgress() *Progress

GetProgress returns the current progress

func (*Manager) HasPendingRestore

func (m *Manager) HasPendingRestore() bool

HasPendingRestore checks if there is a pending restore operation

func (*Manager) List

func (m *Manager) List() []*BackupInfo

List returns all available backups

func (*Manager) ListFiles

func (m *Manager) ListFiles(id string) ([]string, error)

ListFiles returns the list of files in a backup

func (*Manager) RecoverFromLatestBackup

func (m *Manager) RecoverFromLatestBackup(ctx context.Context) (*AutoRecoveryResult, error)

RecoverFromLatestBackup attempts to recover from the most recent valid backup.

func (*Manager) RepairChecksum

func (m *Manager) RepairChecksum(id string) error

RepairChecksum recalculates and updates the checksum for a backup

func (*Manager) Restore

func (m *Manager) Restore(ctx context.Context, id string, opts RestoreOptions) (*RestoreResult, error)

Restore restores a backup

func (*Manager) RestoreFile

func (m *Manager) RestoreFile(ctx context.Context, id string, filePath string, targetPath string) error

RestoreFile restores a single file from a backup

func (*Manager) StageRestore

func (m *Manager) StageRestore(ctx context.Context, id string) (*PendingRestore, error)

StageRestore prepares a backup for restore on next restart. This is the recommended approach for hot recovery to avoid database lock issues. The actual restore will happen when ApplyPendingRestore is called during startup.

func (*Manager) StartAutoBackup

func (m *Manager) StartAutoBackup(parent context.Context)

StartAutoBackup starts background auto backup (periodic and/or change-triggered).

func (*Manager) StopAutoBackup

func (m *Manager) StopAutoBackup()

StopAutoBackup stops the background auto backup loop.

func (*Manager) Verify

func (m *Manager) Verify(id string) error

Verify checks the integrity of a backup

type Migration

type Migration struct {
	Version     string                                      `json:"version"`
	Description string                                      `json:"description"`
	Up          func(ctx context.Context, m *Manager) error `json:"-"`
	Down        func(ctx context.Context, m *Manager) error `json:"-"`
}

Migration represents a database/config migration.

type MigrationHistory

type MigrationHistory struct {
	CurrentVersion string            `json:"current_version"`
	Migrations     []MigrationRecord `json:"migrations"`
}

MigrationHistory stores the history of applied migrations.

type MigrationManager

type MigrationManager struct {
	// contains filtered or unexported fields
}

MigrationManager handles version migrations.

func NewMigrationManager

func NewMigrationManager(m *Manager, dataDir string) *MigrationManager

NewMigrationManager creates a new migration manager.

func (*MigrationManager) CheckCompatibility

func (mm *MigrationManager) CheckCompatibility(backupVersion, currentVersion string) (*CompatibilityResult, error)

CheckCompatibility checks if a backup is compatible with the current version.

func (*MigrationManager) GetCurrentVersion

func (mm *MigrationManager) GetCurrentVersion() (string, error)

GetCurrentVersion returns the current schema version.

func (*MigrationManager) GetHistory

func (mm *MigrationManager) GetHistory() (*MigrationHistory, error)

GetHistory returns the migration history.

func (*MigrationManager) GetPendingMigrations

func (mm *MigrationManager) GetPendingMigrations(targetVersion string) ([]Migration, error)

GetPendingMigrations returns migrations that need to be applied.

func (*MigrationManager) Migrate

func (mm *MigrationManager) Migrate(ctx context.Context, targetVersion string) (*MigrationResult, error)

Migrate runs all pending migrations up to the target version.

func (*MigrationManager) RegisterMigration

func (mm *MigrationManager) RegisterMigration(m Migration)

RegisterMigration adds a new migration.

func (*MigrationManager) RestoreWithMigration

func (mm *MigrationManager) RestoreWithMigration(ctx context.Context, backupID string, opts RestoreOptions, currentVersion string) (*RestoreWithMigrationResult, error)

RestoreWithMigration restores a backup and applies necessary migrations.

func (*MigrationManager) Rollback

func (mm *MigrationManager) Rollback(ctx context.Context, targetVersion string) (*MigrationResult, error)

Rollback rolls back to a specific version.

type MigrationRecord

type MigrationRecord struct {
	Version   string `json:"version"`
	AppliedAt string `json:"applied_at"`
	Success   bool   `json:"success"`
}

MigrationRecord tracks applied migrations.

type MigrationResult

type MigrationResult struct {
	Success         bool     `json:"success"`
	Message         string   `json:"message"`
	MigrationsRun   int      `json:"migrations_run"`
	MigrationsTotal int      `json:"migrations_total"`
	AppliedVersions []string `json:"applied_versions"`
	Errors          []string `json:"errors,omitempty"`
}

MigrationResult contains the result of a migration operation.

type PendingRestore

type PendingRestore struct {
	BackupID   string `json:"backup_id"`
	BackupPath string `json:"backup_path"`
	StagingDir string `json:"staging_dir"`
	CreatedAt  string `json:"created_at"`
}

PendingRestore represents a pending restore operation that will be applied on restart

type Progress

type Progress struct {
	InProgress     bool      `json:"in_progress"`
	Operation      string    `json:"operation"` // "backup" or "restore"
	ProgressPct    int       `json:"progress"`  // 0-100
	CurrentFile    string    `json:"current_file"`
	FilesProcessed int       `json:"files_processed"`
	TotalFiles     int       `json:"total_files"`
	BytesProcessed int64     `json:"bytes_processed"`
	TotalBytes     int64     `json:"total_bytes"`
	StartedAt      time.Time `json:"started_at"`
	Error          string    `json:"error,omitempty"`
}

Progress tracks the current backup/restore operation

type ProgressResponse

type ProgressResponse struct {
	InProgress     bool   `json:"in_progress"`
	Operation      string `json:"operation"` // "backup" or "restore"
	Progress       int    `json:"progress"`  // 0-100
	CurrentFile    string `json:"current_file"`
	FilesProcessed int    `json:"files_processed"`
	TotalFiles     int    `json:"total_files"`
	BytesProcessed int64  `json:"bytes_processed"`
	TotalBytes     int64  `json:"total_bytes"`
	StartedAt      string `json:"started_at"`
	Error          string `json:"error,omitempty"`
}

ProgressResponse represents the backup/restore progress

type RestoreOptions

type RestoreOptions struct {
	// OverwriteExisting overwrites existing files
	OverwriteExisting bool
	// RestoreConfig restores configuration files
	RestoreConfig bool
	// RestoreData restores data files
	RestoreData bool
	// RestoreSkills restores skills files
	RestoreSkills bool
	// CreateCheckpoint creates a full backup before restore.
	CreateCheckpoint bool
	// CheckpointReason tags the pre-restore checkpoint metadata.
	CheckpointReason string
	// DryRun only validates without actually restoring
	DryRun bool
	// SkipVerify skips checksum verification
	// Security: This option is deprecated and will log a warning.
	// Checksum verification is critical for detecting tampered backups.
	SkipVerify bool
	// RequireRestart if true, stages the restore for next restart instead of immediate restore
	// This is the recommended approach for hot recovery to avoid database lock issues
	RequireRestart bool
}

RestoreOptions configures restore behavior

func DefaultRestoreOptions

func DefaultRestoreOptions() RestoreOptions

DefaultRestoreOptions returns default restore options Security: SkipVerify defaults to false to ensure backup integrity

type RestoreRequest

type RestoreRequest struct {
	Force            bool  `json:"force"`                       // Skip checksum verification
	RequireRestart   *bool `json:"require_restart,omitempty"`   // Default true for DB-safe restore
	CreateCheckpoint *bool `json:"create_checkpoint,omitempty"` // Default true
	AutoRestart      *bool `json:"auto_restart,omitempty"`      // Default true when require_restart=true
}

RestoreRequest represents a restore request

type RestoreResult

type RestoreResult struct {
	Success          bool     `json:"success"`
	FilesRestored    int      `json:"files_restored"`
	FilesSkipped     int      `json:"files_skipped"`
	CheckpointID     string   `json:"checkpoint_id,omitempty"`
	CheckpointAt     string   `json:"checkpoint_at,omitempty"`
	CheckpointReason string   `json:"checkpoint_reason,omitempty"`
	Errors           []string `json:"errors,omitempty"`
}

RestoreResult contains the result of a restore operation

type RestoreWithMigrationResult

type RestoreWithMigrationResult struct {
	Success         bool                 `json:"success"`
	Message         string               `json:"message"`
	Compatibility   *CompatibilityResult `json:"compatibility"`
	RestoreResult   *RestoreResult       `json:"restore_result,omitempty"`
	MigrationResult *MigrationResult     `json:"migration_result,omitempty"`
}

RestoreWithMigrationResult contains the result of a restore with migration.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL