carlos / platform Public

console: refuse an app's first rootfs release while it has instances made for a binary app, ordered with instance create (rootfs spec §5.0)

The rootfs ship's first-ship slot (fixFirstRootfsKind) takes the app lock
every instance record writer holds through its first-kind recheck and its
write, rereads the kind, counts the app's binary instances with the
strict judged listing (fail closed: C79 at 503), and only with none puts
the kind marker. A create and a first rootfs ship are ordered at that
lock: the ship counts the create's record and refuses with RFS-4-C11, or
the create's recheck reads the ship's marker. The lock never covers the
image upload. Plan 4 rows 5.1 to 5.4.

TestAPIShipRootfsCarriesAssets seeded binary records under an app whose
first ship is rootfs, which C11 now refuses: its records are minted
rootfs-v1, as the console would mint them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 7d99f6bbcf765256103c6d14d6a8ea95b36ea32f parent ad993ce
5 files changed, +458 −5
  • approved_rootfs_copy_test.go +3 −0
  • internal/console/apiship_assets_test.go +5 −0
  • internal/console/apiship_rootfs.go +67 −5
  • internal/console/rootfs.go +33 −0
  • internal/console/rootfs_test.go +350 −0
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index 964d1e149..e0d38b679 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -198,6 +198,9 @@ var rootfsCopyBuilt = []string{
// Plan 4 Task 3: instance create refuses a seeded or replica rootfs
// instance (internal/console/rootfs.go)
"RFS-4-C09", "RFS-4-C10",
+ // Plan 4 Task 5: the first rootfs release of an app with binary
+ // instances (internal/console/rootfs.go)
+ "RFS-4-C11",
}
func mustParseRootfsRecord(t *testing.T) []copyRow {
diff --git a/internal/console/apiship_assets_test.go b/internal/console/apiship_assets_test.go
index 38d0eb8eb..1a401e49d 100644
--- a/internal/console/apiship_assets_test.go
+++ b/internal/console/apiship_assets_test.go
@@ -193,10 +193,15 @@ func TestAPIShipRootfsCarriesAssets(t *testing.T) {
// is bab, and every rootfs door test shares it.
const acct = "bab"
ctx := context.Background()
+ // The records are a rootfs app's instances, minted rootfs-v1: binary
+ // instances made before the first release would refuse a first rootfs
+ // ship (RFS-4-C11, Plan 4 Task 5).
+ alwaysOn := false
for _, host := range []string{"shop.example.com", "shop-2.example.com"} {
if err := provision.CreateRecord(ctx, fx.fx.rel, provision.Record{
Schema: 1, Host: host, Slug: strings.SplitN(host, ".", 2)[0], App: "shop", Account: acct,
Region: "ie", Channel: "stable", CreatedAt: time.Now().UTC(),
+ Runtime: provision.RuntimeRootfsV1, Hibernate: &alwaysOn,
}); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/apiship_rootfs.go b/internal/console/apiship_rootfs.go
index a54b3e686..3d52c1008 100644
--- a/internal/console/apiship_rootfs.go
+++ b/internal/console/apiship_rootfs.go
@@ -288,11 +288,14 @@ func (s *Server) shipRootfsParts(w http.ResponseWriter, r *http.Request, mr *mul
writeJSON(w, http.StatusOK, rootfsShipAnswer(ver, existing.Artifacts, existing.Swap, existing.Assets, probe))
return
}
- // The first-ship slot. Plan 4 Task 5 puts its first-rootfs-ship
- // refusal and the first-kind boundary here: after the re-ship short
- // circuit above, so a re-ship stays a 200, and before ShipSpooled,
- // the only place a rootfs publication can still be refused. Keep the
- // two adjacent.
+ // The first-ship slot (Plan 4 Task 5): after the re-ship short circuit
+ // above, so a re-ship stays a 200, and before ShipSpooled, the only
+ // place a rootfs publication can still be refused. Keep the two
+ // adjacent.
+ if ref := s.fixFirstRootfsKind(ctx, acct, &m); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
if err := release.ShipSpooled(ctx, s.cfg.Releases, acct.Sqid, m, map[string]string{release.RootfsArtifactKey: spool}); err != nil {
log.Printf("console: api ship %s %s (rootfs): %v", app, ver, err)
if shipKindRefusedAtPublication(w, err) {
@@ -315,6 +318,65 @@ func (s *Server) shipRootfsParts(w http.ResponseWriter, r *http.Request, mr *mul
writeJSON(w, http.StatusCreated, rootfsShipAnswer(ver, m.Artifacts, m.Swap, m.Assets, probe))
}
+// fixFirstRootfsKind is the ship side of the first-kind boundary (Astra R2
+// finding 2; Plan 4 Task 5, rows 5.1 to 5.3). An app whose kind a release
+// or a first ship's marker already fixed is left to ShipSpooled, which
+// decides by Plan 1's rule. For an app with no kind yet, it takes the app
+// lock (s.lockApp), the lock every console writer of an instance record
+// holds through its first-kind recheck and its write (createRecordMarked,
+// createRecordWithLifetimeLocked: rootfs.go), and under it reads the kind
+// again, counts the app's binary instances (firstRootfsShipRefusal) and,
+// with none, puts the kind marker (release.EstablishFirstKind). So a
+// create and a first rootfs ship are ordered at the lock: a create first
+// leaves a binary record this count sees, and the ship refuses with C11
+// writing nothing; a ship first leaves a marker the create's recheck reads,
+// and the create refuses with its try-again sentence, its retry minting
+// rootfs. The lock is released before the answer and before ShipSpooled,
+// so it never covers the image upload.
+//
+// It takes only the app lock and holds nothing else while it waits for it
+// (the request's ship slot is already given back, and the scratch
+// reservation is not a lock anyone waits on), so it keeps the lock order:
+// the account lock, then the app lock, then withHostname.
+//
+// Every failure to check is RFS-1-C79 at 503 (row 5.1), and a conflict at
+// the marker is Plan 1's 409 through its Error().
+func (s *Server) fixFirstRootfsKind(ctx context.Context, acct *Account, m *release.Manifest) *doorRefusal {
+ info, err := release.EstablishedKind(ctx, s.cfg.Releases, acct.Sqid, m.App)
+ if err == nil && info.Kind != "" {
+ return nil
+ }
+ if err == nil {
+ var ref *doorRefusal
+ ref, err = s.fixFirstRootfsKindLocked(ctx, acct, m)
+ if err == nil {
+ return ref
+ }
+ }
+ log.Printf("console: api ship %s/%s %s: first kind: %v", acct.Sqid, m.App, m.Version, err)
+ if msg, ok := shipKindConflict(err); ok {
+ return &doorRefusal{http.StatusConflict, msg}
+ }
+ return &doorRefusal{http.StatusServiceUnavailable, shipKindUnchecked}
+}
+
+// fixFirstRootfsKindLocked is fixFirstRootfsKind's part under the app
+// lock: the recheck, the count and the marker, nothing else.
+func (s *Server) fixFirstRootfsKindLocked(ctx context.Context, acct *Account, m *release.Manifest) (*doorRefusal, error) {
+ defer s.lockApp(acct.Sqid, m.App)()
+ // Another first ship may have fixed the kind while this one waited.
+ switch info, err := release.EstablishedKind(ctx, s.cfg.Releases, acct.Sqid, m.App); {
+ case err != nil:
+ return nil, err
+ case info.Kind != "":
+ return nil, nil
+ }
+ if ref := s.firstRootfsShipRefusal(ctx, acct, m.App); ref != nil {
+ return ref, nil
+ }
+ return nil, release.EstablishFirstKind(ctx, s.cfg.Releases, acct.Sqid, m)
+}
+
// spoolRootfsPart copies the image part to spool, hashing as it writes and
// never reading more than size and one byte, and returns its sha256. A
// part of another length is refused. It has answered w when it reports
diff --git a/internal/console/rootfs.go b/internal/console/rootfs.go
index da630d8bd..dff477943 100644
--- a/internal/console/rootfs.go
+++ b/internal/console/rootfs.go
@@ -6,6 +6,7 @@ import (
"fmt"
"log"
"net/http"
+ "slices"
"time"
"github.com/carlosframework/platform/internal/provision"
@@ -40,6 +41,9 @@ const (
rootfsSeededMsg = "%s is a rootfs app, and a new rootfs instance cannot start from a copy of another database yet. create it empty, then load the data from your app"
// rootfsReplicaMsg is RFS-4-C10, filled with the app.
rootfsReplicaMsg = "%s is a rootfs app, and a rootfs app has no replicas yet"
+ // rootfsFirstShipMsg is RFS-4-C11, filled with the app, how many
+ // binary instances it has and the first of their hosts in sort order.
+ rootfsFirstShipMsg = "%s already has %d instances made before its first release, such as %s. an app's first release decides its kind, and those instances were made for a binary app. delete them, ship again, then create them again"
)
// rootfsHead is what the release an instance would be created from says
@@ -303,3 +307,32 @@ func (s *Server) firstKindRecheck(ctx context.Context, rec provision.Record) err
}
return nil
}
+
+// firstRootfsShipRefusal is the first rootfs release's refusal (RFS-4-C11;
+// Plan 4 Task 5): the app's instances made before any release are binary
+// for ever (§5.0), so a first release that would make the app rootfs is
+// refused while any is left. It counts the app's records that run a
+// process the platform starts (DerivesPaths) and have no runtime, read
+// with the strict judged listing the place door uses (placeRecords, row
+// 5.2): a record that does not read could be one of them, so it refuses
+// with RFS-1-C79 at 503, fail closed. A tombstone is no instance. The
+// caller holds the app lock (fixFirstRootfsKind), so no record write lands
+// between this count and the kind marker.
+func (s *Server) firstRootfsShipRefusal(ctx context.Context, acct *Account, app string) *doorRefusal {
+ recs, err := placeRecords(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct.Sqid, app)
+ if err != nil {
+ log.Printf("console: api ship %s/%s: count the instances made before the first release: %v", acct.Sqid, app, err)
+ return &doorRefusal{http.StatusServiceUnavailable, shipKindUnchecked}
+ }
+ var hosts []string
+ for _, rec := range recs {
+ if !rec.Retired && rec.DerivesPaths() && rec.Runtime == "" {
+ hosts = append(hosts, rec.Host)
+ }
+ }
+ if len(hosts) == 0 {
+ return nil
+ }
+ slices.Sort(hosts)
+ return &doorRefusal{http.StatusConflict, fmt.Sprintf(rootfsFirstShipMsg, app, len(hosts), hosts[0])}
+}
diff --git a/internal/console/rootfs_test.go b/internal/console/rootfs_test.go
index c0178adb1..a3f9ac740 100644
--- a/internal/console/rootfs_test.go
+++ b/internal/console/rootfs_test.go
@@ -5,7 +5,11 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"net/http"
+ "os"
+ "path/filepath"
+ "slices"
"strings"
"sync"
"sync/atomic"
@@ -821,3 +825,349 @@ func TestBinaryCreateReadsTheHeadOnce(t *testing.T) {
})
}
}
+
+// Plan 4 Task 5: the first rootfs release of an app with binary instances.
+
+// rootfsShipWorld is rootfsCreateWorld that also takes rootfs ships through
+// the door: a scratch pool with room to spare and the ship budget lifted.
+func rootfsShipWorld(t *testing.T, code string) (*consoleFixture, string, *registry.Registry) {
+ t.Helper()
+ fx, token, reg := rootfsCreateWorld(t, code, rootfsShopManifest())
+ liftShipBudget(fx)
+ scratch := filepath.Join(t.TempDir(), "scratch", "seeds")
+ if err := clearSeedScratch(scratch); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.seedScratch = newSeedScratch(scratch, func(string) (int64, error) { return 64 << 30, nil })
+ return fx, token, reg
+}
+
+// shopRootfsShipParts is the request `carlos ship --rootfs` sends for
+// release ver of shop.
+func shopRootfsShipParts(t *testing.T, ver string, hibernate bool) []shipPart {
+ t.Helper()
+ img := []byte("hsqs" + ver + strings.Repeat("x", 4<<10))
+ return []shipPart{rootfsMeta(t, ver, len(img), hibernate), {name: release.RootfsArtifactKey, body: img}}
+}
+
+func shopShipURL(fx *consoleFixture) string {
+ return fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/shop/releases"
+}
+
+// shipRootfsThroughTheDoor ships rootfs release ver of shop through the
+// ship door (Plan 1's request shape), always on.
+func shipRootfsThroughTheDoor(t *testing.T, fx *consoleFixture, token, ver string) (int, map[string]any) {
+ t.Helper()
+ return postShip(t, shopShipURL(fx), token, shopRootfsShipParts(t, ver, false))
+}
+
+// createShopInstance creates host through the instance door, before or
+// after any release; it must answer 201.
+func createShopInstance(t *testing.T, fx *consoleFixture, token, body string) {
+ t.Helper()
+ if code, out := createShop(t, fx, token, body); code != http.StatusCreated {
+ t.Fatalf("create %s = %d %s", body, code, out)
+ }
+}
+
+// deleteShopInstance deletes host through the instance delete door.
+func deleteShopInstance(t *testing.T, fx *consoleFixture, token, host string) {
+ t.Helper()
+ if code, _, raw := rawReq(t, http.MethodDelete, instancesURL(fx, fx.sqid, "shop")+"/"+host, token, ""); code/100 != 2 {
+ t.Fatalf("delete %s = %d %s", host, code, raw)
+ }
+}
+
+// shopFirstShipLeftNothing: no marker, no artifact and no manifest of ver.
+func shopFirstShipLeftNothing(t *testing.T, fx *consoleFixture, ver string) {
+ t.Helper()
+ ctx := context.Background()
+ if _, err := release.GetManifest(ctx, fx.rel, fx.sqid, "shop", ver); err == nil {
+ t.Fatal("the refused release was stored")
+ }
+ if _, _, err := fx.rel.Get(ctx, release.AppKindMarkerKey(fx.sqid, "shop")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the refused first ship fixed the app's kind: %v", err)
+ }
+ if keys, err := fx.rel.List(ctx, "apps/"+fx.sqid+"/shop/releases/"); err != nil || len(keys) != 0 {
+ t.Fatalf("the refused first ship wrote %v (%v)", keys, err)
+ }
+}
+
+// An instance created before any release is minted binary, for ever
+// (§5.0), so the app's first release may not make it a rootfs app: C11,
+// nothing written, the kind marker included, so the remedy C11 names
+// (delete them, ship again) works.
+func TestShipFirstRootfsReleaseOverBinaryInstances(t *testing.T) {
+ fx, token, _ := rootfsShipWorld(t, "code-rfs-firstship")
+ createShopInstance(t, fx, token, `{"host":"shop.example.com"}`)
+ if rec, _ := storedShop(t, fx, rootfsShopHost); rec.Runtime != "" {
+ t.Fatalf("a create before any release minted %+v; want binary", rec)
+ }
+ status, body := shipRootfsThroughTheDoor(t, fx, token, "r1")
+ if status != http.StatusConflict || body["error"] != fmt.Sprintf(rootfsFirstShipMsg, "shop", 1, "shop.example.com") {
+ t.Fatalf("ship = %d %v", status, body)
+ }
+ shopFirstShipLeftNothing(t, fx, "r1")
+ deleteShopInstance(t, fx, token, rootfsShopHost)
+ if status, body := shipRootfsThroughTheDoor(t, fx, token, "r1"); status != http.StatusCreated {
+ t.Fatalf("ship after deleting the instance = %d %v", status, body)
+ }
+}
+
+// C11 counts the binary instances only, and names the first in sort order.
+// A static record is not a process the platform starts, so it does not
+// count.
+func TestShipFirstRootfsReleaseCountsBinaryInstancesOnly(t *testing.T) {
+ fx, token, _ := rootfsShipWorld(t, "code-rfs-firstship-count")
+ createShopInstance(t, fx, token, `{"host":"zeta.example.com"}`)
+ createShopInstance(t, fx, token, `{"host":"beta.example.com"}`)
+ createShopInstance(t, fx, token, `{"host":"alpha.example.com","kind":"static"}`)
+ status, body := shipRootfsThroughTheDoor(t, fx, token, "r1")
+ if status != http.StatusConflict || body["error"] != fmt.Sprintf(rootfsFirstShipMsg, "shop", 2, "beta.example.com") {
+ t.Fatalf("ship = %d %v", status, body)
+ }
+ shopFirstShipLeftNothing(t, fx, "r1")
+}
+
+func TestShipFirstRootfsReleaseWithStaticRecordsOnly(t *testing.T) {
+ fx, token, _ := rootfsShipWorld(t, "code-rfs-firstship-static")
+ createShopInstance(t, fx, token, `{"host":"shop.example.com","kind":"static"}`)
+ if status, body := shipRootfsThroughTheDoor(t, fx, token, "r1"); status != http.StatusCreated {
+ t.Fatalf("ship = %d %v", status, body)
+ }
+}
+
+// Row 5.2: the count fails closed. A record that does not read could be a
+// binary instance, so the first ship is refused with C79 at 503 and
+// writes nothing.
+func TestShipFirstRootfsReleaseRefusesOnARecordThatDoesNotRead(t *testing.T) {
+ fx, token, _ := rootfsShipWorld(t, "code-rfs-firstship-unreadable")
+ if _, err := fx.rel.Put(context.Background(), provision.RecordKey(fx.sqid, "shop", rootfsShopHost), []byte("{not json"), ""); err != nil {
+ t.Fatal(err)
+ }
+ status, body := shipRootfsThroughTheDoor(t, fx, token, "r1")
+ if status != http.StatusServiceUnavailable || body["error"] != shipKindUnchecked {
+ t.Fatalf("ship = %d %v; want 503 C79", status, body)
+ }
+ shopFirstShipLeftNothing(t, fx, "r1")
+}
+
+// Once the app's kind is fixed, the slot leaves the ship to Plan 1's rule:
+// r1 shipped and an instance made from it, r2 ships.
+func TestShipLaterRootfsReleaseIsPlanOnesRule(t *testing.T) {
+ fx, token, reg := rootfsShipWorld(t, "code-rfs-latership")
+ placeShop(t, fx, token, "home")
+ fleetBoxNow(t, fx, reg, "home", "pi-1", true)
+ if status, body := shipRootfsThroughTheDoor(t, fx, token, "r1"); status != http.StatusCreated {
+ t.Fatalf("ship r1 = %d %v", status, body)
+ }
+ createShopInstance(t, fx, token, `{"host":"shop.example.com"}`)
+ if rec, _ := storedShop(t, fx, rootfsShopHost); rec.Runtime != provision.RuntimeRootfsV1 {
+ t.Fatalf("instance from r1 = %+v", rec)
+ }
+ if status, body := shipRootfsThroughTheDoor(t, fx, token, "r2"); status != http.StatusCreated {
+ t.Fatalf("ship r2 = %d %v", status, body)
+ }
+}
+
+// heldWriteStore holds the first write (Put or PutFrom) of one key until
+// let is closed, and logs every write's key in arrival order.
+type heldWriteStore struct {
+ release.Store
+ key string
+ reached chan struct{} // closed when key's write arrives
+ let chan struct{}
+ once sync.Once
+ mu sync.Mutex
+ log []string
+}
+
+func newHeldWriteStore(t *testing.T, inner release.Store, key string) *heldWriteStore {
+ s := &heldWriteStore{Store: inner, key: key, reached: make(chan struct{}), let: make(chan struct{})}
+ t.Cleanup(s.release)
+ return s
+}
+
+func (s *heldWriteStore) release() {
+ select {
+ case <-s.let:
+ default:
+ close(s.let)
+ }
+}
+
+func (s *heldWriteStore) arrive(key string) {
+ s.mu.Lock()
+ s.log = append(s.log, key)
+ s.mu.Unlock()
+ if key == s.key {
+ s.once.Do(func() { close(s.reached) })
+ <-s.let
+ }
+}
+
+// wrote reports whether a write of key has arrived.
+func (s *heldWriteStore) wrote(key string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Contains(s.log, key)
+}
+
+func (s *heldWriteStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ s.arrive(key)
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (s *heldWriteStore) PutFrom(ctx context.Context, key string, body io.ReadSeeker, size int64, ifMatch string) (string, error) {
+ s.arrive(key)
+ return release.PutObjectFrom(ctx, s.Store, key, body, size, ifMatch)
+}
+
+// Astra R2 finding 2, the ship past its marker: a create while the first
+// rootfs ship is still uploading its image (its kind marker written, its
+// manifest not) reads the marker and mints rootfs, with the ship's
+// hibernation, without waiting for the upload: the ship holds no lock
+// through it. Then the ship publishes.
+func TestCreateDuringAnUnpublishedFirstRootfsShipMintsRootfs(t *testing.T) {
+ for i := range 20 {
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ fx, token, reg := rootfsShipWorld(t, "code-rfs-create-during-ship")
+ placeShop(t, fx, token, "home")
+ fleetBoxNow(t, fx, reg, "home", "pi-1", true)
+ held := newHeldWriteStore(t, fx.srv.cfg.Releases, release.ArtifactKey(fx.sqid, "shop", "r1", release.RootfsArtifactFile))
+ fx.srv.cfg.Releases = held
+ shipped := make(chan uploadResult, 1)
+ parts := shopRootfsShipParts(t, "r1", true)
+ go func() { shipped <- postShipErr(shopShipURL(fx), token, parts) }()
+ select {
+ case <-held.reached:
+ case a := <-shipped:
+ t.Fatalf("the ship answered %d %v %v before uploading its image", a.status, a.out, a.err)
+ case <-time.After(10 * time.Second):
+ t.Fatal("the ship never reached its image upload")
+ }
+ if !held.wrote(release.AppKindMarkerKey(fx.sqid, "shop")) {
+ t.Fatal("the ship is uploading its image with no kind marker written")
+ }
+ if _, err := release.GetManifest(context.Background(), fx.rel, fx.sqid, "shop", "r1"); err == nil {
+ t.Fatal("the manifest is written before the image")
+ }
+ createShopInstance(t, fx, token, `{"host":"shop.example.com"}`)
+ if rec, _ := storedShop(t, fx, rootfsShopHost); rec.Runtime != provision.RuntimeRootfsV1 || rec.Hibernate == nil || !*rec.Hibernate {
+ t.Fatalf("a create during the first rootfs ship stored %+v; want rootfs-v1 with the ship's hibernate true", rec)
+ }
+ held.release()
+ if a := <-shipped; a.err != nil || a.status != http.StatusCreated {
+ t.Fatalf("ship = %d %v %v", a.status, a.out, a.err)
+ }
+ })
+ }
+}
+
+// Astra R2 finding 2, the create inside the boundary: while a create's
+// record write is in flight (its writer holds the app lock, past its
+// recheck), a first rootfs ship reaches the slot and waits, writing no
+// kind marker. Then the create answers 201 with a binary record (no kind
+// was fixed when it was checked), and the ship counts it: 409 C11, with
+// no marker, no artifact and no manifest. Both record writers.
+func TestFirstRootfsShipWaitsForAnInFlightCreate(t *testing.T) {
+ for _, lifetimes := range []bool{false, true} {
+ t.Run(fmt.Sprintf("lifetimes=%v", lifetimes), func(t *testing.T) {
+ for i := range 20 {
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ firstRootfsShipWaitsForAnInFlightCreate(t, lifetimes)
+ })
+ }
+ })
+ }
+}
+
+func firstRootfsShipWaitsForAnInFlightCreate(t *testing.T, lifetimes bool) {
+ var clock *lifetimesClock
+ if lifetimes {
+ clock = useLifetimesClock(t)
+ }
+ fx, token, _ := rootfsShipWorld(t, "code-rfs-ship-waits")
+ if lifetimes {
+ turnLifetimesOn(t, fx.srv, clock)
+ }
+ appKey := fx.sqid + "/shop"
+ recordKey := provision.RecordKey(fx.sqid, "shop", rootfsShopHost)
+ held := newHeldWriteStore(t, fx.srv.cfg.Releases, recordKey)
+ fx.srv.cfg.Releases = held
+
+ // The app lock as the hook sees it: how many hold it, and whether
+ // anyone waited for it after the record write arrived.
+ var holders atomic.Int32
+ shipWaiting := make(chan struct{})
+ var waitOnce sync.Once
+ h := func(kind, key, event string) {
+ if kind != "app" || key != appKey {
+ return
+ }
+ switch event {
+ case lockHeld:
+ holders.Add(1)
+ case lockReleased:
+ holders.Add(-1)
+ case lockWaiting:
+ select {
+ case <-held.reached:
+ waitOnce.Do(func() { close(shipWaiting) })
+ default:
+ }
+ }
+ }
+ lifetimeLockHook.Store(&h)
+ t.Cleanup(func() { lifetimeLockHook.Store(nil) })
+
+ created := make(chan string, 1)
+ go func() {
+ code, out := createShop(t, fx, token, `{"host":"shop.example.com"}`)
+ created <- fmt.Sprintf("%d %s", code, out)
+ }()
+ select {
+ case <-held.reached:
+ case got := <-created:
+ t.Fatalf("the create answered %s before writing its record", got)
+ case <-time.After(10 * time.Second):
+ t.Fatal("the create never wrote its record")
+ }
+ if n := holders.Load(); n != 1 {
+ t.Fatalf("the create writes its record with %d holders of the app lock; want its own", n)
+ }
+
+ shipped := make(chan uploadResult, 1)
+ parts := shopRootfsShipParts(t, "r1", false)
+ go func() { shipped <- postShipErr(shopShipURL(fx), token, parts) }()
+ select {
+ case <-shipWaiting:
+ case a := <-shipped:
+ t.Fatalf("the ship answered %d %v %v while the create was writing; it never waited for the app lock", a.status, a.out, a.err)
+ case <-time.After(10 * time.Second):
+ t.Fatal("the ship never reached the first-ship slot")
+ }
+ // Give a ship that did not really wait the time to show it.
+ time.Sleep(50 * time.Millisecond)
+ if held.wrote(release.AppKindMarkerKey(fx.sqid, "shop")) {
+ t.Fatal("the first ship wrote its kind marker while a create held the app lock")
+ }
+ select {
+ case a := <-shipped:
+ t.Fatalf("the ship answered %d %v %v while the create held the app lock", a.status, a.out, a.err)
+ default:
+ }
+
+ held.release()
+ if got := <-created; !strings.HasPrefix(got, fmt.Sprint(http.StatusCreated)+" ") {
+ t.Fatalf("create = %s", got)
+ }
+ if rec, _ := storedShop(t, fx, rootfsShopHost); rec.Runtime != "" || rec.Hibernate != nil {
+ t.Fatalf("the create stored %+v; want binary (no kind was fixed)", rec)
+ }
+ a := <-shipped
+ if a.err != nil || a.status != http.StatusConflict || a.out["error"] != fmt.Sprintf(rootfsFirstShipMsg, "shop", 1, rootfsShopHost) {
+ t.Fatalf("ship = %d %v %v; want 409 C11", a.status, a.out, a.err)
+ }
+ shopFirstShipLeftNothing(t, fx, "r1")
+}