alta-adopt: dry runs read a copy; rollback preview; live output
A dry run, status and preflight never open the state file: it and its WAL are copied to a private temporary directory, restored into memory and the copy removed, so a pending migration or WAL mode never touches the file. rollback-config without --apply names the keys it would remove and the host it would restart. RunLive takes its writer, and alta-adopt passes its own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+309
−37
adopt/live.go+13 −10adopt/live_test.go+11 −12adopt/words.go+19 −1cmd/alta-adopt/main.go+55 −10cmd/alta-adopt/main_test.go+114 −4cmd/alta-adopt/snapshot.go+97 −0
diff --git a/adopt/live.go b/adopt/live.go| index 5c239b5..d7e029a 100644 |
| --- a/adopt/live.go |
| +++ b/adopt/live.go |
| @@ -26,13 +26,11 @@ import ( |
| "amadan.net/oficina/agent-access.git/client" |
| ) |
| -// Variables only so tests can reach the fake connect, move the clock and |
| -// read what is printed. |
| +// Variables only so tests can reach the fake connect and move the clock. |
| var ( |
| liveTransport http.RoundTripper // nil: http.DefaultTransport |
| - liveNow = time.Now |
| - liveOut io.Writer = os.Stdout |
| - liveOwnerAttempts = 3 |
| + liveNow = time.Now |
| + liveOwnerAttempts = 3 |
| ) |
| // The live checks' outcomes as SaveCheck records them. |
| @@ -335,8 +333,9 @@ var errLiveSignOut = errors.New("adopt: live-sign-out-failed") |
| // Every connection RunLive makes is signed out (connect revokes it) |
| // before it returns, whatever happened, and the saved requests and |
| // tokens are zeroed. Without apply it prints the steps and contacts |
| -// nothing: no browser, no prompt, no request, no record. |
| -func RunLive(ctx context.Context, server, sqid string, p Prompter, s *Store, open func(string) error, foreignEventID string, apply bool) (err error) { |
| +// nothing: no browser, no prompt, no request, no record. Everything it |
| +// says goes to out (os.Stdout when nil). |
| +func RunLive(ctx context.Context, out io.Writer, server, sqid string, p Prompter, s *Store, open func(string) error, foreignEventID string, apply bool) (err error) { |
| u, perr := url.Parse(server) |
| switch { |
| case perr != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" && u.Path != "/": |
| @@ -348,21 +347,25 @@ func RunLive(ctx context.Context, server, sqid string, p Prompter, s *Store, ope |
| if perr != nil || event < 1 || strconv.FormatInt(event, 10) != foreignEventID { |
| return errors.New("adopt: " + LiveNeedEvent) |
| } |
| + if out == nil { |
| + out = os.Stdout |
| + } |
| if !apply { |
| for _, line := range LiveSteps { |
| - fmt.Fprintln(liveOut, line) |
| + fmt.Fprintln(out, line) |
| } |
| return nil |
| } |
| if s == nil || p == nil || open == nil { |
| return errors.New("adopt: " + LiveNeedRunners) |
| } |
| - r := &liveRun{server: u.Scheme + "://" + u.Host, sqid: sqid, event: event, p: p, s: s, open: open} |
| + r := &liveRun{out: out, server: u.Scheme + "://" + u.Host, sqid: sqid, event: event, p: p, s: s, open: open} |
| defer func() { err = errors.Join(err, r.close()) }() |
| return r.run(ctx) |
| } |
| type liveRun struct { |
| + out io.Writer |
| server, sqid string |
| event int64 |
| p Prompter |
| @@ -372,7 +375,7 @@ type liveRun struct { |
| saved []*savedRequest |
| } |
| -func (r *liveRun) say(line string) { fmt.Fprintln(liveOut, line) } |
| +func (r *liveRun) say(line string) { fmt.Fprintln(r.out, line) } |
| // record saves name's outcome. Anything but passed stops the run, with an |
| // error naming the check and the outcome only. |
diff --git a/adopt/live_test.go b/adopt/live_test.go| index 5d56eda..7157af6 100644 |
| --- a/adopt/live_test.go |
| +++ b/adopt/live_test.go |
| @@ -352,11 +352,10 @@ func newLive(t *testing.T) *liveFixture { |
| t.Helper() |
| f := newFakeConnect(t) |
| x := &liveFixture{f: f, p: &fakePrompter{f: f}, s: newJournal(t), out: &bytes.Buffer{}} |
| - oldT, oldNow, oldOut := liveTransport, liveNow, liveOut |
| + oldT, oldNow := liveTransport, liveNow |
| liveTransport = f.srv.Client().Transport |
| liveNow = func() time.Time { return time.Now().Add(time.Duration(f.skew.Load())) } |
| - liveOut = x.out |
| - t.Cleanup(func() { liveTransport, liveNow, liveOut = oldT, oldNow, oldOut }) |
| + t.Cleanup(func() { liveTransport, liveNow = oldT, oldNow }) |
| return x |
| } |
| @@ -365,7 +364,7 @@ func (x *liveFixture) run(t *testing.T) error { |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| x.p.cancel = nil |
| - return RunLive(ctx, x.f.srv.URL, liveSQID, x.p, x.s, x.f.open, liveEvent, true) |
| + return RunLive(ctx, x.out, x.f.srv.URL, liveSQID, x.p, x.s, x.f.open, liveEvent, true) |
| } |
| // checks lists the journal's live checks in the order recorded. |
| @@ -799,7 +798,7 @@ func TestLiveCloseZeroes(t *testing.T) { |
| l := newLiveConn() |
| l.out = true |
| _ = l.store.Save(client.Credentials{Token: &oauth2.Token{AccessToken: "bearer-canary-2"}}) |
| - r := &liveRun{conns: []*liveConn{l}, saved: []*savedRequest{c}} |
| + r := &liveRun{out: io.Discard, conns: []*liveConn{l}, saved: []*savedRequest{c}} |
| if err := r.close(); err != nil { |
| t.Fatal(err) |
| } |
| @@ -835,7 +834,7 @@ func TestLiveCloseZeroesEveryCapturedRequest(t *testing.T) { |
| x := newLive(t) |
| brk(x) |
| ev, _ := strconv.ParseInt(liveEvent, 10, 64) |
| - r := &liveRun{server: x.f.srv.URL, sqid: liveSQID, event: ev, p: x.p, s: x.s, open: x.f.open} |
| + r := &liveRun{out: x.out, server: x.f.srv.URL, sqid: liveSQID, event: ev, p: x.p, s: x.s, open: x.f.open} |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| _ = r.run(ctx) |
| @@ -1014,7 +1013,7 @@ func TestLiveAlwaysLogsOut(t *testing.T) { |
| defer cancel() |
| x.p.failOn = LiveRemovedMember |
| x.p.cancel = cancel |
| - if err := RunLive(ctx, x.f.srv.URL, liveSQID, x.p, x.s, x.f.open, liveEvent, true); err == nil { |
| + if err := RunLive(ctx, x.out, x.f.srv.URL, liveSQID, x.p, x.s, x.f.open, liveEvent, true); err == nil { |
| t.Fatal("a cancelled run went on") |
| } |
| allRevoked(t, x.f) |
| @@ -1048,10 +1047,10 @@ func TestLiveDryRunContactsNothing(t *testing.T) { |
| x := newLive(t) |
| open := func(string) error { t.Fatal("dry run opened a browser"); return nil } |
| p := askFunc(func(context.Context, string) error { t.Fatal("dry run asked Paul"); return nil }) |
| - if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, p, x.s, open, liveEvent, false); err != nil { |
| + if err := RunLive(context.Background(), x.out, x.f.srv.URL, liveSQID, p, x.s, open, liveEvent, false); err != nil { |
| t.Fatal(err) |
| } |
| - if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, p, nil, open, liveEvent, false); err != nil { |
| + if err := RunLive(context.Background(), x.out, x.f.srv.URL, liveSQID, p, nil, open, liveEvent, false); err != nil { |
| t.Fatalf("dry run needs the journal: %v", err) |
| } |
| _, _, _, paths, _ := x.f.state() |
| @@ -1083,15 +1082,15 @@ func TestLiveRefusesBadInputs(t *testing.T) { |
| "event spaced": {x.f.srv.URL, liveSQID, " 4"}, |
| } { |
| for _, apply := range []bool{false, true} { |
| - if err := RunLive(context.Background(), tc.server, tc.sqid, x.p, x.s, open, tc.event, apply); err == nil { |
| + if err := RunLive(context.Background(), x.out, tc.server, tc.sqid, x.p, x.s, open, tc.event, apply); err == nil { |
| t.Fatalf("%s (apply %v) accepted", name, apply) |
| } |
| } |
| } |
| - if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, nil, x.s, open, liveEvent, true); err == nil { |
| + if err := RunLive(context.Background(), x.out, x.f.srv.URL, liveSQID, nil, x.s, open, liveEvent, true); err == nil { |
| t.Fatal("ran with no prompter") |
| } |
| - if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, x.p, nil, open, liveEvent, true); err == nil { |
| + if err := RunLive(context.Background(), x.out, x.f.srv.URL, liveSQID, x.p, nil, open, liveEvent, true); err == nil { |
| t.Fatal("ran with no journal") |
| } |
| _, _, _, paths, _ := x.f.state() |
diff --git a/adopt/words.go b/adopt/words.go| index 26e79fa..437bec6 100644 |
| --- a/adopt/words.go |
| +++ b/adopt/words.go |
| @@ -4,7 +4,7 @@ |
| // |
| // PENDING COPY REVIEW: WitnessSentence, WriteSummary, the live checks' |
| // words (LiveSteps, the LiveSay lines, the four sentences and the |
| -// LiveNeed refusals) and the command's words (Usage and every Say and |
| +// LiveNeed refusals) and the command's words (Usage and every Say, Refuse and |
| // Hint below) are drafts, not yet reviewed with Paul. They are reviewed |
| // in Task 14 step 5, all together. |
| package adopt |
| @@ -199,6 +199,24 @@ func SayRolledBack(host string) string { |
| return host + ": both agent keys removed, and the app restarted on its previous configuration." |
| } |
| +// SayRollbackWould is rollback-config's dry run when both agent keys are |
| +// still in place: which keys go, from which bundle, and which host |
| +// restarts. |
| +func SayRollbackWould(keys [2]string, bundle, host string) string { |
| + return "This removes " + keys[0] + " and " + keys[1] + " from " + bundle + ", then restarts " + host + " alone and waits for it to serve its previous configuration." |
| +} |
| + |
| +// SayRollbackRestartOnly is rollback-config's dry run when the keys are |
| +// already gone but the restart has not been seen through. |
| +func SayRollbackRestartOnly(keys [2]string, host string) string { |
| + return keys[0] + " and " + keys[1] + " are already removed. This restarts " + host + " alone and waits for it to serve its previous configuration." |
| +} |
| + |
| +// SayRollbackNothing is rollback-config once the rollback is complete. |
| +func SayRollbackNothing(host string) string { |
| + return host + " is already rolled back. There is nothing to do." |
| +} |
| + |
| // SayDisableType is disable's prompt. |
| func SayDisableType(app string) string { |
| return "This disables " + app + "'s team binding at Home. Type the team's label to go on:" |
diff --git a/cmd/alta-adopt/main.go b/cmd/alta-adopt/main.go| index 6174b14..e8daeb4 100644 |
| --- a/cmd/alta-adopt/main.go |
| +++ b/cmd/alta-adopt/main.go |
| @@ -208,15 +208,16 @@ func (r *runner) open(ctx context.Context) error { |
| return err |
| } |
| r.cfg = cfg |
| - path := cfg.state |
| - if !r.o.apply { |
| - // A dry run creates nothing: with no state yet, it reads an |
| - // empty one in memory. |
| - if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { |
| - path = ":memory:" |
| - } |
| + if r.o.apply { |
| + r.db, err = provision.OpenDB(cfg.state) |
| + } else { |
| + // A dry run (and every read-only command) works on a copy in |
| + // memory: the state file is never opened by SQLite, so nothing |
| + // in it moves, not its WAL mode, a pending migration or its |
| + // mtime. With no state yet, the copy is an empty database. |
| + r.db, err = snapshot(ctx, cfg.state) |
| } |
| - if r.db, err = provision.OpenDB(path); err != nil { |
| + if err != nil { |
| return errors.New(adopt.RefuseStateOpen) |
| } |
| if r.ps, err = provision.NewStore(ctx, r.db, cfg.dek, r.e.now, adopt.Schema); err != nil { |
| @@ -826,7 +827,7 @@ func (r *runner) live(ctx context.Context) error { |
| r.say(adopt.SayLiveOpen, u) |
| return nil |
| } |
| - if err := adopt.RunLive(ctx, r.o.connect, sqid, prompter{r}, r.js, open, r.o.event, r.o.apply); err != nil { |
| + if err := adopt.RunLive(ctx, r.e.stdout, r.o.connect, sqid, prompter{r}, r.js, open, r.o.event, r.o.apply); err != nil { |
| return err |
| } |
| if !r.o.apply { |
| @@ -852,13 +853,57 @@ func (r *runner) rollback(ctx context.Context) error { |
| return err |
| } |
| if !r.o.apply { |
| - r.say(adopt.SayDryRun) |
| + preview, err := r.rollbackPreview(ctx, c, a) |
| + if err != nil { |
| + return err |
| + } |
| + r.say(preview, adopt.SayDryRun) |
| return nil |
| } |
| r.say(adopt.SayRolledBack(adopt.CanonicalHost(a))) |
| return nil |
| } |
| +// rollbackPreview says what a rollback would do now, from the journal |
| +// and a fresh read of the write layer, classified as RollbackAgentKeys |
| +// classifies it. It writes nothing. RollbackAgentKeys's own dry run has |
| +// already refused every stop. |
| +func (r *runner) rollbackPreview(ctx context.Context, c *carlosop.Client, a provision.App) (string, error) { |
| + keys, host := adopt.AgentKeys(a), adopt.CanonicalHost(a) |
| + rb, have, err := r.js.Rollback(ctx, a.Slug) |
| + if err != nil { |
| + return "", err |
| + } |
| + switch { |
| + case have && rb.State == "restarted": |
| + return adopt.SayRollbackNothing(host), nil |
| + case have && rb.State == "unset": |
| + return adopt.SayRollbackRestartOnly(keys, host), nil |
| + } |
| + base, okBase, err := r.js.Baseline(ctx, a.Slug) |
| + if err != nil { |
| + return "", err |
| + } |
| + w, okWrite, err := r.js.Write(ctx, a.Slug) |
| + if err != nil { |
| + return "", err |
| + } |
| + if !okBase || !okWrite { |
| + return "", refuse("rollback-nothing-written", "") |
| + } |
| + read, err := c.Config(ctx, a.Slug, base.WriteLayer) |
| + if err != nil { |
| + return "", err |
| + } |
| + switch adopt.ClassifyRollback(base.Layer, read, w.Sent) { |
| + case adopt.RetryUnset: |
| + return adopt.SayRollbackWould(keys, base.Layer.Bundle, host), nil |
| + case adopt.RolledBack: |
| + return adopt.SayRollbackRestartOnly(keys, host), nil |
| + } |
| + return "", refuse("rollback-refused", "") |
| +} |
| + |
| // disable opens a directory-only plan disabling app's team binding. The |
| // label is typed on the terminal. |
| func (r *runner) disable(ctx context.Context) error { |
diff --git a/cmd/alta-adopt/main_test.go b/cmd/alta-adopt/main_test.go| index 8a7579b..d2a6fa2 100644 |
| --- a/cmd/alta-adopt/main_test.go |
| +++ b/cmd/alta-adopt/main_test.go |
| @@ -15,6 +15,7 @@ import ( |
| "net/http/httptest" |
| "os" |
| "path/filepath" |
| + "reflect" |
| "strconv" |
| "strings" |
| "sync" |
| @@ -514,10 +515,21 @@ func rehearse(t *testing.T) *rig { |
| r.runState("done") |
| r.tick(homeop.WindowLifetime * time.Second) |
| - r.dry("", false, "live", "--event", "7", "--connect", r.connect.URL) |
| + // The live checks' steps come through the command's own writer. |
| + if out := r.dry("", false, "live", "--event", "7", "--connect", r.connect.URL); !strings.Contains(out, strings.Join(adopt.LiveSteps, "\n")) { |
| + t.Fatalf("live without --apply did not list its steps\n%s", out) |
| + } |
| - r.dry("", true, "rollback-config", "--app", adopt.CanaryApp) |
| + // The rollback's dry run names the keys it would remove, the bundle |
| + // and the host it would restart. |
| + keys, host := adopt.AgentKeys(cal), adopt.CanonicalHost(cal) |
| + if out := r.dry("", true, "rollback-config", "--app", adopt.CanaryApp); !strings.Contains(out, adopt.SayRollbackWould(keys, "default", host)) { |
| + t.Fatalf("rollback-config without --apply did not preview\n%s", out) |
| + } |
| r.applied("", true, "rollback-config", "--app", adopt.CanaryApp) |
| + if out := r.dry("", true, "rollback-config", "--app", adopt.CanaryApp); !strings.Contains(out, adopt.SayRollbackNothing(host)) { |
| + t.Fatalf("a finished rollback's dry run did not say so\n%s", out) |
| + } |
| r.dry("", false, "disable", "--app", adopt.CanaryApp) |
| r.applied(provision.AdoptionLabel+"\n", false, "disable", "--app", adopt.CanaryApp) |
| @@ -543,6 +555,100 @@ func TestWritesNeedApply(t *testing.T) { |
| } |
| } |
| +// fileState is a file's bytes and mtime, or its absence. |
| +type fileState struct { |
| + exists bool |
| + sum [32]byte |
| + mtime time.Time |
| +} |
| + |
| +func stateOf(t *testing.T, path string) fileState { |
| + t.Helper() |
| + fi, err := os.Stat(path) |
| + if os.IsNotExist(err) { |
| + return fileState{} |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return fileState{true, sha256.Sum256(b), fi.ModTime()} |
| +} |
| + |
| +func (r *rig) files() map[string]fileState { |
| + r.t.Helper() |
| + m := map[string]fileState{} |
| + for _, s := range []string{"", "-wal", "-shm", "-journal"} { |
| + m[s] = stateOf(r.t, r.state+s) |
| + } |
| + return m |
| +} |
| + |
| +// read-only runs: the dry runs that read the state, and status. |
| +func (r *rig) readOnly() string { |
| + r.t.Helper() |
| + var out strings.Builder |
| + out.WriteString(r.ok("", false, "status")) |
| + out.WriteString(r.ok("", true, "preflight")) |
| + out.WriteString(r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize)) |
| + return out.String() |
| +} |
| + |
| +func TestDryRunLeavesStateUntouched(t *testing.T) { |
| + t.Parallel() |
| + r := newRig(t) |
| + r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") |
| + |
| + // Make the journal's migration pending again: its ledger rows and |
| + // tables go, so any open by Alta's store would apply it to the file. |
| + db, err := sql.Open("sqlite", "file:"+r.state+"?_pragma=busy_timeout(5000)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, q := range []string{ |
| + "DELETE FROM rastrillo_migrations WHERE id LIKE 'adopt/%'", |
| + "DROP TABLE adopt_home_preflights", "DROP TABLE adopt_baselines", "DROP TABLE adopt_writes", "DROP TABLE adopt_rollbacks", |
| + "DROP TABLE adopt_afters", "DROP TABLE adopt_witnesses", "DROP TABLE adopt_checks", |
| + "PRAGMA wal_checkpoint(TRUNCATE)", |
| + } { |
| + if _, err := db.Exec(q); err != nil { |
| + t.Fatalf("%s: %v", q, err) |
| + } |
| + } |
| + db.Close() |
| + before := r.files() |
| + if !before[""].exists || before["-wal"].exists || before["-shm"].exists { |
| + t.Fatalf("setup: %+v", before) |
| + } |
| + out := r.readOnly() |
| + if after := r.files(); !reflect.DeepEqual(after, before) { |
| + t.Fatalf("a read-only run touched the state: before %+v after %+v", before, after) |
| + } |
| + // The pending migration was applied to the copy, which the runs read. |
| + if !strings.Contains(out, adopt.SayStatusPreflight(adopt.PhasePreInitialize, false)) { |
| + t.Fatalf("status did not read the migrated copy\n%s", out) |
| + } |
| + |
| + // Committed transactions still in the WAL, with another process |
| + // holding the state open, are read too, and the WAL is untouched. |
| + r.saveChecks(func() { |
| + before := r.files() |
| + if !before["-wal"].exists { |
| + t.Fatal("setup: no WAL") |
| + } |
| + out := r.readOnly() |
| + if after := r.files(); !reflect.DeepEqual(after, before) { |
| + t.Fatalf("a read-only run touched the state: before %+v after %+v", before, after) |
| + } |
| + if !strings.Contains(out, adopt.SayStatusLive(true)) { |
| + t.Fatalf("status did not read the WAL\n%s", out) |
| + } |
| + }) |
| +} |
| + |
| func TestInitializeRefusedWithoutHomePreflight(t *testing.T) { |
| t.Parallel() |
| r := newRig(t) |
| @@ -575,8 +681,9 @@ func TestPlanARefusedWithoutHomePreflight(t *testing.T) { |
| r.applied(owner+"\n", false, "plan-a") |
| } |
| -// saveChecks records every live check as passed, as a run of live would. |
| -func (r *rig) saveChecks() { |
| +// saveChecks records every live check as passed, as a run of live would, |
| +// then runs each of during while it still holds the state open. |
| +func (r *rig) saveChecks(during ...func()) { |
| r.t.Helper() |
| db, err := provision.OpenDB(r.state) |
| if err != nil { |
| @@ -597,6 +704,9 @@ func (r *rig) saveChecks() { |
| r.t.Fatal(err) |
| } |
| } |
| + for _, f := range during { |
| + f() |
| + } |
| } |
| func TestActivateNonCanaryRefusedWithoutLive(t *testing.T) { |
diff --git a/cmd/alta-adopt/snapshot.go b/cmd/alta-adopt/snapshot.go| new file mode 100644 |
| index 0000000..c91ec23 |
| --- /dev/null |
| +++ b/cmd/alta-adopt/snapshot.go |
| @@ -0,0 +1,97 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + |
| + "amadan.net/oficina/alta/provision" |
| + "modernc.org/sqlite" |
| +) |
| + |
| +// snapshot answers an in-memory copy of the state at path, for a run |
| +// that must not write. SQLite never opens path itself: even a read-only |
| +// open of a WAL database may create its -shm, and Alta's own open sets |
| +// pragmas and applies migrations. Instead the file (and its -wal, which |
| +// holds committed transactions not yet checkpointed) is copied byte for |
| +// byte into a private temporary directory, that copy is restored into |
| +// memory, and the directory is removed before anything else runs. The |
| +// copy holds only what the state holds: sealed rows. With no state at |
| +// path, the snapshot is an empty database. |
| +func snapshot(ctx context.Context, path string) (*sql.DB, error) { |
| + mem, err := provision.OpenDB(":memory:") |
| + if err != nil { |
| + return nil, err |
| + } |
| + if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { |
| + return mem, nil |
| + } |
| + if err := restore(ctx, mem, path); err != nil { |
| + mem.Close() |
| + return nil, err |
| + } |
| + return mem, nil |
| +} |
| + |
| +func restore(ctx context.Context, mem *sql.DB, path string) error { |
| + dir, err := os.MkdirTemp("", "alta-adopt-") |
| + if err != nil { |
| + return err |
| + } |
| + defer os.RemoveAll(dir) |
| + cp := filepath.Join(dir, "state.db") |
| + if err := copyFile(path, cp); err != nil { |
| + return err |
| + } |
| + if err := copyFile(path+"-wal", cp+"-wal"); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + conn, err := mem.Conn(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer conn.Close() |
| + return conn.Raw(func(dc any) error { |
| + r, ok := dc.(interface { |
| + NewRestore(string) (*sqlite.Backup, error) |
| + }) |
| + if !ok { |
| + return errors.New("alta-adopt: the SQLite driver cannot restore") |
| + } |
| + b, err := r.NewRestore(cp) |
| + if err != nil { |
| + return err |
| + } |
| + for { |
| + more, err := b.Step(-1) |
| + if err != nil { |
| + _ = b.Finish() |
| + return err |
| + } |
| + if !more { |
| + return b.Finish() |
| + } |
| + } |
| + }) |
| +} |
| + |
| +// copyFile copies src, opened read-only, to a new private file dst. |
| +func copyFile(src, dst string) error { |
| + in, err := os.Open(src) |
| + if err != nil { |
| + return err |
| + } |
| + defer in.Close() |
| + out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := io.Copy(out, in); err != nil { |
| + out.Close() |
| + return err |
| + } |
| + return out.Close() |
| +} |