Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/edge/masque-authority.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ Answers map to HTTP status as follows. 401 is unauthenticated: an unknown, malfo

### Retries and replacement

Each `authorize` call carries a random nonce and the time it was first sent. A retry resends both. The authority refuses a call sent more than 10 s ago (`RetryWindow`) or more than 2 s in the future. A retired incarnation is deleted only after `RetryWindow` has passed and core has released every client-pool address it held (`status.allocations` empty). A retry therefore either finds the incarnation it created, or is refused as stale. It never creates a second one.
Each `authorize` call carries a random nonce and the time it was first sent. A retry resends both. The authority refuses a call sent more than 10 s ago (`RetryWindow`) or more than 2 s in the future. A retired incarnation is kept `RetryWindow` after its retirement, or only until a retry of the call that issued it can no longer be accepted when that is sooner: 12 s after its issue (`RetryWindow` plus the 2 s allowance), by the issue time the authority records in `masque.galactic.datumapis.com/issued-at`. An incarnation retired long after its issue, as at a provider's shutdown, is therefore not held for retries. It is deleted only once core has released every client-pool address it held (`status.allocations` empty), and the delete is conditioned on the resourceVersion read, so an address core records after that read keeps the incarnation for a later pass. A retry therefore either finds the incarnation it created, or is refused as stale. It never creates a second one.

A connector's pool is the same in every incarnation, and core refuses the attachments of the later of two services with overlapping pools. Replacement is therefore sequential:

1. Retire the old incarnation, which ends its forwarding at core and galactic-edge.
2. Wait for core to release its attachments and for `RetryWindow` to pass.
2. Wait for core to release its attachments and, unless a retry of its issuing call can no longer be accepted, for `RetryWindow` to pass.
3. Delete it.
4. Issue the successor.

Expand All @@ -82,7 +82,7 @@ Until then, `authorize` answers 503 and the client retries. An incarnation is na
- its record is at another revision; or
- it reached `validUntil` less MaxSkew without renewal.

Retired incarnations that core has released are deleted after `RetryWindow`. The provider learns of a revocation from its next `refresh` (403), at most 5 s later. The service's `validUntil` is the backstop if the provider, the authority or the API stalls: no packets 31 s after a committed revocation, or 1 s after credential expiry. Revocation push notifications are not built. Revoking one connector never touches another connector's incarnation, and the shared instance Lease keeps renewing.
Retired incarnations that core has released are deleted as the retry rule above allows. A provider retires the grants of the requests it ends at shutdown, so a connector it served can be admitted elsewhere without waiting for the sweep. The provider learns of a revocation from its next `refresh` (403), at most 5 s later. The service's `validUntil` is the backstop if the provider, the authority or the API stalls: no packets 31 s after a committed revocation, or 1 s after credential expiry. Revocation push notifications are not built. Revoking one connector never touches another connector's incarnation, and the shared instance Lease keeps renewing.

## Operator tasks

Expand Down
2 changes: 1 addition & 1 deletion docs/edge/masque-provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Every 5 seconds (`Config.Refresh`) the adapter calls `Authorizer.Refresh` for ea

When core drains an attachment, after its service is deleted or its authority ends, the adapter ends that attachment's requests at its next check and serves no new request on it. Core deletes the attachment after the service's `drainSeconds`.

On shutdown, stop the transports first so every request ends, then call `Shutdown`. It stops admitting, releases each route claim the adapter still holds, deletes its attachments and releases the instance Lease. A replacement can therefore take nothing over while this pod still forwards. Shutdown is bounded by the caller's context; the service and the fixture give it 20 seconds.
On shutdown, call `BeginShutdown`, stop the transports so every request ends, then call `Shutdown`. From `BeginShutdown` on, every request that ends retires its grant (`Authorizer.Retire`), unless a newer request of its connector on this pod is being admitted or is open with the same authorization, which the authority renews in place. Retiring the grants lets another pod admit the same connectors as soon as core releases them, rather than when the authority's sweep finds the grants unrenewed. `Shutdown` stops admitting, ends what is left, releases each route claim the adapter still holds, deletes its attachments and releases the instance Lease, and reports any retirement that failed. A replacement can therefore take nothing over while this pod still forwards. Shutdown is bounded by the caller's context; the service and the fixture give it 20 seconds.

## Cleanup

Expand Down
4 changes: 2 additions & 2 deletions docs/edge/masque-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -581,8 +581,8 @@ A request is admitted only after the authority authorizes its credential and the
SIGTERM or SIGINT starts shutdown:

1. `/readyz` fails. With a public listener, the pod reports its listener attachment not `Ready` and keeps serving for 5 seconds while core and the gateways stop sending it new flows.
2. Both listeners close, which ends every session on either transport, including the HTTP/2 connections a listener accepted.
3. The pod deletes its listener attachment. The adapter stops renewing, releases each route claim, deletes its attachments and releases the Lease ([drain and shutdown](masque-provider.md#drain-and-shutdown)).
2. The server closes, which ends every session on either transport and sends each HTTP/3 client a QUIC CONNECTION_CLOSE. Only then do the listener's sockets close, including the HTTP/2 connections it accepted. Closing the UDP socket first would leave the server nothing to send the close on, and clients would learn of it only at their 30 second idle timeout.
3. The pod deletes its listener attachment. The adapter retires the authorization of every request it ended, stops renewing, releases each route claim, deletes its attachments and releases the Lease ([drain and shutdown](masque-provider.md#drain-and-shutdown)).

Step 3 has 20 seconds, so give the pod a termination grace period of at least 30 seconds, or 40 seconds with a public listener, whose step 1 takes up to 10. A pod killed before it finishes leaves its routes to expire: galactic-edge closes their gates at the Lease deadline, and core reaps the pod's objects.

Expand Down
32 changes: 32 additions & 0 deletions internal/edge/connectip/close_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2026 Datum Cloud, Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package connectip

import (
"testing"
"time"
)

// TestServerCloseTwice checks that a second Close returns at once. The
// MASQUE listener closes the server when it stops, and the service closes it
// again afterwards.
func TestServerCloseTwice(t *testing.T) {
env := startServer(t, nil)
conn := env.dialQUIC(t)
for i := range 2 {
done := make(chan error, 1)
go func() { done <- env.server.Close() }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatalf("Close call %d did not return", i+1)
}
}
select {
case <-conn.Context().Done():
case <-time.After(time.Second):
t.Fatal("the client's connection is still open after Close")
}
}
56 changes: 54 additions & 2 deletions internal/edge/masque/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,14 @@ type Adapter struct {
cancelStop context.CancelFunc
admitting sync.WaitGroup

// retiring is set once shutdown begins: every request that ends from
// then on retires its grant.
retiring atomic.Bool

mu sync.Mutex
closing bool
// retireErrs holds the retirements that failed during shutdown.
retireErrs []error
// pending holds the connectors whose request is being prepared.
pending map[string]bool
// revokeSeq counts Revoke calls and revokedAt holds each connector's
Expand Down Expand Up @@ -540,10 +546,13 @@ func (a *Adapter) isClosing() bool {
// Shutdown stops admitting requests and waits, bounded by ctx, for those
// still being prepared to give up. It then ends every request, releases the
// routes, deletes the attachments and releases the lease, in that order, so
// that nothing is taken over while this pod still forwards. Call it after
// Run returned and the transports stopped serving.
// that nothing is taken over while this pod still forwards. Every request
// that ended since BeginShutdown, or that Shutdown ends, retired its grant;
// Shutdown reports the retirements that failed. Call it after Run returned
// and the transports stopped serving.
func (a *Adapter) Shutdown(ctx context.Context) error {
defer untrack(a)
a.BeginShutdown()
a.mu.Lock()
a.closing = true
a.mu.Unlock()
Expand Down Expand Up @@ -573,6 +582,7 @@ func (a *Adapter) Shutdown(ctx context.Context) error {
s.close(ctx)
}
a.mu.Lock()
errs = append(errs, a.retireErrs...)
routes := make([]*route, 0, len(a.routes))
for _, r := range a.routes {
routes = append(routes, r)
Expand Down Expand Up @@ -611,6 +621,48 @@ func (a *Adapter) Shutdown(ctx context.Context) error {
return errors.Join(errs...)
}

// BeginShutdown marks the adapter as shutting down. Call it before the
// transports stop: every request that ends from then on, as the server
// closes its connections, retires its grant, so the authority releases the
// connector at once rather than when its sweep finds the authorization
// unrenewed, and another pod can admit the connector as soon as core
// revokes what this pod held. Shutdown calls it too.
func (a *Adapter) BeginShutdown() { a.retiring.Store(true) }

// retireAtShutdown retires the grant g of a request that ended once
// shutdown has begun, bounded by ctx and refreshTimeout, and records a
// failure for Shutdown to report. It leaves g alone while a newer request of
// the connector on this pod is being admitted or is open with the same
// authorization: the authority renews a pod's authorization in place, so
// that request may hold g's.
func (a *Adapter) retireAtShutdown(ctx context.Context, g Grant) {
a.mu.Lock()
inUse := a.pending[g.Connector]
for _, s := range a.sessions {
if s.grant.Connector == g.Connector && s.grant.Authorization == g.Authorization {
inUse = true
}
}
a.mu.Unlock()
if inUse {
return
}
err := ctx.Err()
if err == nil {
rctx, cancel := context.WithTimeout(ctx, refreshTimeout)
err = a.cfg.Authorizer.Retire(rctx, g)
cancel()
}
if err == nil {
return
}
a.log.Warn("could not retire a grant at shutdown", "connector", g.Connector, "serviceUID", g.Service.UID,
"error", err)
a.mu.Lock()
a.retireErrs = append(a.retireErrs, fmt.Errorf("retire the grant of connector %s: %w", g.Connector, err))
a.mu.Unlock()
}

// check ends the requests whose attachment or route is no longer current
// and deletes attachments idle for longer than cfg.Idle.
func (a *Adapter) check(ctx context.Context) {
Expand Down
110 changes: 108 additions & 2 deletions internal/edge/masque/adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ type harness struct {
authorize func(context.Context) error
// retired holds the connectors whose grants were retired.
retired map[string]bool
// retireErr, when set, fails every Retire after recording it.
retireErr error
// beforeStart, when set, runs on the adapter before it starts.
beforeStart func(*Adapter)
}
Expand Down Expand Up @@ -303,6 +305,9 @@ func (h *harness) Retire(_ context.Context, g Grant) error {
h.record("retired " + g.Connector)
h.mu.Lock()
defer h.mu.Unlock()
if h.retireErr != nil {
return h.retireErr
}
if h.retired == nil {
h.retired = map[string]bool{}
}
Expand Down Expand Up @@ -1296,14 +1301,115 @@ func TestShutdownReleasesInOrder(t *testing.T) {
h.mu.Lock()
calls := strings.Join(h.calls, ", ")
h.mu.Unlock()
if want := "claim released, attachment deleted, lease released"; calls != want {
if want := "claim released, retired a1, attachment deleted, lease released"; calls != want {
t.Fatalf("shutdown did %q, want %q", calls, want)
}
if _, err := h.a.Admit(context.Background(), credA1, testVPCName); !errors.Is(err, ErrUnavailable) {
// a1's grant is retired now; a2's is not, so the adapter's own refusal
// is what answers.
if _, err := h.a.Admit(context.Background(), "cred-a2", testVPCName); !errors.Is(err, ErrUnavailable) {
t.Fatalf("Admit after shutdown = %v", err)
}
}

// retiredCounts returns how often each connector's grant was retired.
func (h *harness) retiredCounts() map[string]int {
h.mu.Lock()
defer h.mu.Unlock()
retired := map[string]int{}
for _, c := range h.calls {
if connector, ok := strings.CutPrefix(c, "retired "); ok {
retired[connector]++
}
}
return retired
}

// TestShutdownRetiresGrants shuts down as the service does: BeginShutdown,
// then the server closes every connection, which closes each request, then
// Shutdown. Every connector served retires its grant once, so another
// provider pod can admit it without waiting for the authority to find the
// grant unrenewed.
func TestShutdownRetiresGrants(t *testing.T) {
h := newHarness(t)
h.start()
a1 := h.admit(credA1)
b := h.admit("cred-b")
h.a.BeginShutdown()
if err := a1.Close(); err != nil {
t.Fatal(err)
}
if err := b.Close(); err != nil {
t.Fatal(err)
}
if err := h.a.Shutdown(context.Background()); err != nil {
t.Fatal(err)
}
if retired := h.retiredCounts(); retired["a1"] != 1 || retired["b"] != 1 || len(retired) != 2 {
t.Fatalf("shutdown retired %v, want a1 and b once each", retired)
}
}

// TestRequestEndBeforeShutdownKeepsGrant checks that a request ending in
// normal service leaves its grant to be renewed by a reconnect.
func TestRequestEndBeforeShutdownKeepsGrant(t *testing.T) {
h := newHarness(t)
h.start()
if err := h.admit(credA1).Close(); err != nil {
t.Fatal(err)
}
if retired := h.retiredCounts(); len(retired) != 0 {
t.Fatalf("a request ending in service retired %v", retired)
}
}

// TestShutdownSparesReplacedRequest checks that a request replaced by a
// newer one of its connector during shutdown does not retire the grant,
// which the newer request may hold too. The newer one retires it as it ends.
func TestShutdownSparesReplacedRequest(t *testing.T) {
h := newHarness(t)
h.start()
old := h.admit(credA1)
serve(old, nil)
h.a.BeginShutdown()
cur := h.admit(credA1)
<-old.(*session).closed
if retired := h.retiredCounts(); len(retired) != 0 {
t.Fatalf("the replaced request retired %v", retired)
}
if err := cur.Close(); err != nil {
t.Fatal(err)
}
if retired := h.retiredCounts(); retired["a1"] != 1 || len(retired) != 1 {
t.Fatalf("shutdown retired %v, want a1 once", retired)
}
}

// TestShutdownReportsFailedRetirement checks that a grant the authority
// could not retire is reported, and that shutdown still releases the claim,
// the attachment and the lease.
func TestShutdownReportsFailedRetirement(t *testing.T) {
h := newHarness(t)
h.start()
l := h.admit(credA1)
h.mu.Lock()
h.retireErr = errors.New("authority unavailable")
h.mu.Unlock()
h.a.BeginShutdown()
if err := l.Close(); err != nil {
t.Fatal(err)
}
err := h.a.Shutdown(context.Background())
if err == nil || !strings.Contains(err.Error(), "retire the grant of connector a1") {
t.Fatalf("Shutdown = %v, want the failed retirement reported", err)
}
h.mu.Lock()
calls := strings.Join(h.calls, ", ")
h.mu.Unlock()
if want := "claim released, retired a1, attachment deleted, lease released"; calls != want {
t.Fatalf("shutdown did %q, want %q", calls, want)
}
}

// TestConcurrentRequestsOfOneConnector admits several requests of one
// connector at once, each closed by its transport once it ends: every
// request is either admitted, replacing the one before it, or refused while
Expand Down
51 changes: 41 additions & 10 deletions internal/edge/masque/authority/authority.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ const (
AnnotationRetired = annotationPrefix + "retired"
// AnnotationRetiredAt is when the authorization was retired.
AnnotationRetiredAt = annotationPrefix + "retired-at"
// AnnotationIssuedAt is when the authority issued the authorization, by
// its own clock.
AnnotationIssuedAt = annotationPrefix + "issued-at"
// AnnotationCell is the cell of the authority that issued it.
AnnotationCell = annotationPrefix + "cell"

Expand All @@ -74,8 +77,9 @@ const (
// DefaultIssuerSkew is the issuer clock allowance subtracted from TTL.
DefaultIssuerSkew = 2 * time.Second
// RetryWindow is how long after it was issued an Authorize call is
// accepted. A retired authorization is kept at least this long, so a
// retry of the call that issued it finds it and is refused.
// accepted. A retired authorization is kept until a retry of the call
// that issued it can no longer be accepted, so the retry finds it and is
// refused.
RetryWindow = 10 * time.Second
// maxCallerSkew is how far ahead of the authority's clock a call's
// issue time may be.
Expand Down Expand Up @@ -402,7 +406,7 @@ func (a *Authority) issue(ctx context.Context, id admission.Identity, r *Record,
Annotations: map[string]string{
AnnotationAuthorization: auth, AnnotationPod: id.PodUID, AnnotationNonce: nonce,
AnnotationRevision: strconv.FormatInt(r.Revision, 10), AnnotationAllocation: e.Allocation,
AnnotationCell: a.Cell,
AnnotationCell: a.Cell, AnnotationIssuedAt: a.now().UTC().Format(time.RFC3339Nano),
},
},
Spec: galacticv1alpha1.EdgeServiceSpec{
Expand Down Expand Up @@ -668,24 +672,51 @@ func (a *Authority) retire(ctx context.Context, s *galacticv1alpha1.EdgeService,
return fmt.Errorf("%w: EdgeService %s/%s kept changing", ErrUnavailable, s.Namespace, s.Name)
}

// reap deletes retired service s once it was retired for RetryWindow and
// core holds no client pool address for it, conditioned on its UID. It
// reports whether s is gone.
// reap deletes retired service s once a retry of the call that issued it
// no longer needs it (retryDeadline) and core holds no client pool address
// for it. The delete is conditioned on the UID and resourceVersion read: core
// records an allocation in the service's status before the node programs the
// address, and an admission core began before the retirement may still
// record one after s was read, so a changed service is kept for a later
// pass. It reports whether s is gone.
func (a *Authority) reap(ctx context.Context, s *galacticv1alpha1.EdgeService) (bool, error) {
if !retired(s) || len(s.Status.Allocations) > 0 {
return false, nil
}
at, err := time.Parse(time.RFC3339Nano, s.Annotations[AnnotationRetiredAt])
if err == nil && a.now().Before(at.Add(RetryWindow)) {
if a.now().Before(retryDeadline(s)) {
return false, nil
}
err = a.Client.Delete(ctx, s, client.Preconditions{UID: &s.UID})
if err != nil && !apierrors.IsNotFound(err) {
err := a.Client.Delete(ctx, s, client.Preconditions{UID: &s.UID, ResourceVersion: &s.ResourceVersion})
switch {
case apierrors.IsConflict(err):
return false, nil
case err != nil && !apierrors.IsNotFound(err):
return false, err
}
return true, nil
}

// retryDeadline is how long retired s is kept so that a retry of the
// Authorize call that issued it finds it: RetryWindow after its retirement,
// or, when sooner, once the retry can no longer be accepted. A call is
// accepted only while its issue time is within RetryWindow, and that time is
// at most maxCallerSkew ahead of the authority's clock when it issued s. An
// authorization retired long after its issue is therefore not held at all.
// One issued before AnnotationIssuedAt was recorded is held the full
// RetryWindow after its retirement.
func retryDeadline(s *galacticv1alpha1.EdgeService) time.Time {
var deadline time.Time
if at, err := time.Parse(time.RFC3339Nano, s.Annotations[AnnotationRetiredAt]); err == nil {
deadline = at.Add(RetryWindow)
}
if at, err := time.Parse(time.RFC3339Nano, s.Annotations[AnnotationIssuedAt]); err == nil {
if issued := at.Add(RetryWindow + maxCallerSkew); deadline.IsZero() || issued.Before(deadline) {
deadline = issued
}
}
return deadline
}

// Sweep retires every issued authorization whose grant record is gone,
// disabled, expired or at another revision, or that reached validUntil less
// MaxSkew unrenewed, and deletes retired ones core has released. It returns
Expand Down
Loading
Loading