diff --git a/docs/edge/masque-authority.md b/docs/edge/masque-authority.md index 9d10aa419..d811affd8 100644 --- a/docs/edge/masque-authority.md +++ b/docs/edge/masque-authority.md @@ -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. @@ -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 diff --git a/docs/edge/masque-provider.md b/docs/edge/masque-provider.md index 3ac17d101..f5a4268f7 100644 --- a/docs/edge/masque-provider.md +++ b/docs/edge/masque-provider.md @@ -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 diff --git a/docs/edge/masque-service.md b/docs/edge/masque-service.md index 2ebcab971..a49abeea1 100644 --- a/docs/edge/masque-service.md +++ b/docs/edge/masque-service.md @@ -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. diff --git a/internal/edge/connectip/close_test.go b/internal/edge/connectip/close_test.go new file mode 100644 index 000000000..161ef71c9 --- /dev/null +++ b/internal/edge/connectip/close_test.go @@ -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") + } +} diff --git a/internal/edge/masque/adapter.go b/internal/edge/masque/adapter.go index b283504e5..54ac9c144 100644 --- a/internal/edge/masque/adapter.go +++ b/internal/edge/masque/adapter.go @@ -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 @@ -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() @@ -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) @@ -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) { diff --git a/internal/edge/masque/adapter_test.go b/internal/edge/masque/adapter_test.go index fc234d7d4..2a3c4a287 100644 --- a/internal/edge/masque/adapter_test.go +++ b/internal/edge/masque/adapter_test.go @@ -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) } @@ -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{} } @@ -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 diff --git a/internal/edge/masque/authority/authority.go b/internal/edge/masque/authority/authority.go index 3fa65d09c..2523dee6d 100644 --- a/internal/edge/masque/authority/authority.go +++ b/internal/edge/masque/authority/authority.go @@ -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" @@ -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. @@ -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{ @@ -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 diff --git a/internal/edge/masque/authority/authority_envtest_test.go b/internal/edge/masque/authority/authority_envtest_test.go index 1122bcedd..a412d4454 100644 --- a/internal/edge/masque/authority/authority_envtest_test.go +++ b/internal/edge/masque/authority/authority_envtest_test.go @@ -464,6 +464,8 @@ func TestAuthority(t *testing.T) { //nolint:gocyclo // one ordered scenario over } t.Run("unrenewed authorization is swept", func(t *testing.T) { + // Core holds an address of it, so the sweep keeps it retired. + f.holdPool(g2) f.advance(DefaultTTL) if err := f.auth.Sweep(ctx); err != nil { t.Fatal(err) @@ -471,6 +473,7 @@ func TestAuthority(t *testing.T) { //nolint:gocyclo // one ordered scenario over if s := f.service(g2); s == nil || !retired(s) { t.Fatal("the sweep left an authorization past its validUntil unretired") } + f.releasePool(g2) f.advance(RetryWindow) if err := f.auth.Sweep(ctx); err != nil { t.Fatal(err) diff --git a/internal/edge/masque/authority/handover_envtest_test.go b/internal/edge/masque/authority/handover_envtest_test.go new file mode 100644 index 000000000..079767ccc --- /dev/null +++ b/internal/edge/masque/authority/handover_envtest_test.go @@ -0,0 +1,91 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package authority + +import ( + "context" + "testing" + "time" +) + +// TestHandoverAfterProviderRetires covers a provider pod that shuts down and +// retires the authorization of a connector it served for longer than +// RetryWindow. Once core released the connector's addresses, another pod +// admits the connector at once: no retry of the call that issued the old +// authorization can still be accepted, so nothing needs it kept. The +// authority used to keep it RetryWindow after its retirement and answer 503 +// meanwhile. +func TestHandoverAfterProviderRetires(t *testing.T) { + f := startFixture(t) + ctx := context.Background() + podA, podB := podID(testPodA), podID("pod-b") + c := f.connector() + g := f.authorize(podA, c.Credential, "nonceH0000000001") + f.set(f.clock().Add(RetryWindow + maxCallerSkew + time.Second)) + if _, err := f.auth.Refresh(ctx, podA, g.Authorization, g.Revision, g.Service); err != nil { + t.Fatalf("Refresh while serving: %v", err) + } + if err := f.auth.Retire(ctx, podA, g.Authorization, g.Service); err != nil { + t.Fatalf("Retire at shutdown: %v", err) + } + gb, err := f.tryAuthorize(podB, c.Credential, "nonceH0000000002") + if err != nil { + t.Fatalf("Authorize on another pod right after the retirement = %v, want a successor", err) + } + if gb.Service.UID == g.Service.UID || gb.Prefix != g.Prefix || f.service(g) != nil { + t.Fatalf("handover = %+v, want a new service for the same /96 with the old one deleted", gb.Service) + } + _, err = f.tryAuthorize(podA, c.Credential, "nonceH0000000001") + expectErr(t, "a retry of the retired authorization's call", err, ErrInvalid) +} + +// TestHandoverWaitsForCore checks that an authorization retired long after +// its issue is still kept while core holds an address of it. +func TestHandoverWaitsForCore(t *testing.T) { + f := startFixture(t) + ctx := context.Background() + podA, podB := podID(testPodA), podID("pod-b") + c := f.connector() + g := f.authorize(podA, c.Credential, "nonceW0000000001") + f.set(f.clock().Add(RetryWindow + maxCallerSkew + time.Second)) + if _, err := f.auth.Refresh(ctx, podA, g.Authorization, g.Revision, g.Service); err != nil { + t.Fatalf("Refresh while serving: %v", err) + } + f.holdPool(g) + if err := f.auth.Retire(ctx, podA, g.Authorization, g.Service); err != nil { + t.Fatal(err) + } + _, err := f.tryAuthorize(podB, c.Credential, "nonceW0000000002") + expectErr(t, "Authorize while core holds the retired service's address", err, ErrUnavailable) + f.releasePool(g) + if gb := f.authorize(podB, c.Credential, "nonceW0000000002"); gb.Service.UID == g.Service.UID { + t.Fatal("the successor reused the retired service") + } +} + +// TestReapKeepsChangedService covers core recording an address in a retired +// service after the authority read it with none: an admission core began +// before the retirement may still do so. The delete must not remove the +// service from under that address. +func TestReapKeepsChangedService(t *testing.T) { + f := startFixture(t) + ctx := context.Background() + podA := podID(testPodA) + c := f.connector() + g := f.authorize(podA, c.Credential, "nonceR0000000001") + if err := f.auth.Retire(ctx, podA, g.Authorization, g.Service); err != nil { + t.Fatal(err) + } + f.set(f.clock().Add(RetryWindow + maxCallerSkew + time.Second)) + stale := f.service(g) + f.holdPool(g) + released, err := f.auth.reap(ctx, stale) + if err != nil || released { + t.Fatalf("reap of a service read before core recorded an address = %v, %v; want kept", released, err) + } + if f.service(g) == nil { + t.Fatal("reap deleted a service core holds an address of") + } +} diff --git a/internal/edge/masque/authority/retry_deadline_test.go b/internal/edge/masque/authority/retry_deadline_test.go new file mode 100644 index 000000000..90e4e5cb7 --- /dev/null +++ b/internal/edge/masque/authority/retry_deadline_test.go @@ -0,0 +1,44 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package authority + +import ( + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +func TestRetryDeadline(t *testing.T) { + t0 := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + stamp := func(d time.Duration) string { return t0.Add(d).Format(time.RFC3339Nano) } + for name, tc := range map[string]struct { + issued, retired string + want time.Time + }{ + "neither recorded": {want: time.Time{}}, + "issued before issue time recorded": {retired: stamp(0), want: t0.Add(RetryWindow)}, + "retired right after issue": {issued: stamp(0), retired: stamp(time.Second), + want: t0.Add(time.Second + RetryWindow)}, + "retired long after issue": {issued: stamp(0), retired: stamp(time.Minute), + want: t0.Add(RetryWindow + maxCallerSkew)}, + "issued, not retired": {issued: stamp(0), want: t0.Add(RetryWindow + maxCallerSkew)}, + } { + t.Run(name, func(t *testing.T) { + s := &galacticv1alpha1.EdgeService{ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{}}} + if tc.issued != "" { + s.Annotations[AnnotationIssuedAt] = tc.issued + } + if tc.retired != "" { + s.Annotations[AnnotationRetiredAt] = tc.retired + } + if got := retryDeadline(s); !got.Equal(tc.want) { + t.Fatalf("retryDeadline = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/internal/edge/masque/authority/skew_envtest_test.go b/internal/edge/masque/authority/skew_envtest_test.go index ec5eb1fcc..ce5f1de0e 100644 --- a/internal/edge/masque/authority/skew_envtest_test.go +++ b/internal/edge/masque/authority/skew_envtest_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" "go.datum.net/galactic/internal/edge/connectip" "go.datum.net/galactic/internal/edge/timing" ) @@ -19,6 +20,29 @@ func (f *fixture) set(now time.Time) { f.now = now } +// holdPool records an address of g's service in its status, as core does +// before the node programs it. +func (f *fixture) holdPool(g Grant) { + f.t.Helper() + s := f.service(g) + s.Status.Allocations = []galacticv1alpha1.EdgeAllocation{{Address: "fd20:a1b:2c3d:10:2::101", + Attachment: "edge/a", AttachmentUID: "u"}} + if err := f.admin.Status().Update(context.Background(), s); err != nil { + f.t.Fatal(err) + } +} + +// releasePool clears the addresses of g's service, as core does once the +// node released them. +func (f *fixture) releasePool(g Grant) { + f.t.Helper() + s := f.service(g) + s.Status.Allocations = nil + if err := f.admin.Status().Update(context.Background(), s); err != nil { + f.t.Fatal(err) + } +} + // TestStoppedGrantIsNotRenewed covers an incarnation within the cell's // MaxSkew of its validUntil: core already refused its attachments with // GrantExpired and never readmits them, so the authority must not renew it in @@ -33,6 +57,7 @@ func TestStoppedGrantIsNotRenewed(t *testing.T) { t.Run("authorize", func(t *testing.T) { c := f.connector() g := f.authorize(podA, c.Credential, "nonceK0000000001") + f.holdPool(g) stopped(g) r, err := f.tryAuthorize(podA, c.Credential, "nonceK0000000002") if err == nil && r.Service == g.Service { @@ -43,6 +68,7 @@ func TestStoppedGrantIsNotRenewed(t *testing.T) { if s := f.service(g); s == nil || !retired(s) { t.Fatal("the stopped incarnation was left live") } + f.releasePool(g) f.set(f.clock().Add(RetryWindow)) r = f.authorize(podA, c.Credential, "nonceK0000000007") if r.Service.UID == g.Service.UID || f.service(g) != nil { @@ -78,6 +104,7 @@ func TestStoppedGrantIsNotRenewed(t *testing.T) { next() c := f.connector() g := f.authorize(podA, c.Credential, "nonceK0000000005") + f.holdPool(g) stopped(g) if err := f.auth.Sweep(ctx); err != nil { t.Fatal(err) diff --git a/internal/edge/masque/listener.go b/internal/edge/masque/listener.go index 10c6bac44..848f603e1 100644 --- a/internal/edge/masque/listener.go +++ b/internal/edge/masque/listener.go @@ -15,6 +15,7 @@ import ( "net/netip" "strconv" "sync" + "sync/atomic" "syscall" "time" @@ -33,10 +34,13 @@ import ( const SocketAccess = "SocketAccess" // ListenerServer serves CONNECT-IP on the sockets a Listener binds. -// connectip.Server implements it. +// connectip.Server implements it. Close ends every connection, sending each +// HTTP/3 client a CONNECTION_CLOSE on the socket it serves, and must allow +// a second call. type ListenerServer interface { Serve(net.PacketConn) error ServeTLS(net.Listener) error + Close() error } // ListenFunc opens the UDP socket, and the TCP listener when tcpPort is not @@ -72,7 +76,7 @@ type ListenerConfig struct { // Gateways send new flows only to an attachment that is Ready. // // Create it with NewListener before Adapter.Start, run Run beside -// Adapter.Run, and on shutdown call Stop before the server closes and +// Adapter.Run, and on shutdown call Stop, which closes the server, and // Delete before Adapter.Shutdown releases the lease. type Listener struct { a *Adapter @@ -82,6 +86,10 @@ type Listener struct { // rec serializes reconcile, Stop and Delete. rec sync.Mutex + // stopping is set once Stop closes the server, so that a serve loop + // ending for that reason is expected rather than a failure. + stopping atomic.Bool + // The fields below are guarded by rec. // svcUID is the EdgeService's UID once read. attUID is the UID of the @@ -476,7 +484,7 @@ func (l *Listener) bind(ctx context.Context, att *galacticv1alpha1.EdgeAttachmen } go func() { err := l.cfg.Server.Serve(pc) - if b.serving() { + if b.serving() && !l.stopping.Load() { l.log.Error("listener HTTP/3 server stopped", "error", err) } b.stop() @@ -484,7 +492,7 @@ func (l *Listener) bind(ctx context.Context, att *galacticv1alpha1.EdgeAttachmen if b.ln != nil { go func() { err := l.cfg.Server.ServeTLS(b.ln) - if b.serving() { + if b.serving() && !l.stopping.Load() { l.log.Error("listener HTTP/2 server stopped", "error", err) } b.stop() @@ -512,9 +520,12 @@ func (l *Listener) unbind(reason string) { } // Stop reports the listener attachment not Ready, so gateways send it no -// new flows, keeps the sockets open for StopDelay or until ctx ends while -// they stop, then closes them. Reconcile does nothing afterwards. Call it -// before the server closes. +// new flows, and keeps the sockets open for StopDelay or until ctx ends +// while they stop. It then closes the server, which sends every client a +// close on the still open sockets, and only then closes the sockets: with +// the UDP socket closed first, the server could send no close, and clients +// would learn of it only at their idle timeout. Reconcile does nothing +// afterwards. func (l *Listener) Stop(ctx context.Context) { l.rec.Lock() defer l.rec.Unlock() @@ -536,6 +547,19 @@ func (l *Listener) Stop(ctx context.Context) { t.Stop() } } + // The server waits for every request to end, so the wait is bounded by + // ctx; the sockets close regardless, which ends whatever is left. + l.stopping.Store(true) + closed := make(chan error, 1) + go func() { closed <- l.cfg.Server.Close() }() + select { + case err := <-closed: + if err != nil { + l.log.Warn("closing the listener's server", "error", err) + } + case <-ctx.Done(): + l.log.Warn("the listener's server did not close in time; closing its sockets", "error", ctx.Err()) + } l.unbind(reasonShuttingDown) } diff --git a/internal/edge/masque/listener_close_test.go b/internal/edge/masque/listener_close_test.go new file mode 100644 index 000000000..29b42feee --- /dev/null +++ b/internal/edge/masque/listener_close_test.go @@ -0,0 +1,113 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +//go:build linux + +package masque + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "errors" + "math/big" + "net" + "net/http" + "testing" + "time" + + "github.com/quic-go/quic-go" + "github.com/quic-go/quic-go/http3" +) + +// h3Server is a ListenerServer that serves HTTP/3 with quic-go, as +// connectip.Server does, and holds every request open until its connection +// ends. Its HTTP/2 side is the fakeServer's. +type h3Server struct { + fakeServer + h3 *http3.Server +} + +func newH3Server(t *testing.T, idle time.Duration) *h3Server { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + leaf := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{"listener.example"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour)} + der, err := x509.CreateCertificate(rand.Reader, leaf, leaf, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + return &h3Server{h3: &http3.Server{ + TLSConfig: http3.ConfigureTLSConfig(&tls.Config{ + Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}}), + QUICConfig: &quic.Config{MaxIdleTimeout: idle}, + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.(http.Flusher).Flush() + <-r.Context().Done() + }), + }} +} + +func (s *h3Server) Serve(pc net.PacketConn) error { return s.h3.Serve(pc) } +func (s *h3Server) Close() error { return s.h3.Close() } + +// TestListenerStopClosesClients holds an HTTP/3 request open on the public +// listener and stops the listener, as shutdown does. The client must learn +// that its connection ended from the server's CONNECTION_CLOSE, well before +// its idle timeout. Stop used to close the UDP socket before the server, so +// the close was never sent and the client waited out the idle timeout. +func TestListenerStopClosesClients(t *testing.T) { + const idle = 10 * time.Second + srv := newH3Server(t, idle) + lh := newListenerHarnessServing(t, srv) + lh.settle("Serving") + binds := lh.binds() + server := binds[len(binds)-1].pc.LocalAddr() + + cpc, err := (&net.ListenConfig{}).ListenPacket(t.Context(), "udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + tr := &quic.Transport{Conn: cpc} + t.Cleanup(func() { _ = tr.Close() }) + dctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + conn, err := tr.Dial(dctx, server, &tls.Config{InsecureSkipVerify: true, //nolint:gosec // test peer + NextProtos: []string{http3.NextProtoH3}}, &quic.Config{MaxIdleTimeout: idle}) + if err != nil { + t.Fatal(err) + } + cc := (&http3.Transport{}).NewClientConn(conn) + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "https://listener.example/", nil) + if err != nil { + t.Fatal(err) + } + res, err := cc.RoundTrip(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = res.Body.Close() }() + + start := time.Now() + lh.l.Stop(t.Context()) + select { + case <-conn.Context().Done(): + case <-time.After(idle / 2): + t.Fatalf("the client's connection was still open %v after Stop; the server sent no close", idle/2) + } + if d := time.Since(start); d > 2*time.Second { + t.Fatalf("the client learned its connection ended %v after Stop, want within 2s", d) + } + var appErr *quic.ApplicationError + if cause := context.Cause(conn.Context()); !errors.As(cause, &appErr) || !appErr.Remote { + t.Fatalf("the client's connection ended with %v, want the server's close", cause) + } +} diff --git a/internal/edge/masque/listener_test.go b/internal/edge/masque/listener_test.go index f326aa6ff..189b199a6 100644 --- a/internal/edge/masque/listener_test.go +++ b/internal/edge/masque/listener_test.go @@ -45,6 +45,10 @@ type fakeServer struct { failTLS bool } +// Close implements ListenerServer. The fake's serve loops end when their +// sockets close. +func (s *fakeServer) Close() error { return nil } + func (s *fakeServer) Serve(pc net.PacketConn) error { s.mu.Lock() s.serves++ @@ -107,8 +111,18 @@ type listenerHarness struct { } func newListenerHarness(t *testing.T) *listenerHarness { + t.Helper() + return newListenerHarnessServing(t, nil) +} + +// newListenerHarnessServing is newListenerHarness whose listener serves +// with srv, or with the harness's fakeServer when srv is nil. +func newListenerHarnessServing(t *testing.T, srv ListenerServer) *listenerHarness { t.Helper() lh := &listenerHarness{harness: newHarness(t), srv: &fakeServer{}} + if srv == nil { + srv = lh.srv + } lh.createService() lh.setCore(func(att *galacticv1alpha1.EdgeAttachment) { lh.programmed(att) @@ -118,7 +132,7 @@ func newListenerHarness(t *testing.T) *listenerHarness { }, lh.accepted) lh.beforeStart = func(a *Adapter) { l, err := NewListener(a, ListenerConfig{Namespace: listenerNS, Name: listenerName, UDPPort: 8443, - TCPPort: 8443, Server: lh.srv, Listen: lh.listen}) + TCPPort: 8443, Server: srv, Listen: lh.listen}) if err != nil { t.Fatal(err) } diff --git a/internal/edge/masque/service/service.go b/internal/edge/masque/service/service.go index fc27459a3..bb60b4765 100644 --- a/internal/edge/masque/service/service.go +++ b/internal/edge/masque/service/service.go @@ -229,9 +229,13 @@ func Run(ctx context.Context, cfg Config) error { } runErr <- err } - // The listener attachment stops taking new flows first. Sessions then - // end before the routes, attachments and lease are released. + // The listener attachment stops taking new flows first. The server then + // closes while the listener's sockets are still open, so every client + // receives a close rather than waiting for its idle timeout, and each + // request that ends retires its grant. Sessions end before the routes, + // attachments and lease are released. listening.Store(false) + a.BeginShutdown() t.stop() _ = srv.Close() cancelRun() @@ -323,7 +327,8 @@ func (t *transports) start(ctx context.Context) { } // stop reports the listener attachment not Ready, so gateways send it no new -// flows, and closes its sockets. Call it before the server closes. +// flows, then closes the server and, after it, the listener's sockets, so +// that the server can still send its clients a close on them. func (t *transports) stop() { if t.l == nil { return diff --git a/internal/edge/masque/session.go b/internal/edge/masque/session.go index b33077d45..a3a7e9de5 100644 --- a/internal/edge/masque/session.go +++ b/internal/edge/masque/session.go @@ -142,7 +142,9 @@ func (s *session) Close() error { // close is Close with the release of the route claim bounded by ctx. It // closes the request's packet registration before dropping its references, -// so packets the device queued for this request are discarded with it. +// so packets the device queued for this request are discarded with it. Once +// shutdown has begun it then retires the request's grant, unless a newer +// request of the connector on this pod may hold it. func (s *session) close(ctx context.Context) { s.closeOnce.Do(func() { s.end(reasonClosed) @@ -157,6 +159,9 @@ func (s *session) close(ctx context.Context) { s.a.mu.Unlock() s.a.releaseRoute(ctx, s.rt) s.a.releaseAttachment(s.att) + if s.a.retiring.Load() { + s.a.retireAtShutdown(ctx, s.grant) + } close(s.closed) }) }