feat: user service
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
package internalhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"galaxy/user/internal/service/adminusers"
|
||||
"galaxy/user/internal/service/shared"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type getUserByEmailRequest struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
type getUserByRaceNameRequest struct {
|
||||
RaceName string `json:"race_name"`
|
||||
}
|
||||
|
||||
func handleGetUserByID(useCase GetUserByIDUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, adminusers.GetUserByIDInput{
|
||||
UserID: c.Param("user_id"),
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetUserByEmail(useCase GetUserByEmailUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request getUserByEmailRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, adminusers.GetUserByEmailInput{
|
||||
Email: request.Email,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetUserByRaceName(useCase GetUserByRaceNameUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request getUserByRaceNameRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, adminusers.GetUserByRaceNameInput{
|
||||
RaceName: request.RaceName,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func handleListUsers(useCase ListUsersUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
input, err := buildListUsersInput(c)
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, input)
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func buildListUsersInput(c *gin.Context) (adminusers.ListUsersInput, error) {
|
||||
pageSize, err := parseOptionalPageSize(c, "page_size")
|
||||
if err != nil {
|
||||
return adminusers.ListUsersInput{}, err
|
||||
}
|
||||
pageToken, err := parseOptionalPageToken(c, "page_token")
|
||||
if err != nil {
|
||||
return adminusers.ListUsersInput{}, err
|
||||
}
|
||||
paidExpiresBefore, err := parseOptionalRFC3339Query(c, "paid_expires_before")
|
||||
if err != nil {
|
||||
return adminusers.ListUsersInput{}, err
|
||||
}
|
||||
paidExpiresAfter, err := parseOptionalRFC3339Query(c, "paid_expires_after")
|
||||
if err != nil {
|
||||
return adminusers.ListUsersInput{}, err
|
||||
}
|
||||
canLogin, err := parseOptionalBoolQuery(c, "can_login")
|
||||
if err != nil {
|
||||
return adminusers.ListUsersInput{}, err
|
||||
}
|
||||
canCreatePrivateGame, err := parseOptionalBoolQuery(c, "can_create_private_game")
|
||||
if err != nil {
|
||||
return adminusers.ListUsersInput{}, err
|
||||
}
|
||||
canJoinGame, err := parseOptionalBoolQuery(c, "can_join_game")
|
||||
if err != nil {
|
||||
return adminusers.ListUsersInput{}, err
|
||||
}
|
||||
|
||||
return adminusers.ListUsersInput{
|
||||
PageSize: pageSize,
|
||||
PageToken: pageToken,
|
||||
PaidState: c.Query("paid_state"),
|
||||
PaidExpiresBefore: paidExpiresBefore,
|
||||
PaidExpiresAfter: paidExpiresAfter,
|
||||
DeclaredCountry: c.Query("declared_country"),
|
||||
SanctionCode: c.Query("sanction_code"),
|
||||
LimitCode: c.Query("limit_code"),
|
||||
CanLogin: canLogin,
|
||||
CanCreatePrivateGame: canCreatePrivateGame,
|
||||
CanJoinGame: canJoinGame,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseOptionalPageSize(c *gin.Context, name string) (int, error) {
|
||||
raw, present := c.GetQuery(name)
|
||||
if !present {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
value, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil || value < 1 || value > 200 {
|
||||
return 0, shared.InvalidRequest("page_size must be between 1 and 200")
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func parseOptionalPageToken(c *gin.Context, name string) (string, error) {
|
||||
raw, present := c.GetQuery(name)
|
||||
if !present {
|
||||
return "", nil
|
||||
}
|
||||
if strings.TrimSpace(raw) != raw {
|
||||
return "", shared.InvalidRequest("page_token must not contain surrounding whitespace")
|
||||
}
|
||||
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func parseOptionalRFC3339Query(c *gin.Context, name string) (*time.Time, error) {
|
||||
raw, present := c.GetQuery(name)
|
||||
if !present {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
parsed, err := time.Parse(time.RFC3339, strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return nil, shared.InvalidRequest(name + " must be a valid RFC 3339 timestamp")
|
||||
}
|
||||
|
||||
return &parsed, nil
|
||||
}
|
||||
|
||||
func parseOptionalBoolQuery(c *gin.Context, name string) (*bool, error) {
|
||||
raw, present := c.GetQuery(name)
|
||||
if !present {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseBool(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return nil, shared.InvalidRequest(name + " must be a valid boolean")
|
||||
}
|
||||
|
||||
return &parsed, nil
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package internalhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"galaxy/user/internal/service/accountview"
|
||||
"galaxy/user/internal/service/adminusers"
|
||||
"galaxy/user/internal/service/shared"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAdminReadHandlersSuccessCases(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler := mustNewHandler(t, Dependencies{
|
||||
GetUserByID: getUserByIDFunc(func(_ context.Context, input adminusers.GetUserByIDInput) (adminusers.LookupResult, error) {
|
||||
require.Equal(t, "user-123", input.UserID)
|
||||
return adminusers.LookupResult{User: sampleAccountView()}, nil
|
||||
}),
|
||||
GetUserByEmail: getUserByEmailFunc(func(_ context.Context, input adminusers.GetUserByEmailInput) (adminusers.LookupResult, error) {
|
||||
require.Equal(t, "pilot@example.com", input.Email)
|
||||
return adminusers.LookupResult{User: sampleAccountView()}, nil
|
||||
}),
|
||||
GetUserByRaceName: getUserByRaceNameFunc(func(_ context.Context, input adminusers.GetUserByRaceNameInput) (adminusers.LookupResult, error) {
|
||||
require.Equal(t, "Pilot Nova", input.RaceName)
|
||||
return adminusers.LookupResult{User: sampleAccountView()}, nil
|
||||
}),
|
||||
ListUsers: listUsersFunc(func(_ context.Context, input adminusers.ListUsersInput) (adminusers.ListUsersResult, error) {
|
||||
require.Equal(t, 2, input.PageSize)
|
||||
require.Equal(t, "cursor-1", input.PageToken)
|
||||
require.Equal(t, "paid", input.PaidState)
|
||||
require.Equal(t, "DE", input.DeclaredCountry)
|
||||
require.Equal(t, "login_block", input.SanctionCode)
|
||||
require.Equal(t, "max_owned_private_games", input.LimitCode)
|
||||
require.NotNil(t, input.PaidExpiresBefore)
|
||||
require.NotNil(t, input.PaidExpiresAfter)
|
||||
require.NotNil(t, input.CanLogin)
|
||||
require.NotNil(t, input.CanCreatePrivateGame)
|
||||
require.NotNil(t, input.CanJoinGame)
|
||||
require.False(t, *input.CanLogin)
|
||||
require.True(t, *input.CanCreatePrivateGame)
|
||||
require.True(t, *input.CanJoinGame)
|
||||
require.Equal(t, time.Date(2026, time.April, 10, 12, 0, 0, 0, time.UTC), input.PaidExpiresBefore.UTC())
|
||||
require.Equal(t, time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC), input.PaidExpiresAfter.UTC())
|
||||
|
||||
other := sampleAccountView()
|
||||
other.UserID = "user-234"
|
||||
other.Email = "second@example.com"
|
||||
other.RaceName = "Second Pilot"
|
||||
|
||||
return adminusers.ListUsersResult{
|
||||
Items: []accountview.AccountView{sampleAccountView(), other},
|
||||
NextPageToken: "cursor-2",
|
||||
}, nil
|
||||
}),
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
body string
|
||||
wantStatus int
|
||||
wantBody string
|
||||
}{
|
||||
{
|
||||
name: "get user by id",
|
||||
method: http.MethodGet,
|
||||
path: "/api/v1/internal/users/user-123",
|
||||
wantStatus: http.StatusOK,
|
||||
wantBody: `{"user":{"user_id":"user-123","email":"pilot@example.com","race_name":"Pilot Nova","preferred_language":"en","time_zone":"Europe/Kaliningrad","declared_country":"DE","entitlement":{"plan_code":"free","is_paid":false,"source":"auth_registration","actor":{"type":"service","id":"user-service"},"reason_code":"initial_free_entitlement","starts_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"},"active_sanctions":[],"active_limits":[],"created_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"}}`,
|
||||
},
|
||||
{
|
||||
name: "get user by email",
|
||||
method: http.MethodPost,
|
||||
path: "/api/v1/internal/user-lookups/by-email",
|
||||
body: `{"email":"pilot@example.com"}`,
|
||||
wantStatus: http.StatusOK,
|
||||
wantBody: `{"user":{"user_id":"user-123","email":"pilot@example.com","race_name":"Pilot Nova","preferred_language":"en","time_zone":"Europe/Kaliningrad","declared_country":"DE","entitlement":{"plan_code":"free","is_paid":false,"source":"auth_registration","actor":{"type":"service","id":"user-service"},"reason_code":"initial_free_entitlement","starts_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"},"active_sanctions":[],"active_limits":[],"created_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"}}`,
|
||||
},
|
||||
{
|
||||
name: "get user by race name",
|
||||
method: http.MethodPost,
|
||||
path: "/api/v1/internal/user-lookups/by-race-name",
|
||||
body: `{"race_name":"Pilot Nova"}`,
|
||||
wantStatus: http.StatusOK,
|
||||
wantBody: `{"user":{"user_id":"user-123","email":"pilot@example.com","race_name":"Pilot Nova","preferred_language":"en","time_zone":"Europe/Kaliningrad","declared_country":"DE","entitlement":{"plan_code":"free","is_paid":false,"source":"auth_registration","actor":{"type":"service","id":"user-service"},"reason_code":"initial_free_entitlement","starts_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"},"active_sanctions":[],"active_limits":[],"created_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"}}`,
|
||||
},
|
||||
{
|
||||
name: "list users",
|
||||
method: http.MethodGet,
|
||||
path: "/api/v1/internal/users?page_size=2&page_token=cursor-1&paid_state=paid&paid_expires_before=2026-04-10T12:00:00Z&paid_expires_after=2026-04-01T12:00:00Z&declared_country=DE&sanction_code=login_block&limit_code=max_owned_private_games&can_login=false&can_create_private_game=true&can_join_game=true",
|
||||
wantStatus: http.StatusOK,
|
||||
wantBody: `{"items":[{"user_id":"user-123","email":"pilot@example.com","race_name":"Pilot Nova","preferred_language":"en","time_zone":"Europe/Kaliningrad","declared_country":"DE","entitlement":{"plan_code":"free","is_paid":false,"source":"auth_registration","actor":{"type":"service","id":"user-service"},"reason_code":"initial_free_entitlement","starts_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"},"active_sanctions":[],"active_limits":[],"created_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"},{"user_id":"user-234","email":"second@example.com","race_name":"Second Pilot","preferred_language":"en","time_zone":"Europe/Kaliningrad","declared_country":"DE","entitlement":{"plan_code":"free","is_paid":false,"source":"auth_registration","actor":{"type":"service","id":"user-service"},"reason_code":"initial_free_entitlement","starts_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"},"active_sanctions":[],"active_limits":[],"created_at":"2026-04-09T10:00:00Z","updated_at":"2026-04-09T10:00:00Z"}],"next_page_token":"cursor-2"}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var body *bytes.Buffer
|
||||
if tt.body != "" {
|
||||
body = bytes.NewBufferString(tt.body)
|
||||
} else {
|
||||
body = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(tt.method, tt.path, body)
|
||||
if tt.body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, tt.wantStatus, recorder.Code)
|
||||
assertJSONEq(t, recorder.Body.String(), tt.wantBody)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminReadHandlersErrorCases(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler := mustNewHandler(t, Dependencies{
|
||||
GetUserByID: getUserByIDFunc(func(context.Context, adminusers.GetUserByIDInput) (adminusers.LookupResult, error) {
|
||||
return adminusers.LookupResult{}, shared.SubjectNotFound()
|
||||
}),
|
||||
GetUserByEmail: getUserByEmailFunc(func(context.Context, adminusers.GetUserByEmailInput) (adminusers.LookupResult, error) {
|
||||
return adminusers.LookupResult{}, shared.SubjectNotFound()
|
||||
}),
|
||||
GetUserByRaceName: getUserByRaceNameFunc(func(context.Context, adminusers.GetUserByRaceNameInput) (adminusers.LookupResult, error) {
|
||||
return adminusers.LookupResult{}, shared.SubjectNotFound()
|
||||
}),
|
||||
ListUsers: listUsersFunc(func(context.Context, adminusers.ListUsersInput) (adminusers.ListUsersResult, error) {
|
||||
return adminusers.ListUsersResult{}, shared.InvalidRequest("page_token is invalid or does not match current filters")
|
||||
}),
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
body string
|
||||
wantStatus int
|
||||
wantBody string
|
||||
}{
|
||||
{
|
||||
name: "get user by id not found",
|
||||
method: http.MethodGet,
|
||||
path: "/api/v1/internal/users/user-missing",
|
||||
wantStatus: http.StatusNotFound,
|
||||
wantBody: `{"error":{"code":"subject_not_found","message":"subject not found"}}`,
|
||||
},
|
||||
{
|
||||
name: "get user by email malformed json",
|
||||
method: http.MethodPost,
|
||||
path: "/api/v1/internal/user-lookups/by-email",
|
||||
body: `{"email":"pilot@example.com","extra":true}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
wantBody: `{"error":{"code":"invalid_request","message":"request body contains unknown field \"extra\""}}`,
|
||||
},
|
||||
{
|
||||
name: "get user by race name not found",
|
||||
method: http.MethodPost,
|
||||
path: "/api/v1/internal/user-lookups/by-race-name",
|
||||
body: `{"race_name":"Missing Pilot"}`,
|
||||
wantStatus: http.StatusNotFound,
|
||||
wantBody: `{"error":{"code":"subject_not_found","message":"subject not found"}}`,
|
||||
},
|
||||
{
|
||||
name: "list users invalid page size",
|
||||
method: http.MethodGet,
|
||||
path: "/api/v1/internal/users?page_size=201",
|
||||
wantStatus: http.StatusBadRequest,
|
||||
wantBody: `{"error":{"code":"invalid_request","message":"page_size must be between 1 and 200"}}`,
|
||||
},
|
||||
{
|
||||
name: "list users invalid timestamp",
|
||||
method: http.MethodGet,
|
||||
path: "/api/v1/internal/users?paid_expires_before=not-a-time",
|
||||
wantStatus: http.StatusBadRequest,
|
||||
wantBody: `{"error":{"code":"invalid_request","message":"paid_expires_before must be a valid RFC 3339 timestamp"}}`,
|
||||
},
|
||||
{
|
||||
name: "list users invalid boolean",
|
||||
method: http.MethodGet,
|
||||
path: "/api/v1/internal/users?can_login=maybe",
|
||||
wantStatus: http.StatusBadRequest,
|
||||
wantBody: `{"error":{"code":"invalid_request","message":"can_login must be a valid boolean"}}`,
|
||||
},
|
||||
{
|
||||
name: "list users invalid page token",
|
||||
method: http.MethodGet,
|
||||
path: "/api/v1/internal/users?page_token=cursor-1",
|
||||
wantStatus: http.StatusBadRequest,
|
||||
wantBody: `{"error":{"code":"invalid_request","message":"page_token is invalid or does not match current filters"}}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var body *bytes.Buffer
|
||||
if tt.body != "" {
|
||||
body = bytes.NewBufferString(tt.body)
|
||||
} else {
|
||||
body = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(tt.method, tt.path, body)
|
||||
if tt.body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, tt.wantStatus, recorder.Code)
|
||||
assertJSONEq(t, recorder.Body.String(), tt.wantBody)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,841 @@
|
||||
package internalhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"galaxy/user/internal/logging"
|
||||
"galaxy/user/internal/service/authdirectory"
|
||||
"galaxy/user/internal/service/entitlementsvc"
|
||||
"galaxy/user/internal/service/geosync"
|
||||
"galaxy/user/internal/service/lobbyeligibility"
|
||||
"galaxy/user/internal/service/policysvc"
|
||||
"galaxy/user/internal/service/selfservice"
|
||||
"galaxy/user/internal/service/shared"
|
||||
"galaxy/user/internal/telemetry"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
)
|
||||
|
||||
const internalHTTPServiceName = "galaxy-user-internal"
|
||||
|
||||
type errorResponse struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type resolveByEmailRequest struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
type resolveByEmailResponse struct {
|
||||
Kind string `json:"kind"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
BlockReasonCode string `json:"block_reason_code,omitempty"`
|
||||
}
|
||||
|
||||
type existsByUserIDResponse struct {
|
||||
Exists bool `json:"exists"`
|
||||
}
|
||||
|
||||
type ensureByEmailRequest struct {
|
||||
Email string `json:"email"`
|
||||
RegistrationContext *ensureRegistrationContextDTO `json:"registration_context"`
|
||||
}
|
||||
|
||||
type ensureRegistrationContextDTO struct {
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
}
|
||||
|
||||
type ensureByEmailResponse struct {
|
||||
Outcome string `json:"outcome"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
BlockReasonCode string `json:"block_reason_code,omitempty"`
|
||||
}
|
||||
|
||||
type blockByUserIDRequest struct {
|
||||
ReasonCode string `json:"reason_code"`
|
||||
}
|
||||
|
||||
type blockByEmailRequest struct {
|
||||
Email string `json:"email"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
}
|
||||
|
||||
type blockResponse struct {
|
||||
Outcome string `json:"outcome"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
type getMyAccountResponse struct {
|
||||
Account selfservice.AccountView `json:"account"`
|
||||
}
|
||||
|
||||
type updateMyProfileRequest struct {
|
||||
RaceName string `json:"race_name"`
|
||||
}
|
||||
|
||||
type updateMySettingsRequest struct {
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
}
|
||||
|
||||
type syncDeclaredCountryRequest struct {
|
||||
DeclaredCountry string `json:"declared_country"`
|
||||
}
|
||||
|
||||
type syncDeclaredCountryResponse struct {
|
||||
UserID string `json:"user_id"`
|
||||
DeclaredCountry string `json:"declared_country"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type actorDTO struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
type grantEntitlementRequest struct {
|
||||
PlanCode string `json:"plan_code"`
|
||||
Source string `json:"source"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
StartsAt string `json:"starts_at"`
|
||||
EndsAt string `json:"ends_at,omitempty"`
|
||||
}
|
||||
|
||||
type extendEntitlementRequest struct {
|
||||
Source string `json:"source"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
EndsAt string `json:"ends_at"`
|
||||
}
|
||||
|
||||
type revokeEntitlementRequest struct {
|
||||
Source string `json:"source"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
}
|
||||
|
||||
type applySanctionRequest struct {
|
||||
SanctionCode string `json:"sanction_code"`
|
||||
Scope string `json:"scope"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
AppliedAt string `json:"applied_at"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
}
|
||||
|
||||
type removeSanctionRequest struct {
|
||||
SanctionCode string `json:"sanction_code"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
}
|
||||
|
||||
type setLimitRequest struct {
|
||||
LimitCode string `json:"limit_code"`
|
||||
Value int `json:"value"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
AppliedAt string `json:"applied_at"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
}
|
||||
|
||||
type removeLimitRequest struct {
|
||||
LimitCode string `json:"limit_code"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
}
|
||||
|
||||
type entitlementSnapshotResponse struct {
|
||||
PlanCode string `json:"plan_code"`
|
||||
IsPaid bool `json:"is_paid"`
|
||||
Source string `json:"source"`
|
||||
Actor actorDTO `json:"actor"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
StartsAt time.Time `json:"starts_at"`
|
||||
EndsAt *time.Time `json:"ends_at,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type entitlementCommandResponse struct {
|
||||
UserID string `json:"user_id"`
|
||||
Entitlement entitlementSnapshotResponse `json:"entitlement"`
|
||||
}
|
||||
|
||||
func newHandlerWithConfig(cfg Config, deps Dependencies) (http.Handler, error) {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
normalizedDeps, err := normalizeDependencies(deps)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
configureGinModeOnce.Do(func() {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
})
|
||||
|
||||
engine := gin.New()
|
||||
engine.Use(newOTelMiddleware(normalizedDeps.Telemetry))
|
||||
engine.Use(withObservability(normalizedDeps.Logger, normalizedDeps.Telemetry))
|
||||
engine.POST("/api/v1/internal/user-resolutions/by-email", handleResolveByEmail(normalizedDeps.ResolveByEmail, cfg.RequestTimeout))
|
||||
engine.GET("/api/v1/internal/users/:user_id/exists", handleExistsByUserID(normalizedDeps.ExistsByUserID, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/ensure-by-email", handleEnsureByEmail(normalizedDeps.EnsureByEmail, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/block", handleBlockByUserID(normalizedDeps.BlockByUserID, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/user-blocks/by-email", handleBlockByEmail(normalizedDeps.BlockByEmail, cfg.RequestTimeout))
|
||||
engine.GET("/api/v1/internal/users/:user_id/account", handleGetMyAccount(normalizedDeps.GetMyAccount, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/profile", handleUpdateMyProfile(normalizedDeps.UpdateMyProfile, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/settings", handleUpdateMySettings(normalizedDeps.UpdateMySettings, cfg.RequestTimeout))
|
||||
engine.GET("/api/v1/internal/users/:user_id", handleGetUserByID(normalizedDeps.GetUserByID, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/user-lookups/by-email", handleGetUserByEmail(normalizedDeps.GetUserByEmail, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/user-lookups/by-race-name", handleGetUserByRaceName(normalizedDeps.GetUserByRaceName, cfg.RequestTimeout))
|
||||
engine.GET("/api/v1/internal/users", handleListUsers(normalizedDeps.ListUsers, cfg.RequestTimeout))
|
||||
engine.GET("/api/v1/internal/users/:user_id/eligibility", handleGetUserEligibility(normalizedDeps.GetUserEligibility, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/declared-country/sync", handleSyncDeclaredCountry(normalizedDeps.SyncDeclaredCountry, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/entitlements/grant", handleGrantEntitlement(normalizedDeps.GrantEntitlement, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/entitlements/extend", handleExtendEntitlement(normalizedDeps.ExtendEntitlement, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/entitlements/revoke", handleRevokeEntitlement(normalizedDeps.RevokeEntitlement, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/sanctions/apply", handleApplySanction(normalizedDeps.ApplySanction, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/sanctions/remove", handleRemoveSanction(normalizedDeps.RemoveSanction, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/limits/set", handleSetLimit(normalizedDeps.SetLimit, cfg.RequestTimeout))
|
||||
engine.POST("/api/v1/internal/users/:user_id/limits/remove", handleRemoveLimit(normalizedDeps.RemoveLimit, cfg.RequestTimeout))
|
||||
|
||||
return engine, nil
|
||||
}
|
||||
|
||||
func handleResolveByEmail(useCase ResolveByEmailUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request resolveByEmailRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, authdirectory.ResolveByEmailInput{
|
||||
Email: request.Email,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resolveByEmailResponse{
|
||||
Kind: result.Kind,
|
||||
UserID: result.UserID,
|
||||
BlockReasonCode: result.BlockReasonCode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleExistsByUserID(useCase ExistsByUserIDUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, authdirectory.ExistsByUserIDInput{
|
||||
UserID: c.Param("user_id"),
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, existsByUserIDResponse{Exists: result.Exists})
|
||||
}
|
||||
}
|
||||
|
||||
func handleEnsureByEmail(useCase EnsureByEmailUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request ensureByEmailRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
if request.RegistrationContext == nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest("registration_context must be present")))
|
||||
return
|
||||
}
|
||||
|
||||
var registrationContext *authdirectory.RegistrationContext
|
||||
registrationContext = &authdirectory.RegistrationContext{
|
||||
PreferredLanguage: request.RegistrationContext.PreferredLanguage,
|
||||
TimeZone: request.RegistrationContext.TimeZone,
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, authdirectory.EnsureByEmailInput{
|
||||
Email: request.Email,
|
||||
RegistrationContext: registrationContext,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, ensureByEmailResponse{
|
||||
Outcome: result.Outcome,
|
||||
UserID: result.UserID,
|
||||
BlockReasonCode: result.BlockReasonCode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleBlockByUserID(useCase BlockByUserIDUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request blockByUserIDRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, authdirectory.BlockByUserIDInput{
|
||||
UserID: c.Param("user_id"),
|
||||
ReasonCode: request.ReasonCode,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, blockResponse{
|
||||
Outcome: result.Outcome,
|
||||
UserID: result.UserID,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleBlockByEmail(useCase BlockByEmailUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request blockByEmailRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, authdirectory.BlockByEmailInput{
|
||||
Email: request.Email,
|
||||
ReasonCode: request.ReasonCode,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, blockResponse{
|
||||
Outcome: result.Outcome,
|
||||
UserID: result.UserID,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetMyAccount(useCase GetMyAccountUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, selfservice.GetMyAccountInput{
|
||||
UserID: c.Param("user_id"),
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, getMyAccountResponse{
|
||||
Account: result.Account,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleUpdateMyProfile(useCase UpdateMyProfileUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request updateMyProfileRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, selfservice.UpdateMyProfileInput{
|
||||
UserID: c.Param("user_id"),
|
||||
RaceName: request.RaceName,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, getMyAccountResponse{
|
||||
Account: result.Account,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleUpdateMySettings(useCase UpdateMySettingsUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request updateMySettingsRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, selfservice.UpdateMySettingsInput{
|
||||
UserID: c.Param("user_id"),
|
||||
PreferredLanguage: request.PreferredLanguage,
|
||||
TimeZone: request.TimeZone,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, getMyAccountResponse{
|
||||
Account: result.Account,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetUserEligibility(useCase GetUserEligibilityUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, lobbyeligibility.GetUserEligibilityInput{
|
||||
UserID: c.Param("user_id"),
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSyncDeclaredCountry(useCase SyncDeclaredCountryUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request syncDeclaredCountryRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, geosync.SyncDeclaredCountryInput{
|
||||
UserID: c.Param("user_id"),
|
||||
DeclaredCountry: request.DeclaredCountry,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, syncDeclaredCountryResponse{
|
||||
UserID: result.UserID,
|
||||
DeclaredCountry: result.DeclaredCountry,
|
||||
UpdatedAt: result.UpdatedAt.UTC(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleGrantEntitlement(useCase GrantEntitlementUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request grantEntitlementRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, entitlementsvc.GrantInput{
|
||||
UserID: c.Param("user_id"),
|
||||
PlanCode: request.PlanCode,
|
||||
Source: request.Source,
|
||||
ReasonCode: request.ReasonCode,
|
||||
Actor: entitlementsvc.ActorInput{
|
||||
Type: request.Actor.Type,
|
||||
ID: request.Actor.ID,
|
||||
},
|
||||
StartsAt: request.StartsAt,
|
||||
EndsAt: request.EndsAt,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, entitlementCommandResponseFromResult(result))
|
||||
}
|
||||
}
|
||||
|
||||
func handleExtendEntitlement(useCase ExtendEntitlementUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request extendEntitlementRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, entitlementsvc.ExtendInput{
|
||||
UserID: c.Param("user_id"),
|
||||
Source: request.Source,
|
||||
ReasonCode: request.ReasonCode,
|
||||
Actor: entitlementsvc.ActorInput{
|
||||
Type: request.Actor.Type,
|
||||
ID: request.Actor.ID,
|
||||
},
|
||||
EndsAt: request.EndsAt,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, entitlementCommandResponseFromResult(result))
|
||||
}
|
||||
}
|
||||
|
||||
func handleRevokeEntitlement(useCase RevokeEntitlementUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request revokeEntitlementRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, entitlementsvc.RevokeInput{
|
||||
UserID: c.Param("user_id"),
|
||||
Source: request.Source,
|
||||
ReasonCode: request.ReasonCode,
|
||||
Actor: entitlementsvc.ActorInput{
|
||||
Type: request.Actor.Type,
|
||||
ID: request.Actor.ID,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, entitlementCommandResponseFromResult(result))
|
||||
}
|
||||
}
|
||||
|
||||
func handleApplySanction(useCase ApplySanctionUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request applySanctionRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, policysvc.ApplySanctionInput{
|
||||
UserID: c.Param("user_id"),
|
||||
SanctionCode: request.SanctionCode,
|
||||
Scope: request.Scope,
|
||||
ReasonCode: request.ReasonCode,
|
||||
Actor: policysvc.ActorInput{
|
||||
Type: request.Actor.Type,
|
||||
ID: request.Actor.ID,
|
||||
},
|
||||
AppliedAt: request.AppliedAt,
|
||||
ExpiresAt: request.ExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func handleRemoveSanction(useCase RemoveSanctionUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request removeSanctionRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, policysvc.RemoveSanctionInput{
|
||||
UserID: c.Param("user_id"),
|
||||
SanctionCode: request.SanctionCode,
|
||||
ReasonCode: request.ReasonCode,
|
||||
Actor: policysvc.ActorInput{
|
||||
Type: request.Actor.Type,
|
||||
ID: request.Actor.ID,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSetLimit(useCase SetLimitUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request setLimitRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, policysvc.SetLimitInput{
|
||||
UserID: c.Param("user_id"),
|
||||
LimitCode: request.LimitCode,
|
||||
Value: request.Value,
|
||||
ReasonCode: request.ReasonCode,
|
||||
Actor: policysvc.ActorInput{
|
||||
Type: request.Actor.Type,
|
||||
ID: request.Actor.ID,
|
||||
},
|
||||
AppliedAt: request.AppliedAt,
|
||||
ExpiresAt: request.ExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func handleRemoveLimit(useCase RemoveLimitUseCase, timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var request removeLimitRequest
|
||||
if err := decodeJSONRequest(c.Request, &request); err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(shared.InvalidRequest(err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
callCtx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
result, err := useCase.Execute(callCtx, policysvc.RemoveLimitInput{
|
||||
UserID: c.Param("user_id"),
|
||||
LimitCode: request.LimitCode,
|
||||
ReasonCode: request.ReasonCode,
|
||||
Actor: policysvc.ActorInput{
|
||||
Type: request.Actor.Type,
|
||||
ID: request.Actor.ID,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
abortWithProjection(c, shared.ProjectInternalError(err))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeDependencies(deps Dependencies) (Dependencies, error) {
|
||||
switch {
|
||||
case deps.ResolveByEmail == nil:
|
||||
return Dependencies{}, fmt.Errorf("resolve-by-email use case must not be nil")
|
||||
case deps.EnsureByEmail == nil:
|
||||
return Dependencies{}, fmt.Errorf("ensure-by-email use case must not be nil")
|
||||
case deps.ExistsByUserID == nil:
|
||||
return Dependencies{}, fmt.Errorf("exists-by-user-id use case must not be nil")
|
||||
case deps.BlockByUserID == nil:
|
||||
return Dependencies{}, fmt.Errorf("block-by-user-id use case must not be nil")
|
||||
case deps.BlockByEmail == nil:
|
||||
return Dependencies{}, fmt.Errorf("block-by-email use case must not be nil")
|
||||
case deps.GetMyAccount == nil:
|
||||
return Dependencies{}, fmt.Errorf("get-my-account use case must not be nil")
|
||||
case deps.UpdateMyProfile == nil:
|
||||
return Dependencies{}, fmt.Errorf("update-my-profile use case must not be nil")
|
||||
case deps.UpdateMySettings == nil:
|
||||
return Dependencies{}, fmt.Errorf("update-my-settings use case must not be nil")
|
||||
case deps.GetUserByID == nil:
|
||||
return Dependencies{}, fmt.Errorf("get-user-by-id use case must not be nil")
|
||||
case deps.GetUserByEmail == nil:
|
||||
return Dependencies{}, fmt.Errorf("get-user-by-email use case must not be nil")
|
||||
case deps.GetUserByRaceName == nil:
|
||||
return Dependencies{}, fmt.Errorf("get-user-by-race-name use case must not be nil")
|
||||
case deps.ListUsers == nil:
|
||||
return Dependencies{}, fmt.Errorf("list-users use case must not be nil")
|
||||
case deps.GetUserEligibility == nil:
|
||||
return Dependencies{}, fmt.Errorf("get-user-eligibility use case must not be nil")
|
||||
case deps.SyncDeclaredCountry == nil:
|
||||
return Dependencies{}, fmt.Errorf("sync-declared-country use case must not be nil")
|
||||
case deps.GrantEntitlement == nil:
|
||||
return Dependencies{}, fmt.Errorf("grant-entitlement use case must not be nil")
|
||||
case deps.ExtendEntitlement == nil:
|
||||
return Dependencies{}, fmt.Errorf("extend-entitlement use case must not be nil")
|
||||
case deps.RevokeEntitlement == nil:
|
||||
return Dependencies{}, fmt.Errorf("revoke-entitlement use case must not be nil")
|
||||
case deps.ApplySanction == nil:
|
||||
return Dependencies{}, fmt.Errorf("apply-sanction use case must not be nil")
|
||||
case deps.RemoveSanction == nil:
|
||||
return Dependencies{}, fmt.Errorf("remove-sanction use case must not be nil")
|
||||
case deps.SetLimit == nil:
|
||||
return Dependencies{}, fmt.Errorf("set-limit use case must not be nil")
|
||||
case deps.RemoveLimit == nil:
|
||||
return Dependencies{}, fmt.Errorf("remove-limit use case must not be nil")
|
||||
default:
|
||||
if deps.Logger == nil {
|
||||
deps.Logger = slog.Default()
|
||||
}
|
||||
return deps, nil
|
||||
}
|
||||
}
|
||||
|
||||
func entitlementCommandResponseFromResult(result entitlementsvc.CommandResult) entitlementCommandResponse {
|
||||
response := entitlementCommandResponse{
|
||||
UserID: result.UserID,
|
||||
Entitlement: entitlementSnapshotResponse{
|
||||
PlanCode: string(result.Entitlement.PlanCode),
|
||||
IsPaid: result.Entitlement.IsPaid,
|
||||
Source: result.Entitlement.Source.String(),
|
||||
Actor: actorDTO{Type: result.Entitlement.Actor.Type.String(), ID: result.Entitlement.Actor.ID.String()},
|
||||
ReasonCode: result.Entitlement.ReasonCode.String(),
|
||||
StartsAt: result.Entitlement.StartsAt.UTC(),
|
||||
UpdatedAt: result.Entitlement.UpdatedAt.UTC(),
|
||||
},
|
||||
}
|
||||
if result.Entitlement.EndsAt != nil {
|
||||
value := result.Entitlement.EndsAt.UTC()
|
||||
response.Entitlement.EndsAt = &value
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func newOTelMiddleware(runtime *telemetry.Runtime) gin.HandlerFunc {
|
||||
options := []otelgin.Option{}
|
||||
if runtime != nil {
|
||||
options = append(
|
||||
options,
|
||||
otelgin.WithTracerProvider(runtime.TracerProvider()),
|
||||
otelgin.WithMeterProvider(runtime.MeterProvider()),
|
||||
)
|
||||
}
|
||||
|
||||
return otelgin.Middleware(internalHTTPServiceName, options...)
|
||||
}
|
||||
|
||||
func withObservability(logger *slog.Logger, metrics *telemetry.Runtime) gin.HandlerFunc {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
|
||||
return func(c *gin.Context) {
|
||||
startedAt := time.Now()
|
||||
c.Next()
|
||||
|
||||
statusCode := c.Writer.Status()
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
|
||||
errorCode, _ := c.Get(internalErrorCodeContextKey)
|
||||
errorCodeValue, _ := errorCode.(string)
|
||||
outcome := outcomeFromStatusCode(statusCode)
|
||||
duration := time.Since(startedAt)
|
||||
|
||||
attrs := []any{
|
||||
"transport", "http",
|
||||
"route", route,
|
||||
"method", c.Request.Method,
|
||||
"status_code", statusCode,
|
||||
"duration_ms", float64(duration.Microseconds()) / 1000,
|
||||
"edge_outcome", string(outcome),
|
||||
}
|
||||
if errorCodeValue != "" {
|
||||
attrs = append(attrs, "error_code", errorCodeValue)
|
||||
}
|
||||
attrs = append(attrs, logging.TraceAttrsFromContext(c.Request.Context())...)
|
||||
|
||||
metricAttrs := []attribute.KeyValue{
|
||||
attribute.String("route", route),
|
||||
attribute.String("method", c.Request.Method),
|
||||
attribute.String("edge_outcome", string(outcome)),
|
||||
}
|
||||
if errorCodeValue != "" {
|
||||
metricAttrs = append(metricAttrs, attribute.String("error_code", errorCodeValue))
|
||||
}
|
||||
metrics.RecordInternalHTTPRequest(c.Request.Context(), metricAttrs, duration)
|
||||
|
||||
switch outcome {
|
||||
case edgeOutcomeSuccess:
|
||||
logger.InfoContext(c.Request.Context(), "internal request completed", attrs...)
|
||||
case edgeOutcomeFailed:
|
||||
logger.ErrorContext(c.Request.Context(), "internal request failed", attrs...)
|
||||
default:
|
||||
logger.WarnContext(c.Request.Context(), "internal request rejected", attrs...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type edgeOutcome string
|
||||
|
||||
const (
|
||||
edgeOutcomeSuccess edgeOutcome = "success"
|
||||
edgeOutcomeRejected edgeOutcome = "rejected"
|
||||
edgeOutcomeFailed edgeOutcome = "failed"
|
||||
)
|
||||
|
||||
func outcomeFromStatusCode(statusCode int) edgeOutcome {
|
||||
switch {
|
||||
case statusCode >= 500:
|
||||
return edgeOutcomeFailed
|
||||
case statusCode >= 400:
|
||||
return edgeOutcomeRejected
|
||||
default:
|
||||
return edgeOutcomeSuccess
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,88 @@
|
||||
package internalhttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"galaxy/user/internal/service/shared"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const internalErrorCodeContextKey = "internal_error_code"
|
||||
|
||||
type malformedJSONRequestError struct {
|
||||
message string
|
||||
}
|
||||
|
||||
func (err *malformedJSONRequestError) Error() string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return err.message
|
||||
}
|
||||
|
||||
func decodeJSONRequest(request *http.Request, target any) error {
|
||||
if request == nil || request.Body == nil {
|
||||
return &malformedJSONRequestError{message: "request body must not be empty"}
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(request.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return describeJSONDecodeError(err)
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &malformedJSONRequestError{message: "request body must contain a single JSON object"}
|
||||
}
|
||||
|
||||
return &malformedJSONRequestError{message: "request body must contain a single JSON object"}
|
||||
}
|
||||
|
||||
func describeJSONDecodeError(err error) error {
|
||||
var syntaxErr *json.SyntaxError
|
||||
var typeErr *json.UnmarshalTypeError
|
||||
|
||||
switch {
|
||||
case errors.Is(err, io.EOF):
|
||||
return &malformedJSONRequestError{message: "request body must not be empty"}
|
||||
case errors.As(err, &syntaxErr):
|
||||
return &malformedJSONRequestError{message: "request body contains malformed JSON"}
|
||||
case errors.Is(err, io.ErrUnexpectedEOF):
|
||||
return &malformedJSONRequestError{message: "request body contains malformed JSON"}
|
||||
case errors.As(err, &typeErr):
|
||||
if strings.TrimSpace(typeErr.Field) != "" {
|
||||
return &malformedJSONRequestError{
|
||||
message: fmt.Sprintf("request body contains an invalid value for %q", typeErr.Field),
|
||||
}
|
||||
}
|
||||
|
||||
return &malformedJSONRequestError{message: "request body contains an invalid JSON value"}
|
||||
case strings.HasPrefix(err.Error(), "json: unknown field "):
|
||||
return &malformedJSONRequestError{
|
||||
message: fmt.Sprintf("request body contains unknown field %s", strings.TrimPrefix(err.Error(), "json: unknown field ")),
|
||||
}
|
||||
default:
|
||||
return &malformedJSONRequestError{message: "request body contains invalid JSON"}
|
||||
}
|
||||
}
|
||||
|
||||
func abortWithProjection(c *gin.Context, projection shared.InternalErrorProjection) {
|
||||
c.Set(internalErrorCodeContextKey, projection.Code)
|
||||
c.AbortWithStatusJSON(projection.StatusCode, errorResponse{
|
||||
Error: errorBody{
|
||||
Code: projection.Code,
|
||||
Message: projection.Message,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package internalhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"galaxy/user/internal/service/authdirectory"
|
||||
usertelemetry "galaxy/user/internal/telemetry"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/metric/metricdata"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
)
|
||||
|
||||
func TestInternalHandlerEmitsTraceFieldsAndMetrics(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
logger, buffer := newObservedLogger()
|
||||
telemetryRuntime, reader, recorder := newObservedInternalTelemetryRuntime(t)
|
||||
handler := mustNewHandler(t, Dependencies{
|
||||
Logger: logger,
|
||||
Telemetry: telemetryRuntime,
|
||||
ExistsByUserID: existsByUserIDFunc(func(context.Context, authdirectory.ExistsByUserIDInput) (authdirectory.ExistsByUserIDResult, error) {
|
||||
return authdirectory.ExistsByUserIDResult{Exists: true}, nil
|
||||
}),
|
||||
})
|
||||
|
||||
recorderHTTP := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/internal/users/user-123/exists", nil)
|
||||
request.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
|
||||
|
||||
handler.ServeHTTP(recorderHTTP, request)
|
||||
|
||||
require.Equal(t, http.StatusOK, recorderHTTP.Code)
|
||||
require.NotEmpty(t, recorder.Ended())
|
||||
assert.Contains(t, buffer.String(), "otel_trace_id")
|
||||
assert.Contains(t, buffer.String(), "otel_span_id")
|
||||
|
||||
assertMetricCount(t, reader, "user.internal_http.requests", map[string]string{
|
||||
"route": "/api/v1/internal/users/:user_id/exists",
|
||||
"method": http.MethodGet,
|
||||
"edge_outcome": "success",
|
||||
}, 1)
|
||||
}
|
||||
|
||||
func newObservedInternalTelemetryRuntime(t *testing.T) (*usertelemetry.Runtime, *sdkmetric.ManualReader, *tracetest.SpanRecorder) {
|
||||
t.Helper()
|
||||
|
||||
reader := sdkmetric.NewManualReader()
|
||||
meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
|
||||
recorder := tracetest.NewSpanRecorder()
|
||||
tracerProvider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder))
|
||||
|
||||
runtime, err := usertelemetry.NewWithProviders(meterProvider, tracerProvider)
|
||||
require.NoError(t, err)
|
||||
|
||||
return runtime, reader, recorder
|
||||
}
|
||||
|
||||
func newObservedLogger() (*slog.Logger, *bytes.Buffer) {
|
||||
buffer := &bytes.Buffer{}
|
||||
return slog.New(slog.NewJSONHandler(buffer, &slog.HandlerOptions{Level: slog.LevelDebug})), buffer
|
||||
}
|
||||
|
||||
func assertMetricCount(t *testing.T, reader *sdkmetric.ManualReader, metricName string, wantAttrs map[string]string, wantValue int64) {
|
||||
t.Helper()
|
||||
|
||||
var resourceMetrics metricdata.ResourceMetrics
|
||||
require.NoError(t, reader.Collect(context.Background(), &resourceMetrics))
|
||||
|
||||
for _, scopeMetrics := range resourceMetrics.ScopeMetrics {
|
||||
for _, metric := range scopeMetrics.Metrics {
|
||||
if metric.Name != metricName {
|
||||
continue
|
||||
}
|
||||
|
||||
sum, ok := metric.Data.(metricdata.Sum[int64])
|
||||
require.True(t, ok)
|
||||
|
||||
for _, point := range sum.DataPoints {
|
||||
if hasMetricAttributes(point.Attributes.ToSlice(), wantAttrs) {
|
||||
assert.Equal(t, wantValue, point.Value)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
require.Failf(t, "test failed", "metric %q with attrs %v not found", metricName, wantAttrs)
|
||||
}
|
||||
|
||||
func hasMetricAttributes(values []attribute.KeyValue, want map[string]string) bool {
|
||||
if len(values) != len(want) {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
if want[string(value.Key)] != value.Value.AsString() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
// Package internalhttp exposes the trusted internal HTTP API used by auth,
|
||||
// gateway self-service, and internal administrative workflows.
|
||||
package internalhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"galaxy/user/internal/service/adminusers"
|
||||
"galaxy/user/internal/service/authdirectory"
|
||||
"galaxy/user/internal/service/entitlementsvc"
|
||||
"galaxy/user/internal/service/geosync"
|
||||
"galaxy/user/internal/service/lobbyeligibility"
|
||||
"galaxy/user/internal/service/policysvc"
|
||||
"galaxy/user/internal/service/selfservice"
|
||||
"galaxy/user/internal/telemetry"
|
||||
)
|
||||
|
||||
const jsonContentType = "application/json; charset=utf-8"
|
||||
|
||||
var configureGinModeOnce sync.Once
|
||||
|
||||
// ResolveByEmailUseCase describes the auth-facing resolve-by-email service
|
||||
// consumed by the HTTP transport layer.
|
||||
type ResolveByEmailUseCase interface {
|
||||
// Execute resolves one e-mail subject without creating any account.
|
||||
Execute(ctx context.Context, input authdirectory.ResolveByEmailInput) (authdirectory.ResolveByEmailResult, error)
|
||||
}
|
||||
|
||||
// EnsureByEmailUseCase describes the auth-facing ensure-by-email service
|
||||
// consumed by the HTTP transport layer.
|
||||
type EnsureByEmailUseCase interface {
|
||||
// Execute returns an existing user, creates a new one, or reports a blocked
|
||||
// outcome for one e-mail subject.
|
||||
Execute(ctx context.Context, input authdirectory.EnsureByEmailInput) (authdirectory.EnsureByEmailResult, error)
|
||||
}
|
||||
|
||||
// ExistsByUserIDUseCase describes the auth-facing exists-by-user-id service
|
||||
// consumed by the HTTP transport layer.
|
||||
type ExistsByUserIDUseCase interface {
|
||||
// Execute reports whether one stable user identifier exists.
|
||||
Execute(ctx context.Context, input authdirectory.ExistsByUserIDInput) (authdirectory.ExistsByUserIDResult, error)
|
||||
}
|
||||
|
||||
// BlockByUserIDUseCase describes the auth-facing block-by-user-id service
|
||||
// consumed by the HTTP transport layer.
|
||||
type BlockByUserIDUseCase interface {
|
||||
// Execute blocks one account addressed by stable user identifier.
|
||||
Execute(ctx context.Context, input authdirectory.BlockByUserIDInput) (authdirectory.BlockResult, error)
|
||||
}
|
||||
|
||||
// BlockByEmailUseCase describes the auth-facing block-by-email service
|
||||
// consumed by the HTTP transport layer.
|
||||
type BlockByEmailUseCase interface {
|
||||
// Execute blocks one exact normalized e-mail subject.
|
||||
Execute(ctx context.Context, input authdirectory.BlockByEmailInput) (authdirectory.BlockResult, error)
|
||||
}
|
||||
|
||||
// GetMyAccountUseCase describes the self-service account-read use case
|
||||
// consumed by the HTTP transport layer.
|
||||
type GetMyAccountUseCase interface {
|
||||
// Execute returns the authenticated account aggregate for one user.
|
||||
Execute(ctx context.Context, input selfservice.GetMyAccountInput) (selfservice.GetMyAccountResult, error)
|
||||
}
|
||||
|
||||
// UpdateMyProfileUseCase describes the self-service profile-mutation use case
|
||||
// consumed by the HTTP transport layer.
|
||||
type UpdateMyProfileUseCase interface {
|
||||
// Execute updates the allowed self-service profile fields for one user.
|
||||
Execute(ctx context.Context, input selfservice.UpdateMyProfileInput) (selfservice.UpdateMyProfileResult, error)
|
||||
}
|
||||
|
||||
// UpdateMySettingsUseCase describes the self-service settings-mutation use
|
||||
// case consumed by the HTTP transport layer.
|
||||
type UpdateMySettingsUseCase interface {
|
||||
// Execute updates the allowed self-service settings fields for one user.
|
||||
Execute(ctx context.Context, input selfservice.UpdateMySettingsInput) (selfservice.UpdateMySettingsResult, error)
|
||||
}
|
||||
|
||||
// GetUserByIDUseCase describes the trusted admin exact-read by stable user id
|
||||
// consumed by the HTTP transport layer.
|
||||
type GetUserByIDUseCase interface {
|
||||
// Execute returns the full current account aggregate for one user id.
|
||||
Execute(ctx context.Context, input adminusers.GetUserByIDInput) (adminusers.LookupResult, error)
|
||||
}
|
||||
|
||||
// GetUserByEmailUseCase describes the trusted admin exact-read by normalized
|
||||
// e-mail consumed by the HTTP transport layer.
|
||||
type GetUserByEmailUseCase interface {
|
||||
// Execute returns the full current account aggregate for one normalized
|
||||
// e-mail address.
|
||||
Execute(ctx context.Context, input adminusers.GetUserByEmailInput) (adminusers.LookupResult, error)
|
||||
}
|
||||
|
||||
// GetUserByRaceNameUseCase describes the trusted admin exact-read by exact
|
||||
// stored race name consumed by the HTTP transport layer.
|
||||
type GetUserByRaceNameUseCase interface {
|
||||
// Execute returns the full current account aggregate for one exact race
|
||||
// name.
|
||||
Execute(ctx context.Context, input adminusers.GetUserByRaceNameInput) (adminusers.LookupResult, error)
|
||||
}
|
||||
|
||||
// ListUsersUseCase describes the trusted admin paginated listing use case
|
||||
// consumed by the HTTP transport layer.
|
||||
type ListUsersUseCase interface {
|
||||
// Execute returns one deterministic filtered page of full account
|
||||
// aggregates.
|
||||
Execute(ctx context.Context, input adminusers.ListUsersInput) (adminusers.ListUsersResult, error)
|
||||
}
|
||||
|
||||
// GetUserEligibilityUseCase describes the trusted lobby-facing eligibility
|
||||
// snapshot use case consumed by the HTTP transport layer.
|
||||
type GetUserEligibilityUseCase interface {
|
||||
// Execute returns one read-optimized lobby eligibility snapshot for one
|
||||
// user.
|
||||
Execute(ctx context.Context, input lobbyeligibility.GetUserEligibilityInput) (lobbyeligibility.GetUserEligibilityResult, error)
|
||||
}
|
||||
|
||||
// SyncDeclaredCountryUseCase describes the trusted geo-facing declared-country
|
||||
// sync use case consumed by the HTTP transport layer.
|
||||
type SyncDeclaredCountryUseCase interface {
|
||||
// Execute synchronizes the current effective declared country for one user.
|
||||
Execute(ctx context.Context, input geosync.SyncDeclaredCountryInput) (geosync.SyncDeclaredCountryResult, error)
|
||||
}
|
||||
|
||||
// GrantEntitlementUseCase describes the trusted entitlement-grant use case
|
||||
// consumed by the HTTP transport layer.
|
||||
type GrantEntitlementUseCase interface {
|
||||
// Execute grants a new current paid entitlement for one user.
|
||||
Execute(ctx context.Context, input entitlementsvc.GrantInput) (entitlementsvc.CommandResult, error)
|
||||
}
|
||||
|
||||
// ExtendEntitlementUseCase describes the trusted entitlement-extend use case
|
||||
// consumed by the HTTP transport layer.
|
||||
type ExtendEntitlementUseCase interface {
|
||||
// Execute extends the current finite paid entitlement for one user.
|
||||
Execute(ctx context.Context, input entitlementsvc.ExtendInput) (entitlementsvc.CommandResult, error)
|
||||
}
|
||||
|
||||
// RevokeEntitlementUseCase describes the trusted entitlement-revoke use case
|
||||
// consumed by the HTTP transport layer.
|
||||
type RevokeEntitlementUseCase interface {
|
||||
// Execute revokes the current paid entitlement for one user.
|
||||
Execute(ctx context.Context, input entitlementsvc.RevokeInput) (entitlementsvc.CommandResult, error)
|
||||
}
|
||||
|
||||
// ApplySanctionUseCase describes the trusted sanction-apply use case consumed
|
||||
// by the HTTP transport layer.
|
||||
type ApplySanctionUseCase interface {
|
||||
// Execute applies one new active sanction record.
|
||||
Execute(ctx context.Context, input policysvc.ApplySanctionInput) (policysvc.SanctionCommandResult, error)
|
||||
}
|
||||
|
||||
// RemoveSanctionUseCase describes the trusted sanction-remove use case
|
||||
// consumed by the HTTP transport layer.
|
||||
type RemoveSanctionUseCase interface {
|
||||
// Execute removes one current active sanction record by code.
|
||||
Execute(ctx context.Context, input policysvc.RemoveSanctionInput) (policysvc.SanctionCommandResult, error)
|
||||
}
|
||||
|
||||
// SetLimitUseCase describes the trusted limit-set use case consumed by the
|
||||
// HTTP transport layer.
|
||||
type SetLimitUseCase interface {
|
||||
// Execute creates or replaces one current active limit record.
|
||||
Execute(ctx context.Context, input policysvc.SetLimitInput) (policysvc.LimitCommandResult, error)
|
||||
}
|
||||
|
||||
// RemoveLimitUseCase describes the trusted limit-remove use case consumed by
|
||||
// the HTTP transport layer.
|
||||
type RemoveLimitUseCase interface {
|
||||
// Execute removes one current active limit record by code.
|
||||
Execute(ctx context.Context, input policysvc.RemoveLimitInput) (policysvc.LimitCommandResult, error)
|
||||
}
|
||||
|
||||
// Config describes the trusted internal HTTP listener owned by the user
|
||||
// service.
|
||||
type Config struct {
|
||||
// Addr stores the TCP listen address.
|
||||
Addr string
|
||||
|
||||
// ReadHeaderTimeout bounds how long the listener may spend reading request
|
||||
// headers before rejecting the connection.
|
||||
ReadHeaderTimeout time.Duration
|
||||
|
||||
// ReadTimeout bounds how long the listener may spend reading one request.
|
||||
ReadTimeout time.Duration
|
||||
|
||||
// IdleTimeout bounds how long keep-alive connections stay open.
|
||||
IdleTimeout time.Duration
|
||||
|
||||
// RequestTimeout bounds one application-layer request execution.
|
||||
RequestTimeout time.Duration
|
||||
}
|
||||
|
||||
// Validate reports whether cfg contains a usable internal HTTP listener
|
||||
// configuration.
|
||||
func (cfg Config) Validate() error {
|
||||
switch {
|
||||
case cfg.Addr == "":
|
||||
return errors.New("internal HTTP addr must not be empty")
|
||||
case cfg.ReadHeaderTimeout <= 0:
|
||||
return errors.New("internal HTTP read header timeout must be positive")
|
||||
case cfg.ReadTimeout <= 0:
|
||||
return errors.New("internal HTTP read timeout must be positive")
|
||||
case cfg.IdleTimeout <= 0:
|
||||
return errors.New("internal HTTP idle timeout must be positive")
|
||||
case cfg.RequestTimeout <= 0:
|
||||
return errors.New("internal HTTP request timeout must be positive")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Dependencies describes the collaborators used by the trusted internal HTTP
|
||||
// transport layer.
|
||||
type Dependencies struct {
|
||||
// ResolveByEmail executes the auth-facing resolve-by-email use case.
|
||||
ResolveByEmail ResolveByEmailUseCase
|
||||
|
||||
// EnsureByEmail executes the auth-facing ensure-by-email use case.
|
||||
EnsureByEmail EnsureByEmailUseCase
|
||||
|
||||
// ExistsByUserID executes the auth-facing exists-by-user-id use case.
|
||||
ExistsByUserID ExistsByUserIDUseCase
|
||||
|
||||
// BlockByUserID executes the auth-facing block-by-user-id use case.
|
||||
BlockByUserID BlockByUserIDUseCase
|
||||
|
||||
// BlockByEmail executes the auth-facing block-by-email use case.
|
||||
BlockByEmail BlockByEmailUseCase
|
||||
|
||||
// GetMyAccount executes the self-service authenticated account-read use
|
||||
// case.
|
||||
GetMyAccount GetMyAccountUseCase
|
||||
|
||||
// UpdateMyProfile executes the self-service profile-mutation use case.
|
||||
UpdateMyProfile UpdateMyProfileUseCase
|
||||
|
||||
// UpdateMySettings executes the self-service settings-mutation use case.
|
||||
UpdateMySettings UpdateMySettingsUseCase
|
||||
|
||||
// GetUserByID executes the trusted admin exact-read by stable user id.
|
||||
GetUserByID GetUserByIDUseCase
|
||||
|
||||
// GetUserByEmail executes the trusted admin exact-read by normalized
|
||||
// e-mail.
|
||||
GetUserByEmail GetUserByEmailUseCase
|
||||
|
||||
// GetUserByRaceName executes the trusted admin exact-read by exact stored
|
||||
// race name.
|
||||
GetUserByRaceName GetUserByRaceNameUseCase
|
||||
|
||||
// ListUsers executes the trusted admin paginated filtered listing use case.
|
||||
ListUsers ListUsersUseCase
|
||||
|
||||
// GetUserEligibility executes the trusted lobby-facing eligibility snapshot
|
||||
// read.
|
||||
GetUserEligibility GetUserEligibilityUseCase
|
||||
|
||||
// SyncDeclaredCountry executes the trusted geo-facing declared-country sync
|
||||
// command.
|
||||
SyncDeclaredCountry SyncDeclaredCountryUseCase
|
||||
|
||||
// GrantEntitlement executes the trusted entitlement-grant use case.
|
||||
GrantEntitlement GrantEntitlementUseCase
|
||||
|
||||
// ExtendEntitlement executes the trusted entitlement-extend use case.
|
||||
ExtendEntitlement ExtendEntitlementUseCase
|
||||
|
||||
// RevokeEntitlement executes the trusted entitlement-revoke use case.
|
||||
RevokeEntitlement RevokeEntitlementUseCase
|
||||
|
||||
// ApplySanction executes the trusted sanction-apply use case.
|
||||
ApplySanction ApplySanctionUseCase
|
||||
|
||||
// RemoveSanction executes the trusted sanction-remove use case.
|
||||
RemoveSanction RemoveSanctionUseCase
|
||||
|
||||
// SetLimit executes the trusted limit-set use case.
|
||||
SetLimit SetLimitUseCase
|
||||
|
||||
// RemoveLimit executes the trusted limit-remove use case.
|
||||
RemoveLimit RemoveLimitUseCase
|
||||
|
||||
// Logger writes structured transport logs. When nil, the default logger is
|
||||
// used.
|
||||
Logger *slog.Logger
|
||||
|
||||
// Telemetry records OpenTelemetry spans and low-cardinality HTTP metrics.
|
||||
Telemetry *telemetry.Runtime
|
||||
}
|
||||
|
||||
// Server owns the trusted internal HTTP listener exposed by the user service.
|
||||
type Server struct {
|
||||
cfg Config
|
||||
|
||||
handler http.Handler
|
||||
logger *slog.Logger
|
||||
|
||||
stateMu sync.RWMutex
|
||||
server *http.Server
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
// NewServer constructs one trusted internal HTTP server for cfg and deps.
|
||||
func NewServer(cfg Config, deps Dependencies) (*Server, error) {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("new internal HTTP server: %w", err)
|
||||
}
|
||||
|
||||
handler, err := newHandlerWithConfig(cfg, deps)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new internal HTTP server: %w", err)
|
||||
}
|
||||
|
||||
logger := deps.Logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
handler: handler,
|
||||
logger: logger,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Run binds the configured listener and serves the trusted internal HTTP
|
||||
// surface until ctx is cancelled or Shutdown closes the server.
|
||||
func (server *Server) Run(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return errors.New("run internal HTTP server: nil context")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
listener, err := net.Listen("tcp", server.cfg.Addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("run internal HTTP server: listen on %q: %w", server.cfg.Addr, err)
|
||||
}
|
||||
|
||||
httpServer := &http.Server{
|
||||
Handler: server.handler,
|
||||
ReadHeaderTimeout: server.cfg.ReadHeaderTimeout,
|
||||
ReadTimeout: server.cfg.ReadTimeout,
|
||||
IdleTimeout: server.cfg.IdleTimeout,
|
||||
}
|
||||
|
||||
server.stateMu.Lock()
|
||||
server.server = httpServer
|
||||
server.listener = listener
|
||||
server.stateMu.Unlock()
|
||||
|
||||
server.logger.Info("internal HTTP server started", "addr", listener.Addr().String())
|
||||
|
||||
shutdownDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(shutdownDone)
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), server.cfg.RequestTimeout)
|
||||
defer cancel()
|
||||
_ = server.Shutdown(shutdownCtx)
|
||||
}()
|
||||
|
||||
defer func() {
|
||||
server.stateMu.Lock()
|
||||
server.server = nil
|
||||
server.listener = nil
|
||||
server.stateMu.Unlock()
|
||||
<-shutdownDone
|
||||
}()
|
||||
|
||||
err = httpServer.Serve(listener)
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, http.ErrServerClosed):
|
||||
server.logger.Info("internal HTTP server stopped")
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("run internal HTTP server: serve on %q: %w", server.cfg.Addr, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown gracefully stops the internal HTTP server within ctx.
|
||||
func (server *Server) Shutdown(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return errors.New("shutdown internal HTTP server: nil context")
|
||||
}
|
||||
|
||||
server.stateMu.RLock()
|
||||
httpServer := server.server
|
||||
server.stateMu.RUnlock()
|
||||
|
||||
if httpServer == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := httpServer.Shutdown(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return fmt.Errorf("shutdown internal HTTP server: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user