package hostclaim import ( "context" "encoding/json" "fmt" "slices" "strconv" "github.com/carlosframework/platform/internal/regionname" "github.com/carlosframework/platform/internal/release" ) const KindRelocating = "relocating" // PreFlipGuard verifies the durable pre-flip conversion decision in the // authoritative instance record. That decision's record CAS competes with // MoveFlip and makes the move terminal for every cutting/flip transition. // It preserves the old move journal for replay, and binds this op, incarnation, // source and exact fence reference. A snapshot of an undecided record is not // an implementation of this interface. While the claim is moving the source // is its "source" and the region is the record's; once relocating they are // its "source_box" and "region". The returned region is the verified engine // identity of the record placement, never an empty placement code. type PreFlipGuard interface { CheckMovingBeforeFlip(context.Context, Observed, string, FenceRef) (string, error) } // RelocationRecoveryOwner reports replay ownership, never execution authority. func RelocationRecoveryOwner(c *Claim) (string, error) { if c == nil || c.Op.Kind != KindRelocating || c.Op.Intent["region"] == "" { return "", ErrWrongState } return "region:" + c.Op.Intent["region"], nil } func validateRelocating(c *Claim) error { if c.Op.Kind != KindRelocating { return nil } if c.Holder == nil || c.Op.Intent["region"] == "" || !validBoxReference(c.Op.Intent["source_box"]) || c.Op.Intent["source_box"] == "none" { return ErrMalformed } switch c.Op.Phase { case "starting", "releasing": if c.Op.Exec != c.Op.Intent["source_box"] && c.Op.Exec != "none" { return ErrMalformed } case "pinning": if c.Op.Exec != "none" { return ErrMalformed } case "installing", "installed", "probing", "probe-failed", "serving": if !validBoxReference(c.Op.Exec) || c.Op.Exec == "none" || c.Op.Exec != c.Op.Intent["target_box"] { return ErrMalformed } default: return ErrMalformed } return nil } // ConvertMovingToRelocating performs exactly one claim CAS. It deliberately // exposes no transition capable of granting relocation execution. Callers must // be claim-enabled and first persist the record conversion decision. func ConvertMovingToRelocating(ctx context.Context, s release.Store, observed Observed, opID string, ref FenceRef, authority FenceAuthority, guard PreFlipGuard) (Observed, error) { if guard == nil || observed.Absent || observed.Claim == nil || observed.ETag == "" { return Observed{}, ErrWrongState } before := observed.Claim if opID == "" || before.Op.ID != opID { return Observed{}, ErrStaleOp } // The move's own intent, as BeginAdmittedMove writes it: "source" and // "target", the source enrollment from the signed roster, and the app // admission the request ran under (claim Plan 5 Task 7). source := before.Op.Intent["source"] if before.Holder == nil || !validBoxReference(source) || source == "none" || before.Op.Intent["source_enrollment"] == "" || before.Op.Intent["app_id"] == "" || before.Op.Intent["admission_id"] != before.Op.ID || before.Holder.Family != "instance" || before.Op.Kind != KindMoving || before.Op.Phase == "landing" || before.Op.Phase == "committed" { return Observed{}, ErrWrongState } // Check the instance record even while the claim still says moving: the // instance flip is earlier than final commit and can precede claim landing. region, err := guard.CheckMovingBeforeFlip(ctx, observed, opID, ref) if err != nil { return Observed{}, err } fence, err := VerifyFence(ctx, s, authority, ref) if err != nil { return Observed{}, err } // The region is the guard's (the authoritative record) and must equal the // fence's roster binding; the claim names only the target region. if region == "" || region != fence.binding.Region || source != fence.record.Box || before.Op.Intent["source_enrollment"] != ref.Enrollment || (before.Op.Exec != fence.record.Box && before.Op.Exec != "none" && before.Op.Exec != "") { return Observed{}, ErrFence } raw, err := json.Marshal(ref) if err != nil { return Observed{}, err } decisionDigest := "" if bound, ok := guard.(interface { ConversionDecisionDigest(context.Context, Observed, string, FenceRef) (string, error) }); ok { decisionDigest, err = bound.ConversionDecisionDigest(ctx, observed, opID, ref) if err != nil { return Observed{}, err } if !isHex64(decisionDigest) { return Observed{}, ErrWrongState } } return Update(ctx, s, observed, func(c *Claim) error { if c.Op.ID != opID || c.Op.Kind != KindMoving || c.Op.Phase != before.Op.Phase { return ErrStaleOp } key := "fence." + fence.record.Box if old, ok := c.Op.Journal[key]; ok && old != string(raw) { return fmt.Errorf("%w: fence reference already bound", ErrFence) } // Recheck the durable record decision immediately before the claim CAS. // Its terminal state prevents any intervening flip. currentRegion, err := guard.CheckMovingBeforeFlip(ctx, observed, opID, ref) if err != nil { return err } if currentRegion != region { return ErrWrongState } if c.Op.Journal == nil { c.Op.Journal = map[string]string{} } c.Op.Journal[key] = string(raw) c.Op.Journal["reason"] = "source-terminated-before-flip" c.Op.Journal["source_stamp"] = strconv.FormatUint(c.Holder.Stamp, 10) c.Op.Journal["source_generation"] = c.Holder.Generation c.Op.Journal["roster_revision"] = strconv.FormatUint(fence.binding.RosterRevision, 10) c.Op.Journal["roster_etag"] = fence.binding.RosterETag c.Op.Journal["app_id"] = before.Op.Intent["app_id"] c.Op.Journal["admission_id"] = before.Op.Intent["admission_id"] c.Op.Journal["conversion_claim_gen"] = strconv.FormatUint(before.Gen, 10) c.Op.Journal["conversion_claim_etag"] = observed.ETag if decisionDigest != "" { c.Op.Journal["conversion_decision_sha256"] = decisionDigest } c.Op.Kind, c.Op.Phase, c.Op.Exec = KindRelocating, "pinning", "none" if c.Op.Intent == nil { c.Op.Intent = map[string]string{} } c.Op.Intent["region"] = region c.Op.Intent["source_box"] = source // The original move target is in a different region. It is not a selected // same-region replacement. Keep the move history without authorizing it. for from, to := range map[string]string{"target": "move_target_box", "to": "move_to_region", "target_enrollment": "move_target_enrollment"} { if v := c.Op.Intent[from]; v != "" { c.Op.Intent[to] = v } delete(c.Op.Intent, from) } delete(c.Op.Intent, "source") participants := make([]string, 0, len(c.Op.Participants)) for _, box := range c.Op.Participants { if box != fence.record.Box { participants = append(participants, box) } } c.Op.Participants = participants return nil }) } // CommittedLanding is the authoritative instance record's committed move // as a CommittedLandingGuard read it: the regions it moved between, as // engine regions (park.PlacementRegion of the record's placement codes, so // the home is park.HomeRegion, exactly the regions moves' own commit // queues its parks in), and the two parks the commit queues, built by // moves.CommitScopes from the record's flip time and the claim's seal (the one builder moves' own // commit uses). The scopes are used only when the claim has not yet // followed the commit. type CommittedLanding struct { FromRegion, ToRegion string SourceScope, StagingScope ParkScope } // CommittedLandingGuard verifies in the authoritative instance record that // move opID has committed (moves §7.5: the record's commit CAS, record // first, terminal) for this claim's incarnation. A record still landing, // rolling back, or naming another move or incarnation refuses with // ErrWrongState: before the commit the target's fence takes moves' // declared-loss rollback (moves §7.10), never this conversion. A snapshot // of an undecided record is not an implementation of this interface. type CommittedLandingGuard interface { CheckLandingCommitted(context.Context, Observed, string) (CommittedLanding, error) } // landingConvertible reports the landing phases at which a committed // record can stand: the record commits only after its probed, so the // claim is at probing or probed (lagging, the record-commit race) or has // followed it to committed. func landingConvertible(phase string) bool { return phase == PhaseLandingProbing || phase == PhaseLandingProbed || phase == PhaseLandingCommitted } // ConvertCommittedLanding is J3 (Paul's ruling J3/F5 on amadan #236; the // model's fence-converts-committed-landing): a landing whose move record // has committed and whose target is then terminated becomes a same-region // relocating failover in the target's region, in exactly one claim CAS. // The record's commit is the evidence (guard), never the claim's phase // alone; the claim may lag the record at probing or probed, and then the // same CAS first follows the commit exactly as moves does (probed, then // Commit under KeepWriterSession, queueing the source region's location // park, the source's park-local and the staging lane's park), so every // cleanup obligation the commit owes exists before the op stops being a // landing. Before the commit the guard refuses and the fence is moves' // (declared-loss rollback). // // The result is the failover StartRelocation starts for a fenced // executor, without a target: relocating in starting, op.exec none, the // dead target as source_box (on lost, its fence journaled with its // observation time and the loss retained in evidence_refs by fenceBox, as // FenceSource does), the op id, holder and every obligation kept. The // target is named in starting (NameTarget) and acknowledges before // PinFailover, as an initial failover does. The move's own intent is kept // as history under move_* keys and its journal is kept whole. It // deliberately exposes no transition capable of granting execution. func ConvertCommittedLanding(ctx context.Context, s release.Store, observed Observed, opID, targetBox string, ref FenceRef, authority FenceAuthority, guard CommittedLandingGuard, d *LocalDischarge, newID func() string) (Observed, error) { if guard == nil || newID == nil || observed.Absent || observed.Claim == nil || observed.ETag == "" { return Observed{}, ErrWrongState } before := observed.Claim if opID == "" || before.Op.ID != opID { return Observed{}, ErrStaleOp } // The landing's own intent, as BeginAdmittedMove wrote it: "source", // "target" and "to", the target's enrollment from the signed roster, // and the app admission the move ran under. in := before.Op.Intent if before.Holder == nil || before.Holder.Family != "instance" || before.Op.Kind != KindLanding || !landingConvertible(before.Op.Phase) || !validBoxReference(targetBox) || targetBox == "none" || in["target"] != targetBox || before.Op.Exec != targetBox || slices.Contains(before.Lost, targetBox) || !validBoxReference(in["source"]) || in["source"] == "none" || in["source"] == targetBox || in["to"] == "" || !validEnrollment(in["target_enrollment"]) || in["app_id"] == "" || in["admission_id"] != opID { return Observed{}, ErrWrongState } committed, err := guard.CheckLandingCommitted(ctx, observed, opID) if err != nil { return Observed{}, err } // The committed regions are engine regions, and so is the move's "to" // (BeginClaimMove's park.PlacementRegion); the home's two names are one // region only under the move's own home binding (main's hostclaim reads // it from the intent the same way). home := in["home_region"] if committed.FromRegion == "" || !regionname.SameRegion(home, committed.ToRegion, in["to"]) || regionname.SameRegion(home, committed.FromRegion, committed.ToRegion) { return Observed{}, ErrWrongState } fence, err := VerifyFence(ctx, s, authority, ref) if err != nil { return Observed{}, err } // The fence is the target's, bound to the target's region in the // roster, which is the record's destination. The binding is the roster // name, so a landing in the home matches its park.HomeRegion only under // the move's home binding. if fence.record.Box != targetBox || fence.record.Enrollment != in["target_enrollment"] || !regionname.SameRegion(home, fence.binding.Region, committed.ToRegion) { return Observed{}, ErrFence } return Update(ctx, s, observed, func(c *Claim) error { if c.Op.ID != opID || c.Op.Kind != KindLanding || c.Op.Phase != before.Op.Phase || c.Op.Exec != targetBox || slices.Contains(c.Lost, targetBox) { return ErrStaleOp } // Recheck the record immediately before the claim CAS. again, err := guard.CheckLandingCommitted(ctx, observed, opID) if err != nil { return err } if again.FromRegion != committed.FromRegion || again.ToRegion != committed.ToRegion { return ErrWrongState } phase := c.Op.Phase // The claim half of the record's commit, as moves writes it // (moveslandcommit.go commitClaim): a claim lagging at probing is // stepped to probed first, then Commit, on the same session. if c.Op.Phase == PhaseLandingProbing { if err := KeepWriterSession(opID, SetMovePhase(opID, KindLanding, PhaseLandingProbing, PhaseLandingProbed))(c); err != nil { return err } } if c.Op.Phase == PhaseLandingProbed { if err := KeepWriterSession(opID, Commit(opID, committed.FromRegion, in["source"], committed.ToRegion, committed.SourceScope, committed.StagingScope, newID))(c); err != nil { return err } } // Defensive: SetMovePhase and Commit above leave every accepted // phase at committed, so this cannot fire today. It keeps the // conversion from running over a landing the commit did not reach // if either helper ever changes. if c.Op.Phase != PhaseLandingCommitted { return ErrWrongState } ensureJournal(c) c.Op.Journal["reason"] = ReasonFailover c.Op.Journal["conversion"] = "committed-landing" c.Op.Journal["conversion_landing_phase"] = phase c.Op.Journal["conversion_claim_gen"] = strconv.FormatUint(before.Gen, 10) c.Op.Journal["conversion_claim_etag"] = observed.ETag c.Op.Journal["move_from_region"] = committed.FromRegion c.Op.Journal["roster_revision"] = strconv.FormatUint(fence.binding.RosterRevision, 10) c.Op.Journal["roster_etag"] = fence.binding.RosterETag c.Op.Kind, c.Op.Phase, c.Op.Exec = KindRelocating, PhaseStarting, "none" intent := make(map[string]string, len(c.Op.Intent)+4) for k, v := range c.Op.Intent { intent[k] = v } // The move's other side is in another region and is no participant: // its finalization chores are obligations, kept as they are. Keep // the move's history without authorizing it. for from, to := range map[string]string{"source": "move_source_box", "source_enrollment": "move_source_enrollment", "to": "move_to_region"} { if v := intent[from]; v != "" { intent[to] = v } delete(intent, from) } delete(intent, "target") delete(intent, "target_enrollment") // The relocation's region is the verified roster identity, as // ConvertMovingToRelocating's is (the fence binding, which matched // the destination above): the region worker's own name, never // park.HomeRegion. intent["region"] = fence.binding.Region intent["source_box"] = targetBox intent["source_enrollment"] = in["target_enrollment"] intent["stamp_from"] = strconv.FormatUint(c.Holder.Stamp, 10) intent["generation_from"] = c.Holder.Generation c.Op.Intent = intent c.Op.Participants = nil return fenceBox(c, targetBox, ref, fence.record.ObservedAt, d) }) } // Box and Region expose a verified fence's terminated box and its roster // region binding, so a caller binds them to the authoritative record rather // than to a decoded reference. func (v VerifiedFence) Box() string { return v.record.Box } func (v VerifiedFence) Region() string { return v.binding.Region }