Skip to content
Merged
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
15 changes: 2 additions & 13 deletions server/pkg/handler/create_hub_by_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 1 addition & 12 deletions server/pkg/handler/join_hub.go
Original file line number Diff line number Diff line change
@@ -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"
)

Expand Down Expand Up @@ -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
Expand Down
26 changes: 6 additions & 20 deletions server/pkg/handler/join_or_create_hub_by_id.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions server/pkg/handler/join_or_create_upgrade_failure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package handler

import (
"net"
"strings"
"testing"

"github.com/hotcode-dev/zerohub/pkg/config"
Expand Down Expand Up @@ -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)
}
}
20 changes: 20 additions & 0 deletions server/pkg/handler/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
}
Loading