From 8ef7990c5f469a20fde607b23bc7b2650c143d16 Mon Sep 17 00:00:00 2001 From: ntsd Date: Sat, 21 Nov 2026 16:29:45 +0700 Subject: [PATCH] refactor(server): drop single-implementer Handler interface Task: zf-z-94cae19a refactor(server): drop single-implementer Handler interface (Ponytail Rung 1/6) --- server/pkg/handler/auth.go | 2 +- server/pkg/handler/claim_hub_for_create.go | 2 +- server/pkg/handler/create_hub_by_id.go | 2 +- .../pkg/handler/create_hub_permanent_test.go | 2 +- server/pkg/handler/create_hub_random.go | 2 +- server/pkg/handler/create_static_hub.go | 2 +- server/pkg/handler/get_hub.go | 2 +- server/pkg/handler/get_hub_test.go | 2 +- server/pkg/handler/handler.go | 29 +++++++------------ server/pkg/handler/hub_id_validation_test.go | 4 +-- server/pkg/handler/join_hub.go | 2 +- .../pkg/handler/join_or_create_hub_by_id.go | 2 +- server/pkg/handler/join_or_create_hub_ip.go | 2 +- .../pkg/handler/join_or_create_hub_ip_test.go | 2 +- server/pkg/handler/metadata_size_test.go | 4 +-- .../pkg/handler/metadata_validation_test.go | 2 +- server/pkg/handler/migrate.go | 8 ++--- server/pkg/handler/migrate_test.go | 6 ++-- server/pkg/handler/response.go | 2 +- server/pkg/handler/status.go | 2 +- server/pkg/handler/validation.go | 16 +++++----- server/pkg/handler/websocket.go | 6 ++-- server/pkg/handler/websocket_origin_test.go | 2 +- 23 files changed, 49 insertions(+), 56 deletions(-) diff --git a/server/pkg/handler/auth.go b/server/pkg/handler/auth.go index ed23f9e..fb34747 100644 --- a/server/pkg/handler/auth.go +++ b/server/pkg/handler/auth.go @@ -18,7 +18,7 @@ var errAdminUnauthorized = errors.New("admin authorization failed") // CheckAdminAuth checks if the request is authorized to perform admin actions. // On failure it writes the 401 JSON body AND returns a non-nil error so the // caller can bail out without touching any state. -func (h *handler) CheckAdminAuth(ctx *fasthttp.RequestCtx) error { +func (h *Handler) CheckAdminAuth(ctx *fasthttp.RequestCtx) error { authCode, err := base64.StdEncoding.DecodeString(string(ctx.Request.Header.Peek("Authorization"))) if err != nil { log.Error().Err(fmt.Errorf("error decoding authorization code: %w", err)).Send() diff --git a/server/pkg/handler/claim_hub_for_create.go b/server/pkg/handler/claim_hub_for_create.go index aa02be5..e8345f7 100644 --- a/server/pkg/handler/claim_hub_for_create.go +++ b/server/pkg/handler/claim_hub_for_create.go @@ -16,7 +16,7 @@ import ( // "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) { +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) { diff --git a/server/pkg/handler/create_hub_by_id.go b/server/pkg/handler/create_hub_by_id.go index 1213577..d6e25b8 100644 --- a/server/pkg/handler/create_hub_by_id.go +++ b/server/pkg/handler/create_hub_by_id.go @@ -11,7 +11,7 @@ import ( // exactly one wins and the rest get 409. Random-hub callers pass a fresh // uuid that cannot collide, so the 409 branch is unreachable there — the // shared path just stays safe. -func (h *handler) CreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error { +func (h *Handler) CreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error { // Static callers pass the `id` param verbatim; random-hub callers pass // a generated uuid. The shared validation helper rejects an // empty/whitespace id and oversized params before any hub state is diff --git a/server/pkg/handler/create_hub_permanent_test.go b/server/pkg/handler/create_hub_permanent_test.go index 5bdc853..05b378a 100644 --- a/server/pkg/handler/create_hub_permanent_test.go +++ b/server/pkg/handler/create_hub_permanent_test.go @@ -16,7 +16,7 @@ import ( // migration endpoints) on a random local port so requests land in fasthttp // worker goroutines, exactly like production. This is what a real unauthenticated // WebSocket client would hit. -func startStaticCreateTestServer(t *testing.T, h *handler) string { +func startStaticCreateTestServer(t *testing.T, h *Handler) string { t.Helper() requestHandler := func(ctx *fasthttp.RequestCtx) { diff --git a/server/pkg/handler/create_hub_random.go b/server/pkg/handler/create_hub_random.go index 5928c17..ab1443f 100644 --- a/server/pkg/handler/create_hub_random.go +++ b/server/pkg/handler/create_hub_random.go @@ -7,7 +7,7 @@ import ( ) // CreateHubRandom creates a new hub with a random ID. -func (h *handler) CreateHubRandom(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { +func (h *Handler) CreateHubRandom(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { if h.isMigrating.Load() { return h.ForwardMigrate(ctx) } diff --git a/server/pkg/handler/create_static_hub.go b/server/pkg/handler/create_static_hub.go index 4526086..78d7d36 100644 --- a/server/pkg/handler/create_static_hub.go +++ b/server/pkg/handler/create_static_hub.go @@ -12,7 +12,7 @@ import ( // create goes through the atomic CreateHubIfAbsent primitive, so // concurrent requests for the same ID never orphan a hub: exactly one wins // and the rest get 409. -func (h *handler) CreateStaticHub(ctx *fasthttp.RequestCtx) error { +func (h *Handler) CreateStaticHub(ctx *fasthttp.RequestCtx) error { // Auth runs before the migration check so an unauthenticated request is // answered with 401 instead of a WebSocket close whose reason is the // internal backup host. No state is mutated between the two checks, so diff --git a/server/pkg/handler/get_hub.go b/server/pkg/handler/get_hub.go index 6ccd2bb..26b929d 100644 --- a/server/pkg/handler/get_hub.go +++ b/server/pkg/handler/get_hub.go @@ -10,7 +10,7 @@ import ( ) // GetHub returns the hub with the given ID. -func (h *handler) GetHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { +func (h *Handler) GetHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { hubId := string(ctx.QueryArgs().Peek("id")) // Reject a missing/empty ID up front with 400 for consistency with the // other hub endpoints. diff --git a/server/pkg/handler/get_hub_test.go b/server/pkg/handler/get_hub_test.go index d647f14..24469aa 100644 --- a/server/pkg/handler/get_hub_test.go +++ b/server/pkg/handler/get_hub_test.go @@ -14,7 +14,7 @@ import ( // startGetHubTestServer serves the plain-HTTP hub-metadata read endpoint on a // random local port, mirroring the routing in handler.go: // /v1/random-hubs/get against the random instance. -func startGetHubTestServer(t *testing.T, h *handler) string { +func startGetHubTestServer(t *testing.T, h *Handler) string { t.Helper() requestHandler := func(ctx *fasthttp.RequestCtx) { diff --git a/server/pkg/handler/handler.go b/server/pkg/handler/handler.go index 0bbff96..62685fe 100644 --- a/server/pkg/handler/handler.go +++ b/server/pkg/handler/handler.go @@ -49,19 +49,12 @@ import ( "github.com/valyala/fasthttp" ) -// Handler is the entrypoint contract for the signaling server. It exposes -// the HTTP route set documented in the package comment +// Handler is the HTTP handler for the signaling server. It exposes the +// HTTP route set documented in the package comment // (/v1/status, /v1/admin/migrate, /v1/static-hubs/{create,join}, // /v1/random-hubs/{create,get,join}, /v1/ip-hubs/join-or-create). The -// per-route handlers live on the unexported handler type and are wired -// inside Serve. -type Handler interface { - // Serve starts the fasthttp server on the configured address. - Serve() error -} - -// handler implements the Handler interface. -type handler struct { +// per-route handlers are wired inside Serve. +type Handler struct { // address is the address to listen on. address string // clientSecret is the client secret to use for authentication. @@ -132,14 +125,14 @@ type handler struct { // idleTimeout / pingInterval return the effective probe timings, falling // back to the config defaults when the handler was built by NewHandler // (which leaves the fields at zero). -func (h *handler) idleTimeout() time.Duration { +func (h *Handler) idleTimeout() time.Duration { if h.wsIdleTimeout > 0 { return h.wsIdleTimeout } return config.WSIdleTimeout } -func (h *handler) pingInterval() time.Duration { +func (h *Handler) pingInterval() time.Duration { if h.wsPingInterval > 0 { return h.wsPingInterval } @@ -151,12 +144,12 @@ func (h *handler) pingInterval() time.Duration { return config.WSIdleTimeout / 4 } -// NewHandler create a new handler -func NewHandler(cfg *config.Config, zeroHubStatic zerohub.ZeroHub, zeroHubRandom zerohub.ZeroHub, zeroHubIP zerohub.ZeroHub) (Handler, error) { +// NewHandler creates a new Handler. +func NewHandler(cfg *config.Config, zeroHubStatic zerohub.ZeroHub, zeroHubRandom zerohub.ZeroHub, zeroHubIP zerohub.ZeroHub) (*Handler, error) { if cfg.App.ClientSecret == "" { return nil, fmt.Errorf("APP_CLIENT_SECRET must not be empty: an empty secret would leave admin endpoints open to unauthenticated requests") } - return &handler{ + return &Handler{ address: fmt.Sprintf("%s:%s", cfg.App.Host, cfg.App.Port), clientSecret: cfg.App.ClientSecret, trustProxy: cfg.App.TrustProxy, @@ -186,7 +179,7 @@ func NewHandler(cfg *config.Config, zeroHubStatic zerohub.ZeroHub, zeroHubRandom // SECURITY: safe only behind a proxy that strips or replaces // X-Forwarded-For; in front of an untrusted hop any client could forge a // fresh hub IP per request. -func (h *handler) clientIP(ctx *fasthttp.RequestCtx) string { +func (h *Handler) clientIP(ctx *fasthttp.RequestCtx) string { if h.trustProxy { if ip := ipFromForwardedHeader(ctx); ip != "" { return ip @@ -240,7 +233,7 @@ func ipFromForwardedHeader(ctx *fasthttp.RequestCtx) string { return ip.String() } -func (h *handler) Serve() error { +func (h *Handler) Serve() error { rateLimitMiddleware := newRateLimitMiddleware(h.trustProxy) requestHandler := func(ctx *fasthttp.RequestCtx) { diff --git a/server/pkg/handler/hub_id_validation_test.go b/server/pkg/handler/hub_id_validation_test.go index 5914f60..863d559 100644 --- a/server/pkg/handler/hub_id_validation_test.go +++ b/server/pkg/handler/hub_id_validation_test.go @@ -29,7 +29,7 @@ func TestCreateStaticHubRejectsEmptyHubId(t *testing.T) { ctrl := gomock.NewController(t) staticMock := zerohub.NewMockZeroHub(ctrl) // No expectations: the 400 must be written before CreateHubIfAbsent. - h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} + h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=") ctx.Request.Header.Set("Authorization", adminAuthHeader()) @@ -44,7 +44,7 @@ func TestCreateStaticHubRejectsEmptyHubId(t *testing.T) { func TestCreateStaticHubAuthPrecedenceOverInvalidId(t *testing.T) { ctrl := gomock.NewController(t) staticMock := zerohub.NewMockZeroHub(ctrl) - h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} + h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create") // No Authorization header. diff --git a/server/pkg/handler/join_hub.go b/server/pkg/handler/join_hub.go index b6aca41..7992673 100644 --- a/server/pkg/handler/join_hub.go +++ b/server/pkg/handler/join_hub.go @@ -7,7 +7,7 @@ import ( ) // JoinHub joins an existing hub with the given ID. -func (h *handler) JoinHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { +func (h *Handler) JoinHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { hubId := string(ctx.QueryArgs().Peek("id")) // Reject a missing/empty ID up front with 400 for consistency: before // this, such a request degraded to 404 (or a migration forward). 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 eba37eb..457de01 100644 --- a/server/pkg/handler/join_or_create_hub_by_id.go +++ b/server/pkg/handler/join_or_create_hub_by_id.go @@ -10,7 +10,7 @@ import ( // JoinOrCreateHubByID joins an existing hub with the given ID or creates a new one if it does not exist. // The get-or-create is atomic at the ZeroHub layer, so concurrent join-or-create // calls for the same ID always land in the same hub. -func (h *handler) JoinOrCreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error { +func (h *Handler) JoinOrCreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error { // Static callers pass the `id` param verbatim; IP-hub callers pass a // generated FNV hash. The shared validation helper rejects an // empty/whitespace id and oversized params before any hub state is diff --git a/server/pkg/handler/join_or_create_hub_ip.go b/server/pkg/handler/join_or_create_hub_ip.go index aa3db78..0473a75 100644 --- a/server/pkg/handler/join_or_create_hub_ip.go +++ b/server/pkg/handler/join_or_create_hub_ip.go @@ -27,7 +27,7 @@ func fnvHash64a(s string) string { // connections from one client IP share a hub; that is intentionally // different from the rate limiter, which keys by the full socket address // (IP:port) so each connection gets its own DoS budget. See clientIP. -func (h *handler) JoinOrCreateHubIP(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { +func (h *Handler) JoinOrCreateHubIP(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error { if h.isMigrating.Load() { return h.ForwardMigrate(ctx) } diff --git a/server/pkg/handler/join_or_create_hub_ip_test.go b/server/pkg/handler/join_or_create_hub_ip_test.go index 8e61e61..2ac7a11 100644 --- a/server/pkg/handler/join_or_create_hub_ip_test.go +++ b/server/pkg/handler/join_or_create_hub_ip_test.go @@ -43,7 +43,7 @@ func captureHubKey(t *testing.T, got *string) zerohub.ZeroHub { // joinOrCreateHubIPRequest assembles a handler-level request with the given // socket peer address and optional X-Forwarded-For value, then invokes // JoinOrCreateHubIP on it, returning the hub ID the handler derived. -func joinOrCreateHubIPRequest(t *testing.T, h *handler, got *string, socketIP, xff string) string { +func joinOrCreateHubIPRequest(t *testing.T, h *Handler, got *string, socketIP, xff string) string { t.Helper() ctx := &fasthttp.RequestCtx{} diff --git a/server/pkg/handler/metadata_size_test.go b/server/pkg/handler/metadata_size_test.go index 45f3d85..6655881 100644 --- a/server/pkg/handler/metadata_size_test.go +++ b/server/pkg/handler/metadata_size_test.go @@ -111,7 +111,7 @@ func TestCreateStaticHubRejectsOversizedHubMetadata(t *testing.T) { ctrl := gomock.NewController(t) staticMock := zerohub.NewMockZeroHub(ctrl) // No expectations: the 413 must be written before any hub-state access. - h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} + h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=static-hub&hubMetadata=" + oversizedValue) ctx.Request.Header.Set("Authorization", adminAuthHeader()) @@ -181,7 +181,7 @@ func TestOversizedIdRejected(t *testing.T) { staticMock := zerohub.NewMockZeroHub(ctrl) // The 413 for the oversized id must win over the cross-mode // collision guard, so zeroHubRandom can stay nil. - h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} + h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=" + oversizedID) ctx.Request.Header.Set("Authorization", adminAuthHeader()) diff --git a/server/pkg/handler/metadata_validation_test.go b/server/pkg/handler/metadata_validation_test.go index 723a08e..8f94108 100644 --- a/server/pkg/handler/metadata_validation_test.go +++ b/server/pkg/handler/metadata_validation_test.go @@ -101,7 +101,7 @@ func TestCreateStaticHubRejectsMalformedHubMetadata(t *testing.T) { staticMock := zerohub.NewMockZeroHub(ctrl) // No expectations: the 400 for malformed metadata must be written // before any hub-state access (CreateHubIfAbsent). - h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} + h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock} ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=static-hub&hubMetadata=not-json") ctx.Request.Header.Set("Authorization", adminAuthHeader()) diff --git a/server/pkg/handler/migrate.go b/server/pkg/handler/migrate.go index bc93498..b5d8e59 100644 --- a/server/pkg/handler/migrate.go +++ b/server/pkg/handler/migrate.go @@ -24,7 +24,7 @@ import ( // 4. Wait until no hub left. // 5. Graceful shutdown. // 6. redeploy the new version of server. -func (h *handler) Migrate(ctx *fasthttp.RequestCtx) error { +func (h *Handler) Migrate(ctx *fasthttp.RequestCtx) error { if err := h.CheckAdminAuth(ctx); err != nil { return err } @@ -57,7 +57,7 @@ func (h *handler) Migrate(ctx *fasthttp.RequestCtx) error { return nil } -func (h *handler) ForwardMigrate(ctx *fasthttp.RequestCtx) error { +func (h *Handler) ForwardMigrate(ctx *fasthttp.RequestCtx) error { backupHost := h.getBackupHost() // The 301 status is not working on multi library following the rfc6455 @@ -109,14 +109,14 @@ func (h *handler) ForwardMigrate(ctx *fasthttp.RequestCtx) error { // attempting an upgrade would fail the handshake and surface as a 503 // "websocket handshake". Plain-HTTP handlers must return this response // instead and must never call ForwardMigrate. -func (h *handler) migrateHTTPResponse(ctx *fasthttp.RequestCtx) error { +func (h *Handler) migrateHTTPResponse(ctx *fasthttp.RequestCtx) error { return h.Response(ctx, fasthttp.StatusMovedPermanently, map[string]string{"status": "migrating", "backupHost": h.getBackupHost()}) } // getBackupHost returns the current backup host under a read lock so it is // safe to read concurrently with Migrate. -func (h *handler) getBackupHost() string { +func (h *Handler) getBackupHost() string { h.migrateMu.RLock() defer h.migrateMu.RUnlock() return h.backupHost diff --git a/server/pkg/handler/migrate_test.go b/server/pkg/handler/migrate_test.go index 96881fb..9744cdf 100644 --- a/server/pkg/handler/migrate_test.go +++ b/server/pkg/handler/migrate_test.go @@ -21,8 +21,8 @@ const ( // newTestHandler builds a handler with a known client secret, matching how // handler.go constructs the handler from the config's client secret. -func newTestHandler() *handler { - return &handler{clientSecret: testClientSecret} +func newTestHandler() *Handler { + return &Handler{clientSecret: testClientSecret} } // adminAuthHeader returns the base64-encoded admin authorization header value. @@ -33,7 +33,7 @@ func adminAuthHeader() string { // startTestServer serves the handler's real migration endpoints on a random // local port. Requests therefore land in fasthttp worker goroutines, exactly // like production, which is what the regression test below hammers. -func startTestServer(t *testing.T, h *handler) string { +func startTestServer(t *testing.T, h *Handler) string { t.Helper() requestHandler := func(ctx *fasthttp.RequestCtx) { diff --git a/server/pkg/handler/response.go b/server/pkg/handler/response.go index 0ec8a43..852d7cc 100644 --- a/server/pkg/handler/response.go +++ b/server/pkg/handler/response.go @@ -8,7 +8,7 @@ import ( ) // Response is a helper function to write a JSON response to the client. -func (h *handler) Response(ctx *fasthttp.RequestCtx, statusCode int, body interface{}) error { +func (h *Handler) Response(ctx *fasthttp.RequestCtx, statusCode int, body interface{}) error { data, err := json.Marshal(body) if err != nil { ctx.SetStatusCode(fasthttp.StatusInternalServerError) diff --git a/server/pkg/handler/status.go b/server/pkg/handler/status.go index 4862153..740c767 100644 --- a/server/pkg/handler/status.go +++ b/server/pkg/handler/status.go @@ -16,7 +16,7 @@ import ( // anti-pattern, and is unnecessary here since the endpoint is open to all // origins anyway. The exposed data (status + backupHost) is considered // public. -func (h *handler) Status(ctx *fasthttp.RequestCtx) error { +func (h *Handler) Status(ctx *fasthttp.RequestCtx) error { ctx.Response.Header.Set("Access-Control-Allow-Origin", "*") ctx.Response.Header.Add("Vary", "Origin") diff --git a/server/pkg/handler/validation.go b/server/pkg/handler/validation.go index c745639..8998c3f 100644 --- a/server/pkg/handler/validation.go +++ b/server/pkg/handler/validation.go @@ -29,7 +29,7 @@ func validHubId(hubId string) bool { // rejectInvalidHubIdParam writes the 400 for a missing/empty `id` query // parameter. It reuses Response (which returns nil on success) so the // caller's 503 error fallback in Serve cannot overwrite the 400 body. -func (h *handler) rejectInvalidHubIdParam(ctx *fasthttp.RequestCtx) error { +func (h *Handler) rejectInvalidHubIdParam(ctx *fasthttp.RequestCtx) error { return h.Response(ctx, fasthttp.StatusBadRequest, map[string]string{"error": "id query parameter is required"}) } @@ -50,7 +50,7 @@ func validMetadataSize(raw string, max int) bool { // rejectOversizedParam writes the 413 for a query parameter that exceeds // the size cap. It reuses Response (which returns nil on success) so the // caller's 503 error fallback in Serve cannot overwrite the 413 body. -func (h *handler) rejectOversizedParam(ctx *fasthttp.RequestCtx, param string, max int) error { +func (h *Handler) rejectOversizedParam(ctx *fasthttp.RequestCtx, param string, max int) error { return h.Response(ctx, fasthttp.StatusRequestEntityTooLarge, map[string]string{"error": param + " query parameter exceeds the maximum size of " + strconv.Itoa(max) + " bytes"}) } @@ -71,7 +71,7 @@ func validJSONQueryParam(ctx *fasthttp.RequestCtx, param string) bool { // rejectInvalidJSONParam writes the 400 for a malformed JSON query // parameter. It reuses Response (which returns nil on success) so the // caller's 503 error fallback cannot overwrite the 400 body. -func (h *handler) rejectInvalidJSONParam(ctx *fasthttp.RequestCtx, param string) error { +func (h *Handler) rejectInvalidJSONParam(ctx *fasthttp.RequestCtx, param string) error { return h.Response(ctx, fasthttp.StatusBadRequest, map[string]string{"error": "invalid " + param + " query parameter: must be JSON"}) } @@ -100,7 +100,7 @@ func (h *handler) rejectInvalidJSONParam(ctx *fasthttp.RequestCtx, param string) // it is stored and re-sent to every joiner, and the size guard answers an // oversized blob with 413 without running json.Valid on a large payload — // the cheaper path, and the real DoS guard. -func (h *handler) validateHubCreateParams(ctx *fasthttp.RequestCtx, hubId string) bool { +func (h *Handler) validateHubCreateParams(ctx *fasthttp.RequestCtx, hubId string) bool { if !validHubId(hubId) { _ = h.rejectInvalidHubIdParam(ctx) return true @@ -128,7 +128,7 @@ func (h *handler) validateHubCreateParams(ctx *fasthttp.RequestCtx, hubId string // sibling instances. Callers run it and the subsequent create under // h.hubIdCrossModeMu so the cross-mode check-and-store is mutually // exclusive. -func (h *handler) probeSiblingsForCollision(ctx *fasthttp.RequestCtx, hubId string, siblings []zerohub.ZeroHub) bool { +func (h *Handler) probeSiblingsForCollision(ctx *fasthttp.RequestCtx, hubId string, siblings []zerohub.ZeroHub) bool { for _, instance := range siblings { if instance == nil { continue @@ -163,7 +163,7 @@ func (h *handler) probeSiblingsForCollision(ctx *fasthttp.RequestCtx, hubId stri // same-mode ErrHubAlreadyExists) is passed through with rejected=false. // A nil sibling holds no hubs and is skipped, keeping the guard usable // from call sites that only have some of the sibling instances. -func (h *handler) claimUserChosenHubId(ctx *fasthttp.RequestCtx, hubId string, siblings []zerohub.ZeroHub, create func() (hub.Hub, error)) (newHub hub.Hub, err error, rejected bool) { +func (h *Handler) claimUserChosenHubId(ctx *fasthttp.RequestCtx, hubId string, siblings []zerohub.ZeroHub, create func() (hub.Hub, error)) (newHub hub.Hub, err error, rejected bool) { h.hubIdCrossModeMu.Lock() defer h.hubIdCrossModeMu.Unlock() if h.probeSiblingsForCollision(ctx, hubId, siblings) { @@ -179,7 +179,7 @@ func (h *handler) claimUserChosenHubId(ctx *fasthttp.RequestCtx, hubId string, s // h.hubIdCrossModeMu — so a join-or-create that would mint a new hub can't // race a create in another mode into storing two hubs under one public id. // The 409/rejected contract matches claimUserChosenHubId. -func (h *handler) claimGetOrCreateHub(ctx *fasthttp.RequestCtx, hubId string, siblings []zerohub.ZeroHub, getOrCreate func() (hub.Hub, bool, error)) (newHub hub.Hub, created bool, err error, rejected bool) { +func (h *Handler) claimGetOrCreateHub(ctx *fasthttp.RequestCtx, hubId string, siblings []zerohub.ZeroHub, getOrCreate func() (hub.Hub, bool, error)) (newHub hub.Hub, created bool, err error, rejected bool) { h.hubIdCrossModeMu.Lock() defer h.hubIdCrossModeMu.Unlock() if h.probeSiblingsForCollision(ctx, hubId, siblings) { @@ -196,7 +196,7 @@ func (h *handler) claimGetOrCreateHub(ctx *fasthttp.RequestCtx, hubId string, si // tests) where only some of the instances are present. Excluding self // avoids a self-probe that would 409 its own just-created hub; same-mode // duplicates are already caught atomically by the create primitive. -func (h *handler) siblingInstances(self zerohub.ZeroHub) []zerohub.ZeroHub { +func (h *Handler) siblingInstances(self zerohub.ZeroHub) []zerohub.ZeroHub { siblings := []zerohub.ZeroHub{} for _, instance := range []zerohub.ZeroHub{h.zeroHubStatic, h.zeroHubRandom, h.zeroHubIP} { if instance == nil || instance == self { diff --git a/server/pkg/handler/websocket.go b/server/pkg/handler/websocket.go index 840b109..ac5d7c1 100644 --- a/server/pkg/handler/websocket.go +++ b/server/pkg/handler/websocket.go @@ -61,7 +61,7 @@ func sameOriginOrAllowed(ctx *fasthttp.RequestCtx, allowedOrigins []string) bool // newWSUpgrader builds the shared WebSocket upgrader with origin validation // wired to the configured APP_ALLOWED_ORIGINS allow-list. -func (h *handler) newWSUpgrader() *websocket.FastHTTPUpgrader { +func (h *Handler) newWSUpgrader() *websocket.FastHTTPUpgrader { return &websocket.FastHTTPUpgrader{ HandshakeTimeout: config.WSHandshakeTimeout, ReadBufferSize: config.WSReadBufferSize, @@ -77,7 +77,7 @@ func (h *handler) newWSUpgrader() *websocket.FastHTTPUpgrader { // (returned as a nil error with responseWritten=true); any other failure is // a handshake error. When responseWritten is true the caller must not write // another response. -func (h *handler) Upgrade(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hub hub.Hub) (error, bool) { +func (h *Handler) Upgrade(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hub hub.Hub) (error, bool) { // Reject an oversized `peerMetadata` before the handshake: it would // otherwise be stored on the peer and re-broadcast to every existing // peer, amplifying a single value O(N) across the hub. Once upgraded, @@ -248,7 +248,7 @@ func (h *handler) Upgrade(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hub hub. // 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( +func (h *Handler) finishUpgradeFailure( ctx *fasthttp.RequestCtx, err error, responseWritten bool, rollback func(), ) error { if rollback != nil { diff --git a/server/pkg/handler/websocket_origin_test.go b/server/pkg/handler/websocket_origin_test.go index 0a680fb..63e99d0 100644 --- a/server/pkg/handler/websocket_origin_test.go +++ b/server/pkg/handler/websocket_origin_test.go @@ -30,7 +30,7 @@ func newWSHandshakeCtx(host string, origin string) *fasthttp.RequestCtx { // when the gate passes and the handshake completes (the hijacked connection // has no real network behind it in-process, but the 101 response is already // written at that point). -func wsUpgradeStatus(t *testing.T, h *handler, host, origin string) int { +func wsUpgradeStatus(t *testing.T, h *Handler, host, origin string) int { t.Helper() ctx := newWSHandshakeCtx(host, origin) seed, _, err := h.zeroHubStatic.GetOrCreateHub("room", "", false)