From f6244a4ebc488e996e4935c6a08478f6c1eec4ea Mon Sep 17 00:00:00 2001 From: ntsd Date: Fri, 20 Nov 2026 02:18:31 +0700 Subject: [PATCH] refactor(server): dedup triplicated upgrade-failure epilogue in 3 hub handlers Task: zf-z-69f76171 refactor(server): dedup triplicated upgrade-failure epilogue in 3 hub handlers (Ponytail Rung 2) --- server/pkg/handler/create_hub_by_id.go | 15 ++------ server/pkg/handler/join_hub.go | 13 +------ .../pkg/handler/join_or_create_hub_by_id.go | 26 ++++---------- .../join_or_create_upgrade_failure_test.go | 34 +++++++++++++++++++ server/pkg/handler/websocket.go | 20 +++++++++++ 5 files changed, 63 insertions(+), 45 deletions(-) diff --git a/server/pkg/handler/create_hub_by_id.go b/server/pkg/handler/create_hub_by_id.go index 52ca464..86eaae7 100644 --- a/server/pkg/handler/create_hub_by_id.go +++ b/server/pkg/handler/create_hub_by_id.go @@ -52,19 +52,8 @@ func (h *handler) CreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hu } if err, responseWritten := h.Upgrade(ctx, zh, newHub); err != nil || responseWritten { - // remove the hub if the upgrade failed — including the up-front - // peerMetadata rejection, which returns a pre-written 400 instead of - // an error - zh.RemoveHubById(newHub.GetId()) - if err != nil { - log.Error().Err(fmt.Errorf("websocket upgrade error: %w", err)).Send() - } - // The up-front peerMetadata rejection already wrote a 400; do not - // overwrite it with a 500. - if responseWritten { - return nil - } - return h.Response(ctx, fasthttp.StatusInternalServerError, map[string]string{"error": "websocket upgrade error"}) + return h.finishUpgradeFailure(ctx, err, responseWritten, + func() { zh.RemoveHubById(newHub.GetId()) }) } return nil diff --git a/server/pkg/handler/join_hub.go b/server/pkg/handler/join_hub.go index 49238eb..b6aca41 100644 --- a/server/pkg/handler/join_hub.go +++ b/server/pkg/handler/join_hub.go @@ -1,11 +1,8 @@ package handler import ( - "fmt" - "github.com/hotcode-dev/zerohub/pkg/config" "github.com/hotcode-dev/zerohub/pkg/zerohub" - "github.com/rs/zerolog/log" "github.com/valyala/fasthttp" ) @@ -35,15 +32,7 @@ func (h *handler) JoinHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { } if err, responseWritten := h.Upgrade(ctx, zh, hub); err != nil || responseWritten { - if err != nil { - log.Error().Err(fmt.Errorf("websocket upgrade error: %w", err)).Send() - } - // The up-front peerMetadata rejection already wrote a 400; do not - // overwrite it with a 500. - if responseWritten { - return nil - } - return h.Response(ctx, fasthttp.StatusInternalServerError, map[string]string{"error": "websocket upgrade error"}) + return h.finishUpgradeFailure(ctx, err, responseWritten, nil) } return nil diff --git a/server/pkg/handler/join_or_create_hub_by_id.go b/server/pkg/handler/join_or_create_hub_by_id.go index ed04b94..c13423e 100644 --- a/server/pkg/handler/join_or_create_hub_by_id.go +++ b/server/pkg/handler/join_or_create_hub_by_id.go @@ -1,8 +1,6 @@ package handler import ( - "fmt" - hub "github.com/hotcode-dev/zerohub/pkg/hub" "github.com/hotcode-dev/zerohub/pkg/zerohub" "github.com/rs/zerolog/log" @@ -44,24 +42,12 @@ func (h *handler) JoinOrCreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroH } if err, responseWritten := h.Upgrade(ctx, zh, newHub); err != nil || responseWritten { - // AddPeer only runs inside the upgrade callback, so whenever the - // upgrade does not fully succeed — a real handshake error, or the - // up-front peerMetadata rejection that already wrote a 400 — this - // request never added a peer. Remove the hub only when this call - // created it: a pre-existing hub may hold live peers and must be - // left in place. - if created { - zh.RemoveHubById(newHub.GetId()) - } - if err != nil { - log.Error().Err(fmt.Errorf("websocket upgrade error: %w", err)).Send() - } - // The up-front peerMetadata rejection already wrote a 400; do not - // overwrite it with a 500. - if responseWritten { - return nil - } - return h.Response(ctx, fasthttp.StatusInternalServerError, map[string]string{"error": "websocket upgrade error"}) + return h.finishUpgradeFailure(ctx, err, responseWritten, + func() { + if created { + zh.RemoveHubById(newHub.GetId()) + } + }) } return nil diff --git a/server/pkg/handler/join_or_create_upgrade_failure_test.go b/server/pkg/handler/join_or_create_upgrade_failure_test.go index 8ab3682..c3ecce6 100644 --- a/server/pkg/handler/join_or_create_upgrade_failure_test.go +++ b/server/pkg/handler/join_or_create_upgrade_failure_test.go @@ -2,6 +2,7 @@ package handler import ( "net" + "strings" "testing" "github.com/hotcode-dev/zerohub/pkg/config" @@ -174,3 +175,36 @@ func TestJoinHubPreserves400OnMalformedPeerMetadata(t *testing.T) { t.Fatalf("hub %q removed after rejected upgrade on a pre-existing hub, want kept", hubId) } } + +// TestFinishUpgradeFailureWrites500Fallback pins the shared epilogue's 500 +// fallback (previously copy-pasted into all three handlers): when the +// websocket handshake fails with a real error and no up-front rejection has +// written a response, finishUpgradeFailure must write a 500 with the shared +// "websocket upgrade error" body. Exercised through JoinHub so the +// no-rollback policy (pre-existing hub survives) is asserted at the same +// time. +func TestFinishUpgradeFailureWrites500Fallback(t *testing.T) { + const hubId = "fallback-500-hub" + zh := newRealZeroHub(t) + + seed, created, err := zh.GetOrCreateHub(hubId, "", false) + if err != nil || !created || seed == nil { + t.Fatalf("seed GetOrCreateHub = (%v, %v, %v), want (hub, true, nil)", seed, created, err) + } + + h := newTestHandler() + // Plain GET: the handshake fails with a real error and no up-front + // rejection wrote a response, so the shared fallback must write the 500. + ctx := newRequestCtx("http://127.0.0.1/v1/random-hubs/join?id=" + hubId) + _ = h.JoinHub(ctx, zh) + + if got := ctx.Response.StatusCode(); got != fasthttp.StatusInternalServerError { + t.Fatalf("status = %d, want %d", got, fasthttp.StatusInternalServerError) + } + if body := ctx.Response.String(); !strings.Contains(body, "websocket upgrade error") { + t.Fatalf("body = %q, want it to contain %q", body, "websocket upgrade error") + } + if gotHub := zh.GetHubById(hubId); gotHub == nil { + t.Fatalf("hub %q removed on a no-rollback path, want kept", hubId) + } +} diff --git a/server/pkg/handler/websocket.go b/server/pkg/handler/websocket.go index 256663f..840b109 100644 --- a/server/pkg/handler/websocket.go +++ b/server/pkg/handler/websocket.go @@ -243,3 +243,23 @@ func (h *handler) Upgrade(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hub hub. return nil, false } + +// finishUpgradeFailure handles the shared post-Upgrade failure path: +// optional state rollback, error logging, the responseWritten guard +// (the up-front peerMetadata 400/413 must not be overwritten with a 500), +// and the 500 fallback. `rollback` is nil when no state needs cleanup. +func (h *handler) finishUpgradeFailure( + ctx *fasthttp.RequestCtx, err error, responseWritten bool, rollback func(), +) error { + if rollback != nil { + rollback() + } + if err != nil { + log.Error().Err(fmt.Errorf("websocket upgrade error: %w", err)).Send() + } + if responseWritten { + return nil + } + return h.Response(ctx, fasthttp.StatusInternalServerError, + map[string]string{"error": "websocket upgrade error"}) +}