oficina / base Public

Fix install lifecycle: recorded host, removals, sync claim

Uninstall deletes the host Base recorded for the install, and Home tiles
and the issuer's audience use it too, so a changed slug or apps domain
cannot send a delete or an assertion elsewhere. Once Platform accepts a
delete, Base forgets the install on a bounded context the request cannot
cancel.

An uninstalled default app (Welcome) is remembered in a new
removed_defaults table, so EnsureDefaults leaves it off at boot; installing
it from the Store clears that (R28).

The Store's install POST now calls Installer.Start, which claims the
install before the redirect and provisions in the background, so the next
page always shows Installing with its refresh (R33).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 0d843a437708c6079703717b7dcd995dc028bd6b parent c3b0057
16 files changed, +486 −103
  • cmd/base/main.go +1 −1
  • internal/browsertest/base_test.go +1 −1
  • internal/e2e/handoff_test.go +1 −1
  • internal/install/install.go +99 −21
  • internal/install/install_test.go +153 −0
  • internal/issuer/issuer.go +7 −12
  • internal/issuer/issuer_test.go +33 −1
  • internal/store/installs.go +42 −5
  • internal/store/migrations/0003_removed_defaults.sql +7 −0
  • internal/store/store_test.go +31 −3
  • internal/web/app.go +5 −3
  • internal/web/home.go +2 −3
  • internal/web/store.go +6 −8
  • internal/webtest/harness_test.go +9 −2
  • internal/webtest/home_test.go +18 −0
  • internal/webtest/store_test.go +71 −42
diff --git a/cmd/base/main.go b/cmd/base/main.go
index 5812893..ac155e6 100644
--- a/cmd/base/main.go
+++ b/cmd/base/main.go
@@ -84,5 +84,5 @@ func run(logger *slog.Logger) error {
// noInstaller stands in when Platform settings are missing (local development).
type noInstaller struct{}
-func (noInstaller) Install(context.Context, string) error { return nil }
+func (noInstaller) Start(context.Context, string) error { return nil }
func (noInstaller) Uninstall(context.Context, string) error { return nil }
diff --git a/internal/browsertest/base_test.go b/internal/browsertest/base_test.go
index 0ec92ea..dd4c34b 100644
--- a/internal/browsertest/base_test.go
+++ b/internal/browsertest/base_test.go
@@ -76,7 +76,7 @@ func (m *mailbox) lastLink(t *testing.T) string {
type noInstaller struct{}
-func (noInstaller) Install(context.Context, string) error { return nil }
+func (noInstaller) Start(context.Context, string) error { return nil }
func (noInstaller) Uninstall(context.Context, string) error { return nil }
// baseApp is one Base over its own database, with the owner seeded.
diff --git a/internal/e2e/handoff_test.go b/internal/e2e/handoff_test.go
index 32367be..c3c1b37 100644
--- a/internal/e2e/handoff_test.go
+++ b/internal/e2e/handoff_test.go
@@ -70,7 +70,7 @@ func (m *mailbox) body() string { m.mu.Lock(); defer m.mu.Unlock(); return m.las
type noInstaller struct{}
-func (noInstaller) Install(context.Context, string) error { return nil }
+func (noInstaller) Start(context.Context, string) error { return nil }
func (noInstaller) Uninstall(context.Context, string) error { return nil }
// swappable lets a test replace a running server's handler.
diff --git a/internal/install/install.go b/internal/install/install.go
index ff1e5ec..a7ea44c 100644
--- a/internal/install/install.go
+++ b/internal/install/install.go
@@ -104,31 +104,94 @@ func AppVars(cfg config.Config, app, origin string) map[string]string {
}
}
+// localWriteTimeout bounds a state write that must land after the caller's
+// context is gone: Platform has already acted, so Base records it regardless.
+const localWriteTimeout = 10 * time.Second
+
+// finishing returns a context for such a write: ctx's values without its
+// cancellation, bounded by localWriteTimeout.
+func finishing(ctx context.Context) (context.Context, context.CancelFunc) {
+ return context.WithTimeout(context.WithoutCancel(ctx), localWriteTimeout)
+}
+
// Install claims app, configures and creates its instance, waits for it to
// answer, and records the result. It blocks until then. If the app is
// already installed or being installed it does nothing and returns nil.
// A failure is recorded as a short message on the install row; the returned
-// error carries the same text.
+// error carries the same text. Installing a default app the owner removed
+// clears that removal.
func (in *Installer) Install(ctx context.Context, app string) error {
+ run, err := in.claim(ctx, app, false)
+ if run == nil {
+ return err
+ }
+ return run(ctx)
+}
+
+// Start is Install for a request that must answer at once. It claims app
+// before it returns, so a page loaded next already shows the app
+// installing, and does the rest in the background. The background work
+// keeps ctx's values but not its cancellation: it outlives the request.
+// Failures after the claim are recorded on the install row and logged.
+func (in *Installer) Start(ctx context.Context, app string) error {
+ run, err := in.claim(ctx, app, false)
+ if run == nil {
+ return err
+ }
+ bg := context.WithoutCancel(ctx)
+ go func() {
+ if err := run(bg); err != nil {
+ in.logger.Error("install", "app", app, "err", err)
+ }
+ }()
+ return nil
+}
+
+// claim takes app's lock and moves its row to "installing". It returns the
+// rest of the install, which releases the lock when it ends, or a nil func
+// when there is nothing to do: another install or uninstall of app holds the
+// lock, the app is already installed or installing, or (asDefault) the owner
+// removed this default app. Without asDefault it first clears any such
+// removal: someone chose to install the app.
+func (in *Installer) claim(ctx context.Context, app string, asDefault bool) (func(context.Context) error, error) {
if _, ok := catalog.Get(app); !ok {
- return fmt.Errorf("unknown app %q", app)
+ return nil, fmt.Errorf("unknown app %q", app)
}
if in.cfg.AssertionKey == nil {
- return errors.New("BASE_ASSERTION_KEY is not set")
+ return nil, errors.New("BASE_ASSERTION_KEY is not set")
}
lock := in.lockFor(app)
if !lock.TryLock() {
- return nil // another Install or Uninstall of this app is running
+ return nil, nil // another Install or Uninstall of this app is running
+ }
+ held := true
+ defer func() {
+ if held {
+ lock.Unlock()
+ }
+ }()
+ if asDefault {
+ removed, err := store.DefaultRemoved(ctx, in.db, app)
+ if err != nil || removed {
+ return nil, err
+ }
+ } else if err := store.ClearDefaultRemoved(ctx, in.db, app); err != nil {
+ return nil, err
}
- defer lock.Unlock()
label, host := HostFor(in.cfg, app)
claimed, err := store.ClaimInstall(ctx, in.db, app, host)
- if err != nil {
- return err
- }
- if !claimed {
- return nil
+ if err != nil || !claimed {
+ return nil, err
}
+ held = false // the returned func owns the lock now
+ return func(ctx context.Context) error {
+ defer lock.Unlock()
+ return in.provision(ctx, app, label, host)
+ }, nil
+}
+
+// provision does the claimed install's remote work and records the result.
+func (in *Installer) provision(ctx context.Context, app, label, host 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, msgSettings, err)
@@ -140,7 +203,8 @@ func (in *Installer) Install(ctx context.Context, app string) error {
return in.fail(ctx, app, msgNoAnswer, err)
}
// The final write must land even if ctx was cancelled meanwhile.
- bg := context.WithoutCancel(ctx)
+ bg, cancel := finishing(ctx)
+ defer cancel()
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)
@@ -154,15 +218,19 @@ func (in *Installer) Install(ctx context.Context, app string) error {
func (in *Installer) fail(ctx context.Context, app, msg string, cause error) error {
in.logger.Error("install failed", "app", app, "err", cause)
// The caller's context may be what failed; record the state regardless.
- if err := store.SetInstallState(context.WithoutCancel(ctx), in.db, app, "failed", msg); err != nil {
+ bg, cancel := finishing(ctx)
+ defer cancel()
+ if err := store.SetInstallState(bg, in.db, app, "failed", msg); err != nil {
in.logger.Error("recording install failure", "app", app, "err", err)
}
return errors.New(msg)
}
-// Uninstall removes the instance's route, then forgets the install. The
-// app's data is kept by Platform. It returns ErrBusy, touching nothing, while
-// the app is installing, and store.ErrNoInstall if it is not installed.
+// Uninstall removes the instance Base recorded for app, then forgets the
+// install. The app's data is kept by Platform. It returns ErrBusy, touching
+// nothing, while the app is installing, and store.ErrNoInstall if it is not
+// installed. Uninstalling a default app records that the owner removed it,
+// so EnsureDefaults leaves it off.
func (in *Installer) Uninstall(ctx context.Context, app string) error {
lock := in.lockFor(app)
if !lock.TryLock() {
@@ -185,14 +253,19 @@ func (in *Installer) Uninstall(ctx context.Context, app string) error {
if row.State == "installing" {
return ErrBusy
}
- _, host := HostFor(in.cfg, app)
- if err := in.pc.DeleteInstance(ctx, app, host); err != nil {
+ // The host the instance was made at, not what config would name now: a
+ // changed slug or apps domain must not send the delete elsewhere.
+ if err := in.pc.DeleteInstance(ctx, app, row.Host); err != nil {
in.logger.Error("uninstall failed", "app", app, "err", err)
//lint:ignore ST1005 the text is shown to people as written
return errors.New(msgRemove)
}
+ // Platform has removed it; record that even if the caller has gone.
+ bg, cancel := finishing(ctx)
+ defer cancel()
+ e, _ := catalog.Get(app)
// The store refuses an installing row too, as a second guard.
- busy, err := store.DeleteInstall(ctx, in.db, app)
+ busy, err := store.DeleteInstall(bg, in.db, app, e.Default)
if err != nil {
return err
}
@@ -203,15 +276,20 @@ func (in *Installer) Uninstall(ctx context.Context, app string) error {
}
// EnsureDefaults installs every default catalogue app that is not already
-// installed. Apps that fail are retried on the next call; the first error
-// is returned after every default has been tried.
+// installed and that the owner has not uninstalled. Apps that fail are
+// retried on the next call; the first error is returned after every default
+// has been tried.
func (in *Installer) EnsureDefaults(ctx context.Context) error {
var first error
for _, e := range catalog.All() {
if !e.Default {
continue
}
- if err := in.Install(ctx, e.ID); err != nil && first == nil {
+ run, err := in.claim(ctx, e.ID, true)
+ if run != nil {
+ err = run(ctx)
+ }
+ if err != nil && first == nil {
first = err
}
}
diff --git a/internal/install/install_test.go b/internal/install/install_test.go
index 590343c..493a61b 100644
--- a/internal/install/install_test.go
+++ b/internal/install/install_test.go
@@ -359,3 +359,156 @@ func TestInstalledWriteFailsRowEndsFailed(t *testing.T) {
t.Fatalf("row = %+v", s)
}
}
+
+// Finding 1: the instance Base removes is the one it recorded, even after
+// the slug or apps domain changed.
+func TestUninstallDeletesRecordedHost(t *testing.T) {
+ in, pf, db, _ := setup(t, nil)
+ if err := in.Install(context.Background(), "scratchpad"); err != nil {
+ t.Fatal(err)
+ }
+ in.cfg.Slug, in.cfg.AppsDomain = "newco", "elsewhere.example"
+ if err := in.Uninstall(context.Background(), "scratchpad"); err != nil {
+ t.Fatal(err)
+ }
+ calls := pf.Calls()
+ if last := calls[len(calls)-1]; last.Method != "DeleteInstance" || last.Host != "acme-scratchpad.bab.oncarlos.com" {
+ t.Fatalf("deleted %+v, want the recorded host", last)
+ }
+ if s := state(t, db, "scratchpad"); s.App != "" {
+ t.Errorf("row remains: %+v", s)
+ }
+}
+
+// cancelOnDelete cancels the caller's context the moment Platform accepts the
+// delete, as a browser that disconnects then would.
+type cancelOnDelete struct {
+ platform.Client
+ cancel context.CancelFunc
+}
+
+func (c cancelOnDelete) DeleteInstance(ctx context.Context, app, host string) error {
+ err := c.Client.DeleteInstance(ctx, app, host)
+ c.cancel()
+ return err
+}
+
+// Finding 2: once Platform has removed the instance, Base forgets the
+// install even if the request that asked has gone.
+func TestUninstallFinishesAfterCallerCancels(t *testing.T) {
+ in, pf, db, _ := setup(t, nil)
+ if err := in.Install(context.Background(), "scratchpad"); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ in.pc = cancelOnDelete{Client: pf, cancel: cancel}
+ if err := in.Uninstall(ctx, "scratchpad"); err != nil {
+ t.Fatalf("Uninstall: %v", err)
+ }
+ if s := state(t, db, "scratchpad"); s.App != "" {
+ t.Fatalf("a removed instance is still marked %q", s.State)
+ }
+}
+
+func creates(pf *platform.Fake, app string) int {
+ n := 0
+ for _, c := range pf.Calls() {
+ if c.Method == "CreateInstance" && c.App == app {
+ n++
+ }
+ }
+ return n
+}
+
+// Finding 4 (R28): an owner who uninstalls Welcome does not get it back on
+// the next boot; installing it from the Store brings it back.
+func TestUninstalledDefaultStaysRemoved(t *testing.T) {
+ in, pf, db, _ := setup(t, nil)
+ ctx := context.Background()
+ if err := in.EnsureDefaults(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := in.Uninstall(ctx, "welcome"); err != nil {
+ t.Fatal(err)
+ }
+ for range 2 { // two more boots
+ if err := in.EnsureDefaults(ctx); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if n := creates(pf, "welcome"); n != 1 {
+ t.Fatalf("Welcome created %d times, want once", n)
+ }
+ if s := state(t, db, "welcome"); s.App != "" {
+ t.Fatalf("Welcome came back: %+v", s)
+ }
+ if err := in.Install(ctx, "welcome"); err != nil { // the Store's install
+ t.Fatal(err)
+ }
+ if s := state(t, db, "welcome"); s.State != "installed" {
+ t.Fatalf("Store install: %+v", s)
+ }
+ // Installed again by hand, it is a default like any other: a failed
+ // install is retried at boot.
+ if err := in.EnsureDefaults(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if n := creates(pf, "welcome"); n != 2 {
+ t.Fatalf("Welcome created %d times, want twice", n)
+ }
+}
+
+// blockSetEnv holds the first platform write until released.
+type blockSetEnv struct {
+ platform.Client
+ entered chan struct{}
+ release chan struct{}
+}
+
+func (b *blockSetEnv) SetEnv(ctx context.Context, app, env string, vars map[string]string) error {
+ b.entered <- struct{}{}
+ <-b.release
+ return b.Client.SetEnv(ctx, app, env, vars)
+}
+
+// Finding 5 (R33): Start has claimed the install by the time it returns, and
+// the rest runs on after the caller's context is cancelled.
+func TestStartClaimsThenProvisionsInBackground(t *testing.T) {
+ in, pf, db, _ := setup(t, nil)
+ bc := &blockSetEnv{Client: pf, entered: make(chan struct{}, 1), release: make(chan struct{})}
+ in.pc = bc
+ ctx, cancel := context.WithCancel(context.Background())
+ if err := in.Start(ctx, "scratchpad"); err != nil {
+ t.Fatal(err)
+ }
+ cancel() // the request has ended
+ if s := state(t, db, "scratchpad"); s.State != "installing" {
+ t.Fatalf("after Start the row is %+v, want installing", s)
+ }
+ <-bc.entered
+ // A second Start while the first is running does nothing.
+ if err := in.Start(context.Background(), "scratchpad"); err != nil {
+ t.Fatal(err)
+ }
+ close(bc.release)
+ deadline := time.Now().Add(5 * time.Second)
+ for state(t, db, "scratchpad").State != "installed" {
+ if time.Now().After(deadline) {
+ t.Fatalf("install did not finish: %+v", state(t, db, "scratchpad"))
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if n := creates(pf, "scratchpad"); n != 1 {
+ t.Fatalf("creates = %d", n)
+ }
+}
+
+func TestStartUnknownAppIsAnError(t *testing.T) {
+ in, pf, _, _ := setup(t, nil)
+ if err := in.Start(context.Background(), "nope"); err == nil {
+ t.Fatal("want an error")
+ }
+ if len(pf.Calls()) != 0 {
+ t.Fatal("platform called")
+ }
+}
diff --git a/internal/issuer/issuer.go b/internal/issuer/issuer.go
index 79cdaef..92ee6cd 100644
--- a/internal/issuer/issuer.go
+++ b/internal/issuer/issuer.go
@@ -4,8 +4,8 @@
// An app sends the browser to GET /authorize?consumer=<app>&nonce=<n>. Base
// answers with a page whose form posts the assertion to the app's own
// /auth/assertion, submitted by a deferred script or the Continue button.
-// The audience is always the installed app's origin, derived from config and
-// the app id, never from the request.
+// The audience is always the installed app's origin, the host Base recorded
+// when it installed the app, never from the request.
package issuer
import (
@@ -170,9 +170,9 @@ func (s *issuer) fail(w http.ResponseWriter, app string, err error) {
}
// installedOrigin returns https://<host> for app when its install row is
-// "installed" and was made for the host config names now. A row recorded
-// for another host (the slug or apps domain changed since) is refused, so an
-// assertion only ever goes where Base put the app.
+// "installed", where host is the one Base recorded when it installed the
+// app. That is the origin the app was given as its own (BASE_APP_ORIGIN),
+// so it stays right if the slug or apps domain changes later.
func (s *issuer) installedOrigin(r *http.Request, app string) (string, bool, error) {
if app == "" {
return "", false, nil
@@ -181,19 +181,14 @@ func (s *issuer) installedOrigin(r *http.Request, app string) (string, bool, err
if err != nil {
return "", false, err
}
- _, host := install.HostFor(s.cfg, app)
for _, in := range installs {
if in.App != app {
continue
}
- if in.State != "installed" {
+ if in.State != "installed" || in.Host == "" {
return "", false, nil
}
- if in.Host != host {
- s.logger.Warn("authorize: install host differs from config", "app", app)
- return "", false, nil
- }
- return "https://" + host, true, nil
+ return "https://" + in.Host, true, nil
}
return "", false, nil
}
diff --git a/internal/issuer/issuer_test.go b/internal/issuer/issuer_test.go
index c0bcca8..5a8cbb2 100644
--- a/internal/issuer/issuer_test.go
+++ b/internal/issuer/issuer_test.go
@@ -91,7 +91,7 @@ func (m *mailbox) Send(_ context.Context, _, _, body string) error { m.last = bo
type noInstaller struct{}
-func (noInstaller) Install(context.Context, string) error { return nil }
+func (noInstaller) Start(context.Context, string) error { return nil }
func (noInstaller) Uninstall(context.Context, string) error { return nil }
type resp struct {
@@ -478,3 +478,35 @@ func TestNewNeedsKey(t *testing.T) {
t.Fatal("New accepted a missing assertion key")
}
}
+
+// Finding 1: the assertion goes to the host Base installed the app at, which
+// is where the app was told its own origin is, even after the slug or apps
+// domain changed. It still never comes from the request.
+func TestAuthorizeUsesRecordedHost(t *testing.T) {
+ b := newBase(t)
+ ctx := context.Background()
+ const old = "https://oldco-scratchpad.old.example"
+ if _, err := store.ClaimInstall(ctx, b.db, "scratchpad", strings.TrimPrefix(old, "https://")); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.SetInstallState(ctx, b.db, "scratchpad", "installed", ""); err != nil {
+ t.Fatal(err)
+ }
+ b.signIn(ownerAddress)
+ page := b.get(authorizePath("scratchpad", nonce(t)))
+ v, ok := fields(page.Body, old+"/auth/assertion")
+ if page.Code != 200 || !ok {
+ t.Fatalf("authorize: %d\n%s", page.Code, page.Body)
+ }
+ kid, pub := install.KeySet(b.cfg.AssertionKey)
+ ver, err := assertion.NewVerifier(b.cfg.Origin, old, map[string][]byte{kid: pub})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if c, err := ver.Verify(v.Get("assertion"), time.Now()); err != nil || c.Audience != old {
+ t.Fatalf("assertion for %q: %v", c.Audience, err)
+ }
+ if got := page.Header.Get("Content-Security-Policy"); !strings.HasSuffix(got, "form-action "+old) {
+ t.Errorf("CSP %q", got)
+ }
+}
diff --git a/internal/store/installs.go b/internal/store/installs.go
index 7f0684e..707de42 100644
--- a/internal/store/installs.go
+++ b/internal/store/installs.go
@@ -67,23 +67,60 @@ func SetInstallState(ctx context.Context, db *sql.DB, app, state, errMsg string)
}
// 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)
+// it leaves the row alone and reports busy. A missing row is not busy. When
+// removedDefault is set, the same transaction records that the owner removed
+// this default app, so DefaultRemoved reports it from then on.
+func DeleteInstall(ctx context.Context, db *sql.DB, app string, removedDefault bool) (busy bool, err error) {
+ tx, err := db.BeginTx(ctx, nil)
if err != nil {
return false, err
}
- if n, err := res.RowsAffected(); err != nil || n == 1 {
+ defer tx.Rollback()
+ res, err := tx.ExecContext(ctx, `DELETE FROM installs WHERE app = ? AND state <> 'installing'`, app)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
return false, err
}
+ if n == 0 {
+ var one int
+ err = tx.QueryRowContext(ctx, `SELECT 1 FROM installs WHERE app = ?`, app).Scan(&one)
+ if err == nil {
+ return true, nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return false, err
+ }
+ }
+ if removedDefault {
+ if _, err := tx.ExecContext(ctx, `INSERT INTO removed_defaults (app, removed_at) VALUES (?, ?)
+ ON CONFLICT (app) DO UPDATE SET removed_at = excluded.removed_at`, app, time.Now().UTC()); err != nil {
+ return false, err
+ }
+ }
+ return false, tx.Commit()
+}
+
+// DefaultRemoved reports whether the owner uninstalled app, a default app,
+// and has not installed it again since.
+func DefaultRemoved(ctx context.Context, db *sql.DB, app string) (bool, error) {
var one int
- err = db.QueryRowContext(ctx, `SELECT 1 FROM installs WHERE app = ?`, app).Scan(&one)
+ err := db.QueryRowContext(ctx, `SELECT 1 FROM removed_defaults WHERE app = ?`, app).Scan(&one)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return err == nil, err
}
+// ClearDefaultRemoved forgets that app was removed: someone chose to install
+// it again.
+func ClearDefaultRemoved(ctx context.Context, db *sql.DB, app string) error {
+ _, err := db.ExecContext(ctx, `DELETE FROM removed_defaults WHERE app = ?`, app)
+ return err
+}
+
// 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 {
diff --git a/internal/store/migrations/0003_removed_defaults.sql b/internal/store/migrations/0003_removed_defaults.sql
new file mode 100644
index 0000000..3f85ef7
--- /dev/null
+++ b/internal/store/migrations/0003_removed_defaults.sql
@@ -0,0 +1,7 @@
+-- Default apps (Welcome) an owner has uninstalled. Base installs every
+-- default at boot except these; installing one from the Store clears it.
+CREATE TABLE removed_defaults (
+ app text NOT NULL,
+ removed_at datetime NOT NULL,
+ PRIMARY KEY (app)
+);
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index 40bc53a..6156579 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -74,7 +74,7 @@ func TestClaimInstallRetriesFailed(t *testing.T) {
if err != nil || len(is) != 1 || is[0].State != "installed" {
t.Fatalf("installs = %+v, %v", is, err)
}
- if busy, err := DeleteInstall(ctx, db, "a"); err != nil || busy {
+ if busy, err := DeleteInstall(ctx, db, "a", false); err != nil || busy {
t.Fatalf("delete = %v, %v", busy, err)
}
is, err = Installs(ctx, db)
@@ -108,13 +108,13 @@ func TestInviteAndJoin(t *testing.T) {
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 {
+ if busy, err := DeleteInstall(ctx, db, "a", false); 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 {
+ if busy, err := DeleteInstall(ctx, db, "missing", false); err != nil || busy {
t.Fatalf("delete of missing = %v, %v", busy, err)
}
}
@@ -141,3 +141,31 @@ func TestResetInterrupted(t *testing.T) {
t.Fatal("interrupted install cannot be reclaimed")
}
}
+
+func TestRemovedDefaultIsRemembered(t *testing.T) {
+ ctx, db := context.Background(), open(t)
+ if removed, err := DefaultRemoved(ctx, db, "welcome"); err != nil || removed {
+ t.Fatalf("fresh = %v, %v", removed, err)
+ }
+ ClaimInstall(ctx, db, "welcome", "h")
+ // An installing row is busy, and nothing is recorded.
+ if busy, err := DeleteInstall(ctx, db, "welcome", true); err != nil || !busy {
+ t.Fatalf("delete while installing = %v, %v", busy, err)
+ }
+ if removed, _ := DefaultRemoved(ctx, db, "welcome"); removed {
+ t.Fatal("removal recorded while installing")
+ }
+ SetInstallState(ctx, db, "welcome", "installed", "")
+ if busy, err := DeleteInstall(ctx, db, "welcome", true); err != nil || busy {
+ t.Fatalf("delete = %v, %v", busy, err)
+ }
+ if removed, err := DefaultRemoved(ctx, db, "welcome"); err != nil || !removed {
+ t.Fatalf("after delete = %v, %v", removed, err)
+ }
+ if err := ClearDefaultRemoved(ctx, db, "welcome"); err != nil {
+ t.Fatal(err)
+ }
+ if removed, _ := DefaultRemoved(ctx, db, "welcome"); removed {
+ t.Fatal("still removed after clearing")
+ }
+}
diff --git a/internal/web/app.go b/internal/web/app.go
index 7dcd0d5..1368637 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -32,10 +32,12 @@ import (
//go:embed templates/*.html
var templateFS embed.FS
-// Installer installs and uninstalls catalogue apps for this Base. The
-// implementation arrives with the Store; until then main passes a no-op.
+// Installer installs and uninstalls catalogue apps for this Base;
+// *install.Installer is the real one.
type Installer interface {
- Install(ctx context.Context, app string) error
+ // Start claims app's install before it returns, so the next page shows
+ // it installing, and finishes the install in the background.
+ Start(ctx context.Context, app string) error
Uninstall(ctx context.Context, app string) error
}
diff --git a/internal/web/home.go b/internal/web/home.go
index 629c1d9..1fb562f 100644
--- a/internal/web/home.go
+++ b/internal/web/home.go
@@ -7,7 +7,6 @@ import (
"time"
"amadan.net/carlos/base/internal/catalog"
- "amadan.net/carlos/base/internal/install"
"amadan.net/carlos/base/internal/store"
)
@@ -109,8 +108,8 @@ func (a *app) home(w http.ResponseWriter, r *http.Request) {
if !ok || in.State != "installed" {
continue
}
- _, host := install.HostFor(a.cfg, in.App)
- page.Tiles = append(page.Tiles, tile{Name: e.Name, Href: "https://" + host + "/", Tint: e.Tint, Icon: template.HTML(e.Icon)})
+ // The host the app was installed at: config may name another now.
+ page.Tiles = append(page.Tiles, tile{Name: e.Name, Href: "https://" + in.Host + "/", Tint: e.Tint, Icon: template.HTML(e.Icon)})
if !e.Default {
installedOwn = true
}
diff --git a/internal/web/store.go b/internal/web/store.go
index 6c5dfc6..b2752e2 100644
--- a/internal/web/store.go
+++ b/internal/web/store.go
@@ -1,7 +1,6 @@
package web
import (
- "context"
"errors"
"html/template"
"net/http"
@@ -71,18 +70,17 @@ func (a *app) owner(w http.ResponseWriter, r *http.Request) (catalog.Entry, bool
}
// storeInstall starts an install and answers at once; the Store page shows
-// progress. The install outlives the request.
+// progress. Start has claimed the install before the redirect, so the page
+// the browser loads next shows it installing. The install outlives the
+// request.
func (a *app) storeInstall(w http.ResponseWriter, r *http.Request) {
e, ok := a.owner(w, r)
if !ok {
return
}
- ctx := context.WithoutCancel(r.Context())
- go func() {
- if err := a.inst.Install(ctx, e.ID); err != nil {
- a.logger.Error("install", "app", e.ID, "err", err)
- }
- }()
+ if err := a.inst.Start(r.Context(), e.ID); err != nil {
+ a.logger.Error("install", "app", e.ID, "err", err)
+ }
http.Redirect(w, r, "/store", http.StatusSeeOther)
}
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go
index ed56f8e..39bac7a 100644
--- a/internal/webtest/harness_test.go
+++ b/internal/webtest/harness_test.go
@@ -66,7 +66,7 @@ func (c *capturingMailer) Send(_ context.Context, to, subject, body string) erro
type noInstaller struct{}
-func (noInstaller) Install(context.Context, string) error { return nil }
+func (noInstaller) Start(context.Context, string) error { return nil }
func (noInstaller) Uninstall(context.Context, string) error { return nil }
// Resp is a fully read response.
@@ -92,6 +92,13 @@ func newApp(t *testing.T) *testApp { return newAppWith(t, noInstaller{}, time.UT
// newAppWith is newApp with the Installer and time zone of the caller's choice.
func newAppWith(t *testing.T, inst web.Installer, tz *time.Location) *testApp {
+ t.Helper()
+ return newAppBuilt(t, func(*sql.DB, config.Config) web.Installer { return inst }, tz)
+}
+
+// newAppBuilt is newAppWith for an Installer that needs the app's database
+// and configuration.
+func newAppBuilt(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location) *testApp {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(schema.Path(t), logger)
@@ -105,7 +112,7 @@ func newAppWith(t *testing.T, inst web.Installer, tz *time.Location) *testApp {
cfg := config.Config{Origin: testOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true,
Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: tz}
mailer := &capturingMailer{}
- h, err := web.App(d, cfg, mailer, inst, logger)
+ h, err := web.App(d, cfg, mailer, build(d.Writer(), cfg), logger)
if err != nil {
t.Fatalf("web.App: %v", err)
}
diff --git a/internal/webtest/home_test.go b/internal/webtest/home_test.go
index 888aaa8..fa3b0eb 100644
--- a/internal/webtest/home_test.go
+++ b/internal/webtest/home_test.go
@@ -103,3 +103,21 @@ func TestHomeTilesLinkToOrigins(t *testing.T) {
t.Errorf("ask field missing or not disabled")
}
}
+
+// Finding 1: a tile links to the host Base installed the app at, even after
+// the slug or apps domain changed.
+func TestHomeTileUsesRecordedHost(t *testing.T) {
+ a := newApp(t)
+ a.signedInOwner()
+ ctx := context.Background()
+ if _, err := store.ClaimInstall(ctx, a.DB, "scratchpad", "oldco-scratchpad.old.example"); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.SetInstallState(ctx, a.DB, "scratchpad", "installed", ""); err != nil {
+ t.Fatal(err)
+ }
+ body := a.get("/").Body
+ if !strings.Contains(body, `<a class="app" href="https://oldco-scratchpad.old.example/">`) || strings.Contains(body, "acme-scratchpad") {
+ t.Fatalf("tile does not use the recorded host:\n%s", body)
+ }
+}
diff --git a/internal/webtest/store_test.go b/internal/webtest/store_test.go
index 4a76d0f..71c0c71 100644
--- a/internal/webtest/store_test.go
+++ b/internal/webtest/store_test.go
@@ -2,13 +2,21 @@ package webtest
import (
"context"
+ "database/sql"
+ "io"
+ "log/slog"
"strings"
"sync"
"testing"
"time"
+ "amadan.net/rastrillo/rastrillo/crypto"
+
+ "amadan.net/carlos/base/internal/config"
"amadan.net/carlos/base/internal/install"
+ "amadan.net/carlos/base/internal/platform"
"amadan.net/carlos/base/internal/store"
+ "amadan.net/carlos/base/internal/web"
)
// recorder is a fake Installer that records its calls.
@@ -17,16 +25,14 @@ type recorder struct {
installs []string
uninstalls []string
uninstallErr error
- called chan struct{}
}
-func newRecorder() *recorder { return &recorder{called: make(chan struct{}, 8)} }
+func newRecorder() *recorder { return &recorder{} }
-func (r *recorder) Install(_ context.Context, app string) error {
+func (r *recorder) Start(_ context.Context, app string) error {
r.mu.Lock()
r.installs = append(r.installs, app)
r.mu.Unlock()
- r.called <- struct{}{}
return nil
}
@@ -49,53 +55,25 @@ func contains(body, want string) bool {
return strings.Contains(body, want) || strings.Contains(body, strings.ReplaceAll(want, "'", "&#39;"))
}
-// blocker is an Installer whose Install waits for release, and reports whether
-// its context was cancelled by then.
-type blocker struct {
- noInstaller
- started chan struct{}
- release chan struct{}
- done chan error // ctx.Err() as Install returns
- gotApp chan string
-}
-
-func (b *blocker) Install(ctx context.Context, app string) error {
- b.gotApp <- app
- close(b.started)
- <-b.release
- b.done <- ctx.Err()
- return nil
-}
-
+// Start is synchronous by contract (it only claims), so the handler calls
+// it before redirecting. That the install then outlives the request is
+// install.TestStartClaimsThenProvisionsInBackground's to prove.
func TestStoreInstallButtonPostsAndRedirects(t *testing.T) {
- b := &blocker{started: make(chan struct{}), release: make(chan struct{}), done: make(chan error, 1), gotApp: make(chan string, 1)}
- a := newAppWith(t, b, time.UTC)
+ rec := newRecorder()
+ a := newAppWith(t, rec, time.UTC)
a.signedInOwner()
page := a.get("/store")
if page.Code != 200 || !strings.Contains(page.Body, `action="/store/scratchpad/install"`) {
t.Fatalf("store page lacks an install form: %d\n%s", page.Code, page.Body)
}
- // Install blocks until release, so a 303 here proves the handler did not wait for it.
if r := a.post("/store/scratchpad/install", nil); r.Code != 303 || r.Location() != "/store" {
t.Fatalf("install: %d %q", r.Code, r.Location())
}
- select {
- case <-b.started:
- case <-time.After(5 * time.Second):
- t.Fatal("Installer.Install was not called")
- }
- if app := <-b.gotApp; app != "scratchpad" {
- t.Fatalf("installed %q", app)
- }
- time.Sleep(50 * time.Millisecond) // the request has long ended
- close(b.release)
- select {
- case err := <-b.done:
- if err != nil {
- t.Fatalf("install context was cancelled with the request: %v", err)
- }
- case <-time.After(5 * time.Second):
- t.Fatal("Install did not finish")
+ rec.mu.Lock()
+ got := append([]string(nil), rec.installs...)
+ rec.mu.Unlock()
+ if len(got) != 1 || got[0] != "scratchpad" {
+ t.Fatalf("Start calls = %q, want one for scratchpad", got)
}
if r := a.post("/store/nope/install", nil); r.Code != 404 {
t.Fatalf("unknown app: %d", r.Code)
@@ -198,3 +176,54 @@ func TestMemberSeesStoreButCannotInstall(t *testing.T) {
t.Fatal("member reached the installer")
}
}
+
+// slowWorker is the real Installer, with any blocking Install held back
+// until release closes, as a goroutine slow to get going would be. The
+// handler must not depend on such a goroutine for what the next page shows:
+// Start claims before it returns.
+type slowWorker struct {
+ *install.Installer
+ release chan struct{}
+}
+
+func (s slowWorker) Install(ctx context.Context, app string) error {
+ <-s.release
+ return s.Installer.Install(ctx, app)
+}
+
+// holdSetEnv holds Platform's first write until release closes.
+type holdSetEnv struct {
+ platform.Client
+ release chan struct{}
+}
+
+func (h holdSetEnv) SetEnv(ctx context.Context, app, env string, vars map[string]string) error {
+ <-h.release
+ return h.Client.SetEnv(ctx, app, env, vars)
+}
+
+// Finding 5 (R33): the page the install POST redirects to already shows the
+// app installing, with the refresh that brings the result.
+func TestStoreRedirectShowsInstalling(t *testing.T) {
+ release := make(chan struct{})
+ defer close(release)
+ a := newAppBuilt(t, func(db *sql.DB, cfg config.Config) web.Installer {
+ kp, err := crypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg.AssertionKey = kp
+ pc := holdSetEnv{Client: platform.NewFake(), release: release}
+ in := install.New(db, cfg, pc, func(context.Context, string) error { return nil }, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ return slowWorker{Installer: in, release: release}
+ }, time.UTC)
+ a.signedInOwner()
+ r := a.post("/store/scratchpad/install", nil)
+ if r.Code != 303 || r.Location() != "/store" {
+ t.Fatalf("install: %d %q", r.Code, r.Location())
+ }
+ body := a.get(r.Location()).Body
+ if !strings.Contains(body, `<meta http-equiv="refresh" content="2">`) || !strings.Contains(body, ">Installing<") {
+ t.Fatalf("the page after Install does not show it installing:\n%s", body)
+ }
+}