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
43 changes: 43 additions & 0 deletions server/pkg/handler/claim_hub_for_create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package handler

import (
"errors"
"fmt"

hub "github.com/hotcode-dev/zerohub/pkg/hub"
"github.com/hotcode-dev/zerohub/pkg/zerohub"
"github.com/rs/zerolog/log"
"github.com/valyala/fasthttp"
)

// claimHubForCreate runs the cross-mode claim under h.hubIdCrossModeMu and
// maps the result onto the shared create response contract: rejected -> 409
// already written by the claim helper (stop), ErrHubAlreadyExists -> 409
// "hub id already exists", any other error -> 500 "create hub error".
// Returns (nil, false) whenever a response has already been written and the
// caller must stop; (hub, true) on success.
func (h *handler) claimHubForCreate(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string, isPermanent bool) (hub.Hub, bool) {
hubMetadata := string(ctx.QueryArgs().Peek("hubMetadata"))
newHub, err, rejected := h.claimUserChosenHubId(ctx, hubId, h.siblingInstances(zh),
func() (hub.Hub, error) {
return zh.CreateHubIfAbsent(hubId, hubMetadata, isPermanent)
})
if rejected {
// A sibling mode already holds this id; claimUserChosenHubId
// wrote the 409 Conflict, so stop without overwriting it.
return nil, false
}
if err != nil {
if errors.Is(err, zerohub.ErrHubAlreadyExists) {
log.Error().Err(fmt.Errorf("hub with id %s already exists", hubId)).Send()
// A marshal failure of this static map body is impossible, so
// Response returns nil; callers stop on the bool, not the error.
h.Response(ctx, fasthttp.StatusConflict, map[string]string{"error": "hub id already exists"})
} else {
log.Error().Err(err).Send()
h.Response(ctx, fasthttp.StatusInternalServerError, map[string]string{"error": "create hub error"})
}
return nil, false
}
return newHub, true
}
153 changes: 153 additions & 0 deletions server/pkg/handler/claim_hub_for_create_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package handler

import (
"errors"
"net/url"
"strings"
"testing"

hub "github.com/hotcode-dev/zerohub/pkg/hub"
"github.com/hotcode-dev/zerohub/pkg/zerohub"
"github.com/valyala/fasthttp"
"go.uber.org/mock/gomock"
)

// TestClaimHubForCreateSuccess pins the shared create-claim helper's success
// contract: on a free id it hands back the created hub with ok=true and
// writes no response — the caller owns what happens next (the WebSocket
// upgrade for /hub/create, the 200 JSON for /v1/static-hubs/create). It also
// pins the metadata passthrough: hubMetadata is read verbatim from the query
// args, and the isPermanent flag is forwarded to CreateHubIfAbsent.
func TestClaimHubForCreateSuccess(t *testing.T) {
const hubId = "room"
const metadata = `{"name":"test"}`

ctrl := gomock.NewController(t)
zh := zerohub.NewMockZeroHub(ctrl)
created := hub.NewHub(hubId, metadata, nil, true)
zh.EXPECT().
CreateHubIfAbsent(hubId, metadata, true).
Return(created, nil).
MaxTimes(1)
sibling := zerohub.NewMockZeroHub(ctrl)
sibling.EXPECT().GetHubById(hubId).Return(nil).MaxTimes(1)

h := newTestHandler()
h.zeroHubStatic = zh
h.zeroHubRandom = sibling

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=" + hubId +
"&hubMetadata=" + url.QueryEscape(metadata))

newHub, ok := h.claimHubForCreate(ctx, zh, hubId, true)
if !ok || newHub != created {
t.Fatalf("claimHubForCreate = (hub:%v, ok:%v), want the created hub and ok=true", newHub, ok)
}
if len(ctx.Response.Body()) != 0 {
t.Errorf("success path wrote a response (%q), want none — the caller writes the response", ctx.Response.Body())
}
}

// TestClaimHubForCreateSiblingCollision pins the rejected branch: when a
// sibling hub mode already holds the id, claimUserChosenHubId writes the 409
// collision and the helper must stop without touching the create target or
// overwriting the response.
func TestClaimHubForCreateSiblingCollision(t *testing.T) {
const hubId = "room"
colliding := hub.NewHub(hubId, `{"name":"x"}`, nil, false)

ctrl := gomock.NewController(t)
zh := zerohub.NewMockZeroHub(ctrl)
// No CreateHubIfAbsent expectation: the collision must abort before
// the create target is touched.
sibling := zerohub.NewMockZeroHub(ctrl)
sibling.EXPECT().GetHubById(hubId).Return(colliding).Times(1)

h := newTestHandler()
h.zeroHubStatic = zh
h.zeroHubRandom = sibling

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=" + hubId)

newHub, ok := h.claimHubForCreate(ctx, zh, hubId, true)
if ok || newHub != nil {
t.Fatalf("claimHubForCreate = (hub:%v, ok:%v), want (nil, false) on sibling collision", newHub, ok)
}
if code := ctx.Response.StatusCode(); code != fasthttp.StatusConflict {
t.Errorf("status = %d, want %d", code, fasthttp.StatusConflict)
}
if body := string(ctx.Response.Body()); !strings.Contains(body, "hub id collides with another hub type") {
t.Errorf("body = %q, want it to contain the collision error", body)
}
}

// TestClaimHubForCreateAlreadyExists pins the same-mode 409 mapping: when
// CreateHubIfAbsent reports the hub already exists, the helper must answer
// 409 "hub id already exists" — not 500 — so the losing side of a concurrent
// create gets the documented conflict status.
func TestClaimHubForCreateAlreadyExists(t *testing.T) {
const hubId = "room"

ctrl := gomock.NewController(t)
zh := zerohub.NewMockZeroHub(ctrl)
zh.EXPECT().
CreateHubIfAbsent(gomock.Any(), gomock.Any(), true).
Return(nil, zerohub.ErrHubAlreadyExists).
MaxTimes(1)
sibling := zerohub.NewMockZeroHub(ctrl)
sibling.EXPECT().GetHubById(hubId).Return(nil).MaxTimes(1)

h := newTestHandler()
h.zeroHubStatic = zh
h.zeroHubRandom = sibling

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=" + hubId)

newHub, ok := h.claimHubForCreate(ctx, zh, hubId, true)
if ok || newHub != nil {
t.Fatalf("claimHubForCreate = (hub:%v, ok:%v), want (nil, false) on ErrHubAlreadyExists", newHub, ok)
}
if code := ctx.Response.StatusCode(); code != fasthttp.StatusConflict {
t.Errorf("status = %d, want %d", code, fasthttp.StatusConflict)
}
if body := string(ctx.Response.Body()); !strings.Contains(body, "hub id already exists") {
t.Errorf("body = %q, want it to contain the already-exists error", body)
}
}

// TestClaimHubForCreateGenericErrorMapsTo500 pins the fallback mapping: any
// create failure other than ErrHubAlreadyExists becomes 500
// "create hub error" (and never leaks the internal error to the client).
func TestClaimHubForCreateGenericErrorMapsTo500(t *testing.T) {
const hubId = "room"

ctrl := gomock.NewController(t)
zh := zerohub.NewMockZeroHub(ctrl)
zh.EXPECT().
CreateHubIfAbsent(gomock.Any(), gomock.Any(), false).
Return(nil, errors.New("storage boom")).
MaxTimes(1)
sibling := zerohub.NewMockZeroHub(ctrl)
sibling.EXPECT().GetHubById(hubId).Return(nil).MaxTimes(1)

h := newTestHandler()
h.zeroHubRandom = zh
h.zeroHubStatic = sibling

ctx := newRequestCtx("http://127.0.0.1/hub/create?hubId=" + hubId)

newHub, ok := h.claimHubForCreate(ctx, zh, hubId, false)
if ok || newHub != nil {
t.Fatalf("claimHubForCreate = (hub:%v, ok:%v), want (nil, false) on generic error", newHub, ok)
}
if code := ctx.Response.StatusCode(); code != fasthttp.StatusInternalServerError {
t.Errorf("status = %d, want %d", code, fasthttp.StatusInternalServerError)
}
body := string(ctx.Response.Body())
if !strings.Contains(body, "create hub error") {
t.Errorf("body = %q, want it to contain 'create hub error'", body)
}
if strings.Contains(body, "storage boom") {
t.Errorf("body = %q leaked the internal error; it must stay opaque", body)
}
}
22 changes: 2 additions & 20 deletions server/pkg/handler/create_hub_by_id.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
package handler

import (
"errors"
"fmt"

hub "github.com/hotcode-dev/zerohub/pkg/hub"
"github.com/hotcode-dev/zerohub/pkg/zerohub"
"github.com/rs/zerolog/log"
"github.com/valyala/fasthttp"
)

Expand All @@ -33,23 +28,10 @@ func (h *handler) CreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hu
// both pass the probe and both store (which would fragment the room
// under one public id). Random-hub callers pass a fresh uuid, which no
// sibling holds, so the probe is a no-op there.
newHub, err, rejected := h.claimUserChosenHubId(ctx, hubId, h.siblingInstances(zh),
func() (hub.Hub, error) {
return zh.CreateHubIfAbsent(hubId, string(ctx.QueryArgs().Peek("hubMetadata")), false)
})
if rejected {
// A sibling mode already holds this id; claimUserChosenHubId
// wrote the 409 Conflict, so stop without overwriting it.
newHub, ok := h.claimHubForCreate(ctx, zh, hubId, false)
if !ok {
return nil
}
if err != nil {
if errors.Is(err, zerohub.ErrHubAlreadyExists) {
log.Error().Err(fmt.Errorf("hub with id %s already exists", hubId)).Send()
return h.Response(ctx, fasthttp.StatusConflict, map[string]string{"error": "hub id already exists"})
}
log.Error().Err(err).Send()
return h.Response(ctx, fasthttp.StatusInternalServerError, map[string]string{"error": "create hub error"})
}

if err, responseWritten := h.Upgrade(ctx, zh, newHub); err != nil || responseWritten {
return h.finishUpgradeFailure(ctx, err, responseWritten,
Expand Down
23 changes: 2 additions & 21 deletions server/pkg/handler/create_static_hub.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
package handler

import (
"errors"
"fmt"

hub "github.com/hotcode-dev/zerohub/pkg/hub"
"github.com/hotcode-dev/zerohub/pkg/zerohub"
"github.com/rs/zerolog/log"
"github.com/valyala/fasthttp"
)

Expand Down Expand Up @@ -54,23 +48,10 @@ func (h *handler) CreateStaticHub(ctx *fasthttp.RequestCtx) error {
// the sibling instances and run CreateHubIfAbsent all while holding
// the lock — so a concurrent create of the same id in another mode
// can't interleave between the probe and the store.
newHub, err, rejected := h.claimUserChosenHubId(ctx, hubId, h.siblingInstances(h.zeroHubStatic),
func() (hub.Hub, error) {
return h.zeroHubStatic.CreateHubIfAbsent(hubId, string(ctx.QueryArgs().Peek("hubMetadata")), true)
})
if rejected {
// A sibling mode already holds this id; claimUserChosenHubId
// wrote the 409 Conflict, so stop without overwriting it.
newHub, ok := h.claimHubForCreate(ctx, h.zeroHubStatic, hubId, true)
if !ok {
return nil
}
if err != nil {
if errors.Is(err, zerohub.ErrHubAlreadyExists) {
log.Error().Err(fmt.Errorf("hub with id %s already exists", hubId)).Send()
return h.Response(ctx, fasthttp.StatusConflict, map[string]string{"error": "hub id already exists"})
}
log.Error().Err(err).Send()
return h.Response(ctx, fasthttp.StatusInternalServerError, map[string]string{"error": "create hub error"})
}

return h.Response(ctx, fasthttp.StatusOK, newHub)
}
Loading