carlos / platform Public

appconfig: conditional apply with receipts (#522 plan 1 task 2)

ApplyIf and ApplyEnvironmentOwnedIf make a config write conditional on
the layer's version and answer with a Receipt: versions either side,
exact set/unset/unset-absent names and digests of what was set. The
version compare, the mutation and the write all come from one read;
a stale version or a race lost after that read is ErrVersionMismatch
with nothing written. The owned path checks ownership before the
version and refuses "none" (ErrConditionalCreateOwned).

applyAt and the owned write share applyToManifest; putManifestAt
returns the bytes it wrote so VersionAfter names them. Apply,
ApplyEnvironment, ApplyEnvironmentOwned and ApplyInstance keep their
signatures, ErrCASConflict and etags.

release gains AtomicConditionalStore, implemented by S3Store and
answered through a prefix store; a cmd/console test pins that the
store openStore builds for a bucket reports it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a94b067bd52685d40957df24a42c2aa7b655cf1f parent d730277
10 files changed, +721 −84
  • cmd/console/atomicput_test.go +30 −0
  • internal/appconfig/environments.go +10 −9
  • internal/appconfig/generation.go +29 −2
  • internal/appconfig/instances.go +2 −2
  • internal/appconfig/observe.go +69 −0
  • internal/appconfig/observe_apply_test.go +377 −0
  • internal/appconfig/owned.go +62 −27
  • internal/appconfig/store.go +79 −44
  • internal/release/store.go +32 −0
  • internal/release/store_test.go +31 −0

CI failed — run details

diff --git a/cmd/console/atomicput_test.go b/cmd/console/atomicput_test.go
new file mode 100644
index 000000000..a47727ffe
--- /dev/null
+++ b/cmd/console/atomicput_test.go
@@ -0,0 +1,30 @@
+package main
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The store openStore hands the console for an S3 deployment reports an
+// atomic conditional write, so the config door accepts if_version there
+// (config receipts spec §4.5); the local directory store does not. This is
+// the production shape: TimeS3Store swaps the client in place rather than
+// wrapping the store, and this test fails if either step starts hiding the
+// capability.
+func TestOpenStoreAtomicConditionalPut(t *testing.T) {
+ t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "b")
+ t.Setenv("CARLOS_DEPLOYMENT_DIR", "")
+ t.Setenv("AWS_ACCESS_KEY_ID", "x")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "y")
+ t.Setenv("AWS_REGION", "us-east-1")
+ if s := openStore(nil); !release.HasAtomicConditionalPut(s) {
+ t.Fatalf("openStore over a bucket = %T, want a store with an atomic conditional write", s)
+ }
+
+ t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "")
+ t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir())
+ if s := openStore(nil); release.HasAtomicConditionalPut(s) {
+ t.Fatalf("openStore over a directory = %T, want no atomic conditional write", s)
+ }
+}
diff --git a/internal/appconfig/environments.go b/internal/appconfig/environments.go
index 2d125b346..5bc1b7668 100644
--- a/internal/appconfig/environments.go
+++ b/internal/appconfig/environments.go
@@ -86,7 +86,7 @@ func LoadEnvironment(ctx context.Context, s release.Store, acct, app, envName st
// bundle (applyAt) — a named environment gets the same racing-write
// ErrCASConflict discipline the default bundle already has.
func claimRawSaveEnvironment(ctx context.Context, s release.Store, acct, app, envName string, sets map[string]Var, unsets []string) error {
- _, err := applyEnvironment(ctx, s, acct, app, envName, sets, unsets)
+ _, err := applyEnvironment(ctx, s, acct, app, envName, "", sets, unsets)
return err
}
@@ -97,7 +97,8 @@ func claimRawSaveEnvironment(ctx context.Context, s release.Store, acct, app, en
// refused here rather than minted (applyAt's doc comment has the why; a
// phantom bundle satisfies `carlos route -environment`'s existence rail).
func claimRawUnsetEnvironment(ctx context.Context, s release.Store, acct, app, envName string, keys []string) (int, error) {
- return applyEnvironment(ctx, s, acct, app, envName, nil, keys)
+ r, err := applyEnvironment(ctx, s, acct, app, envName, "", nil, keys)
+ return len(r.Unset), err
}
// applyEnvironment is apply's environment-scoped twin — same validation,
@@ -106,22 +107,22 @@ func claimRawUnsetEnvironment(ctx context.Context, s release.Store, acct, app, e
// route's own (app, environment) pair itself, so one signal per app is
// enough, and a per-bundle signal would mean the watcher had to enumerate
// bundles to know what to watch.
-func applyEnvironment(ctx context.Context, s release.Store, acct, app, envName string, sets map[string]Var, unsets []string) (int, error) {
+func applyEnvironment(ctx context.Context, s release.Store, acct, app, envName, expect string, sets map[string]Var, unsets []string) (Receipt, error) {
if !release.ValidAccount(acct) {
- return 0, fmt.Errorf("config: invalid account %q", acct)
+ return Receipt{}, fmt.Errorf("config: invalid account %q", acct)
}
if !release.ValidApp(app) {
- return 0, fmt.Errorf("config: invalid app %q", app)
+ return Receipt{}, fmt.Errorf("config: invalid app %q", app)
}
if !ValidEnvironmentName(envName) {
- return 0, fmt.Errorf("config: invalid environment name %q", envName)
+ return Receipt{}, fmt.Errorf("config: invalid environment name %q", envName)
}
- removed, _, err := applyAt(ctx, s, EnvironmentKey(acct, app, envName), app, envName, sets, unsets)
+ r, _, err := applyAt(ctx, s, EnvironmentKey(acct, app, envName), app, envName, expect, sets, unsets)
if err != nil {
- return 0, err
+ return Receipt{}, err
}
touchLogged(ctx, s, acct, app)
- return removed, nil
+ return r, nil
}
// ListEnvironments returns app's named environment bundle names (bare
diff --git a/internal/appconfig/generation.go b/internal/appconfig/generation.go
index 4f8769124..d8373acf2 100644
--- a/internal/appconfig/generation.go
+++ b/internal/appconfig/generation.go
@@ -117,14 +117,34 @@ func touchLogged(ctx context.Context, s release.Store, acct, app string) {
// SetEnv/SetSecret/Unset remain the narrow verbs the CLI's direct mode uses;
// this is the same underlying path, just not pre-narrowed to one kind.
func claimRawApply(ctx context.Context, s release.Store, acct, app string, sets map[string]Var, unsets []string) (int, error) {
- return apply(ctx, s, acct, app, DefaultBundle, sets, unsets)
+ r, err := apply(ctx, s, acct, app, DefaultBundle, "", sets, unsets)
+ return len(r.Unset), err
}
// ApplyEnvironment is Apply for a named environment bundle — same one-write
// mixed set/unset contract, same refusal to create a bundle on an
// unset-only call (see applyAt).
func claimRawApplyEnvironment(ctx context.Context, s release.Store, acct, app, envName string, sets map[string]Var, unsets []string) (int, error) {
- return applyEnvironment(ctx, s, acct, app, envName, sets, unsets)
+ r, err := applyEnvironment(ctx, s, acct, app, envName, "", sets, unsets)
+ return len(r.Unset), err
+}
+
+// ApplyIf is Apply and ApplyEnvironment in one, conditional on the target
+// layer's version and answering with a Receipt (config receipts spec
+// §4.5-4.6): envName "" is the default bundle, anything else a named
+// environment. ifVersion "" is the same unconditional write Apply makes,
+// release.ErrCASConflict on a lost race included. Otherwise the layer must
+// be at ifVersion ("none": no object yet) on the one read the write is made
+// against, and a write that loses a race after that read is refused the
+// same way; both are ErrVersionMismatch with nothing written.
+//
+// Owned environments go through ApplyEnvironmentOwnedIf instead, which
+// checks the scope; this function, like ApplyEnvironment, does not.
+func claimRawApplyIf(ctx context.Context, s release.Store, acct, app, envName, ifVersion string, sets map[string]Var, unsets []string) (Receipt, error) {
+ if envName == "" {
+ return apply(ctx, s, acct, app, DefaultBundle, ifVersion, sets, unsets)
+ }
+ return applyEnvironment(ctx, s, acct, app, envName, ifVersion, sets, unsets)
}
func Apply(ctx context.Context, s release.Store, acct, app string, sets map[string]Var, unsets []string) (claimResult0 int, claimResult1 error) {
claimResult1 = release.WithAppMutation(ctx, s, acct, app, "appconfig.Apply", func(claimContext context.Context) error {
@@ -140,6 +160,13 @@ func ApplyEnvironment(ctx context.Context, s release.Store, acct, app, envName s
})
return
}
+func ApplyIf(ctx context.Context, s release.Store, acct, app, envName, ifVersion string, sets map[string]Var, unsets []string) (claimResult0 Receipt, claimResult1 error) {
+ claimResult1 = release.WithAppMutation(ctx, s, acct, app, "appconfig.ApplyIf", func(claimContext context.Context) error {
+ claimResult0, claimResult1 = claimRawApplyIf(claimContext, s, acct, app, envName, ifVersion, sets, unsets)
+ return claimResult1
+ })
+ return
+}
func TouchGeneration(ctx context.Context, s release.Store, acct, app string) (claimResult0 error) {
claimResult0 = release.WithAppMutation(ctx, s, acct, app, "appconfig.TouchGeneration", func(claimContext context.Context) error {
claimResult0 = claimRawTouchGeneration(claimContext, s, acct, app)
diff --git a/internal/appconfig/instances.go b/internal/appconfig/instances.go
index 1cc6eaf87..5a9cf3546 100644
--- a/internal/appconfig/instances.go
+++ b/internal/appconfig/instances.go
@@ -132,7 +132,7 @@ func claimRawApplyInstance(ctx context.Context, s release.Store, acct, app, host
if !ValidInstanceHost(host) {
return 0, "", fmt.Errorf("config: invalid instance host %q", host)
}
- removed, etag, err := applyAt(ctx, s, InstanceConfigKey(acct, app, host), app, "instance "+host, sets, unsets)
+ r, etag, err := applyAt(ctx, s, InstanceConfigKey(acct, app, host), app, "instance "+host, "", sets, unsets)
if err != nil {
return 0, "", err
}
@@ -143,7 +143,7 @@ func claimRawApplyInstance(ctx context.Context, s release.Store, acct, app, host
// best-effort demotion every other write here makes: the manifest has
// landed, so a failed touch is logged, never returned.
touchLogged(ctx, s, acct, app)
- return removed, etag, nil
+ return len(r.Unset), etag, nil
}
// DeleteInstanceConfig removes one instance's overlay outright, which
diff --git a/internal/appconfig/observe.go b/internal/appconfig/observe.go
index c377d1f94..e96d64d49 100644
--- a/internal/appconfig/observe.go
+++ b/internal/appconfig/observe.go
@@ -13,6 +13,7 @@ import (
"errors"
"fmt"
"os"
+ "sort"
"github.com/carlosframework/platform/internal/release"
)
@@ -116,3 +117,71 @@ func BundleKey(acct, app, envName string) string {
}
return EnvironmentKey(acct, app, envName)
}
+
+// ErrVersionMismatch is a conditional write refused because the layer is not
+// at the version the caller expected: either it already differed when read,
+// or another writer moved it between that read and this write. Nothing was
+// written either way. Unconditional writes never return it; they keep
+// release.ErrCASConflict for a lost race, which is what their callers
+// already answer.
+var ErrVersionMismatch = errors.New("config: version mismatch")
+
+// ErrConditionalCreateOwned refuses a conditional write that would create an
+// owned environment. Creating one also mints the environment's platform
+// credentials in further writes, which cannot share the one precondition;
+// a team creates it unconditionally and writes conditionally afterwards.
+var ErrConditionalCreateOwned = errors.New("config: a conditional write cannot create an owned environment")
+
+// Receipt is what one apply did to one layer, told from the single read
+// whose etag guarded the write: the versions either side of it, and the
+// exact names it touched. Set is every name written; Unset is the names
+// asked for that were present (and are gone, unless also set); UnsetAbsent
+// is the names asked for that were not there. Digests covers Set only, so a
+// caller can check what it sent. Lists are sorted and never nil, so they
+// encode as [] rather than null.
+//
+// Changed compares versions, not intent: rewriting a var to the value it
+// already holds still writes, but leaves the bytes and so the version as
+// they were.
+type Receipt struct {
+ VersionBefore, VersionAfter string
+ Changed bool
+ Set, Unset, UnsetAbsent []string
+ Digests map[string]string
+}
+
+// applyToManifest makes sets and unsets on m in memory and describes them,
+// leaving the two versions for the caller, which alone holds the bytes. It
+// is the one mutation both write paths share (applyAt and the owned
+// environment's), so their receipts cannot drift apart. A manifest stored
+// without a "vars" key arrives with a nil map; it is made here, before any
+// write into it. A name repeated in unsets is reported once, as the old
+// removed count only ever counted it once.
+func applyToManifest(m *Manifest, sets map[string]Var, unsets []string) Receipt {
+ if m.Vars == nil {
+ m.Vars = map[string]Var{}
+ }
+ r := Receipt{Set: []string{}, Unset: []string{}, UnsetAbsent: []string{}, Digests: map[string]string{}}
+ seen := make(map[string]bool, len(unsets))
+ for _, k := range unsets {
+ if seen[k] {
+ continue
+ }
+ seen[k] = true
+ if _, ok := m.Vars[k]; ok {
+ r.Unset = append(r.Unset, k)
+ delete(m.Vars, k)
+ } else {
+ r.UnsetAbsent = append(r.UnsetAbsent, k)
+ }
+ }
+ for k, v := range sets {
+ m.Vars[k] = v
+ r.Set = append(r.Set, k)
+ r.Digests[k] = Digest(v)
+ }
+ sort.Strings(r.Set)
+ sort.Strings(r.Unset)
+ sort.Strings(r.UnsetAbsent)
+ return r
+}
diff --git a/internal/appconfig/observe_apply_test.go b/internal/appconfig/observe_apply_test.go
new file mode 100644
index 000000000..6810c5549
--- /dev/null
+++ b/internal/appconfig/observe_apply_test.go
@@ -0,0 +1,377 @@
+package appconfig
+
+// Conditional apply and receipts (spec 2026-11-02-config-receipts-design.md
+// §4.5-4.6). DirStore is enough here: these tests run in one process, so its
+// mutex makes the etag check and the replace one step, which is the property
+// the console only relies on from a store that reports
+// release.HasAtomicConditionalPut.
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "reflect"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// competingPutStore lands other at key immediately before forwarding the
+// caller's first Put there, at whatever position the caller asked for: the
+// interleaving where another writer moves the layer between a conditional
+// write's read and its write.
+type competingPutStore struct {
+ release.Store
+ key string
+ other []byte
+ done bool
+}
+
+func (c *competingPutStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key == c.key && !c.done {
+ c.done = true
+ if _, err := c.Store.Put(ctx, key, c.other, ifMatch); err != nil {
+ return "", err
+ }
+ }
+ return c.Store.Put(ctx, key, body, ifMatch)
+}
+
+func rawAt(t *testing.T, s release.Store, key string) []byte {
+ t.Helper()
+ raw, _, err := s.Get(context.Background(), key)
+ if err != nil {
+ t.Fatalf("Get %s: %v", key, err)
+ }
+ return raw
+}
+
+func layerVersion(t *testing.T, s release.Store, key string) string {
+ t.Helper()
+ l, err := LoadLayer(context.Background(), s, key, "keymail")
+ if err != nil {
+ t.Fatalf("LoadLayer %s: %v", key, err)
+ }
+ return l.Version
+}
+
+func envVars(kv map[string]string) map[string]Var {
+ out := make(map[string]Var, len(kv))
+ for k, v := range kv {
+ out[k] = Var{Kind: "env", Value: v}
+ }
+ return out
+}
+
+func TestApplyIfReceiptExactNames(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "")
+ if _, err := Apply(ctx, s, "bab", "keymail", envVars(map[string]string{"A": "1", "B": "2"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ before := layerVersion(t, s, key)
+ sets := map[string]Var{"C": {Kind: "env", Value: "3"}, "D": {Kind: "secret", Envelope: "sealed-elsewhere"}}
+ r, err := ApplyIf(ctx, s, "bab", "keymail", "", before, sets, []string{"B", "Z"})
+ if err != nil {
+ t.Fatalf("ApplyIf: %v", err)
+ }
+ if !reflect.DeepEqual(r.Set, []string{"C", "D"}) {
+ t.Errorf("Set = %v, want [C D]", r.Set)
+ }
+ if !reflect.DeepEqual(r.Unset, []string{"B"}) {
+ t.Errorf("Unset = %v, want [B]", r.Unset)
+ }
+ if !reflect.DeepEqual(r.UnsetAbsent, []string{"Z"}) {
+ t.Errorf("UnsetAbsent = %v, want [Z]", r.UnsetAbsent)
+ }
+ want := map[string]string{"C": Digest(sets["C"]), "D": Digest(sets["D"])}
+ if !reflect.DeepEqual(r.Digests, want) {
+ t.Errorf("Digests = %v, want exactly C and D's", r.Digests)
+ }
+ if r.VersionBefore != before {
+ t.Errorf("VersionBefore = %q, want the layer's version before the write", r.VersionBefore)
+ }
+ if after := layerVersion(t, s, key); r.VersionAfter != after {
+ t.Errorf("VersionAfter = %q, want the layer's version after the write %q", r.VersionAfter, after)
+ }
+ if !r.Changed || r.VersionAfter == r.VersionBefore {
+ t.Errorf("Changed = %v (%q -> %q), want a change", r.Changed, r.VersionBefore, r.VersionAfter)
+ }
+}
+
+// A receipt's lists are never nil, so the door encodes [] rather than null
+// for an empty half.
+func TestApplyIfReceiptEmptyListsNotNil(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ r, err := ApplyIf(context.Background(), s, "bab", "keymail", "", "", envVars(map[string]string{"A": "1"}), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if r.Unset == nil || r.UnsetAbsent == nil || r.Set == nil || r.Digests == nil {
+ t.Fatalf("receipt has a nil list or map: %+v", r)
+ }
+ if r.VersionBefore != VersionNone {
+ t.Errorf("VersionBefore = %q, want none for a create", r.VersionBefore)
+ }
+}
+
+func TestApplyIfStaleRefusedNothingWritten(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "")
+ if _, err := Apply(ctx, s, "bab", "keymail", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ old := layerVersion(t, s, key)
+ if _, err := Apply(ctx, s, "bab", "keymail", envVars(map[string]string{"A": "2"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ stored := rawAt(t, s, key)
+ _, err := ApplyIf(ctx, s, "bab", "keymail", "", old, envVars(map[string]string{"B": "3"}), []string{"A"})
+ if !errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("ApplyIf with a stale version = %v, want ErrVersionMismatch", err)
+ }
+ if got := rawAt(t, s, key); !bytes.Equal(got, stored) {
+ t.Fatalf("a refused conditional write changed the stored bytes:\n%s\nwas\n%s", got, stored)
+ }
+}
+
+// The same refusal for a named environment, through the same ApplyIf.
+func TestApplyIfStaleEnvironmentRefused(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "staging")
+ if _, err := ApplyEnvironment(ctx, s, "bab", "keymail", "staging", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ cur := layerVersion(t, s, key)
+ stored := rawAt(t, s, key)
+ if _, err := ApplyIf(ctx, s, "bab", "keymail", "staging", VersionNone, envVars(map[string]string{"B": "2"}), nil); !errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("ApplyIf(none) on an existing environment = %v, want ErrVersionMismatch", err)
+ }
+ if got := rawAt(t, s, key); !bytes.Equal(got, stored) {
+ t.Fatal("a refused conditional write changed the environment")
+ }
+ r, err := ApplyIf(ctx, s, "bab", "keymail", "staging", cur, envVars(map[string]string{"B": "2"}), nil)
+ if err != nil {
+ t.Fatalf("ApplyIf at the current version: %v", err)
+ }
+ if after := layerVersion(t, s, key); r.VersionAfter != after {
+ t.Errorf("VersionAfter = %q, want %q", r.VersionAfter, after)
+ }
+}
+
+func TestApplyIfRaceBetweenReadAndPut(t *testing.T) {
+ base := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "")
+ if _, err := Apply(ctx, base, "bab", "keymail", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ cur := layerVersion(t, base, key)
+ other := []byte(`{"schema":1,"app":"keymail","vars":{"OTHER":{"kind":"env","value":"won"}}}`)
+ cs := &competingPutStore{Store: base, key: key, other: other}
+ _, err := ApplyIf(ctx, cs, "bab", "keymail", "", cur, envVars(map[string]string{"B": "2"}), nil)
+ if !errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("ApplyIf losing the race = %v, want ErrVersionMismatch", err)
+ }
+ if !cs.done {
+ t.Fatal("the competing writer never ran: this test proved nothing")
+ }
+ if got := rawAt(t, base, key); !bytes.Equal(got, other) {
+ t.Fatalf("stored = %s, want the competing writer's bytes", got)
+ }
+}
+
+func TestApplyIfNoneCreates(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "")
+ r, err := ApplyIf(ctx, s, "bab", "keymail", "", VersionNone, envVars(map[string]string{"A": "1"}), nil)
+ if err != nil {
+ t.Fatalf("ApplyIf(none) on an absent layer: %v", err)
+ }
+ if r.VersionBefore != VersionNone || !r.Changed {
+ t.Errorf("receipt = %+v, want a change from none", r)
+ }
+ if after := layerVersion(t, s, key); after != r.VersionAfter {
+ t.Errorf("VersionAfter = %q, want %q", r.VersionAfter, after)
+ }
+}
+
+func TestApplyIfNoneOnExisting(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "")
+ if _, err := Apply(ctx, s, "bab", "keymail", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ stored := rawAt(t, s, key)
+ _, err := ApplyIf(ctx, s, "bab", "keymail", "", VersionNone, envVars(map[string]string{"A": "2"}), nil)
+ if !errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("ApplyIf(none) on an existing layer = %v, want ErrVersionMismatch", err)
+ }
+ if got := rawAt(t, s, key); !bytes.Equal(got, stored) {
+ t.Fatal("a refused conditional write changed the stored bytes")
+ }
+}
+
+func TestApplyIfUnchangedWrite(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ if _, err := Apply(ctx, s, "bab", "keymail", envVars(map[string]string{"A": "1", "B": "2"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ r, err := ApplyIf(ctx, s, "bab", "keymail", "", "", envVars(map[string]string{"A": "1"}), nil)
+ if err != nil {
+ t.Fatalf("ApplyIf: %v", err)
+ }
+ if r.Changed || r.VersionBefore != r.VersionAfter {
+ t.Fatalf("rewriting a var to its current value: Changed = %v, %q -> %q; want unchanged", r.Changed, r.VersionBefore, r.VersionAfter)
+ }
+ if !reflect.DeepEqual(r.Set, []string{"A"}) {
+ t.Errorf("Set = %v, want [A]: the write was still made", r.Set)
+ }
+}
+
+// A stored object with no "vars" key parses to a nil map; a conditional
+// write onto it must not panic and must still name its version.
+func TestApplyIfOntoManifestWithoutVars(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "")
+ if _, err := s.Put(ctx, key, []byte(`{"schema":1,"app":"keymail"}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ cur := layerVersion(t, s, key)
+ r, err := ApplyIf(ctx, s, "bab", "keymail", "", cur, envVars(map[string]string{"A": "1"}), []string{"GONE"})
+ if err != nil {
+ t.Fatalf("ApplyIf: %v", err)
+ }
+ if !reflect.DeepEqual(r.UnsetAbsent, []string{"GONE"}) || len(r.Unset) != 0 {
+ t.Errorf("Unset = %v, UnsetAbsent = %v; want [] and [GONE]", r.Unset, r.UnsetAbsent)
+ }
+}
+
+func TestApplyEnvironmentOwnedIfStale(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "team")
+ if _, err := ApplyEnvironmentOwned(ctx, s, "bab", "keymail", "team", "alta", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ old := layerVersion(t, s, key)
+ if _, err := ApplyEnvironmentOwned(ctx, s, "bab", "keymail", "team", "alta", envVars(map[string]string{"A": "2"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ cur := layerVersion(t, s, key)
+ stored := rawAt(t, s, key)
+
+ _, err := ApplyEnvironmentOwnedIf(ctx, s, "bab", "keymail", "team", "alta", old, envVars(map[string]string{"B": "3"}), nil)
+ if !errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("stale owned write = %v, want ErrVersionMismatch", err)
+ }
+ // The wrong scope is refused as not-owned before any version is
+ // compared, even at the right version: a mismatch would tell another
+ // scope the layer exists and has moved.
+ for _, v := range []string{old, cur} {
+ _, err = ApplyEnvironmentOwnedIf(ctx, s, "bab", "keymail", "team", "beta", v, envVars(map[string]string{"B": "3"}), nil)
+ if !errors.Is(err, ErrNotOwnedBy) || errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("wrong scope = %v, want ErrNotOwnedBy alone", err)
+ }
+ }
+ if got := rawAt(t, s, key); !bytes.Equal(got, stored) {
+ t.Fatal("a refused owned write changed the stored bytes")
+ }
+
+ r, err := ApplyEnvironmentOwnedIf(ctx, s, "bab", "keymail", "team", "alta", cur, envVars(map[string]string{"B": "3"}), []string{"A"})
+ if err != nil {
+ t.Fatalf("owned write at the current version: %v", err)
+ }
+ if !reflect.DeepEqual(r.Set, []string{"B"}) || !reflect.DeepEqual(r.Unset, []string{"A"}) {
+ t.Errorf("receipt Set = %v, Unset = %v; want [B] and [A]", r.Set, r.Unset)
+ }
+ if after := layerVersion(t, s, key); r.VersionBefore != cur || r.VersionAfter != after || !r.Changed {
+ t.Errorf("receipt versions %q -> %q (changed %v), want %q -> %q", r.VersionBefore, r.VersionAfter, r.Changed, cur, after)
+ }
+}
+
+// The owned path loses a race the same way the default path does.
+func TestApplyEnvironmentOwnedIfRace(t *testing.T) {
+ base := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "team")
+ if _, err := ApplyEnvironmentOwned(ctx, base, "bab", "keymail", "team", "alta", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ cur := layerVersion(t, base, key)
+ other := []byte(`{"schema":2,"app":"keymail","owner_scope":"alta","vars":{}}`)
+ cs := &competingPutStore{Store: base, key: key, other: other}
+ if _, err := ApplyEnvironmentOwnedIf(ctx, cs, "bab", "keymail", "team", "alta", cur, envVars(map[string]string{"B": "2"}), nil); !errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("owned write losing the race = %v, want ErrVersionMismatch", err)
+ }
+ if got := rawAt(t, base, key); !bytes.Equal(got, other) {
+ t.Fatalf("stored = %s, want the competing writer's bytes", got)
+ }
+}
+
+func TestApplyEnvironmentOwnedIfNoneRefused(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ _, err := ApplyEnvironmentOwnedIf(ctx, s, "bab", "keymail", "fresh", "alta", VersionNone, envVars(map[string]string{"A": "1"}), nil)
+ if !errors.Is(err, ErrConditionalCreateOwned) {
+ t.Fatalf("owned create with if-version none = %v, want ErrConditionalCreateOwned", err)
+ }
+ if _, _, err := s.Get(ctx, BundleKey("bab", "keymail", "fresh")); err == nil {
+ t.Fatal("a refused owned create wrote the environment")
+ }
+ // Any other expected version against an absent environment is a
+ // mismatch, never the mint path.
+ if _, err := ApplyEnvironmentOwnedIf(ctx, s, "bab", "keymail", "fresh", "alta", "cv1:00", envVars(map[string]string{"A": "1"}), nil); !errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("owned write expecting a version of an absent environment = %v, want ErrVersionMismatch", err)
+ }
+ if _, _, err := s.Get(ctx, BundleKey("bab", "keymail", "fresh")); err == nil {
+ t.Fatal("a refused owned write created the environment")
+ }
+}
+
+// The unconditional callers keep today's contract: a lost race is
+// release.ErrCASConflict (the door's 409), never the conditional 412.
+func TestApplyUnchangedSignatures(t *testing.T) {
+ base := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := BundleKey("bab", "keymail", "")
+ if _, err := Apply(ctx, base, "bab", "keymail", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ cs := &competingPutStore{Store: base, key: key, other: []byte(`{"schema":1,"app":"keymail","vars":{}}`)}
+ _, err := Apply(ctx, cs, "bab", "keymail", envVars(map[string]string{"B": "2"}), nil)
+ if !errors.Is(err, release.ErrCASConflict) || errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("Apply losing the race = %v, want ErrCASConflict alone", err)
+ }
+
+ // ApplyIf with no expected version is the same unconditional write.
+ cs = &competingPutStore{Store: base, key: key, other: []byte(`{"schema":1,"app":"keymail","vars":{"X":{"kind":"env","value":"y"}}}`)}
+ if _, err := ApplyIf(ctx, cs, "bab", "keymail", "", "", envVars(map[string]string{"B": "2"}), nil); !errors.Is(err, release.ErrCASConflict) || errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("unconditional ApplyIf losing the race = %v, want ErrCASConflict alone", err)
+ }
+
+ envKey := BundleKey("bab", "keymail", "team")
+ if _, err := ApplyEnvironmentOwned(ctx, base, "bab", "keymail", "team", "alta", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ cs = &competingPutStore{Store: base, key: envKey, other: []byte(`{"schema":2,"app":"keymail","owner_scope":"alta","vars":{}}`)}
+ if _, err := ApplyEnvironmentOwned(ctx, cs, "bab", "keymail", "team", "alta", envVars(map[string]string{"B": "2"}), nil); !errors.Is(err, release.ErrCASConflict) || errors.Is(err, ErrVersionMismatch) {
+ t.Fatalf("ApplyEnvironmentOwned losing the race = %v, want ErrCASConflict alone", err)
+ }
+
+ // removed still counts what was there, once per name.
+ if _, err := Apply(ctx, base, "bab", "keymail", envVars(map[string]string{"A": "1"}), nil); err != nil {
+ t.Fatal(err)
+ }
+ n, err := Apply(ctx, base, "bab", "keymail", nil, []string{"A", "NOPE", "A"})
+ if err != nil || n != 1 {
+ t.Fatalf("Apply unset = %d, %v; want 1 removed", n, err)
+ }
+}
diff --git a/internal/appconfig/owned.go b/internal/appconfig/owned.go
index 2dd5675a3..8f0efa3a7 100644
--- a/internal/appconfig/owned.go
+++ b/internal/appconfig/owned.go
@@ -97,59 +97,87 @@ func EnvironmentOwners(ctx context.Context, s release.Store, acct, app string) (
// rules (no record references the name, under the app's record lock) run
// before this; this function cannot see records.
func claimRawApplyEnvironmentOwned(ctx context.Context, s release.Store, acct, app, envName, scope string, sets map[string]Var, unsets []string) (int, error) {
+ r, err := applyEnvironmentOwned(ctx, s, acct, app, envName, scope, "", sets, unsets)
+ return len(r.Unset), err
+}
+
+// ApplyEnvironmentOwnedIf is ApplyEnvironmentOwned conditional on the
+// bundle's version (config receipts spec §4.5), answering with a Receipt.
+// ifVersion "" is the unconditional write ApplyEnvironmentOwned makes.
+// Otherwise the ownership check comes first, so a scope that does not own
+// the bundle hears ErrNotOwnedBy and learns nothing of its version; then a
+// version other than the one read is ErrVersionMismatch, as is a write that
+// loses a race to another writer. Nothing is written on any refusal.
+//
+// ifVersion "none" is refused outright (ErrConditionalCreateOwned), before
+// anything is read, so the answer says nothing about whether the bundle
+// exists: creating an owned environment is followed by minting its platform
+// credentials in further writes, which one precondition cannot cover.
+func claimRawApplyEnvironmentOwnedIf(ctx context.Context, s release.Store, acct, app, envName, scope, ifVersion string, sets map[string]Var, unsets []string) (Receipt, error) {
+ return applyEnvironmentOwned(ctx, s, acct, app, envName, scope, ifVersion, sets, unsets)
+}
+
+// applyEnvironmentOwned is the owned write both doors share: expect "" for
+// the unconditional one, a version for the conditional one. The ownership
+// check, the version compare, the mutation and the receipt all come from
+// the one read whose etag guards the write.
+func applyEnvironmentOwned(ctx context.Context, s release.Store, acct, app, envName, scope, expect string, sets map[string]Var, unsets []string) (Receipt, error) {
if !release.ValidAccount(acct) {
- return 0, fmt.Errorf("config: invalid account %q", acct)
+ return Receipt{}, fmt.Errorf("config: invalid account %q", acct)
}
if !release.ValidApp(app) {
- return 0, fmt.Errorf("config: invalid app %q", app)
+ return Receipt{}, fmt.Errorf("config: invalid app %q", app)
}
if !ValidEnvironmentName(envName) {
- return 0, fmt.Errorf("config: invalid environment name %q", envName)
+ return Receipt{}, fmt.Errorf("config: invalid environment name %q", envName)
}
if scope == "" {
- return 0, errors.New("config: an owned write needs a scope")
+ return Receipt{}, errors.New("config: an owned write needs a scope")
}
for k, v := range sets {
if !ValidVarName(k) {
- return 0, fmt.Errorf("config: invalid var name %q", k)
+ return Receipt{}, fmt.Errorf("config: invalid var name %q", k)
}
if v.Kind == "env" {
if err := ValidVarValue(v.Value); err != nil {
- return 0, fmt.Errorf("config: var %s: %w", k, err)
+ return Receipt{}, fmt.Errorf("config: var %s: %w", k, err)
}
}
}
+ if expect == VersionNone {
+ return Receipt{}, ErrConditionalCreateOwned
+ }
key := EnvironmentKey(acct, app, envName)
- m, etag, found, err := getForWriteAt(ctx, s, key, app)
+ m, etag, before, found, err := getForWriteAtVersion(ctx, s, key, app)
if err != nil {
- return 0, err
+ return Receipt{}, err
}
if !found {
if len(sets) == 0 {
- return 0, fmt.Errorf("config: %s has no %s bundle — nothing to unset", app, envName)
+ return Receipt{}, fmt.Errorf("config: %s has no %s bundle — nothing to unset", app, envName)
+ }
+ // A conditional write never reaches the create: "none" was refused
+ // above, so any expected version here names an object that is not
+ // there.
+ if expect != "" {
+ return Receipt{}, ErrVersionMismatch
}
m.OwnerScope = scope
} else if m.OwnerScope != scope {
- return 0, ErrNotOwnedBy
- }
- if m.Vars == nil {
- m.Vars = map[string]Var{}
+ return Receipt{}, ErrNotOwnedBy
}
- removed := 0
- for _, k := range unsets {
- if _, ok := m.Vars[k]; ok {
- removed++
- }
- delete(m.Vars, k)
- }
- for k, v := range sets {
- m.Vars[k] = v
+ if expect != "" && expect != before {
+ return Receipt{}, ErrVersionMismatch
}
- if _, err := putManifestAt(ctx, s, key, app, &m, etag); err != nil {
- return 0, err
+ r := applyToManifest(&m, sets, unsets)
+ raw, _, err := putManifestAt(ctx, s, key, app, &m, etag)
+ if err != nil {
+ return Receipt{}, conditionalPutErr(expect, err)
}
+ r.VersionBefore, r.VersionAfter = before, Version(raw, true)
+ r.Changed = r.VersionBefore != r.VersionAfter
touchLogged(ctx, s, acct, app)
- return removed, nil
+ return r, nil
}
// SetEnvironmentOwner marks app's envName bundle as owned by scope (adopt:
@@ -189,7 +217,7 @@ func claimRawSetEnvironmentOwner(ctx context.Context, s release.Store, acct, app
if m.Vars == nil {
m.Vars = map[string]Var{}
}
- if _, err := putManifestAt(ctx, s, key, app, &m, etag); err != nil {
+ if _, _, err := putManifestAt(ctx, s, key, app, &m, etag); err != nil {
return err
}
touchLogged(ctx, s, acct, app)
@@ -246,7 +274,7 @@ func claimRawForkEnvironment(ctx context.Context, s release.Store, acct, app, fr
dst.Vars[k] = v
}
}
- _, err = putManifestAt(ctx, s, EnvironmentKey(acct, app, to), app, dst, "")
+ _, _, err = putManifestAt(ctx, s, EnvironmentKey(acct, app, to), app, dst, "")
if errors.Is(err, release.ErrCASConflict) {
return ErrEnvironmentExists
}
@@ -289,3 +317,10 @@ func ForkEnvironment(ctx context.Context, s release.Store, acct, app, from, to,
})
return
}
+func ApplyEnvironmentOwnedIf(ctx context.Context, s release.Store, acct, app, envName, scope, ifVersion string, sets map[string]Var, unsets []string) (claimResult0 Receipt, claimResult1 error) {
+ claimResult1 = release.WithAppMutation(ctx, s, acct, app, "appconfig.ApplyEnvironmentOwnedIf", func(claimContext context.Context) error {
+ claimResult0, claimResult1 = claimRawApplyEnvironmentOwnedIf(claimContext, s, acct, app, envName, scope, ifVersion, sets, unsets)
+ return claimResult1
+ })
+ return
+}
diff --git a/internal/appconfig/store.go b/internal/appconfig/store.go
index 7993b0b85..c2306ac2c 100644
--- a/internal/appconfig/store.go
+++ b/internal/appconfig/store.go
@@ -94,12 +94,22 @@ func getIfExistsAtETag(ctx context.Context, s release.Store, key string) (*Manif
// Generalized to any manifest key; see getIfExistsAt's doc comment for why
// one path serves both the default bundle and a named environment.
func getForWriteAt(ctx context.Context, s release.Store, key, app string) (Manifest, string, bool, error) {
+ m, etag, _, found, err := getForWriteAtVersion(ctx, s, key, app)
+ return m, etag, found, err
+}
+
+// getForWriteAtVersion is getForWriteAt plus the Version of the exact bytes
+// the manifest was parsed from, for a conditional write: the version it
+// compares, the etag it writes at and the manifest it changes all come from
+// this one read, so none of them can describe a different object than the
+// others. An absent object is VersionNone.
+func getForWriteAtVersion(ctx context.Context, s release.Store, key, app string) (Manifest, string, string, bool, error) {
raw, etag, err := s.Get(ctx, key)
switch {
case err == nil:
var m Manifest
if uerr := json.Unmarshal(raw, &m); uerr != nil {
- return Manifest{}, "", false, fmt.Errorf("config %s: %w", key, uerr)
+ return Manifest{}, "", "", false, fmt.Errorf("config %s: %w", key, uerr)
}
// Same newer-schema refusal as getIfExists — writing back through
// this path would downgrade the object to schema 1 minus the fields
@@ -107,40 +117,41 @@ func getForWriteAt(ctx context.Context, s release.Store, key, app string) (Manif
// this is what keeps an old CLI in bucket mode from rewriting it
// without its owner_scope.
if m.Schema > MaxSchema {
- return Manifest{}, "", false, fmt.Errorf("config %s: schema %d is newer than this binary understands — upgrade carlos", key, m.Schema)
+ return Manifest{}, "", "", false, fmt.Errorf("config %s: schema %d is newer than this binary understands — upgrade carlos", key, m.Schema)
}
- return m, etag, true, nil
+ return m, etag, Version(raw, true), true, nil
case errors.Is(err, os.ErrNotExist):
- return Manifest{Schema: 1, App: app, Vars: map[string]Var{}}, "", false, nil
+ return Manifest{Schema: 1, App: app, Vars: map[string]Var{}}, "", VersionNone, false, nil
default:
- return Manifest{}, "", false, err
+ return Manifest{}, "", "", false, err
}
}
// apply reads, applies sets and unsets, and writes back via CAS, reporting
-// how many of unsets were actually present. A racing concurrent write
-// surfaces as release.ErrCASConflict — callers report it and let the operator
-// re-run; there is no automatic retry, matching release.Promote's own
-// behavior.
+// what it did as a Receipt (len(Unset) is how many of unsets were actually
+// present). A racing concurrent write surfaces as release.ErrCASConflict —
+// callers report it and let the operator re-run; there is no automatic
+// retry, matching release.Promote's own behavior. expect, when not "", makes
+// the write conditional on the layer's version (see applyAt).
//
// On success it also touches the app's generation object (generation.go), so
// the change is visible to the agent's fast loop within seconds rather than
// at the next hourly sweep. Best-effort by construction: the manifest write
// has already landed by then, so a failed touch is logged, never returned
// (see touchLogged).
-func apply(ctx context.Context, s release.Store, acct, app, bundle string, sets map[string]Var, unsets []string) (int, error) {
+func apply(ctx context.Context, s release.Store, acct, app, bundle, expect string, sets map[string]Var, unsets []string) (Receipt, error) {
if !release.ValidAccount(acct) {
- return 0, fmt.Errorf("config: invalid account %q", acct)
+ return Receipt{}, fmt.Errorf("config: invalid account %q", acct)
}
if !release.ValidApp(app) {
- return 0, fmt.Errorf("config: invalid app %q", app)
+ return Receipt{}, fmt.Errorf("config: invalid app %q", app)
}
- removed, _, err := applyAt(ctx, s, Key(acct, app), app, bundle, sets, unsets)
+ r, _, err := applyAt(ctx, s, Key(acct, app), app, bundle, expect, sets, unsets)
if err != nil {
- return 0, err
+ return Receipt{}, err
}
touchLogged(ctx, s, acct, app)
- return removed, nil
+ return r, nil
}
// applyAt is apply generalized to any manifest key — see getIfExistsAt's doc
@@ -159,10 +170,20 @@ func apply(ctx context.Context, s release.Store, acct, app, bundle string, sets
// environment bundles that then satisfied `carlos route -environment`'s
// existence rail. Sets still create, which is how a bundle is meant to come
// into being.
-func applyAt(ctx context.Context, s release.Store, key, app, bundle string, sets map[string]Var, unsets []string) (int, string, error) {
+//
+// expect, when not "", makes the write conditional (config receipts spec
+// §4.5): the layer's version on the one read this write is made against
+// must equal it ("none": no object yet), else ErrVersionMismatch and nothing
+// is written. The comparison follows the existing refusals above it, so a
+// conditional unset-only call against a missing bundle is still refused as
+// a missing bundle. The etag from that same read guards the write, so the
+// compare holds up to the write only on a store whose conditional Put is
+// atomic (release.HasAtomicConditionalPut); choosing to rely on that is the
+// caller's decision, not this function's.
+func applyAt(ctx context.Context, s release.Store, key, app, bundle, expect string, sets map[string]Var, unsets []string) (Receipt, string, error) {
for k, v := range sets {
if !ValidVarName(k) {
- return 0, "", fmt.Errorf("config: invalid var name %q", k)
+ return Receipt{}, "", fmt.Errorf("config: invalid var name %q", k)
}
// Env values are validated here, while the operator can still see
// the plaintext — a bad value that only failed at render time would
@@ -171,51 +192,64 @@ func applyAt(ctx context.Context, s release.Store, key, app, bundle string, sets
// CLI, before sealing; by this point they're opaque envelopes.
if v.Kind == "env" {
if err := ValidVarValue(v.Value); err != nil {
- return 0, "", fmt.Errorf("config: var %s: %w", k, err)
+ return Receipt{}, "", fmt.Errorf("config: var %s: %w", k, err)
}
}
}
- m, etag, found, err := getForWriteAt(ctx, s, key, app)
+ m, etag, before, found, err := getForWriteAtVersion(ctx, s, key, app)
if err != nil {
- return 0, "", err
+ return Receipt{}, "", err
}
if !found && len(sets) == 0 {
- return 0, "", fmt.Errorf("config: %s has no %s bundle — nothing to unset", app, bundle)
- }
- if m.Vars == nil {
- m.Vars = map[string]Var{}
- }
- removed := 0
- for _, k := range unsets {
- if _, ok := m.Vars[k]; ok {
- removed++
- }
- delete(m.Vars, k)
+ return Receipt{}, "", fmt.Errorf("config: %s has no %s bundle — nothing to unset", app, bundle)
}
- for k, v := range sets {
- m.Vars[k] = v
+ if expect != "" && expect != before {
+ return Receipt{}, "", ErrVersionMismatch
}
+ r := applyToManifest(&m, sets, unsets)
// The new etag is returned because the instance layer's writer (design
// §6.5) has to hand it to whoever will later compare it with an agent's
// delivery ack. The other two bundles' callers ignore it.
- newETag, err := putManifestAt(ctx, s, key, app, &m, etag)
+ raw, newETag, err := putManifestAt(ctx, s, key, app, &m, etag)
if err != nil {
- return 0, "", err
+ return Receipt{}, "", conditionalPutErr(expect, err)
}
- return removed, newETag, nil
+ r.VersionBefore, r.VersionAfter = before, Version(raw, true)
+ r.Changed = r.VersionBefore != r.VersionAfter
+ return r, newETag, nil
+}
+
+// conditionalPutErr is a manifest write's error as a conditional caller
+// must see it. The write was made at the etag of the read whose version
+// matched expect, so a CAS conflict means another writer moved the layer in
+// between: for a conditional write that is the same refusal as a mismatch at
+// read, and nothing was written. An unconditional write keeps
+// release.ErrCASConflict, which its callers already answer.
+func conditionalPutErr(expect string, err error) error {
+ if expect != "" && errors.Is(err, release.ErrCASConflict) {
+ return ErrVersionMismatch
+ }
+ return err
}
// putManifestAt is the ONE write of a manifest object: it stamps the app
// and the schema (manifestSchema: 2 for an owned environment, 1 otherwise,
// so owner_scope and the schema number always travel together) and writes
-// at the caller's CAS position. etag "" is create-only.
-func putManifestAt(ctx context.Context, s release.Store, key, app string, m *Manifest, etag string) (string, error) {
+// at the caller's CAS position. etag "" is create-only. It returns the bytes
+// it wrote as well as the new etag: a layer's version is a hash of its
+// bytes, and these are the only bytes this process knows landed, so a
+// receipt names them rather than a second read another writer could race.
+func putManifestAt(ctx context.Context, s release.Store, key, app string, m *Manifest, etag string) ([]byte, string, error) {
m.Schema, m.App = manifestSchema(m), app
raw, err := json.MarshalIndent(m, "", " ")
if err != nil {
- return "", err
+ return nil, "", err
+ }
+ newETag, err := s.Put(ctx, key, raw, etag)
+ if err != nil {
+ return nil, "", err
}
- return s.Put(ctx, key, raw, etag)
+ return raw, newETag, nil
}
// DefaultBundle is how the default bundle (config.json) is named to a human
@@ -230,7 +264,7 @@ func claimRawSetEnv(ctx context.Context, s release.Store, acct, app string, kv m
for k, v := range kv {
sets[k] = Var{Kind: "env", Value: v}
}
- _, err := apply(ctx, s, acct, app, DefaultBundle, sets, nil)
+ _, err := apply(ctx, s, acct, app, DefaultBundle, "", sets, nil)
return err
}
@@ -244,7 +278,7 @@ func claimRawSetSecret(ctx context.Context, s release.Store, acct, app string, s
v.Kind = "secret"
sets[k] = v
}
- _, err := apply(ctx, s, acct, app, DefaultBundle, sets, nil)
+ _, err := apply(ctx, s, acct, app, DefaultBundle, "", sets, nil)
return err
}
@@ -253,7 +287,8 @@ func claimRawSetSecret(ctx context.Context, s release.Store, acct, app string, s
// set is a no-op success, matching heroku config:unset's idempotence —
// unsetting from a bundle that does not EXIST is not (see applyAt).
func claimRawUnset(ctx context.Context, s release.Store, acct, app string, keys []string) (int, error) {
- return apply(ctx, s, acct, app, DefaultBundle, nil, keys)
+ r, err := apply(ctx, s, acct, app, DefaultBundle, "", nil, keys)
+ return len(r.Unset), err
}
// SetExecDelivery writes (`file`) or clears (`""`) the DEFAULT bundle's
@@ -310,7 +345,7 @@ func claimRawSetExecDeliveryAt(ctx context.Context, s release.Store, acct, app,
return fmt.Errorf("config: %s has no %s bundle — nothing to turn off", app, label)
}
m.ExecDelivery = value
- if _, err := putManifestAt(ctx, s, key, app, &m, etag); err != nil {
+ if _, _, err := putManifestAt(ctx, s, key, app, &m, etag); err != nil {
return err
}
// The opt-in flag changes what SyncExec delivers for this app's routes,
diff --git a/internal/release/store.go b/internal/release/store.go
index 6d5f58fde..5154d6681 100644
--- a/internal/release/store.go
+++ b/internal/release/store.go
@@ -111,6 +111,33 @@ func HasBucketListDirs(s Store) bool {
// BucketShapedListDirs: rebasing keeps the shape of the store underneath.
func (p prefixStore) BucketShapedListDirs() bool { return HasBucketListDirs(p.Store) }
+// AtomicConditionalStore is the optional half of Store that promises its
+// Put's ifMatch is checked and applied as one step against every writer,
+// in any process: a write whose etag has moved is refused whoever moved it.
+// A console's conditional config write (if_version, config receipts spec
+// §4.5) rests on exactly that, and refuses on a store without it rather
+// than offer a guarantee the store cannot keep.
+//
+// DirStore deliberately does not implement it: its check and replace are
+// one step only under a mutex inside one store instance, and a bucket-mode
+// CLI builds its own instance, so two processes can both pass the check.
+type AtomicConditionalStore interface {
+ AtomicConditionalPut()
+}
+
+// HasAtomicConditionalPut reports whether s promises an atomic conditional
+// Put (AtomicConditionalStore). A prefix store answers for the store beneath
+// it: rebasing a key changes nothing about how the write is checked, and a
+// marker method on prefixStore itself would claim the promise over a
+// DirStore too.
+func HasAtomicConditionalPut(s Store) bool {
+ if p, ok := s.(prefixStore); ok {
+ return HasAtomicConditionalPut(p.Store)
+ }
+ _, ok := s.(AtomicConditionalStore)
+ return ok
+}
+
// NewPrefixStore wraps s so every key is rebased under prefix. An empty
// prefix returns s UNCHANGED (not a prefixStore with an empty base) — every
// deployment that never sets the namespacing env var (every platform box
@@ -969,6 +996,11 @@ func NewDeploymentS3StoreIn(ctx context.Context, bucket, region string) (*S3Stor
return s, nil
}
+// AtomicConditionalPut: the bucket itself evaluates If-Match and
+// If-None-Match against the object as it stands when the write lands, so no
+// writer in any process can slip between the check and the replace.
+func (s *S3Store) AtomicConditionalPut() {}
+
func (s *S3Store) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
etag, err := s.putRaw(ctx, key, body, ifMatch)
if err == nil {
diff --git a/internal/release/store_test.go b/internal/release/store_test.go
index 22588c7ea..eaa1a687a 100644
--- a/internal/release/store_test.go
+++ b/internal/release/store_test.go
@@ -394,3 +394,34 @@ func TestNewS3StoreInPinsTheRegion(t *testing.T) {
t.Fatalf("region = %q, want eu-west-1", got)
}
}
+
+// TestHasAtomicConditionalPut pins which stores may carry a console's
+// conditional config write (config receipts spec §4.5): the S3 store, whose
+// If-Match is checked by the bucket whoever wrote in between, and not
+// DirStore, whose check is a mutex inside one process. The S3 store is
+// built by the deployment constructor the console uses, and a prefix store
+// keeps the answer of the store beneath it.
+func TestHasAtomicConditionalPut(t *testing.T) {
+ t.Setenv("AWS_REGION", "us-east-1")
+ t.Setenv("AWS_ACCESS_KEY_ID", "k")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "s")
+ s3, err := NewDeploymentS3Store(context.Background(), "b")
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := NewDirStore(t.TempDir())
+ for _, c := range []struct {
+ name string
+ s Store
+ want bool
+ }{
+ {"S3Store", s3, true},
+ {"DirStore", dir, false},
+ {"prefix over S3Store", NewPrefixStore(s3, "fleets/pi/"), true},
+ {"prefix over DirStore", NewPrefixStore(dir, "fleets/pi/"), false},
+ } {
+ if got := HasAtomicConditionalPut(c.s); got != c.want {
+ t.Errorf("HasAtomicConditionalPut(%s) = %v, want %v", c.name, got, c.want)
+ }
+ }
+}