carlos / platform Public

edgesfile: elect for every reader kind; an undecodable host entry is unknown (asset cache plan 3 Task 12 fix round 1)

The shared election takes an explicit reader context (edgesfile.Reader:
own box, own file's network, region HA switch); the edge's fold dials
through Reader.Dial with its real context. The status door elects for
the public-only reader and for a region HA reader on each published
network (ElectHomesForEveryReader); a host they disagree on shows
unknown. Every host entry is decoded with the edge's types first, and
one that does not decode makes every published column unknown, as the
edge loses that whole file. The asset fixture sets a secrets key, so
NewServer's missing-key line stays out of those tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 7cf5525fc23f0347586d555908a02534899a0e93 parent 0fb0425
7 files changed, +483 −173
  • internal/console/apiassets.go +42 −27
  • internal/console/apiassets_test.go +65 −5
  • internal/console/server_test.go +10 −0
  • internal/edge/homemap.go +12 −19
  • internal/edge/homemap_status_election_test.go +81 −48
  • internal/edgesfile/homeelect.go +150 −46
  • internal/edgesfile/homeelect_test.go +123 −28

CI failed — run details

diff --git a/internal/console/apiassets.go b/internal/console/apiassets.go
index 5d89d7c7b..2ae7d0659 100644
--- a/internal/console/apiassets.go
+++ b/internal/console/apiassets.go
@@ -138,9 +138,10 @@ func listOrNone(hosts []string) string {
// and the generation and at its home published in its edges file. A purge
// is complete at the home when PublishedGen matches Gen.
//
-// PublishedUnknown says the published columns could not be read at all (the
-// edges files could not be listed, or one of them could not be read), which
-// the CLI prints as EAC-26 in place of the folders and published columns.
+// PublishedUnknown says the console cannot tell what the instance's home
+// publishes: the edges files could not all be read or decoded, or edges
+// in different places would elect different homes for it. The CLI prints
+// EAC-26 in place of the folders and published columns.
// It is not "publishes nothing": that is a readable winner with no block,
// and leaves PublishedUnknown false and the columns empty. A console that
// predates the field leaves it out, and a CLI that predates it prints the
@@ -159,14 +160,17 @@ type assetStatusView struct {
// prints. Reads only: the records (the instance list's capped read) and the
// edges files through readEdgesSnapshot. Every published column comes from
// one place, the assets block of the host's WINNING home entry, elected the
-// way an edge's home map elects it (homeAssets, edgesfile.ElectHomes): the
+// way an edge's home map elects it (homeAssets): the
// folders, generation and at an edge would use, or none when that entry
// publishes no block. The channel head's declaration is not consulted: it
// says what a release asks for, not what the home is serving (design §6).
//
-// When the edges files cannot all be read, nobody can say which entry wins
-// for any host: an unread file may hold a higher stamp. Every instance's
-// published columns are then unknown (PublishedUnknown), never "none".
+// When the edges files cannot all be read or decoded, nobody can say which
+// entry wins for any host: an unread file may hold a higher stamp. Every
+// instance's published columns are then unknown (PublishedUnknown), never
+// "none". A host whose winner depends on where the edge stands (a box with
+// only a private address, which only its own region's edges can dial) is
+// unknown on its own.
//
// truncated is set when the listing stopped at the cap and also when it
// skipped a record it could not read: either way an instance is missing
@@ -188,10 +192,11 @@ func (s *Server) handleAPIAssetsStatus(w http.ResponseWriter, r *http.Request) {
log.Printf("console: api assets status %s/%s: %d record(s) unreadable %v", acct.Sqid, app, len(skipped), skipped)
truncated = true
}
- published, known := s.homeAssets(ctx, acct.Sqid, app)
+ published, split, known := s.homeAssets(ctx, acct.Sqid, app)
out := make([]assetStatusView, 0, len(recs))
for _, rec := range recs {
- v := assetStatusView{Host: rec.Host, Paths: []string{}, Assets: "on", Gen: rec.AssetGen, PublishedUnknown: !known}
+ v := assetStatusView{Host: rec.Host, Paths: []string{}, Assets: "on", Gen: rec.AssetGen,
+ PublishedUnknown: !known || split[rec.Host]}
if !rec.AssetsOn() {
v.Assets = "off"
}
@@ -209,34 +214,44 @@ func (s *Server) handleAPIAssetsStatus(w http.ResponseWriter, r *http.Request) {
// homeAssets reads the edges files and answers host -> the assets block of
// the entry an edge dials for it, nil when that entry publishes none. The
-// election is edgesfile.ElectHomes, which shares its rule (HomeBeats) and
-// its dial eligibility (DialAddress) with the edge's home map, so a box no
-// edge can dial never wins, however high its stamp (#396). The winner's
-// block is taken whole, its absence included, so a losing box's newer
-// block is never reported as the home's.
+// election is edgesfile.ElectHomesForEveryReader: the edge's own election
+// (its HomeBeats and its Reader.Dial), made for an edge that dials public
+// addresses only and for an edge on each region network the files publish,
+// with region HA on. The console is no edge and has no reader context of
+// its own, so a host those readers disagree on is split: it has no single
+// home to report, and its published columns are unknown. A box no edge can
+// dial never wins, however high its stamp (#396). The winner's block is
+// taken whole, its absence included, so a losing box's newer block is
+// never reported as the home's.
//
-// known is false when the answer cannot be trusted at all: no store, a
-// listing that failed, or a file under the prefix that could not be read
-// or parsed (the snapshot is not Complete). An edge carries an unreadable
-// file's previous parse forward; the console has none to carry, and the
-// unread file may hold the winning entry for any host.
-func (s *Server) homeAssets(ctx context.Context, acct, app string) (map[string]*edgesfile.HostAssets, bool) {
+// known is false when the answer cannot be trusted for any host: no store,
+// a listing that failed, a file under the prefix that could not be read or
+// parsed (the snapshot is not Complete), or a host entry that does not
+// decode. An edge decodes each file whole, so one bad entry costs it the
+// whole file, whose previous parse it carries forward; the console has
+// none to carry, and the unread file may hold the winning entry for any
+// host.
+func (s *Server) homeAssets(ctx context.Context, acct, app string) (blocks map[string]*edgesfile.HostAssets, split map[string]bool, known bool) {
if s.cfg.Releases == nil {
- return nil, false
+ return nil, nil, false
}
snap, err := readEdgesSnapshot(ctx, s.cfg.Releases)
if err != nil {
log.Printf("console: api assets status %s/%s: could not list %s: %v", acct, app, edgesfile.Prefix, err)
- return nil, false
+ return nil, nil, false
}
if !snap.Complete {
log.Printf("console: api assets status %s/%s: an edges file under %s could not be read, so every published column is unknown", acct, app, edgesfile.Prefix)
- return nil, false
+ return nil, nil, false
}
- won := edgesfile.ElectHomes(snap.Files)
- out := make(map[string]*edgesfile.HostAssets, len(won))
+ won, split, err := edgesfile.ElectHomesForEveryReader(snap.Files)
+ if err != nil {
+ log.Printf("console: api assets status %s/%s: %v, so every published column is unknown", acct, app, err)
+ return nil, nil, false
+ }
+ blocks = make(map[string]*edgesfile.HostAssets, len(won))
for host, e := range won {
- out[host] = e.Assets
+ blocks[host] = e.Assets
}
- return out, true
+ return blocks, split, true
}
diff --git a/internal/console/apiassets_test.go b/internal/console/apiassets_test.go
index 27ef42a97..0078ebc16 100644
--- a/internal/console/apiassets_test.go
+++ b/internal/console/apiassets_test.go
@@ -34,7 +34,11 @@ const assetsApp = "shop"
// example.com, and that person's CLI token.
func assetsFixture(t *testing.T, code string) (*consoleFixture, string) {
t.Helper()
- fx := newConsoleFixture(t)
+ // A secrets key, so NewServer's startup line about a missing one
+ // (logRegionConfig) does not run in every asset test's output.
+ fx := newConsoleFixtureConfigured(t, true, nil, func(cfg *Config) {
+ cfg.SecretsPub, _ = mustTestSecretsKey()
+ })
liftShipBudget(fx)
now := time.Now()
if err := fx.st.CreateAccount(shipAssetsAccountID, shipAssetsAccount, "Shop", "paul@keymail.dev", now); err != nil {
@@ -687,9 +691,9 @@ func TestAssetsStatusReportsTheWinningHomesBlock(t *testing.T) {
// at a higher stamp but has neither a public nor a usable private address
// is no dial target, so the edges use the lower-stamped reachable
// publisher, and status reports that publisher's block (#396). The
-// election is the edge's own (edgesfile.ElectHomes; internal/edge
-// TestStatusElectsTheSameHomeAsTheEdge holds the two together). Not
-// acceptance: the edges files are built by hand.
+// election is the edge's own (edgesfile.ElectHomesForEveryReader;
+// internal/edge TestStatusElectsTheSameHomeAsTheEdge holds the two
+// together). Not acceptance: the edges files are built by hand.
func TestAssetsStatusSkipsAHomeNoEdgeCanDial(t *testing.T) {
const host = "shop.example.com"
at := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
@@ -716,6 +720,51 @@ func TestAssetsStatusSkipsAHomeNoEdgeCanDial(t *testing.T) {
}
}
+// TestAssetsStatusIsUnknownWhereEdgesWouldDisagree: a higher-stamped box
+// with only a private address is the home for the edges of its own region
+// with region HA on, and no target for every other edge, which dials the
+// lower-stamped public box. The console is no edge, so it has no single
+// home to report for that host and its published columns are unknown; a
+// host every edge agrees on, in the same files, is still reported. Not
+// acceptance: the edges files are built by hand.
+func TestAssetsStatusIsUnknownWhereEdgesWouldDisagree(t *testing.T) {
+ at := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
+ fx, token := assetsFixture(t, "code-assets-status-split")
+ putAssetRecord(t, fx, "shop.example.com", "aaaaaaaaaaaaaaaa")
+ putAssetRecord(t, fx, "shop-2.example.com", "cccccccccccccccc")
+ putStatusEdges(t, fx, "box-a", map[string]any{
+ "shop.example.com": map[string]any{"role": "home", "stamp": 1, "assets": statusBlock([]string{"/assets/"}, "aaaaaaaaaaaaaaaa", at)},
+ "shop-2.example.com": map[string]any{"role": "home", "stamp": 1, "assets": statusBlock([]string{"/img/"}, "cccccccccccccccc", at)},
+ })
+ raw, err := json.Marshal(map[string]any{"v": 1, "box": "box-b", "eip": "", "private_ip": "10.0.1.2", "private_cidr": "10.0.0.0/16",
+ "region": "eu-west-1", "placement": "ie", "hosts": map[string]any{"shop.example.com": map[string]any{
+ "role": "home", "stamp": 9, "assets": statusBlock([]string{"/new/"}, "bbbbbbbbbbbbbbbb", at.Add(time.Hour))}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(context.Background(), "control/edges/box-b.json", raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ reply := getAssetStatus(t, fx, token)
+ if len(reply.Instances) != 2 {
+ t.Fatalf("status = %+v, want two instances", reply)
+ }
+ for _, in := range reply.Instances {
+ switch in.Host {
+ case "shop.example.com":
+ if !in.PublishedUnknown || in.PublishedGen != "" || in.PublishedAt != "" || len(in.Paths) != 0 || in.Gen != "aaaaaaaaaaaaaaaa" {
+ t.Errorf("%s = %+v, want unknown published columns and the record's gen", in.Host, in)
+ }
+ case "shop-2.example.com":
+ if in.PublishedUnknown || in.PublishedGen != "cccccccccccccccc" || !samePathList(in.Paths, []string{"/img/"}) {
+ t.Errorf("%s = %+v, want box-a's block, which every edge elects", in.Host, in)
+ }
+ default:
+ t.Errorf("unexpected instance %+v", in)
+ }
+ }
+}
+
// assetEdgesFailStore fails the edges files' read: the listing of the
// prefix when key is "", otherwise every Get of key.
type assetEdgesFailStore struct {
@@ -742,7 +791,9 @@ func (f assetEdgesFailStore) Get(ctx context.Context, key string) ([]byte, strin
// unread file may hold the winner), so every instance's published columns
// are unknown (published_unknown, which the CLI prints as EAC-26), never
// "publishes nothing". Each failure separately: an edges file whose GET
-// fails, a malformed one, and a listing that fails. The control read shows
+// fails, a malformed one, a well-formed one with a host entry that does not
+// decode (another host's, which an edge would lose the whole file over),
+// and a listing that fails. The control read shows
// the other state: a host whose winning entry publishes no block is known
// and empty ("-" in the CLI), not unknown. The records are still read and
// shown. Not acceptance: the edges files are built by hand.
@@ -762,6 +813,15 @@ func TestStatusShowsUnknownWhenTheEdgesFileCannotBeRead(t *testing.T) {
t.Fatal(err)
}
}},
+ {"a host entry that does not decode", func(t *testing.T, fx *consoleFixture) {
+ // Valid JSON and a versioned file, so the snapshot is complete;
+ // the edge's typed decoder refuses the whole file for the
+ // string stamp, and so does the door's election.
+ raw := []byte(`{"v":1,"box":"box-b","eip":"192.0.2.2","region":"ie","hosts":{"other.example.com":{"role":"home","stamp":"bad"}}}`)
+ if _, err := fx.rel.Put(context.Background(), broken, raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ }},
{"a listing that fails", func(t *testing.T, fx *consoleFixture) {
fx.srv.cfg.Releases = assetEdgesFailStore{Store: fx.rel}
}},
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index cfad24697..a4684bb0f 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -53,6 +53,13 @@ func newConsoleFixtureKeyed(t *testing.T, withKey bool) *consoleFixture {
// newConsoleFixtureOn is newConsoleFixtureKeyed over rel, when rel is not
// nil, instead of the fixture's seeded DirStore.
func newConsoleFixtureOn(t *testing.T, withKey bool, rel release.Store) *consoleFixture {
+ t.Helper()
+ return newConsoleFixtureConfigured(t, withKey, rel, nil)
+}
+
+// newConsoleFixtureConfigured is newConsoleFixtureOn with tweak, when it is
+// not nil, applied to the server's Config before NewServer reads it.
+func newConsoleFixtureConfigured(t *testing.T, withKey bool, rel release.Store, tweak func(*Config)) *consoleFixture {
t.Helper()
regPath, relStore, priv, pub := buildFixtures(t)
// A test that needs a real S3 store (TestDBForwardMinio) passes its own;
@@ -85,6 +92,9 @@ func newConsoleFixtureOn(t *testing.T, withKey bool, rel release.Store) *console
if withKey {
cfg.Key = priv
}
+ if tweak != nil {
+ tweak(&cfg)
+ }
srv, err = NewServer(cfg, st)
if err != nil {
t.Fatal(err)
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 62dd74315..81f681598 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -137,7 +137,7 @@ type edgesFileView struct {
EIP string `json:"eip"`
Hosts map[string]edgesHostView `json:"hosts"`
// PrivateIP, PrivateCIDR, Region and Placement choose the dial address
- // (region HA spec 2 §6, dialAddress). All are absent from a writer that
+ // (region HA spec 2 §6, edgesfile.Reader.Dial). All are absent from a writer that
// predates them, and the dial is then EIP, as before.
PrivateIP string `json:"private_ip"`
PrivateCIDR string `json:"private_cidr"`
@@ -145,17 +145,6 @@ type edgesFileView struct {
Placement string `json:"placement"`
}
-// dialAddress is where this edge dials f's box: edgesfile.DialAddress, the
-// rule the console's status door also elects a home by (#396). With
-// privateDial (this edge's own region HA switch) on, a box in this box's
-// own region and placement is dialled at its private address when it
-// passes this box's network; every other box at its public address. self
-// is this box's own file, which selfKnown says was found. "" is nothing to
-// dial.
-func dialAddress(f, self edgesFileView, selfKnown, privateDial bool) string {
- return edgesfile.DialAddress(f.dialPoint(), self.dialPoint(), selfKnown, privateDial)
-}
-
// dialPoint is f's dial fields, as edgesfile reads them.
func (f edgesFileView) dialPoint() edgesfile.DialPoint {
return edgesfile.DialPoint{EIP: f.EIP, PrivateIP: f.PrivateIP, PrivateCIDR: f.PrivateCIDR, Region: f.Region, Placement: f.Placement}
@@ -209,7 +198,7 @@ type edgesAssetsView struct {
// homeEntry is one folded answer: where to dial, and which box that is.
type homeEntry struct {
- // eip is the address to dial: dialAddress's answer, the home box's
+ // eip is the address to dial: edgesfile.Reader.Dial's answer, the home box's
// private address within its region and its EIP from anywhere else.
eip string
box string
@@ -304,7 +293,7 @@ type homeMap struct {
keyNext []byte
// privateDial is this edge's region HA switch: only with it on does
- // the fold dial a same-region box's private address (dialAddress).
+ // the fold dial a same-region box's private address (edgesfile.Reader.Dial).
privateDial bool
// health is the load balancer health state (region HA spec 2 §6),
@@ -755,7 +744,7 @@ func (m *homeMap) logPartialPoll(failed, tried int, err error) {
// publisher stamps and what self is derived to match.
// - NO DIAL ADDRESS. Task 1 publishes a box with no discoverable public IP
// as eip:"" so the DR runbook still gets its hosts list. There is
-// nothing to dial, so it is not a target. The address is dialAddress's:
+// nothing to dial, so it is not a target. The address is edgesfile.Reader.Dial's:
// a box in this box's own region is dialled at its private address when
// it publishes one (region HA spec 2 §6), every other at its EIP.
// - A ROLE THIS BUILD DOES NOT KNOW. Only "home" routes. The role field
@@ -770,9 +759,12 @@ func (m *homeMap) logPartialPoll(failed, tried int, err error) {
// on the next publish, where half the fleet aiming at each is a condition that
// looks fine from any single box.
//
-// The console's status door elects through edgesfile.ElectHomes, which
-// takes the same order, the same dial rule and the same HomeBeats, so it
-// names the home this fold dials (#396).
+// The dial rule and the order are shared with the console's status door
+// (#396): this fold dials through edgesfile.Reader.Dial with this edge's
+// own reader context (its box, its own file's network, its region HA
+// switch) and orders claims by edgesfile.HomeBeats; the door elects
+// through edgesfile.ElectHomesForEveryReader, the same election for every
+// kind of reader.
func foldHomes(files map[string]edgesFileView, self string, privateDial bool) (map[string]homeEntry, []string) {
keys := make([]string, 0, len(files))
for k := range files {
@@ -786,13 +778,14 @@ func foldHomes(files map[string]edgesFileView, self string, privateDial bool) (m
own, ownKnown = f, true
}
}
+ reader := edgesfile.Reader{Box: self, Self: own.dialPoint(), SelfKnown: ownKnown, PrivateDial: privateDial}
hosts := make(map[string]homeEntry)
for _, k := range keys {
f := files[k]
if f.Box == "" || f.Box == self {
continue
}
- addr := dialAddress(f, own, ownKnown, privateDial)
+ addr := reader.Dial(f.dialPoint())
for host, h := range f.Hosts {
if host == "" {
continue
diff --git a/internal/edge/homemap_status_election_test.go b/internal/edge/homemap_status_election_test.go
index 5a18b87a7..8efc74ec2 100644
--- a/internal/edge/homemap_status_election_test.go
+++ b/internal/edge/homemap_status_election_test.go
@@ -10,19 +10,21 @@ import (
)
// TestStatusElectsTheSameHomeAsTheEdge: the console's status door elects a
-// host's home through edgesfile.ElectHomes, over the files edgesfile's
-// ReadSnapshot reads (#396). For every row, one store holds the edges
-// files, a real homeMap refreshes from it and folds them (foldHomes), and
-// ElectHomes elects from a ReadSnapshot of the same store: both must name
-// the same winning box and the same assets block, or both no winner.
+// host's home through edgesfile.ElectHomesForEveryReader, over the files
+// edgesfile's ReadSnapshot reads (#396). For every row and every reader, one
+// store holds the edges files and the reader's own file; a real homeMap for
+// that reader refreshes from it and folds them (foldHomes); the door's
+// election runs over a ReadSnapshot of the same store. The door must show
+// the edge's answer (the same winning box and block, or no winner) or
+// unknown, and never another home's answer. Each row also pins which of
+// the two the door shows, so a door that said unknown everywhere fails.
//
-// The reader is a box that homes nothing, so the fold's own-box exclusion
-// plays no part, as the console has no box of its own. Each row runs with
-// the reader's region HA off and on, except the rows about a box with only
-// a private address: only an edge in that box's own region with region HA
-// on can dial it, so those rows run for that reader alone (ElectHomes
-// counts a box any edge can dial; an edge in another region dials only
-// public addresses and cannot reach it at all).
+// The readers are four edges that home nothing, so the fold's own-box
+// exclusion plays no part: one on the eu-west-1/ie network 10.0.0.0/16
+// with region HA on and off, and one in us-east-1 with region HA on and
+// off. Only the first can dial a private address on that network, so a
+// row with a private-only box is where they differ, and the door, which
+// has no reader of its own, says unknown there.
//
// Not acceptance: the files are written by hand, not by the box's
// edgesFilePass.
@@ -38,108 +40,139 @@ func TestStatusElectsTheSameHomeAsTheEdge(t *testing.T) {
return fmt.Sprintf(`{"v":1,"box":%q,"eip":"","private_ip":%q,"private_cidr":"10.0.0.0/16","region":"eu-west-1","placement":"ie","hosts":{%q:{%s}}}`, box, privateIP, host, entry)
}
const owner = `"account":"acct1","app":"shop"`
+ const unknown = "(unknown)"
rows := []struct {
- name string
- files map[string]string // bucket key name -> body
- wantBox string // "" = no winner
- inRegionOnly bool
+ name string
+ files map[string]string // bucket key name -> body
+ // edgeHA is the in-region region HA reader's winner, edge every
+ // other reader's; "" = no winner.
+ edge, edgeHA string
+ // door is what the door shows: a box, "" for no winner, or unknown.
+ door string
}{
{"the higher stamp wins",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/old/", "aaaaaaaaaaaaaaaa", 1761382800)),
"box-b": public("box-b", "192.0.2.2", `"role":"home","stamp":2,`+owner+`,`+block("/assets/", "bbbbbbbbbbbbbbbb", 1761381000)),
- }, "box-b", false},
+ }, "box-b", "box-b", "box-b"},
{"an undialable higher-stamped box loses to the reachable publisher",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
"box-b": public("box-b", "", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "box-a", false},
+ }, "box-a", "box-a", "box-a"},
{"an undialable box earlier in key order does not hold the host",
map[string]string{
"box-a": public("box-a", "", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "aaaaaaaaaaaaaaaa", 1761382800)),
"box-b": public("box-b", "192.0.2.2", `"role":"home",`+owner),
- }, "box-b", false},
+ }, "box-b", "box-b", "box-b"},
{"a private address that fails validation is no address",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
"box-b": privateOnly("box-b", "169.254.169.254", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "box-a", false},
+ }, "box-a", "box-a", "box-a"},
{"only an undialable box publishes the host",
map[string]string{
"box-b": public("box-b", "", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "", false},
+ }, "", "", ""},
{"a winning entry without assets publishes none",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761382800)),
"box-b": public("box-b", "192.0.2.2", `"role":"home","stamp":2,`+owner),
- }, "box-b", false},
+ }, "box-b", "box-b", "box-b"},
{"a route beats an alias with a higher stamp",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home",`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
"box-b": public("box-b", "192.0.2.2", `"role":"home","alias":true,"stamp":9,`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "box-a", false},
+ }, "box-a", "box-a", "box-a"},
{"equal stamps keep the first file in key order",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":3,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
"box-b": public("box-b", "192.0.2.2", `"role":"home","stamp":3,`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "box-a", false},
+ }, "box-a", "box-a", "box-a"},
{"key order is the bucket key's, not the box field's",
map[string]string{
"aaa": public("zed", "192.0.2.1", `"role":"home",`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
"zzz": public("amy", "192.0.2.2", `"role":"home",`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "zed", false},
+ }, "zed", "zed", "zed"},
{"a role this build does not know takes no part",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
"box-b": public("box-b", "192.0.2.2", `"role":"read","stamp":9,`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "box-a", false},
- {"a higher-stamped box with only a private address wins in its region",
+ }, "box-a", "box-a", "box-a"},
+ {"a higher-stamped private-only box wins only inside its region",
map[string]string{
"box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
"box-b": privateOnly("box-b", "10.0.1.2", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
- }, "box-b", true},
+ }, "box-a", "box-b", unknown},
+ {"a private-only box alone is a home inside its region only",
+ map[string]string{
+ "box-b": privateOnly("box-b", "10.0.1.2", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "", "box-b", unknown},
+ {"a host entry the edge cannot decode costs the edge that file",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "box-b": public("box-b", "192.0.2.2", `"role":"home","stamp":"bad",`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "box-a", "box-a", unknown},
+ }
+ readers := []struct {
+ name, file string
+ privateDial bool
+ inRegionHA bool
+ }{
+ {"in-region/regionHA=on", `{"v":1,"box":"reader","eip":"192.0.2.9","private_ip":"10.0.1.9","private_cidr":"10.0.0.0/16","region":"eu-west-1","placement":"ie","hosts":{}}`, true, true},
+ {"in-region/regionHA=off", `{"v":1,"box":"reader","eip":"192.0.2.9","private_ip":"10.0.1.9","private_cidr":"10.0.0.0/16","region":"eu-west-1","placement":"ie","hosts":{}}`, false, false},
+ {"another-region/regionHA=on", `{"v":1,"box":"reader","eip":"198.51.100.9","private_ip":"10.5.1.9","private_cidr":"10.5.0.0/16","region":"us-east-1","placement":"us","hosts":{}}`, true, false},
+ {"another-region/regionHA=off", `{"v":1,"box":"reader","eip":"198.51.100.9","private_ip":"10.5.1.9","private_cidr":"10.5.0.0/16","region":"us-east-1","placement":"us","hosts":{}}`, false, false},
}
- // The reader: in eu-west-1/ie on 10.0.0.0/16, homing nothing.
- const reader = `{"v":1,"box":"reader","eip":"192.0.2.9","private_ip":"10.0.1.9","private_cidr":"10.0.0.0/16","region":"eu-west-1","placement":"ie","hosts":{}}`
for _, row := range rows {
- for _, privateDial := range []bool{false, true} {
- if row.inRegionOnly && !privateDial {
- continue
- }
- t.Run(fmt.Sprintf("%s/regionHA=%v", row.name, privateDial), func(t *testing.T) {
+ for _, rd := range readers {
+ t.Run(row.name+"/"+rd.name, func(t *testing.T) {
s := meshTestStore(t)
- putJSON(t, s, "control/edges/reader.json", reader)
+ putJSON(t, s, "control/edges/reader.json", rd.file)
for name, body := range row.files {
putJSON(t, s, "control/edges/"+name+".json", body)
}
m := newHomeMap(s, "reader")
- m.privateDial = privateDial
+ m.privateDial = rd.privateDial
+ // A file the edge cannot parse is a partial poll, not a
+ // failed refresh: Refresh still succeeds.
refreshHomeMap(t, m)
edgeBox, edgeAssets := "", (*edgesAssetsView)(nil)
if h, ok := m.snapshot().hosts[host]; ok && h.dial {
edgeBox, edgeAssets = h.box, h.assets
}
+ wantEdge := row.edge
+ if rd.inRegionHA {
+ wantEdge = row.edgeHA
+ }
+ if edgeBox != wantEdge {
+ t.Fatalf("the home map elects %q, want %q", edgeBox, wantEdge)
+ }
snap, err := edgesfile.ReadSnapshot(context.Background(), s)
if err != nil || !snap.Complete {
t.Fatalf("ReadSnapshot = complete %v, %v", snap.Complete, err)
}
- won, statusHas := edgesfile.ElectHomes(snap.Files)[host]
-
- if edgeBox != row.wantBox {
- t.Fatalf("the home map elects %q, want %q", edgeBox, row.wantBox)
+ door := unknown
+ won, split, err := edgesfile.ElectHomesForEveryReader(snap.Files)
+ var doorAssets *edgesfile.HostAssets
+ if err == nil && !split[host] {
+ door, doorAssets = won[host].Box, won[host].Assets
}
- if !statusHas {
- if edgeBox != "" {
- t.Fatalf("the status door elects no home, the home map elects %q", edgeBox)
+ if door == unknown {
+ if row.door != unknown {
+ t.Fatalf("the door shows unknown (err %v), want %q", err, row.door)
}
return
}
- if won.Box != edgeBox {
- t.Fatalf("the status door elects %q, the home map elects %q", won.Box, edgeBox)
+ if door != edgeBox {
+ t.Fatalf("the door shows %q's answer, the home map elects %q", door, edgeBox)
+ }
+ if !sameAssetsBlock(doorAssets, edgeAssets) {
+ t.Fatalf("the door reports %+v, the home map holds %+v", doorAssets, edgeAssets)
}
- if !sameAssetsBlock(won.Assets, edgeAssets) {
- t.Fatalf("the status door reports %+v, the home map holds %+v", won.Assets, edgeAssets)
+ if door != row.door {
+ t.Fatalf("the door shows %q, want %q", door, row.door)
}
})
}
diff --git a/internal/edgesfile/homeelect.go b/internal/edgesfile/homeelect.go
index bb0fd6c97..685303ce4 100644
--- a/internal/edgesfile/homeelect.go
+++ b/internal/edgesfile/homeelect.go
@@ -2,6 +2,7 @@ package edgesfile
import (
"encoding/json"
+ "fmt"
"slices"
"strings"
)
@@ -11,8 +12,16 @@ import (
// foldHomes) and the console's `carlos assets status` door both decide it
// here, so the status door names the box an edge dials (#396). The edge
// keeps its own decoder and its own fold, because the fold also merges
-// classes and excludes the edge's own box; what it shares is the rule
-// (HomeBeats) and who may take part (DialAddress).
+// classes; what it shares is the rule (HomeBeats) and who may take part
+// for a given reader (Reader.Dial).
+//
+// The answer depends on the reader. An edge with region HA on, in a box's
+// own region and network, can dial that box's private address; every other
+// edge dials public addresses only. A box with only a private address is
+// therefore a candidate for some edges and not for others, and the winner
+// can differ between them. The console is no edge and has no reader of its
+// own, so it elects for every kind of reader the files imply
+// (ElectHomesForEveryReader) and treats a disagreement as unknown.
// DialPoint is the part of a box's file that says where it can be dialled:
// its public address, its private address and network (region HA spec 2
@@ -26,22 +35,32 @@ type DialPoint struct {
Placement string
}
-// DialAddress is where a reader dials f's box (region HA spec 2 §6). With
-// privateDial (the reader's own region HA switch) on, a box that publishes
-// the same AWS region and placement as the reader is dialled at its
-// private address, so the dial stays inside the region's network, but only
-// when that address passes PrivateAddress against the network the reader's
-// own file publishes (census ruling region-ha-2a). The home's placement
-// code is "", so two home boxes share a placement as two boxes of one named
-// region do; a home box and a named one never do. Every other box, and
-// every box with privateDial off, is dialled at its public address. self is
-// the reader's own file, which selfKnown says was found. "" is nothing to
-// dial, and a home entry of a box with nothing to dial takes no part in
-// the election.
-func DialAddress(f, self DialPoint, selfKnown, privateDial bool) string {
- if privateDial && selfKnown && f.Region != "" &&
- f.Region == self.Region && f.Placement == self.Placement {
- if addr, _ := PrivateAddress(f.PrivateIP, []string{self.PrivateCIDR}); addr != "" {
+// Reader is the edge an election is made for: its own box, whose entries
+// it serves itself and never elects; its own file's dial point, which
+// SelfKnown says was found; and its region HA switch, PrivateDial. The zero
+// Reader is an edge with no own box, file or region HA: it dials public
+// addresses only.
+type Reader struct {
+ Box string
+ Self DialPoint
+ SelfKnown bool
+ PrivateDial bool
+}
+
+// Dial is where r dials f's box (region HA spec 2 §6). With r's region HA
+// on, a box that publishes the same AWS region and placement as r is
+// dialled at its private address, so the dial stays inside the region's
+// network, but only when that address passes PrivateAddress against the
+// network r's own file publishes (census ruling region-ha-2a). The home's
+// placement code is "", so two home boxes share a placement as two boxes
+// of one named region do; a home box and a named one never do. Every other
+// box, and every box with region HA off, is dialled at its public address.
+// "" is nothing to dial, and a home entry of a box with nothing to dial
+// takes no part in r's election.
+func (r Reader) Dial(f DialPoint) string {
+ if r.PrivateDial && r.SelfKnown && f.Region != "" &&
+ f.Region == r.Self.Region && f.Placement == r.Self.Placement {
+ if addr, _ := PrivateAddress(f.PrivateIP, []string{r.Self.PrivateCIDR}); addr != "" {
return addr
}
}
@@ -84,15 +103,6 @@ func HomeBeats(in, prev HomeClaim) bool {
return in.Stamp > prev.Stamp
}
-// Dialable reports whether some edge can dial f's box: DialAddress's answer
-// for the best-placed reader, an edge in the box's own region and
-// placement on its network with region HA on. A box with a public address
-// is dialable from anywhere; a box with only a private address is dialable
-// from inside its region; a box with neither is dialable from nowhere.
-func Dialable(f DialPoint) bool {
- return DialAddress(f, f, true, true) != ""
-}
-
// Elected is a host's winning home entry: the box that published it and
// its assets block, nil when the winner publishes none. The block is the
// winner's whole, never merged with a losing box's.
@@ -101,23 +111,33 @@ type Elected struct {
Assets *HostAssets
}
-// electedEntry is the part of a host entry the election reads, beside the
-// reader's Host: the installation stamp the writer publishes.
+// electedEntry is a host entry decoded with every field the edge's own
+// decoder types (internal/edge homemap.go edgesHostView): the reader's Host
+// plus the owner and the installation stamp. An entry this does not decode
+// is one the edge cannot decode either.
type electedEntry struct {
Host
- Stamp int64 `json:"stamp"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Stamp int64 `json:"stamp"`
}
-// ElectHomes is the election as a reader that is no box (the console)
-// makes it: host -> the winning home entry, over files read by ReadSnapshot.
-// Files are taken in bucket-key order (PlacementView.Key, or Key(Box) for
-// a view built by hand), as the edge's fold takes them. Only a home-role entry of
-// a Dialable box is a claim; claims are ordered by HomeBeats. A reader that
-// is no box has no own box to leave out and no region of its own, so it
-// counts every box some edge can dial (Dialable): a box with only a private
-// address takes part, as it does for the edges of its own region. A host
-// entry that does not decode is skipped, as ReadSnapshot skips a file.
-func ElectHomes(files []PlacementView) map[string]Elected {
+// electFile is one file's entries, decoded once for every reader.
+type electFile struct {
+ key string
+ box string
+ dial DialPoint
+ hosts map[string]electedEntry
+}
+
+// decodeForElection decodes every host entry of every file, in bucket-key
+// order (PlacementView.Key, or Key(Box) for a view built by hand), as the
+// edge's fold takes them. Any entry that does not decode is an error: the
+// edge's decoder types the whole file, so one bad entry, under any role and
+// on any box, costs the edge that whole file (it keeps the file's previous
+// parse, or has none), and an election that skipped the entry instead
+// would answer for a file the edge is not reading.
+func decodeForElection(files []PlacementView) ([]electFile, error) {
sorted := slices.Clone(files)
key := func(f PlacementView) string {
if f.Key != "" {
@@ -126,25 +146,43 @@ func ElectHomes(files []PlacementView) map[string]Elected {
return Key(f.Box)
}
slices.SortStableFunc(sorted, func(a, b PlacementView) int { return strings.Compare(key(a), key(b)) })
+ out := make([]electFile, 0, len(sorted))
+ for _, f := range sorted {
+ ef := electFile{key: key(f), box: f.Box, dial: f.DialPoint(), hosts: make(map[string]electedEntry, len(f.Hosts))}
+ for host, raw := range f.Hosts {
+ var in electedEntry
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return nil, fmt.Errorf("edgesfile: %s: host %q: %w", ef.key, host, err)
+ }
+ ef.hosts[host] = in
+ }
+ out = append(out, ef)
+ }
+ return out, nil
+}
+
+// elect is the election for r over decoded files: only a home-role entry
+// of a box r can dial, other than r's own, is a claim, and claims are
+// ordered by HomeBeats.
+func elect(files []electFile, r Reader) map[string]Elected {
type held struct {
claim HomeClaim
e Elected
}
won := map[string]held{}
- for _, f := range sorted {
- if f.Box == "" || !Dialable(f.DialPoint()) {
+ for _, f := range files {
+ if f.box == "" || f.box == r.Box || r.Dial(f.dial) == "" {
continue
}
- for host, raw := range f.Hosts {
- var in electedEntry
- if host == "" || json.Unmarshal(raw, &in) != nil || in.Role != RoleHome {
+ for host, in := range f.hosts {
+ if host == "" || in.Role != RoleHome {
continue
}
c := HomeClaim{Dial: true, Alias: in.Alias, Stamp: in.Stamp}
if prev, ok := won[host]; ok && !HomeBeats(c, prev.claim) {
continue
}
- won[host] = held{claim: c, e: Elected{Box: f.Box, Assets: in.Assets}}
+ won[host] = held{claim: c, e: Elected{Box: f.box, Assets: in.Assets}}
}
}
out := make(map[string]Elected, len(won))
@@ -154,6 +192,72 @@ func ElectHomes(files []PlacementView) map[string]Elected {
return out
}
+// ElectHomes is the election r makes over files read by ReadSnapshot:
+// host -> the winning home entry. The error is a host entry that does not
+// decode, which leaves nothing to say about any host (decodeForElection).
+func ElectHomes(files []PlacementView, r Reader) (map[string]Elected, error) {
+ decoded, err := decodeForElection(files)
+ if err != nil {
+ return nil, err
+ }
+ return elect(decoded, r), nil
+}
+
+// Readers is every kind of edge whose election the files can tell apart,
+// for a caller that is no edge: one that dials public addresses only (an
+// edge in another region, or with region HA off, or without its own file),
+// and, for each region network a file publishes, an edge on that network
+// with region HA on. The readers own no box, so none is left out of its own
+// election; the box an instance is homed on serves it itself either way.
+func Readers(files []PlacementView) []Reader {
+ out := []Reader{{}}
+ seen := map[DialPoint]bool{}
+ for _, f := range files {
+ if f.Region == "" {
+ continue
+ }
+ net := DialPoint{Region: f.Region, Placement: f.Placement, PrivateCIDR: f.PrivateCIDR}
+ if seen[net] {
+ continue
+ }
+ seen[net] = true
+ out = append(out, Reader{Self: net, SelfKnown: true, PrivateDial: true})
+ }
+ return out
+}
+
+// ElectHomesForEveryReader is the election as a caller that is no edge
+// (the console) can report it: host -> the winning home entry when every
+// reader in Readers elects the same box for it, and split[host] when two
+// readers elect different boxes, or one elects a box and another none. A
+// split host has no single home to report. The error is ElectHomes'.
+func ElectHomesForEveryReader(files []PlacementView) (won map[string]Elected, split map[string]bool, err error) {
+ decoded, err := decodeForElection(files)
+ if err != nil {
+ return nil, nil, err
+ }
+ readers := Readers(files)
+ won = elect(decoded, readers[0])
+ split = map[string]bool{}
+ for _, r := range readers[1:] {
+ other := elect(decoded, r)
+ for host, e := range other {
+ if w, ok := won[host]; !ok || w.Box != e.Box {
+ split[host] = true
+ }
+ }
+ for host := range won {
+ if _, ok := other[host]; !ok {
+ split[host] = true
+ }
+ }
+ }
+ for host := range split {
+ delete(won, host)
+ }
+ return won, split, nil
+}
+
// DialPoint is f's dial fields.
func (f PlacementView) DialPoint() DialPoint {
return DialPoint{EIP: f.EIP, PrivateIP: f.PrivateIP, PrivateCIDR: f.PrivateCIDR, Region: f.Region, Placement: f.Placement}
diff --git a/internal/edgesfile/homeelect_test.go b/internal/edgesfile/homeelect_test.go
index b08c1021d..2feae9e22 100644
--- a/internal/edgesfile/homeelect_test.go
+++ b/internal/edgesfile/homeelect_test.go
@@ -2,43 +2,134 @@ package edgesfile
import (
"context"
+ "encoding/json"
+ "slices"
+ "strings"
"testing"
"github.com/carlosframework/platform/internal/release"
)
-// TestDialableIsDialAddressForSomeReader: a box is Dialable exactly when
-// DialAddress answers an address for the best-placed reader, and that is
-// what the status door's election counts (#396). A public address is
-// dialable from anywhere, a valid private address from its own region, and
-// a box with neither, or with a private address that fails PrivateAddress
-// (the metadata range, a malformed one, one outside its own network, or no
-// region to match on), from nowhere.
-func TestDialableIsDialAddressForSomeReader(t *testing.T) {
+// TestReaderDialIsTheReadersOwn: where a reader dials a box depends on the
+// reader. An edge on the box's own region network with region HA on dials
+// a valid private address; the same edge with region HA off, an edge in
+// another region, and an edge without its own file dial the public
+// address, which may be nothing.
+func TestReaderDialIsTheReadersOwn(t *testing.T) {
+ ie := DialPoint{Region: "eu-west-1", Placement: "ie", PrivateCIDR: "10.0.0.0/16"}
+ inRegion := Reader{Self: ie, SelfKnown: true, PrivateDial: true}
cases := []struct {
- name string
- f DialPoint
- want bool
+ name string
+ f DialPoint
+ inRegion, elsewise string
}{
- {"a public address", DialPoint{EIP: "192.0.2.1"}, true},
- {"a public address and a private one", DialPoint{EIP: "192.0.2.1", PrivateIP: "10.0.1.2", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1"}, true},
- {"a private address alone", DialPoint{PrivateIP: "10.0.1.2", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1", Placement: "ie"}, true},
- {"neither", DialPoint{Region: "eu-west-1", Placement: "ie"}, false},
- {"a private address with no region", DialPoint{PrivateIP: "10.0.1.2", PrivateCIDR: "10.0.0.0/16"}, false},
- {"the metadata range", DialPoint{PrivateIP: "169.254.169.254", PrivateCIDR: "169.254.0.0/16", Region: "eu-west-1"}, false},
- {"a malformed private address", DialPoint{PrivateIP: "10.0.1", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1"}, false},
- {"a private address outside its own network", DialPoint{PrivateIP: "10.9.1.2", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1"}, false},
+ {"a public address", DialPoint{EIP: "192.0.2.1"}, "192.0.2.1", "192.0.2.1"},
+ {"both, in the region", DialPoint{EIP: "192.0.2.1", PrivateIP: "10.0.1.2", Region: "eu-west-1", Placement: "ie"}, "10.0.1.2", "192.0.2.1"},
+ {"a private address alone", DialPoint{PrivateIP: "10.0.1.2", Region: "eu-west-1", Placement: "ie"}, "10.0.1.2", ""},
+ {"another placement", DialPoint{PrivateIP: "10.0.1.2", Region: "eu-west-1", Placement: "fleet/shop"}, "", ""},
+ {"the metadata range", DialPoint{PrivateIP: "169.254.169.254", Region: "eu-west-1", Placement: "ie"}, "", ""},
+ {"outside the reader's network", DialPoint{PrivateIP: "10.9.1.2", Region: "eu-west-1", Placement: "ie"}, "", ""},
+ {"neither", DialPoint{Region: "eu-west-1", Placement: "ie"}, "", ""},
+ }
+ others := map[string]Reader{
+ "region HA off": {Self: ie, SelfKnown: true},
+ "another region": {Self: DialPoint{Region: "us-east-1", Placement: "us", PrivateCIDR: "10.0.0.0/16"}, SelfKnown: true, PrivateDial: true},
+ "no own file": {Self: ie, PrivateDial: true},
+ "the zero value": {},
}
for _, c := range cases {
- t.Run(c.name, func(t *testing.T) {
- if got := Dialable(c.f); got != c.want {
- t.Fatalf("Dialable(%+v) = %v, want %v", c.f, got, c.want)
- }
- // An edge in another region dials the public address alone.
- if got := DialAddress(c.f, DialPoint{Region: "us-east-1"}, true, true); got != c.f.EIP {
- t.Fatalf("from another region: DialAddress = %q, want the public %q", got, c.f.EIP)
+ if got := inRegion.Dial(c.f); got != c.inRegion {
+ t.Errorf("%s: in-region reader dials %q, want %q", c.name, got, c.inRegion)
+ }
+ for name, r := range others {
+ if got := r.Dial(c.f); got != c.elsewise {
+ t.Errorf("%s: %s reader dials %q, want %q", c.name, name, got, c.elsewise)
}
- })
+ }
+ }
+}
+
+// TestReadersAreThePublicOneAndOnePerNetwork: the public-only reader, then
+// one region HA reader per region network the files publish.
+func TestReadersAreThePublicOneAndOnePerNetwork(t *testing.T) {
+ files := []PlacementView{
+ {Box: "a", EIP: "192.0.2.1"},
+ {Box: "b", Region: "eu-west-1", Placement: "ie", PrivateCIDR: "10.0.0.0/16"},
+ {Box: "c", Region: "eu-west-1", Placement: "ie", PrivateCIDR: "10.0.0.0/16"},
+ {Box: "d", Region: "eu-west-2", Placement: "uk", PrivateCIDR: "10.1.0.0/16"},
+ }
+ got := Readers(files)
+ want := []Reader{
+ {},
+ {Self: DialPoint{Region: "eu-west-1", Placement: "ie", PrivateCIDR: "10.0.0.0/16"}, SelfKnown: true, PrivateDial: true},
+ {Self: DialPoint{Region: "eu-west-2", Placement: "uk", PrivateCIDR: "10.1.0.0/16"}, SelfKnown: true, PrivateDial: true},
+ }
+ if !slices.Equal(got, want) {
+ t.Fatalf("Readers = %+v, want %+v", got, want)
+ }
+}
+
+func viewOf(t *testing.T, key, body string) PlacementView {
+ t.Helper()
+ var f PlacementView
+ if err := json.Unmarshal([]byte(body), &f); err != nil {
+ t.Fatal(err)
+ }
+ f.Key = key
+ return f
+}
+
+// TestElectHomesForEveryReaderSplitsWhereReadersDisagree: a host whose
+// winner is the same for every reader is reported; a host a private-only
+// box wins for its own region's edges, while every other edge elects the
+// public box, is split and not reported; so is a host only a private-only
+// box publishes (one reader elects it, another elects none).
+func TestElectHomesForEveryReaderSplitsWhereReadersDisagree(t *testing.T) {
+ files := []PlacementView{
+ viewOf(t, Prefix+"a.json", `{"v":1,"box":"a","eip":"192.0.2.1","region":"eu-west-1","placement":"ie","private_ip":"10.0.1.1","private_cidr":"10.0.0.0/16","hosts":{
+ "same.example.com":{"role":"home","stamp":5},
+ "split.example.com":{"role":"home","stamp":1}}}`),
+ viewOf(t, Prefix+"b.json", `{"v":1,"box":"b","eip":"","region":"eu-west-1","placement":"ie","private_ip":"10.0.1.2","private_cidr":"10.0.0.0/16","hosts":{
+ "same.example.com":{"role":"home","stamp":2},
+ "split.example.com":{"role":"home","stamp":9},
+ "private.example.com":{"role":"home"}}}`),
+ }
+ won, split, err := ElectHomesForEveryReader(files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := won["same.example.com"].Box; got != "a" || split["same.example.com"] {
+ t.Errorf("same.example.com = %q split %v, want a, agreed", got, split["same.example.com"])
+ }
+ for _, host := range []string{"split.example.com", "private.example.com"} {
+ if _, ok := won[host]; ok || !split[host] {
+ t.Errorf("%s: won %v, split %v, want split and not reported", host, ok, split[host])
+ }
+ }
+}
+
+// TestElectionRefusesAHostEntryThatDoesNotDecode: the edge decodes each
+// file whole, so an entry it cannot type (a string stamp, an object where a
+// path list belongs, a bare string for an entry) costs it the whole file.
+// The election refuses rather than skipping the entry, under any role.
+func TestElectionRefusesAHostEntryThatDoesNotDecode(t *testing.T) {
+ for _, entry := range []string{
+ `{"role":"home","stamp":"bad"}`,
+ `{"role":"read","stamp":"bad"}`,
+ `{"role":"home","assets":{"paths":"/assets/"}}`,
+ `{"role":"home","account":7}`,
+ `"home"`,
+ } {
+ files := []PlacementView{
+ viewOf(t, Prefix+"a.json", `{"v":1,"box":"a","eip":"192.0.2.1","hosts":{"shop.example.com":{"role":"home"}}}`),
+ viewOf(t, Prefix+"b.json", `{"v":1,"box":"b","eip":"192.0.2.2","hosts":{"other.example.com":`+entry+`}}`),
+ }
+ if _, err := ElectHomes(files, Reader{}); err == nil || !strings.Contains(err.Error(), "other.example.com") {
+ t.Errorf("entry %s: ElectHomes err = %v, want one naming the host", entry, err)
+ }
+ if _, _, err := ElectHomesForEveryReader(files); err == nil {
+ t.Errorf("entry %s: ElectHomesForEveryReader answered", entry)
+ }
}
}
@@ -62,7 +153,11 @@ func TestReadSnapshotKeepsEachFilesKey(t *testing.T) {
t.Errorf("%s: Key = %q, want %q", f.Box, f.Key, want)
}
}
- if got := ElectHomes(snap.Files)["shop.example.com"].Box; got != "zed" {
+ won, err := ElectHomes(snap.Files, Reader{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := won["shop.example.com"].Box; got != "zed" {
t.Errorf("unstamped duplicates elect %q, want zed, the first file in key order", got)
}
}