oficina / base Public

Make Uninstall and final install writes safe

Uninstall refuses with ErrBusy while an app is installing, and the store
delete is conditional so the check cannot race. SetInstallState reports a
missing row. Final states are written with a context that survives
cancellation, and a failed "installed" write marks the row failed.
ResetInterrupted turns stuck installing rows into failed at boot.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ac59ac73f02a9c12da3072334d40c118f28158e9 parent aaeb95a
6 files changed, +216 −26
  • cmd/base/main.go +3 −0
  • docs/copy-pending.md +7 −0
  • internal/install/install.go +45 −7
  • internal/install/install_test.go +80 −13
  • internal/store/installs.go +41 −4
  • internal/store/store_test.go +40 −2
diff --git a/cmd/base/main.go b/cmd/base/main.go
index 90eadb5..5812893 100644
--- a/cmd/base/main.go
+++ b/cmd/base/main.go
@@ -57,6 +57,9 @@ func run(logger *slog.Logger) error {
hc := &http.Client{Timeout: 30 * time.Second}
in := install.New(d.Writer(), cfg, platform.NewHTTP(cfg.PlatformConsole, cfg.PlatformAccount, cfg.InstanceToken, cfg.OperateToken, hc), install.ProbeVersion(hc), logger)
installer = in
+ if err := store.ResetInterrupted(ctx, d.Writer()); err != nil {
+ return err
+ }
bg, stop := context.WithCancel(context.Background())
defer stop()
go func() {
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index dceaf8a..623cca4 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -60,3 +60,10 @@ People and invitations:
| internal/web/people.go | People list or invite failed (503) | unavailable |
| internal/catalog/catalog.json | Catalogue, Welcome summary | A short tour of your team's Base. |
| internal/catalog/catalog.json | Catalogue, Scratchpad summary | A shared page for quick notes. |
+| internal/install/install.go | Install failed, shown on the app's card | Platform refused the app settings |
+| internal/install/install.go | Install failed, shown on the app's card | Platform refused to create the instance |
+| internal/install/install.go | Install failed, shown on the app's card | The app did not start answering |
+| internal/install/install.go | Install failed, shown on the app's card | The install could not be recorded |
+| internal/install/install.go | Uninstall failed | Platform refused to remove the instance |
+| internal/install/install.go | Uninstall while the app is still installing | This app is still installing. Try again in a moment. |
+| internal/store/installs.go | Install cut short by a restart, shown on the app's card | Interrupted. Try again. |
diff --git a/internal/install/install.go b/internal/install/install.go
index faeb187..8449b73 100644
--- a/internal/install/install.go
+++ b/internal/install/install.go
@@ -28,6 +28,18 @@ const (
probeTimeout = 5 * time.Minute
)
+// Messages stored on install rows and shown to people.
+const (
+ msgSettings = "Platform refused the app settings"
+ msgCreate = "Platform refused to create the instance"
+ msgNoAnswer = "The app did not start answering"
+ msgNotRecorded = "The install could not be recorded"
+ msgRemove = "Platform refused to remove the instance"
+)
+
+// ErrBusy is returned by Uninstall while the app is still being installed.
+var ErrBusy = errors.New("This app is still installing. Try again in a moment.")
+
// Installer installs and uninstalls apps. It satisfies web.Installer.
type Installer struct {
db *sql.DB
@@ -92,15 +104,22 @@ func (in *Installer) Install(ctx context.Context, app string) error {
}
origin := "https://" + host
if err := in.pc.SetEnv(ctx, app, label, AppVars(in.cfg, app, origin)); err != nil {
- return in.fail(ctx, app, "Platform refused the app settings", err)
+ return in.fail(ctx, app, msgSettings, err)
}
if err := in.pc.CreateInstance(ctx, app, host, label); err != nil {
- return in.fail(ctx, app, "Platform refused to create the instance", err)
+ return in.fail(ctx, app, msgCreate, err)
}
if err := in.probe(ctx, origin); err != nil {
- return in.fail(ctx, app, "The app did not start answering", err)
+ return in.fail(ctx, app, msgNoAnswer, err)
}
- return store.SetInstallState(ctx, in.db, app, "installed", "")
+ // The final write must land even if ctx was cancelled meanwhile.
+ bg := context.WithoutCancel(ctx)
+ if err := store.SetInstallState(bg, in.db, app, "installed", ""); err != nil {
+ in.logger.Error("recording install", "app", app, "err", err)
+ _ = store.SetInstallState(bg, in.db, app, "failed", msgNotRecorded)
+ return err
+ }
+ return nil
}
// fail records a short message (never the underlying error text, which may
@@ -115,14 +134,33 @@ func (in *Installer) fail(ctx context.Context, app, msg string, cause error) err
}
// Uninstall removes the instance's route, then forgets the install. The
-// app's data is kept by Platform.
+// app's data is kept by Platform. It returns ErrBusy, touching nothing, while
+// the app is installing.
func (in *Installer) Uninstall(ctx context.Context, app string) error {
+ all, err := store.Installs(ctx, in.db)
+ if err != nil {
+ return err
+ }
+ for _, i := range all {
+ if i.App == app && i.State == "installing" {
+ return ErrBusy
+ }
+ }
_, host := HostFor(in.cfg, app)
if err := in.pc.DeleteInstance(ctx, app, host); err != nil {
in.logger.Error("uninstall failed", "app", app, "err", err)
- return errors.New("Platform refused to remove the instance")
+ return errors.New(msgRemove)
+ }
+ // The delete itself refuses an installing row, closing the gap between
+ // the check above and now.
+ busy, err := store.DeleteInstall(ctx, in.db, app)
+ if err != nil {
+ return err
+ }
+ if busy {
+ return ErrBusy
}
- return store.DeleteInstall(ctx, in.db, app)
+ return nil
}
// EnsureDefaults installs every default catalogue app that is not already
diff --git a/internal/install/install_test.go b/internal/install/install_test.go
index e97bc4f..36bc592 100644
--- a/internal/install/install_test.go
+++ b/internal/install/install_test.go
@@ -1,9 +1,12 @@
package install
import (
+ "bytes"
"context"
+ "crypto/sha256"
"database/sql"
"encoding/base64"
+ "encoding/hex"
"encoding/json"
"errors"
"io"
@@ -11,7 +14,6 @@ import (
"net/http"
"net/http/httptest"
"os"
- "sync"
"sync/atomic"
"testing"
"time"
@@ -100,32 +102,36 @@ func TestInstallWritesEnvThenCreates(t *testing.T) {
func TestKeySetIsHexSHA256OfSignPub(t *testing.T) {
kp, _ := crypto.Generate()
+ sum := sha256.Sum256(kp.SignPub())
kid, pub := KeySet(kp)
- if len(kid) != 64 || len(pub) != 65 {
- t.Fatalf("kid %q pub %d", kid, len(pub))
+ if kid != hex.EncodeToString(sum[:]) || !bytes.Equal(pub, kp.SignPub()) || len(pub) != 65 {
+ t.Fatalf("kid %q pub %x", kid, pub)
}
}
func TestInstallTwiceIsOneInstance(t *testing.T) {
- var n atomic.Int32
+ entered := make(chan struct{}, 2)
gate := make(chan struct{})
- in, pf, _, _ := setup(t, func(context.Context, string) error { n.Add(1); <-gate; return nil })
- var wg sync.WaitGroup
- for range 2 {
- wg.Add(1)
- go func() { defer wg.Done(); _ = in.Install(context.Background(), "scratchpad") }()
+ in, pf, _, _ := setup(t, func(context.Context, string) error { entered <- struct{}{}; <-gate; return nil })
+ errs := make(chan error, 2)
+ go func() { errs <- in.Install(context.Background(), "scratchpad") }()
+ <-entered // first call is now mid-install
+ go func() { errs <- in.Install(context.Background(), "scratchpad") }()
+ if err := <-errs; err != nil { // the second returns while the first is still held
+ t.Fatalf("second Install: %v", err)
}
- time.Sleep(50 * time.Millisecond)
close(gate)
- wg.Wait()
+ if err := <-errs; err != nil {
+ t.Fatalf("first Install: %v", err)
+ }
creates := 0
for _, c := range pf.Calls() {
if c.Method == "CreateInstance" {
creates++
}
}
- if creates != 1 || n.Load() != 1 {
- t.Fatalf("creates %d probes %d", creates, n.Load())
+ if creates != 1 || len(entered) != 0 {
+ t.Fatalf("creates %d extra probes %d", creates, len(entered))
}
}
@@ -238,3 +244,64 @@ func TestProbeVersionGivesUp(t *testing.T) {
t.Fatal("want error")
}
}
+
+// blockingClient pauses CreateInstance until released.
+type blockingClient struct {
+ platform.Client
+ entered chan struct{}
+ release chan struct{}
+}
+
+func (b *blockingClient) CreateInstance(ctx context.Context, app, host, env string) error {
+ b.entered <- struct{}{}
+ <-b.release
+ return b.Client.CreateInstance(ctx, app, host, env)
+}
+
+func TestUninstallRefusedWhileInstalling(t *testing.T) {
+ in, pf, db, _ := setup(t, nil)
+ bc := &blockingClient{Client: pf, entered: make(chan struct{}), release: make(chan struct{})}
+ in.pc = bc
+ done := make(chan error, 1)
+ go func() { done <- in.Install(context.Background(), "scratchpad") }()
+ <-bc.entered
+ if err := in.Uninstall(context.Background(), "scratchpad"); !errors.Is(err, ErrBusy) {
+ t.Fatalf("Uninstall = %v, want ErrBusy", err)
+ }
+ for _, c := range pf.Calls() {
+ if c.Method == "DeleteInstance" {
+ t.Fatal("DeleteInstance called while installing")
+ }
+ }
+ close(bc.release)
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ if s := state(t, db, "scratchpad"); s.State != "installed" {
+ t.Errorf("row = %+v", s)
+ }
+}
+
+func TestInstallFinalStateSurvivesCancelledContext(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ in, _, db, _ := setup(t, func(context.Context, string) error { cancel(); return nil })
+ if err := in.Install(ctx, "scratchpad"); err != nil {
+ t.Fatal(err)
+ }
+ if s := state(t, db, "scratchpad"); s.State != "installed" {
+ t.Errorf("row = %+v", s)
+ }
+}
+
+func TestInstallFailsWhenRowVanishes(t *testing.T) {
+ var in *Installer
+ var db *sql.DB
+ in, _, db, _ = setup(t, nil)
+ in.probe = func(ctx context.Context, _ string) error {
+ _, err := db.ExecContext(ctx, `DELETE FROM installs`)
+ return err
+ }
+ if err := in.Install(context.Background(), "scratchpad"); err == nil {
+ t.Fatal("want an error when the row is gone")
+ }
+}
diff --git a/internal/store/installs.go b/internal/store/installs.go
index b560939..7f0684e 100644
--- a/internal/store/installs.go
+++ b/internal/store/installs.go
@@ -3,6 +3,7 @@ package store
import (
"context"
"database/sql"
+ "errors"
"time"
)
@@ -47,13 +48,49 @@ func ClaimInstall(ctx context.Context, db *sql.DB, app, host string) (bool, erro
return n == 1, err
}
+// ErrNoInstall means an install row that was expected is gone.
+var ErrNoInstall = errors.New("no such install")
+
+// SetInstallState sets app's state. It returns ErrNoInstall if app has no row.
func SetInstallState(ctx context.Context, db *sql.DB, app, state, errMsg string) error {
- _, err := db.ExecContext(ctx, `UPDATE installs SET state = ?, error = ?, updated_at = ? WHERE app = ?`,
+ res, err := db.ExecContext(ctx, `UPDATE installs SET state = ?, error = ?, updated_at = ? WHERE app = ?`,
state, errMsg, time.Now().UTC(), app)
- return err
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil {
+ return err
+ } else if n == 0 {
+ return ErrNoInstall
+ }
+ return nil
+}
+
+// DeleteInstall removes app's row unless it is "installing", in which case
+// it leaves the row alone and reports busy. A missing row is not busy.
+func DeleteInstall(ctx context.Context, db *sql.DB, app string) (busy bool, err error) {
+ res, err := db.ExecContext(ctx, `DELETE FROM installs WHERE app = ? AND state <> 'installing'`, app)
+ if err != nil {
+ return false, err
+ }
+ if n, err := res.RowsAffected(); err != nil || n == 1 {
+ return false, err
+ }
+ var one int
+ err = db.QueryRowContext(ctx, `SELECT 1 FROM installs WHERE app = ?`, app).Scan(&one)
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return err == nil, err
}
-func DeleteInstall(ctx context.Context, db *sql.DB, app string) error {
- _, err := db.ExecContext(ctx, `DELETE FROM installs WHERE app = ?`, app)
+// ResetInterrupted marks every "installing" row "failed". Call it once at
+// boot: Base is one process, so nothing is genuinely installing then.
+func ResetInterrupted(ctx context.Context, db *sql.DB) error {
+ _, err := db.ExecContext(ctx, `UPDATE installs SET state = 'failed', error = ?, updated_at = ? WHERE state = 'installing'`,
+ InterruptedMessage, time.Now().UTC())
return err
}
+
+// InterruptedMessage is stored on installs cut short by a restart.
+const InterruptedMessage = "Interrupted. Try again."
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index c87d8f7..c83f16f 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -3,6 +3,7 @@ package store
import (
"context"
"database/sql"
+ "errors"
"os"
"testing"
@@ -72,8 +73,8 @@ func TestClaimInstallRetriesFailed(t *testing.T) {
if err != nil || len(is) != 1 || is[0].State != "installed" {
t.Fatalf("installs = %+v, %v", is, err)
}
- if err := DeleteInstall(ctx, db, "a"); err != nil {
- t.Fatal(err)
+ if busy, err := DeleteInstall(ctx, db, "a"); err != nil || busy {
+ t.Fatalf("delete = %v, %v", busy, err)
}
is, err = Installs(ctx, db)
if err != nil || len(is) != 0 {
@@ -102,3 +103,40 @@ func TestInviteAndJoin(t *testing.T) {
t.Errorf("stranger lookup = %v, %v; want false, nil", ok, err)
}
}
+
+func TestDeleteInstallRefusesInstalling(t *testing.T) {
+ ctx, db := context.Background(), open(t)
+ ClaimInstall(ctx, db, "a", "h")
+ if busy, err := DeleteInstall(ctx, db, "a"); err != nil || !busy {
+ t.Fatalf("delete = %v, %v; want busy", busy, err)
+ }
+ if is, _ := Installs(ctx, db); len(is) != 1 {
+ t.Fatal("row was removed")
+ }
+ if busy, err := DeleteInstall(ctx, db, "missing"); err != nil || busy {
+ t.Fatalf("delete of missing = %v, %v", busy, err)
+ }
+}
+
+func TestSetInstallStateMissingRow(t *testing.T) {
+ if err := SetInstallState(context.Background(), open(t), "nope", "installed", ""); !errors.Is(err, ErrNoInstall) {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+func TestResetInterrupted(t *testing.T) {
+ ctx, db := context.Background(), open(t)
+ ClaimInstall(ctx, db, "a", "h")
+ ClaimInstall(ctx, db, "b", "h")
+ SetInstallState(ctx, db, "b", "installed", "")
+ if err := ResetInterrupted(ctx, db); err != nil {
+ t.Fatal(err)
+ }
+ is, _ := Installs(ctx, db)
+ if is[0].State != "failed" || is[0].Error != "Interrupted. Try again." || is[1].State != "installed" {
+ t.Fatalf("installs = %+v", is)
+ }
+ if ok, _ := ClaimInstall(ctx, db, "a", "h"); !ok {
+ t.Fatal("interrupted install cannot be reclaimed")
+ }
+}