feat: game lobby service
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
// Package lifecycleevents implements the Redis Streams-backed publisher for
|
||||
// trusted user-lifecycle events consumed by `Game Lobby`.
|
||||
package lifecycleevents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"galaxy/user/internal/ports"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Config configures one Redis-backed user-lifecycle publisher.
|
||||
type Config struct {
|
||||
// Addr is the Redis network address in host:port form.
|
||||
Addr string
|
||||
|
||||
// Username is the optional Redis ACL username.
|
||||
Username string
|
||||
|
||||
// Password is the optional Redis ACL password.
|
||||
Password string
|
||||
|
||||
// DB is the Redis logical database index.
|
||||
DB int
|
||||
|
||||
// TLSEnabled enables TLS with a conservative minimum protocol version.
|
||||
TLSEnabled bool
|
||||
|
||||
// Stream identifies the Redis Stream key used for lifecycle events. The
|
||||
// default platform key is `user:lifecycle_events`.
|
||||
Stream string
|
||||
|
||||
// StreamMaxLen bounds the stream with approximate trimming via
|
||||
// `XADD MAXLEN ~`.
|
||||
StreamMaxLen int64
|
||||
|
||||
// OperationTimeout bounds each Redis round trip performed by the adapter.
|
||||
OperationTimeout time.Duration
|
||||
}
|
||||
|
||||
// Publisher publishes trusted user-lifecycle events into the dedicated Redis
|
||||
// Stream consumed by `Game Lobby` for Race Name Directory cascade release.
|
||||
type Publisher struct {
|
||||
client *redis.Client
|
||||
stream string
|
||||
streamMaxLen int64
|
||||
operationTimeout time.Duration
|
||||
}
|
||||
|
||||
// New constructs a Redis-backed lifecycle-event publisher from cfg.
|
||||
func New(cfg Config) (*Publisher, error) {
|
||||
switch {
|
||||
case strings.TrimSpace(cfg.Addr) == "":
|
||||
return nil, errors.New("new redis lifecycle-event publisher: redis addr must not be empty")
|
||||
case cfg.DB < 0:
|
||||
return nil, errors.New("new redis lifecycle-event publisher: redis db must not be negative")
|
||||
case strings.TrimSpace(cfg.Stream) == "":
|
||||
return nil, errors.New("new redis lifecycle-event publisher: stream must not be empty")
|
||||
case cfg.StreamMaxLen <= 0:
|
||||
return nil, errors.New("new redis lifecycle-event publisher: stream max len must be positive")
|
||||
case cfg.OperationTimeout <= 0:
|
||||
return nil, errors.New("new redis lifecycle-event publisher: operation timeout must be positive")
|
||||
}
|
||||
|
||||
options := &redis.Options{
|
||||
Addr: cfg.Addr,
|
||||
Username: cfg.Username,
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
Protocol: 2,
|
||||
DisableIdentity: true,
|
||||
}
|
||||
if cfg.TLSEnabled {
|
||||
options.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
|
||||
return &Publisher{
|
||||
client: redis.NewClient(options),
|
||||
stream: cfg.Stream,
|
||||
streamMaxLen: cfg.StreamMaxLen,
|
||||
operationTimeout: cfg.OperationTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Close releases the underlying Redis client resources.
|
||||
func (publisher *Publisher) Close() error {
|
||||
if publisher == nil || publisher.client == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return publisher.client.Close()
|
||||
}
|
||||
|
||||
// Ping verifies that the configured Redis backend is reachable within the
|
||||
// adapter operation timeout budget.
|
||||
func (publisher *Publisher) Ping(ctx context.Context) error {
|
||||
operationCtx, cancel, err := publisher.operationContext(ctx, "ping redis lifecycle-event publisher")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
if err := publisher.client.Ping(operationCtx).Err(); err != nil {
|
||||
return fmt.Errorf("ping redis lifecycle-event publisher: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PublishUserLifecycleEvent publishes one committed lifecycle event to the
|
||||
// configured Redis Stream.
|
||||
func (publisher *Publisher) PublishUserLifecycleEvent(ctx context.Context, event ports.UserLifecycleEvent) error {
|
||||
if err := event.Validate(); err != nil {
|
||||
return fmt.Errorf("publish user lifecycle event: %w", err)
|
||||
}
|
||||
|
||||
traceID := traceIDFromContext(ctx, event.TraceID)
|
||||
|
||||
values := map[string]any{
|
||||
"event_type": string(event.EventType),
|
||||
"user_id": event.UserID.String(),
|
||||
"occurred_at_ms": strconv.FormatInt(event.OccurredAt.UTC().UnixMilli(), 10),
|
||||
"source": event.Source.String(),
|
||||
"actor_type": event.Actor.Type.String(),
|
||||
"reason_code": event.ReasonCode.String(),
|
||||
}
|
||||
if !event.Actor.ID.IsZero() {
|
||||
values["actor_id"] = event.Actor.ID.String()
|
||||
}
|
||||
if traceID != "" {
|
||||
values["trace_id"] = traceID
|
||||
}
|
||||
|
||||
operationCtx, cancel, err := publisher.operationContext(ctx, "publish user lifecycle event")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
if err := publisher.client.XAdd(operationCtx, &redis.XAddArgs{
|
||||
Stream: publisher.stream,
|
||||
MaxLen: publisher.streamMaxLen,
|
||||
Approx: true,
|
||||
Values: values,
|
||||
}).Err(); err != nil {
|
||||
return fmt.Errorf("publish user lifecycle event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (publisher *Publisher) operationContext(ctx context.Context, operation string) (context.Context, context.CancelFunc, error) {
|
||||
if publisher == nil || publisher.client == nil {
|
||||
return nil, nil, fmt.Errorf("%s: nil publisher", operation)
|
||||
}
|
||||
if ctx == nil {
|
||||
return nil, nil, fmt.Errorf("%s: nil context", operation)
|
||||
}
|
||||
|
||||
operationCtx, cancel := context.WithTimeout(ctx, publisher.operationTimeout)
|
||||
return operationCtx, cancel, nil
|
||||
}
|
||||
|
||||
func traceIDFromContext(ctx context.Context, fallback string) string {
|
||||
if strings.TrimSpace(fallback) != "" {
|
||||
return fallback
|
||||
}
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
spanContext := trace.SpanContextFromContext(ctx)
|
||||
if !spanContext.IsValid() {
|
||||
return ""
|
||||
}
|
||||
|
||||
return spanContext.TraceID().String()
|
||||
}
|
||||
|
||||
var (
|
||||
_ interface{ Close() error } = (*Publisher)(nil)
|
||||
_ interface{ Ping(context.Context) error } = (*Publisher)(nil)
|
||||
_ ports.UserLifecyclePublisher = (*Publisher)(nil)
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
package lifecycleevents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"galaxy/user/internal/domain/common"
|
||||
"galaxy/user/internal/ports"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPublisherPublishesPermanentBlockedEnvelope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := miniredis.RunT(t)
|
||||
publisher, err := New(Config{
|
||||
Addr: server.Addr(),
|
||||
Stream: "user:lifecycle_events",
|
||||
StreamMaxLen: 10,
|
||||
OperationTimeout: time.Second,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
occurredAt := time.Unix(1_775_240_000, 0).UTC()
|
||||
require.NoError(t, publisher.PublishUserLifecycleEvent(context.Background(), ports.UserLifecycleEvent{
|
||||
EventType: ports.UserLifecyclePermanentBlockedEventType,
|
||||
UserID: common.UserID("user-123"),
|
||||
OccurredAt: occurredAt,
|
||||
Source: common.Source("admin_internal_api"),
|
||||
Actor: common.ActorRef{Type: common.ActorType("admin"), ID: common.ActorID("admin-1")},
|
||||
ReasonCode: common.ReasonCode("terminal_policy_violation"),
|
||||
TraceID: "4bf92f3577b34da6a3ce929d0e0e4736",
|
||||
}))
|
||||
|
||||
entries, err := publisher.client.XRange(context.Background(), publisher.stream, "-", "+").Result()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
values := entries[0].Values
|
||||
require.Equal(t, string(ports.UserLifecyclePermanentBlockedEventType), values["event_type"])
|
||||
require.Equal(t, "user-123", values["user_id"])
|
||||
require.Equal(t, strconv.FormatInt(occurredAt.UnixMilli(), 10), values["occurred_at_ms"])
|
||||
require.Equal(t, "admin_internal_api", values["source"])
|
||||
require.Equal(t, "admin", values["actor_type"])
|
||||
require.Equal(t, "admin-1", values["actor_id"])
|
||||
require.Equal(t, "terminal_policy_violation", values["reason_code"])
|
||||
require.Equal(t, "4bf92f3577b34da6a3ce929d0e0e4736", values["trace_id"])
|
||||
}
|
||||
|
||||
func TestPublisherOmitsOptionalActorIDAndTraceID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := miniredis.RunT(t)
|
||||
publisher, err := New(Config{
|
||||
Addr: server.Addr(),
|
||||
Stream: "user:lifecycle_events",
|
||||
StreamMaxLen: 10,
|
||||
OperationTimeout: time.Second,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, publisher.PublishUserLifecycleEvent(context.Background(), ports.UserLifecycleEvent{
|
||||
EventType: ports.UserLifecycleDeletedEventType,
|
||||
UserID: common.UserID("user-123"),
|
||||
OccurredAt: time.Unix(1_775_240_000, 0).UTC(),
|
||||
Source: common.Source("admin_internal_api"),
|
||||
Actor: common.ActorRef{Type: common.ActorType("admin")},
|
||||
ReasonCode: common.ReasonCode("user_right_to_be_forgotten"),
|
||||
}))
|
||||
|
||||
entries, err := publisher.client.XRange(context.Background(), publisher.stream, "-", "+").Result()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
values := entries[0].Values
|
||||
_, hasActorID := values["actor_id"]
|
||||
require.False(t, hasActorID)
|
||||
_, hasTraceID := values["trace_id"]
|
||||
require.False(t, hasTraceID)
|
||||
require.Equal(t, string(ports.UserLifecycleDeletedEventType), values["event_type"])
|
||||
}
|
||||
|
||||
func TestPublisherRejectsInvalidEventBeforeXAdd(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := miniredis.RunT(t)
|
||||
publisher, err := New(Config{
|
||||
Addr: server.Addr(),
|
||||
Stream: "user:lifecycle_events",
|
||||
StreamMaxLen: 10,
|
||||
OperationTimeout: time.Second,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
err = publisher.PublishUserLifecycleEvent(context.Background(), ports.UserLifecycleEvent{
|
||||
EventType: "user.lifecycle.unknown",
|
||||
UserID: common.UserID("user-123"),
|
||||
OccurredAt: time.Unix(1_775_240_000, 0).UTC(),
|
||||
Source: common.Source("admin_internal_api"),
|
||||
Actor: common.ActorRef{Type: common.ActorType("admin")},
|
||||
ReasonCode: common.ReasonCode("manual_block"),
|
||||
})
|
||||
require.Error(t, err)
|
||||
|
||||
length, xLenErr := publisher.client.XLen(context.Background(), publisher.stream).Result()
|
||||
require.NoError(t, xLenErr)
|
||||
require.Zero(t, length)
|
||||
}
|
||||
|
||||
func TestPublisherTrimsBeyondMaxLen(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := miniredis.RunT(t)
|
||||
publisher, err := New(Config{
|
||||
Addr: server.Addr(),
|
||||
Stream: "user:lifecycle_events",
|
||||
StreamMaxLen: 5,
|
||||
OperationTimeout: time.Second,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
occurredAt := time.Unix(1_775_240_000, 0).UTC()
|
||||
for index := 0; index < 20; index++ {
|
||||
require.NoError(t, publisher.PublishUserLifecycleEvent(context.Background(), ports.UserLifecycleEvent{
|
||||
EventType: ports.UserLifecyclePermanentBlockedEventType,
|
||||
UserID: common.UserID("user-123"),
|
||||
OccurredAt: occurredAt.Add(time.Duration(index+1) * time.Second),
|
||||
Source: common.Source("admin_internal_api"),
|
||||
Actor: common.ActorRef{Type: common.ActorType("admin")},
|
||||
ReasonCode: common.ReasonCode("terminal_policy_violation"),
|
||||
}))
|
||||
}
|
||||
|
||||
length, err := publisher.client.XLen(context.Background(), publisher.stream).Result()
|
||||
require.NoError(t, err)
|
||||
require.LessOrEqual(t, length, int64(20))
|
||||
}
|
||||
|
||||
func TestPublisherPingReportsReachability(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := miniredis.RunT(t)
|
||||
publisher, err := New(Config{
|
||||
Addr: server.Addr(),
|
||||
Stream: "user:lifecycle_events",
|
||||
StreamMaxLen: 10,
|
||||
OperationTimeout: time.Second,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, publisher.Ping(context.Background()))
|
||||
}
|
||||
Reference in New Issue
Block a user