Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: move Francis actor state into its own SQLite database
Kyle Mendell93a740597df7
diff --git a/backend/cli/recovery/recovery.go b/backend/cli/recovery/recovery.goindex a2761804c..15a931827 100644--- a/backend/cli/recovery/recovery.go+++ b/backend/cli/recovery/recovery.go@@ -13,7 +13,6 @@ import (activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"- dbtypes "github.com/getarcaneapp/arcane/types/v2/database"recoverytypes "github.com/getarcaneapp/arcane/types/v2/recovery""github.com/libtnb/sqlite""github.com/moby/moby/api/types/container"@@ -145,7 +144,7 @@ func finalizeRestoredBackupInternal(ctx context.Context, databaseURL, manifestBaif !strings.HasPrefix(databaseURL, "file:") {return errors.New("restored Arcane database is not SQLite")}- dsn, err := database.ParseSQLiteConnectionString(databaseURL, dbtypes.SQLiteConnectionOptions{})+ dsn, err := database.ParseSQLiteConnectionString(databaseURL)if err != nil {return err}diff --git a/backend/cli/recovery/recovery_test.go b/backend/cli/recovery/recovery_test.goindex 083a8f505..64f58f03a 100644--- a/backend/cli/recovery/recovery_test.go+++ b/backend/cli/recovery/recovery_test.go@@ -6,7 +6,6 @@ import ("time"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"- dbtypes "github.com/getarcaneapp/arcane/types/v2/database"recoverytypes "github.com/getarcaneapp/arcane/types/v2/recovery""github.com/libtnb/sqlite""github.com/stretchr/testify/require"@@ -21,7 +20,7 @@ import (func newRestoredDatabaseForTestInternal(t *testing.T, runIDs ...string) (string, string) {t.Helper()databaseURL := "file:" + filepath.Join(t.TempDir(), "arcane.db")- dsn, err := database.ParseSQLiteConnectionString(databaseURL, dbtypes.SQLiteConnectionOptions{})+ dsn, err := database.ParseSQLiteConnectionString(databaseURL)require.NoError(t, err)db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)diff --git a/backend/go.mod b/backend/go.modindex 83030115f..4d4b9c6c2 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -52,7 +52,6 @@ require (github.com/orandin/slog-gorm v1.4.0github.com/pressly/goose/v3 v3.28.0github.com/project-copacetic/copacetic v0.15.0- github.com/quic-go/quic-go v0.63.0github.com/robfig/cron/v3 v3.0.1github.com/samber/hot v0.13.1github.com/samber/mo v1.17.0@@ -250,6 +249,7 @@ require (github.com/prometheus/common v0.71.0 // indirectgithub.com/prometheus/procfs v0.22.0 // indirectgithub.com/quic-go/qpack v0.6.0 // indirect+ github.com/quic-go/quic-go v0.63.0 // indirectgithub.com/quic-go/webtransport-go v0.13.0 // indirectgithub.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirectgithub.com/rivo/uniseg v0.4.7 // indirectdiff --git a/backend/internal/database/database.go b/backend/internal/database/database.goindex 784ff0cf3..9845155f9 100644--- a/backend/internal/database/database.go+++ b/backend/internal/database/database.go@@ -15,7 +15,6 @@ import ("strings""time"- dbtypes "github.com/getarcaneapp/arcane/types/v2/database""github.com/libtnb/sqlite""github.com/pressly/goose/v3""github.com/pressly/goose/v3/lock"@@ -123,7 +122,7 @@ func connectDatabaseInternal(ctx context.Context, databaseURL string) (*DB, erroif err := sqliteutil.RegisterFunctions(); err != nil {return nil, fmt.Errorf("failed to register SQLite functions: %w", err)}- connString, err := ParseSQLiteConnectionString(databaseURL, dbtypes.SQLiteConnectionOptions{})+ connString, err := ParseSQLiteConnectionString(databaseURL)if err != nil {return nil, fmt.Errorf("failed to parse SQLite connection string: %w", err)}@@ -624,7 +623,7 @@ func missingEmbeddedDowngradeMigrationsInternal(ctx context.Context, db *sql.DB,return missing, nil}-func ParseSQLiteConnectionString(connString string, options dbtypes.SQLiteConnectionOptions) (string, error) {+func ParseSQLiteConnectionString(connString string) (string, error) {if !strings.HasPrefix(connString, "file:") {connString = "file:" + connString}@@ -662,35 +661,6 @@ func ParseSQLiteConnectionString(connString string, options dbtypes.SQLiteConnec}}- pragmas := make([]string, 0, len(qs["_pragma"])+2)- journalMode, busyTimeout := false, false- for _, pragma := range qs["_pragma"] {- name, _, _ := strings.Cut(pragma, "(")- name, _, _ = strings.Cut(name, "=")- switch strings.ToLower(strings.TrimSpace(name)) {- case "foreign_keys":- if options.IgnoreForeignKeys {- continue- }- case "journal_mode":- journalMode = true- case "busy_timeout":- busyTimeout = true- }- pragmas = append(pragmas, pragma)- }- if !journalMode && options.JournalMode != "" {- pragmas = append(pragmas, "journal_mode("+options.JournalMode+")")- }- if !busyTimeout && options.BusyTimeout > 0 {- pragmas = append(pragmas, "busy_timeout("+strconv.FormatInt(options.BusyTimeout.Milliseconds(), 10)+")")- }- if len(pragmas) > 0 {- qs["_pragma"] = pragmas- } else {- qs.Del("_pragma")- }-connStringUrl.RawQuery = qs.Encode()return connStringUrl.String(), nil}diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.goindex 131bd33d3..58835850e 100644--- a/backend/internal/database/database_test.go+++ b/backend/internal/database/database_test.go@@ -12,7 +12,6 @@ import ("testing""time"- dbtypes "github.com/getarcaneapp/arcane/types/v2/database""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -1011,16 +1010,11 @@ func TestIdentityNormalizationPostgresUpgrade(t *testing.T) {func TestSQLiteDSN(t *testing.T) {original := "file:arcane.db?_fk=0&_pragma=foreign_keys%3D1&_pragma=synchronous(NORMAL)&_txlock=immediate"- dsn, err := ParseSQLiteConnectionString(original, dbtypes.SQLiteConnectionOptions{- IgnoreForeignKeys: true,- JournalMode: "WAL",- BusyTimeout: 2500 * time.Millisecond,- })+ dsn, err := ParseSQLiteConnectionString(original)require.NoError(t, err)parsed, err := url.Parse(dsn)require.NoError(t, err)require.Equal(t, "immediate", parsed.Query().Get("_txlock"))- require.ElementsMatch(t, []string{"synchronous(NORMAL)", "journal_mode(WAL)", "busy_timeout(2500)"}, parsed.Query()["_pragma"])+ require.ElementsMatch(t, []string{"foreign_keys(0)", "foreign_keys=1", "synchronous(NORMAL)"}, parsed.Query()["_pragma"])require.Empty(t, parsed.Query().Get("_fk"))- require.Contains(t, original, "_fk=0")}diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.goindex 2d8650402..5f8851245 100644--- a/backend/internal/di/providers.go+++ b/backend/internal/di/providers.go@@ -107,12 +107,26 @@ func provideBackupEngineInternal(return engine, nil}-func provideActorRuntimeInternal(appCtx context.Context, cfg *config.Config, settingsService *settings.SettingsService, lc fx.Lifecycle, cancelApp context.CancelFunc) (*francis.Runtime, error) {+func provideActorRuntimeInternal(+ appCtx context.Context,+ cfg *config.Config,+ db *database.DB,+ settingsService *settings.SettingsService,+ lc fx.Lifecycle,+ cancelApp context.CancelFunc,+) (*francis.Runtime, error) {runtime, err := francis.New(cfg.DatabaseURL, "", "", cfg.ActorPort)if err != nil {return nil, err}lc.Append(fx.Hook{OnStart: func(ctx context.Context) error {+ sqlDB, sqlDBErr := db.SQLDB()+ if sqlDBErr != nil {+ return sqlDBErr+ }+ if migrateErr := francis.MigrateLegacyStore(ctx, sqlDB, cfg.DatabaseURL); migrateErr != nil {+ return migrateErr+ }if configureIdentityErr := runtime.ConfigureIdentity(cfg.EncryptionKey, settingsService.GetSettingsConfig().InstanceID.Value); configureIdentityErr != nil {return configureIdentityErr}diff --git a/backend/internal/diagnostics/service.go b/backend/internal/diagnostics/service.goindex 13408a00e..1541731de 100644--- a/backend/internal/diagnostics/service.go+++ b/backend/internal/diagnostics/service.go@@ -18,7 +18,6 @@ import (kit "go.getarcane.app/kit/pkg""gorm.io/gorm"- "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/francis"@@ -38,7 +37,6 @@ const (// layer to avoid an import cycle with the api/ws package.type DiagnosticsService struct {startedAt time.Time- db *database.DBactors *francis.Runtimecoordinator *runs.Coordinatorenvironments *environment.EnvironmentService@@ -47,8 +45,8 @@ type DiagnosticsService struct {leakScannedAt time.Time}-func NewDiagnosticsService(db *database.DB, actors *francis.Runtime, coordinator *runs.Coordinator, environments *environment.EnvironmentService) *DiagnosticsService {- return &DiagnosticsService{startedAt: time.Now(), db: db, actors: actors, coordinator: coordinator, environments: environments}+func NewDiagnosticsService(actors *francis.Runtime, coordinator *runs.Coordinator, environments *environment.EnvironmentService) *DiagnosticsService {+ return &DiagnosticsService{startedAt: time.Now(), actors: actors, coordinator: coordinator, environments: environments}}func (s *DiagnosticsService) Collect() (system.RuntimeInfo, system.MemoryInfo, system.GCInfo) {@@ -197,9 +195,13 @@ func (s *DiagnosticsService) CollectActors(ctx context.Context) (system.ActorDiareturn d, nil}- db := s.db.WithContext(ctx)+ store, err := s.actors.Store()+ if err != nil {+ return d, err+ }+ db := store.WithContext(ctx)var hosts []actorHostModel- if err := db.Order("host_id").Find(&hosts).Error; err != nil {+ if err = db.Order("host_id").Find(&hosts).Error; err != nil {return d, fmt.Errorf("list actor hosts: %w", err)}for _, host := range hosts {diff --git a/backend/internal/diagnostics/service_test.go b/backend/internal/diagnostics/service_test.goindex bffb9334e..53aa83873 100644--- a/backend/internal/diagnostics/service_test.go+++ b/backend/internal/diagnostics/service_test.go@@ -12,7 +12,7 @@ import ()func TestDiagnosticsServiceCollect(t *testing.T) {- s := NewDiagnosticsService(nil, nil, nil, nil)+ s := NewDiagnosticsService(nil, nil, nil)rt, mem, _ := s.Collect()@@ -43,7 +43,7 @@ func TestGoroutineLeakProfileAvailable(t *testing.T) {}func TestDiagnosticsServiceScanGoroutineLeaks(t *testing.T) {- s := NewDiagnosticsService(nil, nil, nil, nil)+ s := NewDiagnosticsService(nil, nil, nil)report, err := s.ScanGoroutineLeaks()require.NoError(t, err)@@ -58,7 +58,7 @@ func TestDiagnosticsServiceScanGoroutineLeaks(t *testing.T) {}func TestDiagnosticsServiceScanGoroutineLeaksDetectsLeak(t *testing.T) {- s := NewDiagnosticsService(nil, nil, nil, nil)+ s := NewDiagnosticsService(nil, nil, nil)leakUnbufferedChannelInternal()deadline := time.Now().Add(5 * time.Second)diff --git a/backend/internal/system/children/backup/children/snapshots/service.go b/backend/internal/system/children/backup/children/snapshots/service.goindex d75ec56ae..0eb551b67 100644--- a/backend/internal/system/children/backup/children/snapshots/service.go+++ b/backend/internal/system/children/backup/children/snapshots/service.go@@ -26,6 +26,7 @@ import ("go.getarcane.app/docker""go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup"+ "gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -34,6 +35,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/backupbrowser"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/francis")const (@@ -54,6 +56,7 @@ const (type Service struct {engine *backup.EnginesqlDB func() (*sql.DB, error)+ actorStore func() (*gorm.DB, error)localRepository func(ctx context.Context, dockerClient *client.Client, readOnly bool) (backup.Repository, error)remoteRepository func(ctx context.Context, destinationID string) (backup.Repository, error)databaseFile func() (string, error)@@ -64,6 +67,7 @@ type Service struct {func NewService(engine *backup.Engine,sqlDB func() (*sql.DB, error),+ actorStore func() (*gorm.DB, error),localRepository func(ctx context.Context, dockerClient *client.Client, readOnly bool) (backup.Repository, error),remoteRepository func(ctx context.Context, destinationID string) (backup.Repository, error),databaseFile func() (string, error),@@ -73,6 +77,7 @@ func NewService(return &Service{engine: engine,sqlDB: sqlDB,+ actorStore: actorStore,localRepository: localRepository,remoteRepository: remoteRepository,databaseFile: databaseFile,@@ -721,6 +726,7 @@ var ("backed up separately mounted projects; create a new system backup to restore project files",)manifestCandidateRoots = []string{snapshotDataPath, "/", "/app/data"}+ sqliteSidecars = []string{"-wal", "-shm", "-journal"})// snapshotLayout locates Arcane data and projects inside one snapshot.@@ -754,12 +760,13 @@ func (layout snapshotLayout) protected(projectRelative string) bool {return false}candidate := path.Join(relative, projectRelative)- switch candidate {- case RecoveryManifestName, RecoveryRequestName, layout.databaseName, layout.databaseName + "-wal", layout.databaseName + "-shm", layout.databaseName + "-journal":+ if candidate == RecoveryManifestName || candidate == RecoveryRequestName {return true- default:- return false}+ return slices.ContainsFunc([]string{layout.databaseName, francis.StorePath(layout.databaseName)}, func(database string) bool {+ sidecar, found := strings.CutPrefix(candidate, database)+ return found && (sidecar == "" || slices.Contains(sqliteSidecars, sidecar))+ })}// projectsCoveredByData reports whether restoring the data root already@@ -1034,9 +1041,15 @@ func (s *Service) Create(if err != nil {return backup.Snapshot{}, err}- databasePath := filepath.Join(layout.dataDirectory, layout.databaseName)- stagedDatabase := filepath.Join(stage, layout.databaseName)- snapshotDatabase := filepath.Join(snapshotDataPath, layout.databaseName)+ actorStore, err := s.actorStore()+ if err != nil {+ return backup.Snapshot{}, err+ }+ actorSQLDB, err := actorStore.DB()+ if err != nil {+ return backup.Snapshot{}, err+ }+ databases := map[string]*sql.DB{layout.databaseName: sqlDB, francis.StorePath(layout.databaseName): actorSQLDB}manifest := recovery.Manifest{FormatVersion: recovery.ManifestFormatVersion, ArcaneVersion: config.Version, BackupID: backupID,ActivityID: activity.IDFromContext(ctx), CreatedAt: time.Now().UTC(),@@ -1052,26 +1065,32 @@ func (s *Service) Create(return backup.Snapshot{}, fmt.Errorf("failed to write recovery manifest: %w", err)}defer func() { _ = os.Remove(manifestPath) }()- layout.excludes = []string{- ".arcane-snapshot-*", RecoveryRequestName,- layout.databaseName + "-wal", layout.databaseName + "-shm", layout.databaseName + "-journal",+ layout.excludes = []string{".arcane-snapshot-*", RecoveryRequestName}+ for name := range databases {+ for _, sidecar := range sqliteSidecars {+ layout.excludes = append(layout.excludes, name+sidecar)+ }}files, err := snapshotSourceFiles(ctx, layout)if err != nil {return backup.Snapshot{}, err}- if stageErr := stageDatabase(ctx, sqlDB, databasePath, stagedDatabase); stageErr != nil {- return backup.Snapshot{}, stageErr- }mounts, inContainer, err := currentMounts(ctx, dockerClient)if err != nil {return backup.Snapshot{}, err}- stagedMounts, err := sourceMounts(mounts, inContainer, stagedDatabase, snapshotDatabase)- if err != nil {- return backup.Snapshot{}, err+ // Mount VACUUM INTO copies over the live databases so the snapshot is consistent.+ for name, db := range databases {+ stagedDatabase := filepath.Join(stage, name)+ if stageErr := stageDatabase(ctx, db, filepath.Join(layout.dataDirectory, name), stagedDatabase); stageErr != nil {+ return backup.Snapshot{}, stageErr+ }+ stagedMounts, mountErr := sourceMounts(mounts, inContainer, stagedDatabase, filepath.Join(snapshotDataPath, name))+ if mountErr != nil {+ return backup.Snapshot{}, mountErr+ }+ layout.mounts = append(layout.mounts, stagedMounts...)}- layout.mounts = append(layout.mounts, stagedMounts...)input := backup.CreateSnapshotInput{Mounts: layout.mounts, Sources: layout.sources}for _, excluded := range layout.excludes {input.Globs = append(input.Globs, "!"+snapshotDataPath+"/"+excluded)@@ -1126,6 +1145,7 @@ func snapshotSourceFiles(ctx context.Context, layout backupSourceLayout) (map[stif statErr != nil {projectsInfo = nil}+ actorDatabase := francis.StorePath(layout.databaseName)files := make(map[string]os.FileInfo)visit := func(filePath string, entry fs.DirEntry, walkErr error) error {if walkErr != nil {@@ -1138,7 +1158,7 @@ func snapshotSourceFiles(ctx context.Context, layout backupSourceLayout) (map[stif err != nil {return err}- if relative == layout.databaseName {+ if relative == layout.databaseName || relative == actorDatabase {return nil}for _, excluded := range layout.excludes {diff --git a/backend/internal/system/children/backup/children/snapshots/service_test.go b/backend/internal/system/children/backup/children/snapshots/service_test.goindex db9ecf1a3..070f849b5 100644--- a/backend/internal/system/children/backup/children/snapshots/service_test.go+++ b/backend/internal/system/children/backup/children/snapshots/service_test.go@@ -20,7 +20,7 @@ func TestSnapshotSourceFilesSkipLiveAndProjectFiles(t *testing.T) {root := t.TempDir()stage := filepath.Join(root, ".arcane-snapshot-stage")require.NoError(t, os.Mkdir(stage, 0o700))- for _, name := range []string{RecoveryRequestName, "settings.txt"} {+ for _, name := range []string{RecoveryRequestName, "settings.txt", "arcane.francis.db"} {require.NoError(t, os.WriteFile(filepath.Join(root, name), []byte("data"), 0o600))}require.NoError(t, os.Symlink("settings.txt", filepath.Join(root, "link")))@@ -39,7 +39,7 @@ func TestSnapshotSourceFilesSkipLiveAndProjectFiles(t *testing.T) {databaseName: "arcane.db",projectsDirectory: projects,projectsPath: snapshotDataPath + "/projects",- excludes: []string{".arcane-snapshot-*", RecoveryRequestName, "arcane.db-wal", "arcane.db-shm", "arcane.db-journal"},+ excludes: []string{".arcane-snapshot-*", RecoveryRequestName, "arcane.db-wal", "arcane.db-shm", "arcane.db-journal", "arcane.francis.db-wal"},}type attributes struct {size int64@@ -59,10 +59,12 @@ func TestSnapshotSourceFilesSkipLiveAndProjectFiles(t *testing.T) {require.NotContains(t, before, projects)require.NotContains(t, before, filepath.Join(root, "arcane.db"))require.NotContains(t, before, filepath.Join(root, "arcane.db-wal"))+ require.NotContains(t, before, filepath.Join(root, "arcane.francis.db"))require.NotContains(t, before, stage)require.Contains(t, before, filepath.Join(root, "settings.txt"))require.NoError(t, os.WriteFile(composePath, []byte("services: {app: {image: nginx}}"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projects, "app.log"), []byte("live"), 0o600))+ require.NoError(t, os.WriteFile(filepath.Join(root, "arcane.francis.db"), []byte("health check"), 0o600))require.NoError(t, stageDatabase(t.Context(), db, filepath.Join(root, "arcane.db"), filepath.Join(stage, "arcane.db")))require.Equal(t, before, walk())require.NoError(t, os.WriteFile(filepath.Join(root, "settings.txt"), []byte("changed"), 0o600))@@ -281,6 +283,8 @@ func TestSnapshotLayoutFromManifest(t *testing.T) {func TestSnapshotLayoutProtectsDataFiles(t *testing.T) {overlapping := snapshotLayout{dataPath: "/data", projectsPath: "/data", databaseName: "arcane.db"}require.True(t, overlapping.protected("arcane.db-wal"))+ require.True(t, overlapping.protected("arcane.francis.db"))+ require.True(t, overlapping.protected("arcane.francis.db-shm"))require.True(t, overlapping.protected(".arcane-recovery.json"))require.False(t, overlapping.protected("demo/arcane.db"))nested := snapshotLayout{dataPath: "/data", projectsPath: "/data/projects", databaseName: "arcane.db"}diff --git a/backend/internal/system/children/backup/service.go b/backend/internal/system/children/backup/service.goindex a8fab5740..5562266be 100644--- a/backend/internal/system/children/backup/service.go+++ b/backend/internal/system/children/backup/service.go@@ -31,6 +31,7 @@ import ("go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""go.getarcane.app/sys/crypto"+ "gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/backup"@@ -107,6 +108,7 @@ type Dependencies struct {Store StoreDB *database.DBSQLDB func() (*sql.DB, error)+ ActorStore func() (*gorm.DB, error)Docker *dockerInternal.DockerClientServiceVolumes *volume.VolumeServiceEngine *backup.Engine@@ -146,6 +148,7 @@ func NewService(deps Dependencies) *Service {service.snapshots = snapshots.NewService(deps.Engine,deps.SQLDB,+ deps.ActorStore,service.localRepositoryInternal,service.remoteRepositoryInternal,service.databaseFileInternal,diff --git a/backend/internal/system/service.go b/backend/internal/system/service.goindex a1f469a8f..a08619102 100644--- a/backend/internal/system/service.go+++ b/backend/internal/system/service.go@@ -51,6 +51,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/francis")// SystemService owns Docker system-wide operations and coordinates the prune@@ -82,6 +83,7 @@ func NewSystemService(backupEngine *backup.Engine,s3Destinations *s3.S3DestinationService,recoveryKeys *backup.RecoveryKeyStore,+ actors *francis.Runtime,cfg *config.Config,) *SystemService {location := time.UTC@@ -108,6 +110,7 @@ func NewSystemService(Store: s.backupStoreInternal(s3Destinations),DB: db,SQLDB: sqlDB,+ ActorStore: actors.Store,Docker: dockerService,Volumes: volumeService,Engine: backupEngine,diff --git a/backend/pkg/utils/francis/provider.go b/backend/pkg/utils/francis/provider.goindex 526797ef5..b9dd7da83 100644--- a/backend/pkg/utils/francis/provider.go+++ b/backend/pkg/utils/francis/provider.go@@ -1,75 +1,117 @@package francisimport (+ "bytes"+ "cmp""context"+ "database/sql""errors""fmt""log/slog"+ "net/url"+ "path/filepath""strings""time"- dbtypes "github.com/getarcaneapp/arcane/types/v2/database""github.com/italypaleale/francis/components""github.com/italypaleale/francis/components/postgres""github.com/italypaleale/francis/components/sqlite""github.com/italypaleale/francis/host/local"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database")-func providerOptionInternal(databaseURL string) (local.HostOption, error) {+// legacyDrops remove the Francis schema that lived in the Arcane SQLite database+// before v2.16. That schema never changes again, so the list is final.+// Remove this in v3.0.0+var legacyDrops = []string{+ "DROP VIEW IF EXISTS " + TablePrefix + "_host_active_actor_count",+ "DROP TABLE IF EXISTS " + TablePrefix + "_host_actor_types",+ "DROP TABLE IF EXISTS " + TablePrefix + "_active_actors",+ "DROP TABLE IF EXISTS " + TablePrefix + "_consumed_join_tokens",+ "DROP TABLE IF EXISTS " + TablePrefix + "_hosts",+ "DROP TABLE IF EXISTS " + TablePrefix + "_actor_state",+ "DROP TABLE IF EXISTS " + TablePrefix + "_alarms",+ "DROP TABLE IF EXISTS " + TablePrefix + "_cluster_config",+ "DROP TABLE IF EXISTS " + TablePrefix + "_terminal_jobs",+ "DROP TABLE IF EXISTS " + TablePrefix + "_dead_jobs",+ "DROP TABLE IF EXISTS " + TablePrefix + "_metadata",+}++// StorePath names the dedicated Francis SQLite file beside the Arcane database.+func StorePath(databasePath string) string {+ extension := filepath.Ext(databasePath)+ return strings.TrimSuffix(databasePath, extension) + ".francis" + cmp.Or(extension, ".db")+}++// StoreURL resolves Francis storage: a sibling SQLite file without application+// pragmas, or the Postgres URL unchanged.+func StoreURL(databaseURL string) (string, error) {switch {case strings.HasPrefix(databaseURL, "file:"):- dsn, err := database.ParseSQLiteConnectionString(databaseURL, dbtypes.SQLiteConnectionOptions{- IgnoreForeignKeys: true,- JournalMode: "WAL",- BusyTimeout: 2500 * time.Millisecond,- })+ parsed, err := url.Parse(databaseURL)if err != nil {- return nil, err+ return "", fmt.Errorf("parse actor database URL: %w", err)+ }+ databasePath := parsed.Path+ if parsed.Opaque != "" {+ if databasePath, err = url.PathUnescape(parsed.Opaque); err != nil {+ return "", fmt.Errorf("parse actor database URL: %w", err)+ }+ }+ if databasePath == "" || strings.HasPrefix(databasePath, ":memory:") || parsed.Query().Get("mode") == "memory" {+ return "", errors.New("actor storage requires a file-backed SQLite database")}- return local.WithSQLiteProvider(sqlite.SQLiteProviderOptions{ConnectionString: dsn, TablePrefix: TablePrefix}), nil+ return "file:" + (&url.URL{Path: StorePath(databasePath)}).EscapedPath(), nilcase strings.HasPrefix(databaseURL, "postgres"):- return local.WithPostgresProvider(postgres.PostgresProviderOptions{ConnectionString: databaseURL, TablePrefix: TablePrefix}), nil+ return databaseURL, nildefault:- return nil, errors.New("unsupported actor database URL")+ return "", errors.New("unsupported actor database URL")}}-// ClearRestoredHosts removes copied live host ownership from an offline restored-// database. Never call this against a running Arcane database.-func ClearRestoredHosts(ctx context.Context, databaseURL string) (err error) {+func providerOption(storeURL string) local.HostOption {+ if strings.HasPrefix(storeURL, "file:") {+ return local.WithSQLiteProvider(sqlite.SQLiteProviderOptions{ConnectionString: storeURL, TablePrefix: TablePrefix})+ }+ return local.WithPostgresProvider(postgres.PostgresProviderOptions{ConnectionString: storeURL, TablePrefix: TablePrefix})+}++// openProvider opens an offline Francis provider on storeURL. Close it when done.+func openProvider(ctx context.Context, storeURL string) (components.ActorProvider, error) {cfg := components.NewProviderConfig()cfg.HostHealthCheckDeadline = 90 * time.Secondcfg.MaxHosts = 1var provider components.ActorProvider- switch {- case strings.HasPrefix(databaseURL, "file:"):- dsn, dsnErr := database.ParseSQLiteConnectionString(databaseURL, dbtypes.SQLiteConnectionOptions{- IgnoreForeignKeys: true,- JournalMode: "WAL",- BusyTimeout: 2500 * time.Millisecond,- })- if dsnErr != nil {- return dsnErr- }- provider, err = sqlite.NewSQLiteProvider(slog.Default(), sqlite.SQLiteProviderOptions{ConnectionString: dsn, TablePrefix: TablePrefix}, cfg)- case strings.HasPrefix(databaseURL, "postgres"):- provider, err = postgres.NewPostgresProvider(slog.Default(), postgres.PostgresProviderOptions{ConnectionString: databaseURL, TablePrefix: TablePrefix}, cfg)- default:- return errors.New("unsupported restored actor database URL")+ var err error+ if strings.HasPrefix(storeURL, "file:") {+ provider, err = sqlite.NewSQLiteProvider(slog.Default(), sqlite.SQLiteProviderOptions{ConnectionString: storeURL, TablePrefix: TablePrefix}, cfg)+ } else {+ provider, err = postgres.NewPostgresProvider(slog.Default(), postgres.PostgresProviderOptions{ConnectionString: storeURL, TablePrefix: TablePrefix}, cfg)+ }+ if err != nil {+ return nil, err+ }+ if err = provider.Init(ctx); err != nil {+ return nil, errors.Join(fmt.Errorf("initialize actor provider: %w", err), provider.Close())}+ return provider, nil+}++// ClearRestoredHosts removes copied live host ownership from an offline restored+// database. Never call this against a running Arcane database.+func ClearRestoredHosts(ctx context.Context, databaseURL string) (err error) {+ storeURL, err := StoreURL(databaseURL)if err != nil {return err}+ provider, err := openProvider(ctx, storeURL)+ if err != nil {+ return fmt.Errorf("open restored actor storage: %w", err)+ }defer func() {if closeErr := provider.Close(); closeErr != nil {err = errors.Join(err, fmt.Errorf("close restored actor provider: %w", closeErr))}}()- if err = provider.Init(ctx); err != nil {- return fmt.Errorf("initialize restored actor provider: %w", err)- }hosts, err := provider.ListHosts(ctx)if err != nil {return fmt.Errorf("list restored actor hosts: %w", err)@@ -83,3 +125,63 @@ func ClearRestoredHosts(ctx context.Context, databaseURL string) (err error) {// Expired registrations are excluded by ListHosts and pruned by RegisterHost.return nil}++// MigrateLegacyStore moves Francis state kept inside the Arcane SQLite database+// into its dedicated file, then drops the old tables. Reruns until the drop succeeds.+func MigrateLegacyStore(ctx context.Context, mainDB *sql.DB, databaseURL string) (err error) {+ if !strings.HasPrefix(databaseURL, "file:") {+ return nil+ }+ var legacy int+ var journalMode string+ err = errors.Join(+ mainDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?", TablePrefix+"_metadata").Scan(&legacy),+ mainDB.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&journalMode),+ )+ if err != nil || legacy == 0 {+ return err+ }+ storeURL, err := StoreURL(databaseURL)+ if err != nil {+ return err+ }+ // Francis needs its own connection with foreign keys on; keep the Arcane journal mode.+ legacyURL, _, _ := strings.Cut(databaseURL, "?")+ source, err := openProvider(ctx, legacyURL+"?_pragma="+url.QueryEscape("journal_mode("+journalMode+")"))+ if err != nil {+ return fmt.Errorf("open legacy actor storage: %w", err)+ }+ var snapshot bytes.Buffer+ err = errors.Join(source.Backup(ctx, &snapshot), source.Close())+ if err != nil {+ return fmt.Errorf("export legacy actor storage: %w", err)+ }+ target, err := openProvider(ctx, storeURL)+ if err != nil {+ return fmt.Errorf("open actor storage: %w", err)+ }+ err = errors.Join(target.Restore(ctx, &snapshot), target.Close())+ if err != nil {+ return fmt.Errorf("import legacy actor storage: %w", err)+ }+ tx, err := mainDB.BeginTx(ctx, nil)+ if err != nil {+ return fmt.Errorf("begin legacy actor storage cleanup: %w", err)+ }+ defer func() {+ if rollbackErr := tx.Rollback(); rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) {+ err = errors.Join(err, fmt.Errorf("roll back legacy actor storage cleanup: %w", rollbackErr))+ }+ }()+ // Keep the metadata marker and every source table intact until cleanup commits.+ for _, drop := range legacyDrops {+ if _, err = tx.ExecContext(ctx, drop); err != nil {+ return fmt.Errorf("drop legacy actor storage: %w", err)+ }+ }+ if err = tx.Commit(); err != nil {+ return fmt.Errorf("commit legacy actor storage cleanup: %w", err)+ }+ slog.InfoContext(ctx, "Migrated actor state to its dedicated database", "path", strings.TrimPrefix(storeURL, "file:"))+ return nil+}diff --git a/backend/pkg/utils/francis/provider_test.go b/backend/pkg/utils/francis/provider_test.gonew file mode 100644index 000000000..6d48a9a28--- /dev/null+++ b/backend/pkg/utils/francis/provider_test.go@@ -0,0 +1,66 @@+package francis++import (+ "context"+ "database/sql"+ "path/filepath"+ "testing"+ "time"++ "github.com/italypaleale/francis/actor"+ "github.com/italypaleale/francis/components/sqlite"+ "github.com/italypaleale/francis/host/local"+ "github.com/stretchr/testify/require"+)++func TestMigrateLegacyStore(t *testing.T) {+ mainPath := filepath.Join(t.TempDir(), "arcane.db")+ databaseURL := "file:" + mainPath + "?_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)&_txlock=immediate"+ storeURL, err := StoreURL(databaseURL)+ require.NoError(t, err)+ require.Equal(t, "file:"+filepath.Join(filepath.Dir(mainPath), "arcane.francis.db"), storeURL)+ for input, expected := range map[string]string{+ "file:/data/arcane%23prod.db?_txlock=immediate": "file:/data/arcane%23prod.francis.db",+ "file:/data/arcane%2Edb": "file:/data/arcane.francis.db",+ "file:data/arcane%23prod%2Edb": "file:data/arcane%23prod.francis.db",+ "file:data/arcane": "file:data/arcane.francis.db",+ "postgres://arcane@localhost/arcane?sslmode=disable": "postgres://arcane@localhost/arcane?sslmode=disable",+ } {+ storeURL, err = StoreURL(input)+ require.NoError(t, err)+ require.Equal(t, expected, storeURL)+ }+ for _, input := range []string{"file::memory:", "file:shared?mode=memory&cache=shared", "mysql://arcane"} {+ _, err = StoreURL(input)+ require.Error(t, err)+ }++ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)+ defer cancel()+ start := func(options ...local.HostOption) *Runtime {+ runtime, newErr := New(databaseURL, "test-encryption-key", "test-instance", freePortInternal(t), options...)+ require.NoError(t, newErr)+ require.NoError(t, runtime.RegisterActor("test", func(string, *actor.Service) actor.Actor { return struct{}{} }))+ require.NoError(t, runtime.Start(ctx, ctx, nil))+ return runtime+ }+ legacy := start(local.WithSQLiteProvider(sqlite.SQLiteProviderOptions{ConnectionString: "file:" + mainPath, TablePrefix: TablePrefix}))+ require.NoError(t, legacy.Service().SetState(ctx, "test", "durable", "kept", nil))+ require.NoError(t, legacy.Stop(ctx))++ mainDB, err := sql.Open("sqlite", mainPath)+ require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, mainDB.Close()) })+ for range 2 {+ require.NoError(t, MigrateLegacyStore(ctx, mainDB, databaseURL))+ }+ var tables int+ require.NoError(t, mainDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE name LIKE ?", TablePrefix+"_%").Scan(&tables))+ require.Zero(t, tables)++ migrated := start()+ t.Cleanup(func() { require.NoError(t, migrated.Stop(context.WithoutCancel(ctx))) })+ var state string+ require.NoError(t, migrated.Service().GetState(ctx, "test", "durable", &state))+ require.Equal(t, "kept", state)+}diff --git a/backend/pkg/utils/francis/runtime.go b/backend/pkg/utils/francis/runtime.goindex 4efbee8e7..01b4c7762 100644--- a/backend/pkg/utils/francis/runtime.go+++ b/backend/pkg/utils/francis/runtime.go@@ -5,12 +5,13 @@ import ("context""crypto/hkdf""crypto/sha256"- "crypto/tls"+ "database/sql""errors""fmt""log/slog""net""strconv"+ "strings""sync""syscall""time"@@ -18,11 +19,13 @@ import ("github.com/italypaleale/francis/actor""github.com/italypaleale/francis/components""github.com/italypaleale/francis/host/local"- "github.com/quic-go/quic-go"- "github.com/quic-go/quic-go/http3"+ "github.com/libtnb/sqlite"+ "gorm.io/driver/postgres"+ "gorm.io/gorm"+ "gorm.io/gorm/logger")-// TablePrefix namespaces the Francis tables inside the Arcane database.+// TablePrefix namespaces the Francis tables in their store.const TablePrefix = "arcane_francis"// Runtime starts one durable actor host and publishes its service after readiness.@@ -30,7 +33,7 @@ const TablePrefix = "arcane_francis"type Runtime struct {mu sync.Mutexoptions []local.HostOption- registrations []registrationInternal+ registrations []registrationservice *actor.Serviceready chan struct{}done chan struct{}@@ -38,10 +41,12 @@ type Runtime struct {started boolrunError erroraddress string+ storeURL string+ store *gorm.DBactorNames sync.Map}-type registrationInternal struct {+type registration struct {actorType stringfactory actor.Factoryoptions []local.RegisterActorOption@@ -55,15 +60,15 @@ func New(databaseURL, encryptionKey, instanceID, port string, options ...local.Hif err != nil || portNumber < 1 || portNumber > 65535 {return nil, errors.New("ACTOR_PORT must be between 1 and 65535")}- providerOption, err := providerOptionInternal(databaseURL)+ storeURL, err := StoreURL(databaseURL)if err != nil {return nil, err}address := net.JoinHostPort("127.0.0.1", port)runtime := &Runtime{- service: &actor.Service{}, ready: make(chan struct{}), done: make(chan struct{}), address: address,+ service: &actor.Service{}, ready: make(chan struct{}), done: make(chan struct{}), address: address, storeURL: storeURL,options: []local.HostOption{- local.WithAddress(address), providerOption,+ local.WithAddress(address), providerOption(storeURL),local.WithMaxHosts(1), local.WithHostHealthCheckDeadline(90 * time.Second),local.WithShutdownGracePeriod(10 * time.Second), local.WithAlarmsPollInterval(time.Second),local.WithAlarmsFetchAheadInterval(30 * time.Second), local.WithAlarmsLeaseDuration(180 * time.Second),@@ -103,6 +108,30 @@ func (r *Runtime) ConfigureIdentity(encryptionKey, instanceID string) error {func (r *Runtime) Service() *actor.Service { return r.service }func (r *Runtime) Ready() <-chan struct{} { return r.ready }+// Store lazily opens a small pool on Francis storage for diagnostics and backups.+func (r *Runtime) Store() (*gorm.DB, error) {+ r.mu.Lock()+ defer r.mu.Unlock()+ if r.store != nil {+ return r.store, nil+ }+ dialector := postgres.Open(r.storeURL)+ if strings.HasPrefix(r.storeURL, "file:") {+ dialector = sqlite.Open(r.storeURL + "?_pragma=busy_timeout(2500)")+ }+ store, err := gorm.Open(dialector, &gorm.Config{Logger: logger.Discard})+ if err != nil {+ return nil, fmt.Errorf("open actor storage: %w", err)+ }+ sqlDB, err := store.DB()+ if err != nil {+ return nil, fmt.Errorf("open actor storage: %w", err)+ }+ sqlDB.SetMaxOpenConns(2)+ r.store = store+ return store, nil+}+func (r *Runtime) RegisterActor(actorType string, factory actor.Factory, options ...local.RegisterActorOption) error {r.mu.Lock()defer r.mu.Unlock()@@ -114,12 +143,12 @@ func (r *Runtime) RegisterActor(actorType string, factory actor.Factory, optionsreturn fmt.Errorf("actor type %q is already registered", actorType)}}- r.registrations = append(r.registrations, registrationInternal{actorType: actorType, factory: factory, options: append([]local.RegisterActorOption(nil), options...)})+ r.registrations = append(r.registrations, registration{actorType: actorType, factory: factory, options: append([]local.RegisterActorOption(nil), options...)})return nil}-// Start waits for registration and the peer listener. appCtx owns the running host;-// ctx only limits startup. onFailure must cancel the application without blocking.+// Start waits for host registration. appCtx owns the running host; ctx only+// limits startup. onFailure must cancel the application without blocking.func (r *Runtime) Start(ctx, appCtx context.Context, onFailure func(error)) error {r.mu.Lock()if r.started {@@ -135,82 +164,71 @@ func (r *Runtime) Start(ctx, appCtx context.Context, onFailure func(error)) erroif err != nil {cancel()err = fmt.Errorf("bind actor loopback UDP listener: %w", err)- r.finishInternal(err)+ r.finish(err)return err}if err = listener.Close(); err != nil {cancel()- r.finishInternal(err)+ r.finish(err)return err}startupCtx, startupCancel := context.WithTimeout(ctx, 120*time.Second)defer startupCancel()- // An ephemeral probe socket can claim the port between the preflight and host bind.bindRetries := 0for {- host, errCh, runHostErr := r.runHostInternal(runCtx)+ host, errCh, runHostErr := r.runHost(runCtx)if runHostErr != nil {cancel()- r.finishInternal(runHostErr)+ r.finish(runHostErr)return runHostErr}select {case <-host.Ready():- runHostErr = waitForPeerInternal(startupCtx, r.address, errCh)- if runHostErr != nil {- if errors.Is(runHostErr, syscall.EADDRINUSE) && bindRetries < 3 {- <-errCh- bindRetries++- continue- }- cancel()- r.finishInternal(<-errCh)- return runHostErr- }select {- case runErr := <-errCh:- cancel()- r.finishInternal(runErr)- return fmt.Errorf("actor host stopped during startup: %w", runErr)+ case runHostErr = <-errCh:default:+ r.publishReady(runCtx, host, errCh, onFailure)+ return nil}- r.publishReadyInternal(runCtx, host, errCh, onFailure)- return nilcase runHostErr = <-errCh:- if errors.Is(runHostErr, syscall.EADDRINUSE) && bindRetries < 3 {- bindRetries++- continue- }- if !errors.Is(runHostErr, components.ErrClusterFull) && !errors.Is(runHostErr, components.ErrHostAlreadyRegistered) {- cancel()- r.finishInternal(runHostErr)- return runHostErr- }- slog.WarnContext(ctx, "Waiting for the previous actor host registration to expire", "error", runHostErr)case <-startupCtx.Done():cancel()- r.finishInternal(<-errCh)+ r.finish(<-errCh)return startupCtx.Err()}+ if runHostErr == nil {+ runHostErr = errors.New("actor host stopped during startup")+ }+ switch {+ case errors.Is(runHostErr, syscall.EADDRINUSE) && bindRetries < 3:+ bindRetries+++ slog.WarnContext(ctx, "Retrying actor host after a UDP port conflict", "error", runHostErr, "retry", bindRetries)+ case errors.Is(runHostErr, components.ErrClusterFull), errors.Is(runHostErr, components.ErrHostAlreadyRegistered):+ slog.WarnContext(ctx, "Waiting for the previous actor host registration to expire", "error", runHostErr)+ default:+ cancel()+ r.finish(runHostErr)+ return runHostErr+ }timer := time.NewTimer(time.Second)select {case <-timer.C:case <-runCtx.Done():timer.Stop()- r.finishInternal(runCtx.Err())+ r.finish(runCtx.Err())return runCtx.Err()case <-startupCtx.Done():timer.Stop()cancel()- runHostErr = fmt.Errorf("another Arcane process owns this database or its registration has not expired: %w", startupCtx.Err())- r.finishInternal(runHostErr)+ runHostErr = fmt.Errorf("actor host startup timed out: %w", errors.Join(startupCtx.Err(), runHostErr))+ r.finish(runHostErr)return runHostErr}}}-func (r *Runtime) runHostInternal(ctx context.Context) (*local.Host, chan error, error) {+func (r *Runtime) runHost(ctx context.Context) (*local.Host, chan error, error) {host, err := local.NewHost(r.options...)if err != nil {return nil, nil, err@@ -231,12 +249,12 @@ func (r *Runtime) runHostInternal(ctx context.Context) (*local.Host, chan error,return host, localErrors, nil}-func (r *Runtime) publishReadyInternal(ctx context.Context, host *local.Host, runErrors <-chan error, onFailure func(error)) {+func (r *Runtime) publishReady(ctx context.Context, host *local.Host, runErrors <-chan error, onFailure func(error)) {*r.service = *host.Service()close(r.ready)go func() {err := <-runErrors- r.finishInternal(err)+ r.finish(err)if ctx.Err() != nil || onFailure == nil {return}@@ -249,57 +267,33 @@ func (r *Runtime) publishReadyInternal(ctx context.Context, host *local.Host, rufunc (r *Runtime) Stop(ctx context.Context) error {r.mu.Lock()- cancel, started := r.cancel, r.started- r.mu.Unlock()- if !started {- return nil+ var err error+ if r.store != nil {+ var sqlDB *sql.DB+ if sqlDB, err = r.store.DB(); err == nil {+ err = sqlDB.Close()+ }+ r.store = nil+ }+ if !r.started {+ r.mu.Unlock()+ return err}- cancel()+ r.mu.Unlock()+ r.cancel()select {case <-r.done:r.mu.Lock()defer r.mu.Unlock()- return r.runError+ return errors.Join(r.runError, err)case <-ctx.Done():- return ctx.Err()+ return errors.Join(ctx.Err(), err)}}-func (r *Runtime) finishInternal(err error) {+func (r *Runtime) finish(err error) {r.mu.Lock()defer r.mu.Unlock()r.runError = errclose(r.done)}--func waitForPeerInternal(ctx context.Context, address string, runErrors chan error) error {- // A TLS rejection proves the loopback listener is serving before shutdown.- //nolint:gosec // This readiness probe never sends credentials or application data.- tlsConfig := &tls.Config{InsecureSkipVerify: true, NextProtos: []string{http3.NextProtoH3}}- for {- probeCtx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)- connection, err := quic.DialAddr(probeCtx, address, tlsConfig, &quic.Config{})- cancel()- if connection != nil {- if closeWithErrorErr := connection.CloseWithError(0, "readiness probe complete"); closeWithErrorErr != nil {- return fmt.Errorf("close actor readiness probe: %w", closeWithErrorErr)- }- return nil- }- var transportError *quic.TransportError- if errors.As(err, &transportError) && transportError.Remote {- return nil- }- timer := time.NewTimer(10 * time.Millisecond)- select {- case <-ctx.Done():- timer.Stop()- return ctx.Err()- case runErr := <-runErrors:- timer.Stop()- runErrors <- runErr- return fmt.Errorf("actor peer listener stopped before readiness: %w", runErr)- case <-timer.C:- }- }-}diff --git a/types/database/connection.go b/types/database/connection.godeleted file mode 100644index 43291faf4..000000000--- a/types/database/connection.go+++ /dev/null@@ -1,10 +0,0 @@-package database--import "time"--// SQLiteConnectionOptions supplies pool-specific pragma defaults.-type SQLiteConnectionOptions struct {- IgnoreForeignKeys bool- JournalMode string- BusyTimeout time.Duration-}