mirror of
https://github.com/hanzoai/base.git
synced 2026-10-21 03:41:50 +00:00
Three things, all the same shape: SQLite's guarantees were being assumed on an engine that does not make them. A backup archives the data directory, which is where the database lives on SQLite and not on Postgres. There it returned 204 and produced an archive with no database in it, and restore then failed inside a goroutine after the 204 had gone out — so an operator saw successful backups, a populated list, plausible sizes, and had nothing recoverable. It refuses on an engine whose database is not in that directory, before extracting anything, and says where to take the backup instead. Refusing beats shelling out to pg_dump: that adds a binary that has to out-version the server, and its output cannot be restored by the path we have, so it would be a second restore mechanism. What stopped a restore is now retrievable. It is recorded in core, so a CLI or a hook caller sees it too, and GET on the restore address renders it: 202 while running, 200 and the reason when stopped, 404 when this process has not tried. POST still answers 204, because the admin client reads a body on any other 2xx. A serialization failure or a deadlock is a transient and is retried at the transaction boundary, which is the only place a retry means anything — the second statement of a deadlocked transaction reports 25P02, so retrying a statement spends the attempt and loses the evidence. The transaction watches its own statements for the two SQLSTATEs rather than reading the returned error, which by then has been wrapped down to a message string. Batch had to become re-runnable for this: it accumulated results outside the transaction. Retrying turns a transient into a success and does not pretend to fix a convoy: with a few concurrent opposing batches the loss goes to zero, and with thirty pairs over six rows every pair collides and no budget clears it. SQLite keeps the same executions at the same intervals. Co-authored-by: Hanzo Dev <[email protected]>
121 lines
3.3 KiB
Go
121 lines
3.3 KiB
Go
package core
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
|
|
"github.com/hanzoai/dbx"
|
|
)
|
|
|
|
// RunInTransaction wraps fn into a transaction for the regular app database.
|
|
//
|
|
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
|
|
func (app *BaseApp) RunInTransaction(fn func(txApp App) error) error {
|
|
return app.runInTransaction(app.NonconcurrentDB(), fn, false)
|
|
}
|
|
|
|
// AuxRunInTransaction wraps fn into a transaction for the auxiliary app database.
|
|
//
|
|
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
|
|
func (app *BaseApp) AuxRunInTransaction(fn func(txApp App) error) error {
|
|
return app.runInTransaction(app.AuxNonconcurrentDB(), fn, true)
|
|
}
|
|
|
|
func (app *BaseApp) runInTransaction(db dbx.Builder, fn func(txApp App) error, isForAuxDB bool) error {
|
|
switch txOrDB := db.(type) {
|
|
case *dbx.Tx:
|
|
// run as part of the already existing transaction
|
|
return fn(app)
|
|
case *dbx.DB:
|
|
// an engine that rolls a transaction back for conflicting with a
|
|
// concurrent one is asking for that transaction, and so for fn, to run
|
|
// again from its first statement; each attempt begins a transaction of
|
|
// its own, on its own tx app, and settles its own after calls
|
|
return retry(func(int) (error, bool) {
|
|
watched, conflicted := watchConflict(txOrDB)
|
|
|
|
var txApp *BaseApp
|
|
txErr := watched.Transactional(func(tx *dbx.Tx) error {
|
|
txApp = app.createTxApp(tx, isForAuxDB)
|
|
return fn(txApp)
|
|
})
|
|
|
|
// execute all after event calls on transaction complete
|
|
if txApp != nil && txApp.txInfo != nil {
|
|
afterFuncErr := txApp.txInfo.runAfterFuncs(txErr)
|
|
if afterFuncErr != nil {
|
|
return errors.Join(txErr, afterFuncErr), false
|
|
}
|
|
}
|
|
|
|
return txErr, conflicted()
|
|
}, defaultMaxLockRetries)
|
|
default:
|
|
return errors.New("failed to start transaction (unknown db type)")
|
|
}
|
|
}
|
|
|
|
// createTxApp shallow clones the current app and assigns a new tx state.
|
|
func (app *BaseApp) createTxApp(tx *dbx.Tx, isForAuxDB bool) *BaseApp {
|
|
clone := *app
|
|
|
|
if isForAuxDB {
|
|
clone.auxConcurrentDB = tx
|
|
clone.auxNonconcurrentDB = tx
|
|
} else {
|
|
clone.concurrentDB = tx
|
|
clone.nonconcurrentDB = tx
|
|
}
|
|
|
|
clone.txInfo = &TxAppInfo{
|
|
parent: app,
|
|
isForAuxDB: isForAuxDB,
|
|
}
|
|
|
|
return &clone
|
|
}
|
|
|
|
// TxAppInfo represents an active transaction context associated to an existing app instance.
|
|
type TxAppInfo struct {
|
|
parent *BaseApp
|
|
afterFuncs []func(txErr error) error
|
|
mu sync.Mutex
|
|
isForAuxDB bool
|
|
}
|
|
|
|
// OnComplete registers the provided callback that will be invoked
|
|
// once the related transaction ends (either completes successfully or rollbacked with an error).
|
|
//
|
|
// The callback receives the transaction error (if any) as its argument.
|
|
// Any additional errors returned by the OnComplete callbacks will be
|
|
// joined together with txErr when returning the final transaction result.
|
|
func (a *TxAppInfo) OnComplete(fn func(txErr error) error) {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
a.afterFuncs = append(a.afterFuncs, fn)
|
|
}
|
|
|
|
// note: can be called only once because TxAppInfo is cleared
|
|
func (a *TxAppInfo) runAfterFuncs(txErr error) error {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
var errs []error
|
|
|
|
for _, call := range a.afterFuncs {
|
|
if err := call(txErr); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
|
|
a.afterFuncs = nil
|
|
|
|
if len(errs) > 0 {
|
|
return fmt.Errorf("transaction afterFunc errors: %w", errors.Join(errs...))
|
|
}
|
|
|
|
return nil
|
|
}
|