Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logic & Stucture Refactor - DB Memory Cache #8

Merged
merged 8 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build/envoy/service-envoy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ static_resources:
- endpoint:
address:
socket_address:
address: "sro-characters"
address: "sro-character"
port_value: 8081
http2_protocol_options: {}
- name: gamebackend_service
Expand Down
46 changes: 29 additions & 17 deletions cmd/character/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,54 +2,66 @@ package character

import (
"context"
"fmt"

"github.com/Nerzal/gocloak/v13"
"github.com/ShatteredRealms/go-backend/pkg/config"
"github.com/ShatteredRealms/go-backend/pkg/helpers"
"github.com/ShatteredRealms/go-backend/pkg/repository"
"github.com/ShatteredRealms/go-backend/pkg/service"
"github.com/WilSimpson/gocloak/v13"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)

var (
ServiceName = "character"
)

type CharactersServerContext struct {
GlobalConfig *config.GlobalConfig
type CharacterServerContext struct {
*config.ServerContext
CharacterService service.CharacterService
InventoryService service.InventoryService
KeycloakClient *gocloak.GoCloak
Tracer trace.Tracer
}

func NewServerContext(ctx context.Context, conf *config.GlobalConfig) *CharactersServerContext {
server := &CharactersServerContext{
GlobalConfig: conf,
Tracer: otel.Tracer("CharactersService"),
KeycloakClient: gocloak.NewClient(conf.Keycloak.BaseURL),
func NewServerContext(ctx context.Context, conf *config.GlobalConfig, tracer trace.Tracer) (*CharacterServerContext, error) {
server := &CharacterServerContext{
ServerContext: &config.ServerContext{
GlobalConfig: conf,
Tracer: tracer,
KeycloakClient: gocloak.NewClient(conf.Keycloak.BaseURL),
RefSROServer: &conf.Character.SROServer,
},
}
ctx, span := server.Tracer.Start(ctx, "server.new")
defer span.End()

server.KeycloakClient.RegisterMiddlewares(gocloak.OpenTelemetryMiddleware)

postgres, err := repository.ConnectDB(server.GlobalConfig.Character.Postgres)
helpers.Check(ctx, err, "connecting to postgres database")
if err != nil {
return nil, fmt.Errorf("connecting to postgres: %w", err)
}

characterRepo, err := repository.NewCharacterRepository(postgres)
helpers.Check(ctx, err, "character repo")
if err != nil {
return nil, fmt.Errorf("postgres: %w", err)
}
characterService, err := service.NewCharacterService(ctx, characterRepo)
helpers.Check(ctx, err, "character serivce")
if err != nil {
return nil, fmt.Errorf("character service: %w", err)
}
server.CharacterService = characterService

opts := options.Client()
opts.Monitor = otelmongo.NewMonitor()
opts.ApplyURI(server.GlobalConfig.Character.Mongo.Master.MongoDSN())
mongoDb, err := mongo.Connect(ctx, opts)
helpers.Check(ctx, err, "connecting to mongo database")
if err != nil {
return nil, fmt.Errorf("connecting to mongo database: %w", err)
}
invRepo := repository.NewInventoryRepository(mongoDb.Database(server.GlobalConfig.Character.Mongo.Master.Name))
server.InventoryService = service.NewInventoryService(invRepo)

return server
return server, nil
}
44 changes: 34 additions & 10 deletions cmd/character/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/ShatteredRealms/go-backend/pkg/log"
"github.com/ShatteredRealms/go-backend/pkg/pb"
"github.com/ShatteredRealms/go-backend/pkg/srv"
"github.com/ShatteredRealms/go-backend/pkg/telemetry"
"go.opentelemetry.io/otel"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

Expand All @@ -22,15 +24,18 @@ var (
)

func init() {
helpers.SetupLogger(character.ServiceName)
conf = config.NewGlobalConfig(context.Background())
var err error
conf, err = config.NewGlobalConfig(context.Background())
if err != nil {
log.Logger.Fatalf("initialization: %v", err)
}
}

func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()

otelShutdown, err := helpers.SetupOTelSDK(ctx, character.ServiceName, config.Version, conf.OpenTelemetry.Addr)
otelShutdown, err := telemetry.SetupOTelSDK(ctx, character.ServiceName, conf.Version, conf.OpenTelemetry.Addr)
defer func() {
err = errors.Join(err, otelShutdown(context.Background()))
if err != nil {
Expand All @@ -39,32 +44,51 @@ func main() {
}()

if err != nil {
log.Logger.Fatal(err)
log.Logger.WithContext(ctx).Errorf("connecting to otel: %v", err)
return
}

server := character.NewServerContext(ctx, conf)
grpcServer, gwmux := helpers.InitServerDefaults()
tracer := otel.Tracer("CharactersService")
ctx, span := tracer.Start(ctx, "initialize")
defer span.End()

server, err := character.NewServerContext(ctx, conf, tracer)
if err != nil {
log.Logger.WithContext(ctx).Errorf("creating server context: %v", err)
return
}
grpcServer, gwmux := helpers.InitServerDefaults(server.KeycloakClient, server.GlobalConfig.Keycloak.Realm)
address := server.GlobalConfig.Character.Local.Address()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}

pb.RegisterHealthServiceServer(grpcServer, srv.NewHealthServiceServer())
err = pb.RegisterHealthServiceHandlerFromEndpoint(ctx, gwmux, address, opts)
helpers.Check(ctx, err, "register health service handler endpoint")
if err != nil {
log.Logger.WithContext(ctx).Errorf("register health service handler endpoint: %v", err)
return
}

css, err := srv.NewCharacterServiceServer(ctx, server)
helpers.Check(ctx, err, "create characters service server")
if err != nil {
log.Logger.WithContext(ctx).Errorf("create character service server: %v", err)
return
}
pb.RegisterCharacterServiceServer(grpcServer, css)
err = pb.RegisterCharacterServiceHandlerFromEndpoint(ctx, gwmux, address, opts)
helpers.Check(ctx, err, "registering characters service handler endpoint")
if err != nil {
log.Logger.WithContext(ctx).Errorf("registering character service handler endpoint: %v", err)
return
}

span.End()
srvErr := make(chan error, 1)
go func() {
srvErr <- helpers.StartServer(ctx, grpcServer, gwmux, server.GlobalConfig.Character.Local.Address())
}()

select {
case err = <-srvErr:
log.Logger.Fatalf("listen server: %v", err)
log.Logger.WithContext(ctx).Errorf("listen server: %v", err)

case <-ctx.Done():
log.Logger.Info("Server canceled by user input.")
Expand Down
39 changes: 26 additions & 13 deletions cmd/chat/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package chat

import (
"context"
"fmt"

"github.com/Nerzal/gocloak/v13"
"github.com/ShatteredRealms/go-backend/pkg/config"
"github.com/ShatteredRealms/go-backend/pkg/helpers"
"github.com/ShatteredRealms/go-backend/pkg/pb"
"github.com/ShatteredRealms/go-backend/pkg/repository"
"github.com/ShatteredRealms/go-backend/pkg/service"
"go.opentelemetry.io/otel"
"github.com/WilSimpson/gocloak/v13"
"go.opentelemetry.io/otel/trace"
)

Expand All @@ -18,31 +18,44 @@ var (
)

type ChatServerContext struct {
GlobalConfig *config.GlobalConfig
*config.ServerContext
ChatService service.ChatService
CharacterService pb.CharacterServiceClient
KeycloakClient *gocloak.GoCloak
Tracer trace.Tracer
}

func NewServerContext(ctx context.Context, conf *config.GlobalConfig) *ChatServerContext {
func NewServerContext(ctx context.Context, conf *config.GlobalConfig, tracer trace.Tracer) (*ChatServerContext, error) {
server := &ChatServerContext{
GlobalConfig: conf,
Tracer: otel.Tracer("ChatService"),
KeycloakClient: gocloak.NewClient(conf.Keycloak.BaseURL),
ServerContext: &config.ServerContext{
GlobalConfig: conf,
Tracer: tracer,
KeycloakClient: gocloak.NewClient(conf.Keycloak.BaseURL),
RefSROServer: &conf.Chat.SROServer,
},
ChatService: nil,
CharacterService: nil,
}
ctx, span := server.Tracer.Start(ctx, "server.connect")
defer span.End()

server.KeycloakClient.RegisterMiddlewares(gocloak.OpenTelemetryMiddleware)

db, err := repository.ConnectDB(conf.Chat.Postgres)
helpers.Check(ctx, err, "connecting to database")
if err != nil {
return nil, fmt.Errorf("connecting to postgres database: %w", err)
}

repo := repository.NewChatRepository(db)
chatService, err := service.NewChatService(ctx, repo, conf.Chat.Kafka)
helpers.Check(ctx, err, "chat service")
if err != nil {
return nil, fmt.Errorf("creating chat service: %w", err)
}
server.ChatService = chatService

charactersConn, err := helpers.GrpcClientWithOtel(conf.Character.Remote.Address())
helpers.Check(ctx, err, "connect characters service")
if err != nil {
return nil, fmt.Errorf("connecting characters service: %w", err)
}
server.CharacterService = pb.NewCharacterServiceClient(charactersConn)

return server
return server, nil
}
45 changes: 34 additions & 11 deletions cmd/chat/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import (
"os"
"os/signal"

character "github.com/ShatteredRealms/go-backend/cmd/character/app"
chat "github.com/ShatteredRealms/go-backend/cmd/chat/app"
"github.com/ShatteredRealms/go-backend/pkg/helpers"
"github.com/ShatteredRealms/go-backend/pkg/log"
"github.com/ShatteredRealms/go-backend/pkg/pb"
"github.com/ShatteredRealms/go-backend/pkg/srv"
"github.com/ShatteredRealms/go-backend/pkg/telemetry"
"go.opentelemetry.io/otel"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

Expand All @@ -23,15 +24,18 @@ var (
)

func init() {
helpers.SetupLogger(chat.ServiceName)
conf = config.NewGlobalConfig(context.Background())
var err error
conf, err = config.NewGlobalConfig(context.Background())
if err != nil {
log.Logger.Fatalf("initialization: %v", err)
}
}

func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()

otelShutdown, err := helpers.SetupOTelSDK(ctx, character.ServiceName, config.Version, conf.OpenTelemetry.Addr)
otelShutdown, err := telemetry.SetupOTelSDK(ctx, chat.ServiceName, config.Version, conf.OpenTelemetry.Addr)
defer func() {
err = errors.Join(err, otelShutdown(context.Background()))
if err != nil {
Expand All @@ -40,32 +44,51 @@ func main() {
}()

if err != nil {
log.Logger.Fatal(err)
log.Logger.WithContext(ctx).Errorf("connecting to otel: %v", err)
return
}

server := chat.NewServerContext(ctx, conf)
grpcServer, gwmux := helpers.InitServerDefaults()
tracer := otel.Tracer("ChatService")
ctx, span := tracer.Start(ctx, "initialize")
defer span.End()

server, err := chat.NewServerContext(ctx, conf, tracer)
if err != nil {
log.Logger.WithContext(ctx).Errorf("creating server context: %v", err)
return
}
grpcServer, gwmux := helpers.InitServerDefaults(server.KeycloakClient, server.GlobalConfig.Keycloak.Realm)
address := server.GlobalConfig.Chat.Local.Address()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}

pb.RegisterHealthServiceServer(grpcServer, srv.NewHealthServiceServer())
err = pb.RegisterHealthServiceHandlerFromEndpoint(ctx, gwmux, address, opts)
helpers.Check(ctx, err, "register health service handler endpoint")
if err != nil {
log.Logger.WithContext(ctx).Errorf("register health service handler endpoint: %v", err)
return
}

srvService, err := srv.NewChatServiceServer(ctx, server)
helpers.Check(ctx, err, "create chat service")
if err != nil {
log.Logger.WithContext(ctx).Errorf("create chat service: %v", err)
return
}
pb.RegisterChatServiceServer(grpcServer, srvService)
err = pb.RegisterChatServiceHandlerFromEndpoint(ctx, gwmux, address, opts)
helpers.Check(ctx, err, "register chat service handler endpoint")
if err != nil {
log.Logger.WithContext(ctx).Errorf("register chat service handler endpoint: %v", err)
return
}

span.End()
srvErr := make(chan error, 1)
go func() {
srvErr <- helpers.StartServer(ctx, grpcServer, gwmux, server.GlobalConfig.Chat.Local.Address())
}()

select {
case err = <-srvErr:
log.Logger.Fatalf("listen server: %v", err)
log.Logger.WithContext(ctx).Errorf("listen server: %v", err)

case <-ctx.Done():
log.Logger.Info("Server canceled by user input.")
Expand Down
Loading
Loading