Documentation
¶
Overview ¶
Package litebackup backs up, replicates, and restores SQLite databases with Litebackup from a Go program. It talks to the litebackup daemon of a session over its unix socket, as the litebackup command does, and starts the daemon when it is not running, with the credential in LITEBACKUP_API_KEY.
The everyday calls are package functions over a shared client:
_, err := litebackup.StartBackup(ctx, "/var/lib/app/main.db", nil)
Connect returns a Client for everything else. Managed runs code against a database it acquires, opens, closes, and releases.
Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.8.2 DO NOT EDIT.
Index ¶
- Constants
- Variables
- func Backup(ctx context.Context, path string, args *BackupArgs) error
- func Binary() (string, error)
- func DatabasePath(ctx context.Context, db *sql.DB) (string, error)
- func InstallCommand() string
- func IsCode(err error, code string) bool
- func SessionSocket(session string) (string, string, error)
- type AcquireArgs
- type AcquireRequest
- type AcquireResult
- type AcquireResultDecision
- type Adapter
- type ArchivedVersion
- type BackupArgs
- type BackupList
- type BackupRequest
- type BackupRequestWatch
- type BackupRule
- type Client
- func (c *Client) Acquire(ctx context.Context, name string, args *AcquireArgs) (*AcquireResult, error)
- func (c *Client) AllDatabases(ctx context.Context) iter.Seq2[DatabaseStatus, error]
- func (c *Client) AllVersions(ctx context.Context, name string, args *VersionsArgs) iter.Seq2[RestorableVersion, error]
- func (c *Client) Backup(ctx context.Context, path string, args *BackupArgs) error
- func (c *Client) BackupRules(ctx context.Context) ([]BackupRule, error)
- func (c *Client) ClientVersion() string
- func (c *Client) Close() error
- func (c *Client) Database(ctx context.Context, name string) (*DatabaseStatus, error)
- func (c *Client) Databases(ctx context.Context) ([]DatabaseStatus, error)
- func (c *Client) DatabasesPage(ctx context.Context, args *DatabasesPageArgs) (*DatabaseStatusList, error)
- func (c *Client) Events(ctx context.Context, args *EventsArgs) (*EventList, error)
- func (c *Client) Offload(ctx context.Context, name string, args *OffloadArgs) (*DatabaseStatus, error)
- func (c *Client) Release(ctx context.Context, name string, args *ReleaseArgs) (*ReleaseResult, error)
- func (c *Client) Replicas(ctx context.Context) (*ReplicaList, error)
- func (c *Client) Replicate(ctx context.Context, name string, args *ReplicateArgs) (*DatabaseStatus, error)
- func (c *Client) ReplicatePrefix(ctx context.Context, prefix string, args *ReplicatePrefixArgs) (*PrefixReplica, error)
- func (c *Client) Restore(ctx context.Context, name string, args *RestoreArgs) (*RestoreResult, error)
- func (c *Client) Revert(ctx context.Context, name string, args *RevertArgs) (*RevertResult, error)
- func (c *Client) Session() string
- func (c *Client) Shutdown(ctx context.Context, args *ShutdownArgs) (*ShutdownResult, error)
- func (c *Client) SocketPath() string
- func (c *Client) StartBackup(ctx context.Context, path string, args *StartBackupArgs) (*BackupRule, error)
- func (c *Client) StartFailover(ctx context.Context, path string, args *FailoverArgs) (*Failover, error)
- func (c *Client) Status(ctx context.Context) (*Status, error)
- func (c *Client) StatusPage(ctx context.Context, args *StatusPageArgs) (*Status, error)
- func (c *Client) StopBackup(ctx context.Context, name string) (*StopBackupResult, error)
- func (c *Client) StopBackupRule(ctx context.Context, id string) (*StopBackupResult, error)
- func (c *Client) StopReplica(ctx context.Context, name string) error
- func (c *Client) StopReplicaPrefix(ctx context.Context, prefix string, args *StopReplicaPrefixArgs) error
- func (c *Client) Sync(ctx context.Context, name string) (*DatabaseStatus, error)
- func (c *Client) Versions(ctx context.Context, name string, args *VersionsArgs) ([]RestorableVersion, error)
- func (c *Client) VersionsPage(ctx context.Context, name string, args *VersionsArgs) (*VersionList, error)
- func (c *Client) WatchEvents(ctx context.Context, args *WatchEventsArgs) iter.Seq2[Event, error]
- func (c *Client) Writer(ctx context.Context, name string) (*Writer, error)
- type ConnectArgs
- type DatabaseStatus
- type DatabaseStatusList
- type DatabaseStatusRole
- type DatabaseStatusState
- type DatabasesPageArgs
- type DrainFailure
- type Durability
- type Error
- type ErrorCode
- type Event
- type EventList
- type EventType
- type EventsArgs
- type Failover
- type FailoverArgs
- type FailoverRequest
- type FailoverStatus
- type FindReleaseArgs
- type LeaseArgs
- type LeaseCleanupError
- type LeaseCleanupStep
- type NameRequest
- type OffloadArgs
- type OffloadRequest
- type Pool
- func (p *Pool[DB]) Close(ctx context.Context) error
- func (p *Pool[DB]) Lease(ctx context.Context, name string, args *LeaseArgs, ...) error
- func (p *Pool[DB]) Release(ctx context.Context, name string) error
- func (p *Pool[DB]) Use(ctx context.Context, name string, work func(ctx context.Context, db DB) error) error
- type PoolArgs
- type PrefixReplica
- type Release
- type ReleaseArgs
- type ReleaseFile
- type ReleaseRequest
- type ReleaseResult
- type ReplicaList
- type ReplicaRequest
- type ReplicaRequestWriteProtection
- type ReplicaResult
- type ReplicateArgs
- type ReplicatePrefixArgs
- type RestorableVersion
- type RestoreArgs
- type RestoreRequest
- type RestoreResult
- type RevertArgs
- type RevertDatabaseJSONRequestBody
- type RevertDatabaseParams
- type RevertRequest
- type RevertResult
- type Role
- type SQLAdapterArgs
- type ShutdownArgs
- type ShutdownRequest
- type ShutdownRequestDurability
- type ShutdownResult
- type StartBackupArgs
- type Status
- type StatusPageArgs
- type StopBackupRequest
- type StopBackupResult
- type StopReplicaPrefixArgs
- type StopReplicaRequest
- type SyncedState
- type VersionList
- type VersionsArgs
- type WatchEventsArgs
- type WriteProtection
- type Writer
Constants ¶
const ( // CodeInvalidArgument means an argument failed local validation; nothing was sent. CodeInvalidArgument = specCodeInvalidArgument // CodeBinaryNotFound means no litebackup binary was found to start the daemon or a foreground backup. CodeBinaryNotFound = "binary_not_found" // CodeLaunchFailed means litebackup launch ran and failed. CodeLaunchFailed = specCodeLaunchFailed // CodeDrainRequired means litebackup launch refused APIKey, a credential // other than the one the session's client took its write locks with: // Shutdown with the current credential releases them first. CodeDrainRequired = specCodeDrainRequired // CodeConnectionFailed means the socket refused the connection or closed it mid-call. CodeConnectionFailed = "connection_failed" // CodeDaemonUnsupported means the daemon is older than MinimumDaemonVersion. CodeDaemonUnsupported = "daemon_unsupported" // CodeCancelled means the caller cancelled the wait; the daemon may still finish the operation. CodeCancelled = specCodeCancelled // CodeClosed means the client was closed. CodeClosed = "closed" // CodeInvalidResponse means the daemon answered 200 with a body the SDK cannot decode. CodeInvalidResponse = "invalid_response" // CodeLeaseCleanupFailed means a pool could not close or release a leased // database; the error is a *LeaseCleanupError that says which step failed. CodeLeaseCleanupFailed = "lease_cleanup_failed" )
Codes the SDK raises itself. Their Status is 0.
const ( // CodeBusy means another job or a continuous backup holds a foreground backup's writer lock. CodeBusy = specCodeBusy // CodeFileExists means the file a restore or an acquire would write, or a // journal file beside it, already exists. CodeFileExists = specCodeFileExists // CodeLockLost means this machine lost the database's write lock: another // machine acquired it or an admin broke it. The copy is conflicted, its // file as it was. CodeLockLost = specCodeLockLost CodeLockUnavailable = specCodeLockUnavailable // CodeNotFound means the database or rule does not exist. CodeNotFound = specCodeNotFound // CodeRuleDatabase means a backup rule on this machine keeps the database // and its write lock, so it cannot be released; stop its backup instead. CodeRuleDatabase = specCodeRuleDatabase // CodeRuleExists means the path already has a backup rule with other // settings; Details["rule"] is the saved rule. CodeRuleExists = specCodeRuleExists // CodeStillOpen means a process still has the database open, so it cannot be released. CodeStillOpen = specCodeStillOpen // CodeTimeout means the operation's timeout ran out. CodeTimeout = specCodeTimeout // CodeSDKUnsupported means this SDK is older than the daemon accepts. CodeSDKUnsupported = specCodeSDKUnsupported // CodeCursorExpired means an events cursor is older than the oldest event // the daemon keeps; a watch ends with it, and the caller picks a new cursor. CodeCursorExpired = specCodeCursorExpired )
Codes the daemon answers with. Codes not listed here are kept verbatim too.
const ( // DefaultCleanupTimeout bounds closing and releasing a leased database // when PoolArgs.CleanupTimeout is 0. DefaultCleanupTimeout = 10 * time.Minute // DefaultOffloadIdleClose is how long a database a backup rule offloads // (MaximumLocalDatabases) stays open unused before the pool closes it, so // the rule can offload it, when PoolArgs.IdleClose is 0. It is well inside // the client's 10-minute idle window. DefaultOffloadIdleClose = 2 * time.Minute // DefaultIdleRelease is how long a leased database stays leased unused // before the pool releases it, when PoolArgs.IdleRelease is 0, so another // machine's lease with a LockTimeout gets it. DefaultIdleRelease = time.Minute )
const ( // CommandPackage is the package that ships the litebackup command. CommandPackage = "cli" // StableChannel is the channel installs follow unless a version is given. StableChannel = "stable" )
const ( // APIKeyEnvironment holds the credential the daemon uses when it starts, // when ConnectArgs.APIKey is empty: an API key, or a join token the // daemon exchanges once for a key of the machine, then @ and the // server's address. APIKeyEnvironment = "LITEBACKUP_API_KEY" // SessionEnvironment names the session when ConnectArgs.Session is empty. SessionEnvironment = "LITEBACKUP_SESSION" // BinaryPathEnvironment overrides the litebackup binary the SDK starts. BinaryPathEnvironment = "LITEBACKUP_PATH" // DefaultSession is the session used when nothing names one. DefaultSession = "default" )
const MinimumDaemonVersion = "1.6.0"
MinimumDaemonVersion is the oldest daemon this SDK talks to. Connect refuses an older one with daemon_unsupported.
const SDKVersion = "1.6.0"
SDKVersion is the version sent with every call. Daemons refuse SDKs older than their minimum with sdk_unsupported.
Variables ¶
var ErrBusy = errors.New("backup writer busy")
ErrBusy matches a writer lock held by another job or a continuous backup.
var ErrSignature = errors.New("the release signature does not match Litebackup's release keys")
ErrSignature means a release's signature does not match ReleaseKeys.
var ReleaseKeys = map[string]string{
"01a1ead6-4b94-79ca-81f4-3a67c112bc0b": "t3C_3l71PimyhkPZOzJ_Xi4dOuHJ1CmSdDZ8lTm0vNI",
}
ReleaseKeys are Litebackup's Ed25519 release keys by key ID, base64url without padding, as the litebackup command checks them.
var SystemConfigurationPath = "/etc/litebackup/client.json"
SystemConfigurationPath records a `litebackup install service` install. While it exists, root and the service's user reach the service's socket.
Functions ¶
func Backup ¶
func Backup(ctx context.Context, path string, args *BackupArgs) error
Backup runs once without connecting to or launching a daemon.
func Binary ¶
Binary finds the litebackup binary: LITEBACKUP_PATH, then litebackup on PATH, then ~/.local/bin/litebackup, where InstallCommand puts it for a user other than root, which an app's PATH may not include. It fails with binary_not_found and the install command when there is none.
func DatabasePath ¶
DatabasePath returns the main database file db opened, read through any driver with PRAGMA database_list, so an app that keeps only its *sql.DB can register it: StartBackup(ctx, path, nil). An in-memory or temporary database has no file and is refused with invalid_argument.
func InstallCommand ¶
func InstallCommand() string
InstallCommand is the one line that installs the litebackup command on Linux and macOS for whoever runs it: into ~/.local/bin, or /usr/local/bin as root.
func IsCode ¶
IsCode reports whether err, or any error it wraps or joins, is an *Error with the given code.
func SessionSocket ¶
SessionSocket resolves a session's name and socket exactly as the litebackup command does. Where `litebackup install service` ran as root, root and the service's user use the service's socket; where a user installed a service of their own, that user uses the directory it recorded, whatever this process's environment. Everyone else uses $XDG_RUNTIME_DIR/litebackup/<session>/client.sock, or a per-user directory under the temporary directory, which must be this user's alone.
Types ¶
type AcquireArgs ¶
type AcquireArgs struct {
// Path is the local file; the path this machine already uses when empty,
// which brings an offloaded database back.
Path string
// Maintenance checkpoints on release and VACUUMs past the freelist threshold.
Maintenance bool
// OffloadOnRelease lets Litebackup remove the local copy once
// OffloadDurability holds the released version; the copy stays when false.
OffloadOnRelease bool
// OffloadDurability is what an offload of the released copy waits for:
// DurabilityServer, the default when empty, once the server holds its
// last version, or DurabilityCloud once the bucket holds it too.
OffloadDurability Durability
// MachineLabel is what other machines see as the writer.
MachineLabel string
// Timeout bounds downloading the head.
Timeout time.Duration
// LockTimeout is how long to wait while another machine holds the write
// lock, trying again until it is released; 0 fails at once with
// lock_unavailable. The daemon tries again with backoff, and the call may
// take Timeout plus LockTimeout.
LockTimeout time.Duration
// Umask is the file mode creation mask a file the acquire creates gets:
// 0666 less it, as a file the caller created would. A copy the head
// replaces keeps its bits. This process's umask when nil.
Umask *fs.FileMode
// DiscardLocal replaces a local file that diverged from the server head
// with the head, discarding its writes the head lacks. Without it such a
// file is refused with conflict and left untouched.
DiscardLocal bool
}
AcquireArgs configures an acquired database.
type AcquireRequest ¶
type AcquireRequest struct {
// DiscardLocal replace a local file that diverged from the server head with the head, discarding its writes the head lacks; without it such a file is refused with 409 conflict and left untouched
DiscardLocal bool `json:"discard_local,omitempty"`
// LockTimeoutMillis how long to wait for the write lock while another machine holds it, trying again until it is released; 0 refuses at once with lock_unavailable. It adds to the timeout.
LockTimeoutMillis int64 `json:"lock_timeout_millis,omitempty"`
// MachineLabel the name this machine shows on the server and as the writer of this database only
MachineLabel string `json:"machine_label,omitempty"`
// Maintenance checkpoint and, past the freelist threshold, VACUUM on release
Maintenance bool `json:"maintenance,omitempty"`
Name string `json:"name"`
// OffloadDurability how far a version must reach: server once the server holds it, cloud once the bucket holds it too
OffloadDurability Durability `json:"offload_durability,omitempty"`
// OffloadOnRelease lets Litebackup delete the released copy once offload_durability holds it
OffloadOnRelease bool `json:"offload_on_release,omitempty"`
// Path absolute path of the local file; defaults to the path this machine uses
Path string `json:"path,omitempty"`
// TimeoutMillis bound on downloading the head
TimeoutMillis int64 `json:"timeout_millis,omitempty"`
// Umask the caller's file mode creation mask, such as 18 for 022; a file the acquire creates, the head downloaded where none was or the empty file an offload removed, gets 0666 less it, as one the caller created would. A copy the head replaces keeps its bits. Absent uses the client's own umask. The litebackup command sends its own.
Umask *int32 `json:"umask,omitempty"`
}
AcquireRequest defines model for AcquireRequest.
type AcquireResult ¶
type AcquireResult struct {
Database DatabaseStatus `json:"database"`
// Decision what the acquire did to the local file
Decision AcquireResultDecision `json:"decision"`
}
AcquireResult defines model for AcquireResult.
type AcquireResultDecision ¶
type AcquireResultDecision string
AcquireResultDecision what the acquire did to the local file
const ( AcquireResultDecisionCreated AcquireResultDecision = "created" AcquireResultDecisionDownloaded AcquireResultDecision = "downloaded" AcquireResultDecisionFastForwarded AcquireResultDecision = "fast_forwarded" AcquireResultDecisionMatched AcquireResultDecision = "matched" AcquireResultDecisionReplaced AcquireResultDecision = "replaced" AcquireResultDecisionResumed AcquireResultDecision = "resumed" )
Defines values for AcquireResultDecision.
func (AcquireResultDecision) Valid ¶
func (e AcquireResultDecision) Valid() bool
Valid indicates whether the value is a known member of the AcquireResultDecision enum.
type Adapter ¶
type Adapter[DB any] interface { Open(ctx context.Context, path string) (DB, error) Close(ctx context.Context, db DB) error }
Adapter opens and closes the handle a Pool gives to its calls. Open must open an existing file and never create one: a missing file is an offloaded copy the pool brings back, never an empty new database. Close must roll back a transaction a call left unfinished and never commit it, and must report an error when a connection may still be open: the pool releases a leased database only after Close succeeds.
func SQLAdapter ¶
func SQLAdapter(driverName string, args *SQLAdapterArgs) Adapter[*sql.DB]
SQLAdapter opens a pool's databases with database/sql and the named driver, such as "sqlite" (modernc.org/sqlite) or "sqlite3" (github.com/mattn/go-sqlite3).
Open refuses a missing file with not_found and opens the existing one in mode=rw. Close closes the *sql.DB. Commit what the work should keep: closing a SQLite connection rolls back its unfinished transaction. A connection still in use, such as a transaction the work never ended, makes Close fail, so a leased database is not released while it may still be written.
type ArchivedVersion ¶
type ArchivedVersion struct {
// Archived when the server recorded the version as archived
Archived time.Time `json:"archived,omitempty"`
Version int64 `json:"version"`
}
ArchivedVersion The newest version the server reported the primary bucket holds.
type BackupArgs ¶
type BackupArgs struct {
// Name is the exact remote name of a single file; the file name when empty.
Name string
// Prefix puts each backed-up file under this namespace.
Prefix string
// Durability is DurabilityServer, the default and enough in most cases,
// or DurabilityCloud to wait for the bucket too.
Durability Durability
// Timeout bounds the job, which then fails with timeout. A job that does
// not answer within Timeout plus 30 seconds is stopped.
Timeout time.Duration
}
BackupArgs configures a foreground backup job.
type BackupList ¶
type BackupList struct {
Rules []BackupRule `json:"rules"`
}
BackupList defines model for BackupList.
type BackupRequest ¶
type BackupRequest struct {
// MaximumLocalDatabases when positive, offload the least recently changed idle databases past this count once offload_durability holds them
MaximumLocalDatabases int64 `json:"maximum_local_databases,omitempty"`
// Name the database name for a single path; must already be a valid name
Name string `json:"name,omitempty"`
// OffloadDurability how far a version must reach: server once the server holds it, cloud once the bucket holds it too
OffloadDurability Durability `json:"offload_durability,omitempty"`
// OffloadRollbackJournal lets maximum_local_databases offload rollback-journal databases too, on the operator's word that nothing keeps them open while idle; WAL databases are offloaded either way
OffloadRollbackJournal bool `json:"offload_rollback_journal,omitempty"`
// Path absolute file, directory, or glob with optional ** segments
Path string `json:"path"`
// Prefix name prefix such as app/ (a trailing / is added when missing); names are the prefix plus the relative file path
Prefix string `json:"prefix,omitempty"`
Watch BackupRequestWatch `json:"watch,omitempty"`
}
BackupRequest defines model for BackupRequest.
type BackupRequestWatch ¶
type BackupRequestWatch string
BackupRequestWatch defines model for BackupRequest.Watch.
const ( BackupRequestWatchInotify BackupRequestWatch = "inotify" BackupRequestWatchPoll BackupRequestWatch = "poll" )
Defines values for BackupRequestWatch.
func (BackupRequestWatch) Valid ¶
func (e BackupRequestWatch) Valid() bool
Valid indicates whether the value is a known member of the BackupRequestWatch enum.
type BackupRule ¶
type BackupRule struct {
Failover bool `json:"failover"`
ID string `json:"id"`
MaximumLocalDatabases int64 `json:"maximum_local_databases"`
// Name the resolved remote name for a single file, or empty for a directory or glob
Name string `json:"name"`
// OffloadDurability how far a version must reach: server once the server holds it, cloud once the bucket holds it too
OffloadDurability Durability `json:"offload_durability"`
OffloadRollbackJournal bool `json:"offload_rollback_journal"`
// Path the path or glob
Path string `json:"path"`
Prefix string `json:"prefix"`
Watch string `json:"watch"`
}
BackupRule defines model for BackupRule.
func StartBackup ¶
func StartBackup(ctx context.Context, path string, args *StartBackupArgs) (*BackupRule, error)
StartBackup saves a continuous rule in the local daemon.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to the daemon of one session.
func Connect ¶
func Connect(ctx context.Context, args *ConnectArgs) (*Client, error)
Connect connects to a session's daemon, starting it like the litebackup command does when nothing listens on its socket. It refuses a daemon older than MinimumDaemonVersion with daemon_unsupported.
func Default ¶
Default returns the shared client the package functions use, connecting on first use. One caller connects at a time; the others wait for it, each only as long as its own context allows. A failed connection is tried again by the next caller.
func (*Client) Acquire ¶
func (c *Client) Acquire( ctx context.Context, name string, args *AcquireArgs, ) (*AcquireResult, error)
Acquire takes the write lock on a database and makes the local file the server's head, for worker pools that move databases between machines. Managed acquires, opens, closes, and releases around a function.
func (*Client) AllDatabases ¶
AllDatabases iterates every database on this machine, a page at a time. It ends after yielding an error.
func (*Client) AllVersions ¶
func (c *Client) AllVersions( ctx context.Context, name string, args *VersionsArgs, ) iter.Seq2[RestorableVersion, error]
AllVersions iterates the versions of a database the server can restore, oldest first, after args.After and at most args.Limit when positive. It ends after yielding an error.
func (*Client) Backup ¶
Backup runs the foreground job for this session. Close ends a job in flight, as cancelling ctx does.
func (*Client) BackupRules ¶
func (c *Client) BackupRules(ctx context.Context) ([]BackupRule, error)
BackupRules lists every backup and failover rule on this machine.
func (*Client) ClientVersion ¶
ClientVersion is the daemon's version, from its last answer.
func (*Client) Close ¶
Close stops following the client's failovers, ends its calls in flight, and closes its connections. The daemon keeps running, and so do the failovers and any acquired databases. Calls after Close fail with closed.
func (*Client) Databases ¶
func (c *Client) Databases(ctx context.Context) ([]DatabaseStatus, error)
Databases returns every database. AllDatabases iterates with bounded memory.
func (*Client) DatabasesPage ¶
func (c *Client) DatabasesPage( ctx context.Context, args *DatabasesPageArgs, ) (*DatabaseStatusList, error)
DatabasesPage returns one page of databases. Pass Next as After to continue.
func (*Client) Events ¶
Events returns one page of events, oldest first, waiting up to Wait for the first new one. WatchEvents follows them.
func (*Client) Offload ¶
func (c *Client) Offload( ctx context.Context, name string, args *OffloadArgs, ) (*DatabaseStatus, error)
Offload removes the local file of a released database once the server holds its last version, or the bucket with DurabilityCloud; until then it fails with not_durable. Acquire brings it back.
func (*Client) Release ¶
func (c *Client) Release( ctx context.Context, name string, args *ReleaseArgs, ) (*ReleaseResult, error)
Release syncs an acquired database a final time, runs its maintenance, and releases its write lock. Every connection to it must be closed first, or it fails with still_open once Timeout runs out.
func (*Client) Replicas ¶
func (c *Client) Replicas(ctx context.Context) (*ReplicaList, error)
Replicas lists prefix replicas and every replica on this machine.
func (*Client) Replicate ¶
func (c *Client) Replicate( ctx context.Context, name string, args *ReplicateArgs, ) (*DatabaseStatus, error)
Replicate keeps a live readonly replica of a database that streams from the server, and returns once its first version is local.
func (*Client) ReplicatePrefix ¶
func (c *Client) ReplicatePrefix( ctx context.Context, prefix string, args *ReplicatePrefixArgs, ) (*PrefixReplica, error)
ReplicatePrefix registers live readonly replicas of current and future databases under prefix. An empty prefix follows all databases. Downloads happen in the background; returning does not mean every replica is local.
func (*Client) Restore ¶
func (c *Client) Restore( ctx context.Context, name string, args *RestoreArgs, ) (*RestoreResult, error)
Restore writes a version of a database to a new file and checks it.
func (*Client) Revert ¶
func (c *Client) Revert( ctx context.Context, name string, args *RevertArgs, ) (*RevertResult, error)
Revert rolls a database back under its own name: the content of a past version becomes a new head, one past the current head, and every later version stays restorable. The database must be one this machine acquired or backs up, and its file closed (still_open otherwise); a replica or a failover standby is refused (invalid_argument), and a file holding writes the server lacks is refused with conflict and left untouched. The daemon takes the write lock when it does not hold it and gives it back once the new head is synced. When that sync fails for any reason but a lost lock or a refused file, which are final, the daemon keeps the lock and syncs again on its own, so release an acquired database afterwards.
func (*Client) Shutdown ¶
func (c *Client) Shutdown(ctx context.Context, args *ShutdownArgs) (*ShutdownResult, error)
Shutdown syncs every database a final time, releases every write lock, ends the session, and stops the daemon. A backup another machine writes holds no lock and stays waiting. Each database it could not sync or release is in Failures, with its code, and keeps any write lock it holds; the session and the daemon then stay. An empty Failures is the only complete shutdown. Close never does this.
func (*Client) StartBackup ¶
func (c *Client) StartBackup( ctx context.Context, path string, args *StartBackupArgs, ) (*BackupRule, error)
StartBackup saves a continuous backup rule for a file, directory, or glob and returns once the daemon saved it; listing and uploads run in the background. Starting the same path again with the same settings returns the saved rule, so call it on every start. Other settings for a saved path fail with rule_exists, and the error's Details["rule"] is the saved rule.
func (*Client) StartFailover ¶
func (c *Client) StartFailover( ctx context.Context, path string, args *FailoverArgs, ) (*Failover, error)
StartFailover starts a failover of the database at path, the same path on every machine, and returns once this machine is the origin or holds a replica. Callbacks run on one goroutine per failover, in event order; the first is OnRoleChange with the role the start answered.
func (*Client) Status ¶
Status returns the session, its server, and the first page of databases on this machine.
func (*Client) StatusPage ¶
StatusPage returns the session, its server, and one page of databases.
func (*Client) StopBackup ¶
StopBackup stops the single-file backup for an exact remote name on this machine.
func (*Client) StopBackupRule ¶
StopBackupRule stops a whole rule and its future listings using its saved ID.
func (*Client) StopReplica ¶
StopReplica stops a replica. The file stays, unlocked, at its last version.
func (*Client) StopReplicaPrefix ¶
func (c *Client) StopReplicaPrefix( ctx context.Context, prefix string, args *StopReplicaPrefixArgs, ) error
StopReplicaPrefix stops a prefix replica and its replicas. Files stay, unlocked, at their last versions. Use the same prefix and directory as at start.
func (*Client) Versions ¶
func (c *Client) Versions( ctx context.Context, name string, args *VersionsArgs, ) ([]RestorableVersion, error)
Versions lists the versions of a database the server can restore, oldest first. AllVersions iterates with bounded memory.
func (*Client) VersionsPage ¶
func (c *Client) VersionsPage( ctx context.Context, name string, args *VersionsArgs, ) (*VersionList, error)
VersionsPage returns one page of versions after args.After, at most args.Limit when positive. Pass Next as After to continue; 0 means no more.
func (*Client) WatchEvents ¶
WatchEvents yields events, oldest first, by long-polling the daemon until the caller stops or ctx ends. A failed long-poll is retried with backoff from the same cursor; cancellation, a closed client, sdk_unsupported, invalid_argument, and cursor_expired (the cursor is older than the oldest event kept; choose a new one) are yielded as the last error.
type ConnectArgs ¶
type ConnectArgs struct {
// APIKey is the credential the daemon uses when it starts: an API key,
// or a join token it exchanges once for a key of this machine, then @
// and the server's address. It overrides LITEBACKUP_API_KEY. The daemon
// keeps the key it saved unless this holds a different credential, which
// the launch refuses with CodeDrainRequired while the client holds write
// locks; a daemon already running keeps its key until it restarts.
// Foreground backups use it too.
APIKey string
// Session names the session; LITEBACKUP_SESSION, then "default", when empty.
Session string
// SocketPath connects to this socket and never starts a daemon.
SocketPath string
// BinaryPath is the litebackup binary that starts the daemon; see Binary
// for the search when empty.
BinaryPath string
}
ConnectArgs selects the session a Client talks to.
type DatabaseStatus ¶
type DatabaseStatus struct {
// Acquired the database is acquired and released by a worker rather than backed up continuously
Acquired bool `json:"acquired"`
// BackupRuleID the backup or failover rule that tracks the database on this machine; absent for an acquired database and a replica
BackupRuleID string `json:"backup_rule_id,omitempty"`
// Draining set on a failover origin while this machine drains, and on one a drain released, which holds no write lock until it takes one again; a failover then reports its role as unknown, as after a draining event
Draining bool `json:"draining,omitempty"`
Error string `json:"error,omitempty"`
Failed time.Time `json:"failed,omitempty"`
// Failover the database belongs to a failover and changes role when the origin does
Failover bool `json:"failover"`
FullScanReason string `json:"full_scan_reason,omitempty"`
HintMisses int64 `json:"hint_misses"`
// JournalMode wal, rollback, or unknown before the first scan. A full scan of a rollback-journal database holds a read lock that blocks the app's writers until it ends, so it runs at full speed rather than at --scan-bytes-per-second, and the first scan past 256 MB records a rollback_scan event with its duration. Switch such a database to WAL mode (PRAGMA journal_mode = WAL), where scans never block writers; Litebackup never changes the journal mode itself.
JournalMode string `json:"journal_mode"`
LocalChanged bool `json:"local_changed"`
// MachineLabel the name this machine shows on the server and as the writer of its databases
MachineLabel string `json:"machine_label,omitempty"`
Maintenance bool `json:"maintenance,omitempty"`
Name string `json:"name"`
// NextRetry when the next attempt of a failed sync runs; absent when none is scheduled
NextRetry time.Time `json:"next_retry,omitempty"`
// OffloadDurability how far a version must reach: server once the server holds it, cloud once the bucket holds it too
OffloadDurability Durability `json:"offload_durability,omitempty"`
// OffloadOnRelease the client deletes the released copy once offload_durability holds it
OffloadOnRelease bool `json:"offload_on_release,omitempty"`
// Offloaded when the local file was removed because the server or the bucket holds its version; absent once an acquire brings it back
Offloaded time.Time `json:"offloaded,omitempty"`
PageCount int64 `json:"page_count"`
Path string `json:"path"`
// Pending when a backup or failover origin was left without its write lock, by a start, a drain, or a dropped lock; absent once a sync takes the lock
Pending time.Time `json:"pending,omitempty"`
// Released when this machine last released the database
Released time.Time `json:"released,omitempty"`
// Retrying when the current run of failed syncs began, with the first failure after the last success; absent once a sync succeeds
Retrying time.Time `json:"retrying,omitempty"`
// Role origin when this machine writes the database and backs it up; replica for a live readonly copy
Role DatabaseStatusRole `json:"role"`
// State pending while a backup or failover origin holds no write lock, as after a start or a drain, until a sync takes it (a start takes back the lock of each backup a drain left pending while the head is still the version it last synced); syncing while changes stream; retrying while an origin's syncs fail, with error saying why and next_retry when the next attempt runs; synced when the server holds every change: a backup or failover origin whose last sync landed with no change seen after it, until its next change, or a released database whose last version is on the server; waiting while another machine is the origin; offloaded when the local file was removed because the server, or the bucket when the offload asked for it, holds its last version; stopped for a stopped replica; conflicted when this copy was refused and left as it is, because its file differs from the server head or its write lock was lost or broken; error, with error saying why
State DatabaseStatusState `json:"state"`
SyncCount int64 `json:"sync_count"`
// Synced when the newest sync landed, the time synced_server holds
Synced time.Time `json:"synced,omitempty"`
// SyncedCloud The newest version the server reported the primary bucket holds.
SyncedCloud ArchivedVersion `json:"synced_cloud"`
// SyncedServer A version the server acknowledged. Clients decide what durability is enough.
SyncedServer SyncedState `json:"synced_server"`
// Syncing when the first change the server lacks was seen; absent when the server has every change seen. It survives restarts and may be earlier than the real first change, never later.
Syncing time.Time `json:"syncing,omitempty"`
// WriterMachineLabel the machine label of the last writer this machine saw; empty once this machine released the database, drained it, or offloaded a copy whose write lock it held, as no writer is known then
WriterMachineLabel string `json:"writer_machine_label,omitempty"`
}
DatabaseStatus defines model for DatabaseStatus.
func Replicate ¶
func Replicate(ctx context.Context, name string, args *ReplicateArgs) (*DatabaseStatus, error)
Replicate starts a replica with the shared client; see Client.Replicate.
type DatabaseStatusList ¶
type DatabaseStatusList struct {
Databases []DatabaseStatus `json:"databases"`
// Next Pass this name as after to read the next page. Omitted on the last page.
Next string `json:"next,omitempty"`
}
DatabaseStatusList defines model for DatabaseStatusList.
type DatabaseStatusRole ¶
type DatabaseStatusRole string
DatabaseStatusRole origin when this machine writes the database and backs it up; replica for a live readonly copy
const ( DatabaseStatusRoleOrigin DatabaseStatusRole = "origin" DatabaseStatusRoleReplica DatabaseStatusRole = "replica" )
Defines values for DatabaseStatusRole.
func (DatabaseStatusRole) Valid ¶
func (e DatabaseStatusRole) Valid() bool
Valid indicates whether the value is a known member of the DatabaseStatusRole enum.
type DatabaseStatusState ¶
type DatabaseStatusState string
DatabaseStatusState pending while a backup or failover origin holds no write lock, as after a start or a drain, until a sync takes it (a start takes back the lock of each backup a drain left pending while the head is still the version it last synced); syncing while changes stream; retrying while an origin's syncs fail, with error saying why and next_retry when the next attempt runs; synced when the server holds every change: a backup or failover origin whose last sync landed with no change seen after it, until its next change, or a released database whose last version is on the server; waiting while another machine is the origin; offloaded when the local file was removed because the server, or the bucket when the offload asked for it, holds its last version; stopped for a stopped replica; conflicted when this copy was refused and left as it is, because its file differs from the server head or its write lock was lost or broken; error, with error saying why
const ( DatabaseStatusStateConflicted DatabaseStatusState = "conflicted" DatabaseStatusStateError DatabaseStatusState = "error" DatabaseStatusStateOffloaded DatabaseStatusState = "offloaded" DatabaseStatusStatePending DatabaseStatusState = "pending" DatabaseStatusStateRetrying DatabaseStatusState = "retrying" DatabaseStatusStateStopped DatabaseStatusState = "stopped" DatabaseStatusStateSynced DatabaseStatusState = "synced" DatabaseStatusStateSyncing DatabaseStatusState = "syncing" DatabaseStatusStateWaiting DatabaseStatusState = "waiting" )
Defines values for DatabaseStatusState.
func (DatabaseStatusState) Valid ¶
func (e DatabaseStatusState) Valid() bool
Valid indicates whether the value is a known member of the DatabaseStatusState enum.
type DatabasesPageArgs ¶
type DatabasesPageArgs struct {
// After returns databases whose names sort after this one; pass Next to continue.
After string
// Limit returns at most this many databases, up to 1000; 100 when 0.
Limit int
}
DatabasesPageArgs selects a page of databases. Nil reads the first page of 100.
type DrainFailure ¶
type DrainFailure struct {
// Code What went wrong, in one word. The socket answers with file_exists (the file a restore or an acquire would write, or a -journal, -wal, or -shm beside it, already exists), rule_exists (a backup rule with other settings already covers the path, and the error carries that rule), lock_unavailable (another machine holds the write lock a command asks for, as an acquire, a revert, or a failover does), not_found, still_open, invalid_argument, timeout, cursor_expired (an events cursor older than the oldest event kept), changed (an offload or acquire refused because the local file changed under it: written after its last sync, never synced, or written while an acquire replaced it), rule_database (a release of a database a backup rule on this machine keeps, whose write lock the rule never gives up; stop its backup to hand it off), not_durable (an offload refused until the server, or the bucket when it waits for cloud, holds the synced version, or a cloud wait whose name now holds another server database), and the others by their names; busy (a foreground backup refused because another job, a continuous backup, or another machine writes the database), cancelled (a command interrupted before it finished), drain_required (a credential other than the one the client took its write locks with, refused until a drain released them), and launch_failed (the command could not start the client on this machine, or the client exited before it listened) come from the litebackup command alone, which also answers unauthenticated when this machine has not joined a server. A refusal from the server becomes client_unsupported (426: the server needs a newer litebackup on this machine) or, with 503, not_configured (the server waits for setup), wrong_server (the server this machine reached is not the one its session joined, or does not own the database), unauthenticated (the server no longer accepts this machine's key), forbidden (the key may not do this), plan_limit (the server's plan has no room for another database), rate_limited (the server sheds load and asks to be tried later: a restore retries it for about 30 seconds, as its Retry-After says, before it answers so), or integrity (the version's bucket objects failed an integrity check). A restore answers integrity too when every page of the version arrived intact but SQLite's quick_check finds the database damaged: the version itself is corrupt, so a retry gives the same file, and an earlier version is the way back. A transfer cut short stays unavailable. lock_unavailable, lock_lost, not_found, invalid_argument, and timeout keep their meaning, and any other refusal (a busy server, one short of disk, one unreachable) is unavailable. A client treats a code it does not know as a failure.
Code ErrorCode `json:"code"`
Message string `json:"message"`
Name string `json:"name"`
}
DrainFailure defines model for DrainFailure.
type Durability ¶
type Durability string
Durability how far a version must reach: server once the server holds it, cloud once the bucket holds it too
const ( DurabilityCloud Durability = "cloud" DurabilityServer Durability = "server" )
Defines values for Durability.
const DurabilityNone Durability = "none"
DurabilityNone is the Durability a shutdown takes to return without waiting for any final sync to reach the server.
func (Durability) Valid ¶
func (e Durability) Valid() bool
Valid indicates whether the value is a known member of the Durability enum.
type Error ¶
type Error struct {
// Code is the daemon's code verbatim, or one of the Code constants.
Code string
Message string
// Status is the HTTP status of the answer, or 0 for errors the SDK raised.
Status int
// Details holds the answer's fields besides code and message under their
// wire names, such as "rule" for rule_exists from StartBackup. For
// lease_cleanup_failed it holds step, name, path, and acquired or durability.
Details map[string]any
// Err is the underlying error, such as the context's error for cancelled.
Err error
}
Error is every failure the SDK returns: the daemon's answer, or an error the SDK raised itself with Status 0.
type ErrorCode ¶
type ErrorCode string
ErrorCode What went wrong, in one word. The socket answers with file_exists (the file a restore or an acquire would write, or a -journal, -wal, or -shm beside it, already exists), rule_exists (a backup rule with other settings already covers the path, and the error carries that rule), lock_unavailable (another machine holds the write lock a command asks for, as an acquire, a revert, or a failover does), not_found, still_open, invalid_argument, timeout, cursor_expired (an events cursor older than the oldest event kept), changed (an offload or acquire refused because the local file changed under it: written after its last sync, never synced, or written while an acquire replaced it), rule_database (a release of a database a backup rule on this machine keeps, whose write lock the rule never gives up; stop its backup to hand it off), not_durable (an offload refused until the server, or the bucket when it waits for cloud, holds the synced version, or a cloud wait whose name now holds another server database), and the others by their names; busy (a foreground backup refused because another job, a continuous backup, or another machine writes the database), cancelled (a command interrupted before it finished), drain_required (a credential other than the one the client took its write locks with, refused until a drain released them), and launch_failed (the command could not start the client on this machine, or the client exited before it listened) come from the litebackup command alone, which also answers unauthenticated when this machine has not joined a server. A refusal from the server becomes client_unsupported (426: the server needs a newer litebackup on this machine) or, with 503, not_configured (the server waits for setup), wrong_server (the server this machine reached is not the one its session joined, or does not own the database), unauthenticated (the server no longer accepts this machine's key), forbidden (the key may not do this), plan_limit (the server's plan has no room for another database), rate_limited (the server sheds load and asks to be tried later: a restore retries it for about 30 seconds, as its Retry-After says, before it answers so), or integrity (the version's bucket objects failed an integrity check). A restore answers integrity too when every page of the version arrived intact but SQLite's quick_check finds the database damaged: the version itself is corrupt, so a retry gives the same file, and an earlier version is the way back. A transfer cut short stays unavailable. lock_unavailable, lock_lost, not_found, invalid_argument, and timeout keep their meaning, and any other refusal (a busy server, one short of disk, one unreachable) is unavailable. A client treats a code it does not know as a failure.
const ( ErrorCodeBusy ErrorCode = "busy" ErrorCodeCancelled ErrorCode = "cancelled" ErrorCodeChanged ErrorCode = "changed" ErrorCodeClientUnsupported ErrorCode = "client_unsupported" ErrorCodeConflict ErrorCode = "conflict" ErrorCodeCursorExpired ErrorCode = "cursor_expired" ErrorCodeDrainRequired ErrorCode = "drain_required" ErrorCodeFileExists ErrorCode = "file_exists" ErrorCodeForbidden ErrorCode = "forbidden" ErrorCodeIntegrity ErrorCode = "integrity" ErrorCodeInternal ErrorCode = "internal" ErrorCodeInvalidArgument ErrorCode = "invalid_argument" ErrorCodeLaunchFailed ErrorCode = "launch_failed" ErrorCodeLimitExceeded ErrorCode = "limit_exceeded" ErrorCodeLockLost ErrorCode = "lock_lost" ErrorCodeMethodNotAllowed ErrorCode = "method_not_allowed" ErrorCodeNotConfigured ErrorCode = "not_configured" ErrorCodeNotDurable ErrorCode = "not_durable" ErrorCodeNotFound ErrorCode = "not_found" ErrorCodePlanLimit ErrorCode = "plan_limit" ErrorCodeRateLimited ErrorCode = "rate_limited" ErrorCodeRuleDatabase ErrorCode = "rule_database" ErrorCodeRuleExists ErrorCode = "rule_exists" ErrorCodeSDKUnsupported ErrorCode = "sdk_unsupported" ErrorCodeStillOpen ErrorCode = "still_open" ErrorCodeTimeout ErrorCode = "timeout" ErrorCodeUnauthenticated ErrorCode = "unauthenticated" ErrorCodeWrongServer ErrorCode = "wrong_server" )
Defines values for ErrorCode.
type Event ¶
type Event struct {
ID int64 `json:"id"`
Message string `json:"message"`
Name string `json:"name,omitempty"`
// Path for refused, the refused file; for path_unreadable, the path the rule could not read
Path string `json:"path,omitempty"`
// Role for role_changed, the new role
Role string `json:"role,omitempty"`
Time time.Time `json:"time"`
// Type What happened to a database: role_changed (role is origin or replica, and message is text), draining (a failover origin stops being the origin before a drain releases its lock: its role is unknown until the next role_changed), denied (path names the refused file, such as a failover's file that holds writes the server lacks), path_unreadable (path names the path a backup rule could not read), and the others by their names.
Type EventType `json:"type"`
}
Event defines model for Event.
type EventList ¶
type EventList struct {
Events []Event `json:"events"`
// Next pass as after to continue
Next int64 `json:"next"`
}
EventList defines model for EventList.
type EventType ¶
type EventType string
EventType What happened to a database: role_changed (role is origin or replica, and message is text), draining (a failover origin stops being the origin before a drain releases its lock: its role is unknown until the next role_changed), denied (path names the refused file, such as a failover's file that holds writes the server lacks), path_unreadable (path names the path a backup rule could not read), and the others by their names.
const ( EventTypeAcquired EventType = "acquired" EventTypeDenied EventType = "denied" EventTypeDownloadFinished EventType = "download_finished" EventTypeDownloadStarted EventType = "download_started" EventTypeDraining EventType = "draining" EventTypeImageWritten EventType = "image_written" EventTypeLocalWrite EventType = "local_write" EventTypeLockLost EventType = "lock_lost" EventTypeOffloaded EventType = "offloaded" EventTypePathUnreadable EventType = "path_unreadable" EventTypeRebased EventType = "rebased" EventTypeReleased EventType = "released" EventTypeReplicating EventType = "replicating" EventTypeRestored EventType = "restored" EventTypeReverted EventType = "reverted" EventTypeRoleChanged EventType = "role_changed" EventTypeRollbackScan EventType = "rollback_scan" EventTypeServerGeneration EventType = "server_generation" EventTypeStopped EventType = "stopped" EventTypeTracked EventType = "tracked" )
Defines values for EventType.
type EventsArgs ¶
type EventsArgs struct {
// After returns events with IDs greater than this one; -1 returns no
// events and, as Next, where the log ends, to follow events from now on.
After int64
// Wait waits up to this long for the first new event.
Wait time.Duration
// Limit returns at most this many events.
Limit int
}
EventsArgs selects a page of events.
type Failover ¶
type Failover struct {
// contains filtered or unexported fields
}
Failover runs a database on several identical machines: one origin backs it up, and the others keep live readonly replicas at the same path. Each replica asks for the write lock about once a second, so one of them takes over once the origin's lease runs out.
func StartFailover ¶
StartFailover starts a failover with the shared client; see Client.StartFailover.
func (*Failover) IsOrigin ¶
IsOrigin reports whether this machine writes the database now. It is false while the role is RoleUnknown.
func (*Failover) Role ¶
Role is this machine's role now: RoleOrigin, RoleReplica, or RoleUnknown while the daemon does not answer and once the failover stopped.
type FailoverArgs ¶
type FailoverArgs struct {
// Name is the database name; the file name when empty.
Name string
// Timeout bounds the first download of a replica.
Timeout time.Duration
// DiscardLocal replaces a file at the path that differs from the server
// head with the head, discarding its writes the head lacks. Without it
// such a file is refused with conflict and left untouched.
DiscardLocal bool
// OnRoleChange is called once with the role the start answered, then
// whenever this machine becomes the origin or a replica, and with
// RoleUnknown when the daemon stops answering. Once the daemon answers
// again, the role is read and reported. The first call may come before
// StartFailover returns, so use its role argument, not the *Failover.
OnRoleChange func(role Role)
// OnDenied is called with the daemon's message when it refused this
// machine's file and the failover stays conflicted there, leaving the
// file as it is: a file that differs from the server head when this machine starts
// as the origin, or one that holds writes the new origin never saw when
// this machine lost the origin role. The database's state is conflicted,
// and the role is RoleUnknown, except for a refusal older than the last
// role read after the daemon answered again, which leaves the role that
// read gave.
OnDenied func(message string)
// OnError is called when reading the daemon's events fails; watching retries.
// An expired cursor (cursor_expired) is reported too, and following
// resumes at the log's end after re-reading the role.
OnError func(err error)
}
FailoverArgs configures a failover.
type FailoverRequest ¶
type FailoverRequest struct {
// DiscardLocal replace a file at the path that differs from the server head with the head, discarding its writes the head lacks; without it such a file is refused with 409 conflict and left untouched
DiscardLocal bool `json:"discard_local,omitempty"`
// Name the database name; defaults to the relative file path
Name string `json:"name,omitempty"`
// Path absolute path of the database, the same on every machine
Path string `json:"path"`
// TimeoutMillis bound on the first download of a replica
TimeoutMillis int64 `json:"timeout_millis,omitempty"`
}
FailoverRequest defines model for FailoverRequest.
type FailoverStatus ¶
type FailoverStatus struct {
Name string `json:"name"`
Path string `json:"path"`
Role Role `json:"role"`
Database DatabaseStatus `json:"database"`
Writer Writer `json:"writer"`
}
FailoverStatus is a failover as the daemon reports it, the socket API's Failover schema. The name Failover is the package function that starts one.
type FindReleaseArgs ¶
type FindReleaseArgs struct {
// Package is the package slug; CommandPackage when empty.
Package string
// Version is the release to find; the release on Channel when empty.
Version string
// Channel is used when Version is empty; StableChannel when empty.
Channel string
// Keys verify the release; ReleaseKeys when nil.
Keys map[string]string
}
FindReleaseArgs selects a release from package metadata.
type LeaseArgs ¶
type LeaseArgs struct {
// Path is the local file. When nothing is there, the pool creates an
// empty file and its directory first, so a database neither the server
// nor this machine has becomes a new one. The path this machine already
// uses when empty.
Path string
// RequireExisting skips creating Path, so a database neither the server
// nor this machine has fails with not_found.
RequireExisting bool
// Durability makes the call return only once the server, or the bucket
// with DurabilityCloud, holds the version its work committed, without
// releasing. Empty returns once the work returns and syncs in the
// background. The release that ends the lease waits for the same
// durability, the server when empty.
Durability Durability
// Offload removes the local file when the lease ends, once the release's
// durability holds the final version, unless the last call failed.
Offload bool
// LockTimeout is how long the first call waits while another machine
// holds the write lock, trying again until that machine releases it; 0
// fails at once with lock_unavailable.
LockTimeout time.Duration
// AcquireTimeout bounds downloading the head.
AcquireTimeout time.Duration
// Maintenance checkpoints on release and VACUUMs past the freelist
// threshold.
Maintenance bool
}
LeaseArgs configures a lease.
type LeaseCleanupError ¶
type LeaseCleanupError struct {
// Name is the database.
Name string
// Step is the step that failed.
Step LeaseCleanupStep
// Err is the lease_cleanup_failed *Error.
Err *Error
}
LeaseCleanupError is a failed release of a leased database. It unwraps to an *Error with CodeLeaseCleanupFailed, whose Err is the cause.
func (*LeaseCleanupError) Error ¶
func (e *LeaseCleanupError) Error() string
func (*LeaseCleanupError) Unwrap ¶
func (e *LeaseCleanupError) Unwrap() error
type LeaseCleanupStep ¶
type LeaseCleanupStep string
LeaseCleanupStep is the step of a lease release that failed.
const ( // LeaseCleanupStepClose means closing the database's handle failed, so // it was not released: it stays acquired by this machine with its file // as it is. Close every connection, then call Pool.Release again. LeaseCleanupStepClose LeaseCleanupStep = "close" // LeaseCleanupStepRelease means the release itself failed, as with // still_open or an unreachable server. The file is intact; call // Pool.Release again before another machine needs the database. LeaseCleanupStepRelease LeaseCleanupStep = "release" )
type NameRequest ¶
type NameRequest struct {
Name string `json:"name"`
}
NameRequest defines model for NameRequest.
type OffloadArgs ¶
type OffloadArgs struct {
// Durability is what the offload waits for before it removes the file:
// DurabilityServer, the daemon's default when empty, once the server
// holds the last version, or DurabilityCloud once the bucket holds it too.
Durability Durability
}
OffloadArgs configures an offload.
type OffloadRequest ¶
type OffloadRequest struct {
// Durability how far a version must reach: server once the server holds it, cloud once the bucket holds it too
Durability Durability `json:"durability,omitempty"`
Name string `json:"name"`
}
OffloadRequest defines model for OffloadRequest.
type Pool ¶
type Pool[DB any] struct { // contains filtered or unexported fields }
Pool keeps databases open for calls, the way an app serving many tenants needs them:
pool, err := litebackup.NewPool(client, &litebackup.PoolArgs[*sql.DB]{
Adapter: litebackup.SQLAdapter("sqlite", nil),
})
err = pool.Use(ctx, "tenants/42.sqlite", func(ctx context.Context, db *sql.DB) error {
_, err := db.ExecContext(ctx, "INSERT INTO notes (body) VALUES (?)", "hello")
return err
})
Use is for databases a backup rule on this machine covers: they stay here, open between calls. Lease is for databases that move between machines: the first call acquires the write lock, and the pool keeps it, with the open handle, until IdleRelease runs out, Release, or Close. A pool is safe for concurrent use; Close it when done, never from inside a call.
func (*Pool[DB]) Close ¶
Close refuses new calls, waits for running ones, then releases every leased database and closes every open one. It returns every failure joined; a *LeaseCleanupError names a database that stays acquired. Never call it from inside a Use or Lease call.
func (*Pool[DB]) Lease ¶
func (p *Pool[DB]) Lease( ctx context.Context, name string, args *LeaseArgs, work func(ctx context.Context, db DB) error, ) error
Lease runs work with a database that moves between machines, exclusively: calls on one name run one at a time, and no other machine writes while the pool keeps the lock. The first call acquires the write lock, creating an empty file at args.Path when nothing is there; later calls reuse the lock and the open handle after checking this machine still holds it. With args.Durability the call returns only once the server, or the bucket, holds what the work committed.
The lock is released, after a final sync and closing the handle, after IdleRelease, on Release, or on Close; the pool never gives it up because another machine waits. A call that finds the lock lost fails with lock_lost without running work, and the next call acquires again. The adapters never commit for the work: commit what it should keep.
func (*Pool[DB]) Release ¶
Release ends the lease of a database: it closes the handle and releases the write lock once the final version reaches the lease's durability, after a running call returns. It fails with a *LeaseCleanupError when closing or releasing fails, and with invalid_argument for a database the pool does not lease.
func (*Pool[DB]) Use ¶
func (p *Pool[DB]) Use(ctx context.Context, name string, work func(ctx context.Context, db DB) error) error
Use runs work with a database a backup rule on this machine covers. The pool opens it on first use and keeps it open; an offloaded copy is brought back first, never recreated empty. Calls on one database run concurrently on the same handle. A name no rule on this machine covers is refused with invalid_argument; use Lease for it.
type PoolArgs ¶
type PoolArgs[DB any] struct { // Adapter opens and closes each database. It is required; SQLAdapter // adapts database/sql. Adapter Adapter[DB] // IdleClose closes a backup rule's database after this long without a // call, to cap open files. 0 keeps it open, except under a rule with // MaximumLocalDatabases, where it is DefaultOffloadIdleClose so the rule // can offload it. IdleClose time.Duration // IdleRelease releases a leased database after this long without a call, // DefaultIdleRelease when 0; a negative value keeps it until Release or // Close. The pool never asks another machine to release: the app // coordinates handovers, and another machine's lease with a LockTimeout // gets the database once this pool released it. IdleRelease time.Duration // CleanupTimeout bounds closing and releasing a leased database together; // DefaultCleanupTimeout when 0. CleanupTimeout time.Duration // MachineLabel is what other machines see as the writer of leased // databases. MachineLabel string // OnReleaseError is called, on a goroutine of its own, with each failure // of a close or release the pool ran on its own: an idle close of a // rule's database, or an IdleRelease (a *LeaseCleanupError). The database // stays as it was, and the pool tries again at its next check and on // Close. OnReleaseError func(err error) }
PoolArgs configures NewPool.
type PrefixReplica ¶
type PrefixReplica struct {
// DatabaseCount how many databases under the prefix this machine replicates
DatabaseCount int64 `json:"database_count"`
// Directory the directory that receives <directory>/<name relative to the prefix>
Directory string `json:"directory"`
ID string `json:"id"`
Prefix string `json:"prefix"`
WriteProtection string `json:"write_protection"`
}
PrefixReplica defines model for PrefixReplica.
func ReplicatePrefix ¶
func ReplicatePrefix( ctx context.Context, prefix string, args *ReplicatePrefixArgs, ) (*PrefixReplica, error)
ReplicatePrefix registers replicas with the shared client; see Client.ReplicatePrefix.
type Release ¶
type Release struct {
Version string `json:"version"`
Channels []string `json:"-"`
Files []ReleaseFile `json:"artifacts"`
}
Release is a package release taken from its verified signed document.
func FindRelease ¶
func FindRelease(metadata []byte, args *FindReleaseArgs) (*Release, error)
FindRelease reads package metadata, as https://litebackup.com/pkg/metadata serves it, and returns the selected release taken from its signed document, never the unsigned listing. A release whose signature does not verify returns ErrSignature.
type ReleaseArgs ¶
type ReleaseArgs struct {
// Durability is server or cloud; the daemon's default when empty.
Durability Durability
// Offload removes the local file once Durability holds the released version:
// the server with server, the bucket with cloud.
Offload bool
// Timeout bounds waiting for the database to close and for Durability.
Timeout time.Duration
}
ReleaseArgs configures a release.
type ReleaseFile ¶
type ReleaseFile struct {
Name string `json:"name"`
Filename string `json:"filename"`
URL string `json:"url"`
SHA256 string `json:"sha256"`
Size int64 `json:"size"`
OS string `json:"os,omitempty"`
Architecture string `json:"architecture,omitempty"`
}
ReleaseFile is one published file of a release.
type ReleaseRequest ¶
type ReleaseRequest struct {
// Durability how far a version must reach: server once the server holds it, cloud once the bucket holds it too
Durability Durability `json:"durability,omitempty"`
Name string `json:"name"`
// Offload remove the local file once durability holds the released version, the server with server and the bucket with cloud; an offload refused as not_durable is left to a later offload pass
Offload bool `json:"offload,omitempty"`
// TimeoutMillis how long to wait for the database to close and for the chosen durability
TimeoutMillis int64 `json:"timeout_millis,omitempty"`
}
ReleaseRequest defines model for ReleaseRequest.
type ReleaseResult ¶
type ReleaseResult struct {
Checkpointed bool `json:"checkpointed"`
Database DatabaseStatus `json:"database"`
// Offloaded when the release removed the local file; absent when it kept the file
Offloaded time.Time `json:"offloaded,omitempty"`
Vacuumed bool `json:"vacuumed"`
}
ReleaseResult defines model for ReleaseResult.
type ReplicaList ¶
type ReplicaList struct {
Prefixes []PrefixReplica `json:"prefixes"`
Replicas []DatabaseStatus `json:"replicas"`
}
ReplicaList defines model for ReplicaList.
type ReplicaRequest ¶
type ReplicaRequest struct {
// Directory with prefix, the directory that receives <directory>/<name relative to the prefix>
Directory string `json:"directory,omitempty"`
Name string `json:"name,omitempty"`
// Path with name, the replica file, defaulting to the path this machine uses
Path string `json:"path,omitempty"`
// Prefix name prefix such as app; replicates every database under it
Prefix string `json:"prefix,omitempty"`
// TimeoutMillis bound on downloading the first version of a single replica
TimeoutMillis int64 `json:"timeout_millis,omitempty"`
// WriteProtection lock (default) holds the SQLite write lock so app writes get SQLITE_BUSY while readers carry on; detect rebases after a local write; none trusts apps to open with mode=ro
WriteProtection ReplicaRequestWriteProtection `json:"write_protection,omitempty"`
}
ReplicaRequest Either name and path, for one database, or prefix and directory, for every database under it.
type ReplicaRequestWriteProtection ¶
type ReplicaRequestWriteProtection string
ReplicaRequestWriteProtection lock (default) holds the SQLite write lock so app writes get SQLITE_BUSY while readers carry on; detect rebases after a local write; none trusts apps to open with mode=ro
const ( ReplicaRequestWriteProtectionDetect ReplicaRequestWriteProtection = "detect" ReplicaRequestWriteProtectionLock ReplicaRequestWriteProtection = "lock" ReplicaRequestWriteProtectionNone ReplicaRequestWriteProtection = "none" )
Defines values for ReplicaRequestWriteProtection.
func (ReplicaRequestWriteProtection) Valid ¶
func (e ReplicaRequestWriteProtection) Valid() bool
Valid indicates whether the value is a known member of the ReplicaRequestWriteProtection enum.
type ReplicaResult ¶
type ReplicaResult struct {
Database DatabaseStatus `json:"database,omitempty"`
PrefixReplica PrefixReplica `json:"prefix_replica,omitempty"`
}
ReplicaResult The replica for a name, or the prefix replica for a prefix.
type ReplicateArgs ¶
type ReplicateArgs struct {
// Path is the replica file; the path this machine uses when empty.
Path string
// WriteProtection is lock (the daemon's default), detect, or none.
WriteProtection WriteProtection
// Timeout bounds downloading the first version.
Timeout time.Duration
}
ReplicateArgs configures a replica.
type ReplicatePrefixArgs ¶
type ReplicatePrefixArgs struct {
// Directory receives each database at its name relative to the prefix.
Directory string
// WriteProtection is lock (the daemon's default), detect, or none.
WriteProtection WriteProtection
}
ReplicatePrefixArgs configures live replicas of a namespace.
type RestorableVersion ¶
type RestorableVersion struct {
// Archived when the server recorded the primary bucket's object of this version as archived; absent when the primary bucket does not hold the version, as for one synced between archive passes, which restores only until history pruning removes its segment
Archived time.Time `json:"archived,omitempty"`
StateDigest string `json:"state_digest"`
// Time when the version was synced
Time time.Time `json:"time"`
Version int64 `json:"version"`
}
RestorableVersion defines model for RestorableVersion.
func Versions ¶
func Versions(ctx context.Context, name string, args *VersionsArgs) ([]RestorableVersion, error)
Versions lists restorable versions with the shared client; see Client.Versions.
type RestoreArgs ¶
type RestoreArgs struct {
// Path is the new file; relative paths resolve against the working
// directory. Its directory must exist, and an existing file is never
// overwritten (file_exists).
Path string
// Version restores this version; the head when neither Version nor Time is set.
Version int64
// Time restores the newest version at or before this time.
Time time.Time
// Umask is the file mode creation mask the new file is created under:
// it gets 0666 less it, as a file the caller created would. This
// process's umask when nil.
Umask *fs.FileMode
}
RestoreArgs picks the file and the version a restore writes.
type RestoreRequest ¶
type RestoreRequest struct {
Name string `json:"name"`
// Path absolute path of a new file in an existing directory
Path string `json:"path"`
// Time restore the newest version at or before this time
Time time.Time `json:"time,omitempty"`
// Umask the caller's file mode creation mask, such as 18 for 022; the file gets 0666 less it, as one the caller created would. Absent uses the client's own umask. The litebackup command sends its own.
Umask *int32 `json:"umask,omitempty"`
// Version the version to restore; the head when neither version nor time is set
Version int64 `json:"version,omitempty"`
}
RestoreRequest defines model for RestoreRequest.
type RestoreResult ¶
type RestoreResult struct {
Name string `json:"name"`
PageCount int64 `json:"page_count"`
PageSize int64 `json:"page_size"`
Path string `json:"path"`
StateDigest string `json:"state_digest"`
Version int64 `json:"version"`
}
RestoreResult defines model for RestoreResult.
func Restore ¶
func Restore(ctx context.Context, name string, args *RestoreArgs) (*RestoreResult, error)
Restore writes a version to a new file with the shared client; see Client.Restore.
type RevertArgs ¶
type RevertArgs struct {
// Version is the version whose content becomes the new head.
Version int64
// Time picks the newest version at or before it.
Time time.Time
}
RevertArgs picks the version a revert publishes again: Version or Time, one of them.
type RevertDatabaseJSONRequestBody ¶
type RevertDatabaseJSONRequestBody = RevertRequest
RevertDatabaseJSONRequestBody defines body for RevertDatabase for application/json ContentType.
type RevertDatabaseParams ¶
type RevertDatabaseParams struct {
// SDKVersion the calling SDK's or command's version, optionally after its name, as in typescript/1.1.0; without it the call is denied with 400 invalid_argument, and older than Litebackup-Minimum-SDK-Version with 426 sdk_unsupported
SDKVersion string `json:"Litebackup-SDK-Version"`
}
RevertDatabaseParams defines parameters for RevertDatabase.
type RevertRequest ¶
type RevertRequest struct {
Name string `json:"name"`
// Time revert to the newest version at or before this time; set version or time
Time time.Time `json:"time,omitempty"`
// Version the version whose content the new head holds; set version or time
Version int64 `json:"version,omitempty"`
}
RevertRequest defines model for RevertRequest.
type RevertResult ¶
type RevertResult struct {
Database DatabaseStatus `json:"database"`
// SourceVersion the version whose content the new head holds; it and every version after it stay restorable
SourceVersion int64 `json:"source_version"`
// StateDigest the new head's state digest, which is the source version's
StateDigest string `json:"state_digest"`
// Version the new head, one past the head before the revert
Version int64 `json:"version"`
}
RevertResult defines model for RevertResult.
func Revert ¶
func Revert(ctx context.Context, name string, args *RevertArgs) (*RevertResult, error)
Revert rolls a database back with the shared client; see Client.Revert.
type Role ¶
type Role = DatabaseStatusRole
Role is what this machine does with a database.
const ( // RoleOrigin means this machine writes the database and backs it up. RoleOrigin Role = DatabaseStatusRoleOrigin // RoleReplica means this machine keeps a live readonly copy. RoleReplica Role = DatabaseStatusRoleReplica // RoleUnknown is a failover's role while its daemon does not answer, from // a draining event until the next role change or a role read past the // drain, and once the failover stopped. The SDK sets it; the daemon never // reports it as a role. RoleUnknown Role = "unknown" )
type SQLAdapterArgs ¶
type SQLAdapterArgs struct {
// DSN builds the data source name from the database's path, for driver
// options such as busy_timeout or foreign_keys. It must return a file: URI,
// which the adapter adds mode=rw to, replacing any mode it sets, so a
// missing file is never created. The file: URI of the bare path when nil.
DSN func(path string) string
}
SQLAdapterArgs configures SQLAdapter.
type ShutdownArgs ¶
type ShutdownArgs struct {
// Durability is how far every final sync must reach.
Durability Durability
// Timeout bounds the shutdown.
Timeout time.Duration
}
ShutdownArgs configures a shutdown.
type ShutdownRequest ¶
type ShutdownRequest struct {
Durability ShutdownRequestDurability `json:"durability,omitempty"`
TimeoutMillis int64 `json:"timeout_millis,omitempty"`
}
ShutdownRequest defines model for ShutdownRequest.
type ShutdownRequestDurability ¶
type ShutdownRequestDurability string
ShutdownRequestDurability defines model for ShutdownRequest.Durability.
const ( ShutdownRequestDurabilityCloud ShutdownRequestDurability = "cloud" ShutdownRequestDurabilityNone ShutdownRequestDurability = "none" ShutdownRequestDurabilityServer ShutdownRequestDurability = "server" )
Defines values for ShutdownRequestDurability.
func (ShutdownRequestDurability) Valid ¶
func (e ShutdownRequestDurability) Valid() bool
Valid indicates whether the value is a known member of the ShutdownRequestDurability enum.
type ShutdownResult ¶
type ShutdownResult struct {
// Failures every database the drain could not sync, wait for, or release, each keeping any write lock it holds, and every conflicted copy whose writes are not on the server, with conflict; empty only when the drain released every database it covers, which is the one case the daemon stops
Failures []DrainFailure `json:"failures"`
// ReleasedCount how many databases the drain synced as asked and released
ReleasedCount int64 `json:"released_count"`
}
ShutdownResult defines model for ShutdownResult.
type StartBackupArgs ¶
type StartBackupArgs struct {
Name string
Prefix string
// MaximumLocalDatabases, when positive, offloads the least recently
// changed idle databases past this count once OffloadDurability holds them.
MaximumLocalDatabases int64
// OffloadDurability is what MaximumLocalDatabases waits for: DurabilityServer,
// the default when empty, once the server holds a copy's last version,
// or DurabilityCloud once the bucket holds it too.
OffloadDurability Durability
// OffloadRollbackJournal lets MaximumLocalDatabases offload rollback-journal
// databases too. Set it only when nothing keeps them open while idle: no
// lock shows an idle rollback-journal connection. WAL databases are
// offloaded either way.
OffloadRollbackJournal bool
}
StartBackupArgs maps matching files to remote names.
type Status ¶
type Status struct {
ClientVersion string `json:"client_version"`
Databases []DatabaseStatus `json:"databases"`
LeaseExpires time.Time `json:"lease_expires,omitempty"`
// Next Pass this name as after to read the next page. Omitted on the last page.
Next string `json:"next,omitempty"`
// OpenFileLimit The soft limit on open files the daemon runs with. Each active backup holds about four, and the daemon lowers its default number of active backups to fit.
OpenFileLimit int64 `json:"open_file_limit,omitempty"`
Server string `json:"server"`
Session string `json:"session"`
SessionID string `json:"session_id"`
// UnreadablePaths the paths a backup rule cannot read, most recent first; the events API has the history
UnreadablePaths []Event `json:"unreadable_paths,omitempty"`
Watch string `json:"watch"`
}
Status defines model for Status.
type StatusPageArgs ¶
type StatusPageArgs struct {
// After returns databases whose names sort after this one; pass Next to continue.
After string
// Limit returns at most this many databases, up to 1000; 100 when 0.
Limit int
}
StatusPageArgs selects a page of Status. Nil reads the first page of 100.
type StopBackupRequest ¶
type StopBackupRequest struct {
// Name Exact remote name of a database with its own backup rule on this machine.
Name string `json:"name,omitempty"`
// RuleID ID returned by start or listed by rules. Stops the whole rule, including future matches.
RuleID string `json:"rule_id,omitempty"`
}
StopBackupRequest defines model for StopBackupRequest.
type StopBackupResult ¶
type StopBackupResult struct {
LeasePending bool `json:"lease_pending"`
}
StopBackupResult defines model for StopBackupResult.
func StopBackup ¶
func StopBackup(ctx context.Context, name string) (*StopBackupResult, error)
StopBackup stops the single-file backup with this remote database name.
func StopBackupRule ¶
func StopBackupRule(ctx context.Context, id string) (*StopBackupResult, error)
StopBackupRule stops a whole backup rule using the ID returned by StartBackup.
type StopReplicaPrefixArgs ¶
type StopReplicaPrefixArgs struct {
// Directory is the one the prefix replica was started with. It is required.
Directory string
}
StopReplicaPrefixArgs names the prefix replica to stop.
type StopReplicaRequest ¶
type StopReplicaRequest struct {
// Directory with prefix, the directory the prefix replica was started with
Directory string `json:"directory,omitempty"`
Name string `json:"name,omitempty"`
Prefix string `json:"prefix,omitempty"`
}
StopReplicaRequest Either name for one replica, or prefix and directory for a prefix.
type SyncedState ¶
SyncedState A version the server acknowledged. Clients decide what durability is enough.
type VersionList ¶
type VersionList struct {
// Next pass as after to read the next page
Next int64 `json:"next,omitempty"`
Versions []RestorableVersion `json:"versions"`
}
VersionList defines model for VersionList.
type VersionsArgs ¶
type VersionsArgs struct {
// After skips versions up to and including this one.
After int64
// Limit returns at most this many versions; every version when 0.
Limit int
}
VersionsArgs pages through versions.
type WatchEventsArgs ¶
type WatchEventsArgs struct {
// After starts with events after this ID; -1 starts at the end of the
// log, for events from now on; 0 starts at the oldest.
After int64
// Wait is how long each long-poll waits for a new event; 30s when 0.
Wait time.Duration
// OnError is called with each failed long-poll before it is retried.
OnError func(err error)
}
WatchEventsArgs selects where a watch starts and how it long-polls.
type WriteProtection ¶
type WriteProtection = ReplicaRequestWriteProtection
WriteProtection is how a replica keeps app writes out.
const ( // WriteProtectionLock holds the SQLite write lock, so app writes get SQLITE_BUSY while readers carry on. WriteProtectionLock WriteProtection = ReplicaRequestWriteProtectionLock // WriteProtectionDetect rebases the replica after a local write. WriteProtectionDetect WriteProtection = ReplicaRequestWriteProtectionDetect // WriteProtectionNone trusts apps to open the replica with mode=ro. WriteProtectionNone WriteProtection = ReplicaRequestWriteProtectionNone )
type Writer ¶
type Writer struct {
// Active whether some machine holds the write lock and its lease still runs
Active bool `json:"active"`
// Lapsed the writer's lease ran out, so another machine may take over
Lapsed bool `json:"lapsed"`
// LeaseExpires on the server's clock
LeaseExpires time.Time `json:"lease_expires,omitempty"`
// LeaseRemainingMillis how long the lease still runs, negative once it ran out
LeaseRemainingMillis int64 `json:"lease_remaining_millis,omitempty"`
// LockAcquired when the writer took the lock
LockAcquired time.Time `json:"lock_acquired,omitempty"`
Name string `json:"name"`
// ThisMachine whether this machine's session holds the write lock
ThisMachine bool `json:"this_machine"`
// WriterMachineLabel the machine label of the writer, or empty when nobody holds the lock
WriterMachineLabel string `json:"writer_machine_label"`
}
Writer defines model for Writer.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
handoff
command
Command handoff is the Go step of the cross-language handoff test: it leases a database from a pool, checks and adds rows with the sqlite3 command, and closes the pool, which releases it.
|
Command handoff is the Go step of the cross-language handoff test: it leases a database from a pool, checks and adds rows with the sqlite3 command, and closes the pool, which releases it. |
|
stripdoc
command
Command stripdoc removes the package comment oapi-codegen writes above the "Code generated" line, so the generated file does not document the package.
|
Command stripdoc removes the package comment oapi-codegen writes above the "Code generated" line, so the generated file does not document the package. |
|
Package sqlitedsn finds the file a database/sql SQLite data source name opens, so an app can register the same database it opens:
|
Package sqlitedsn finds the file a database/sql SQLite data source name opens, so an app can register the same database it opens: |