108 lines
2.4 KiB
Go
108 lines
2.4 KiB
Go
package serverimp
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/tech/sendico/fx/oracle/internal/service/oracle"
|
|
"github.com/tech/sendico/fx/storage"
|
|
mongostorage "github.com/tech/sendico/fx/storage/mongo"
|
|
"github.com/tech/sendico/pkg/api/routers"
|
|
"github.com/tech/sendico/pkg/db"
|
|
msg "github.com/tech/sendico/pkg/messaging"
|
|
"github.com/tech/sendico/pkg/mlogger"
|
|
"github.com/tech/sendico/pkg/server/grpcapp"
|
|
"go.uber.org/zap"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type Imp struct {
|
|
logger mlogger.Logger
|
|
file string
|
|
debug bool
|
|
|
|
config *grpcapp.Config
|
|
app *grpcapp.App[storage.Repository]
|
|
service *oracle.Service
|
|
}
|
|
|
|
func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
|
|
return &Imp{
|
|
logger: logger.Named("server"),
|
|
file: file,
|
|
debug: debug,
|
|
}, nil
|
|
}
|
|
|
|
func (i *Imp) Shutdown() {
|
|
if i.app == nil {
|
|
return
|
|
}
|
|
if i.service != nil {
|
|
i.service.Shutdown()
|
|
}
|
|
timeout := 15 * time.Second
|
|
if i.config != nil && i.config.Runtime != nil {
|
|
timeout = i.config.Runtime.ShutdownTimeout()
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
i.app.Shutdown(ctx)
|
|
cancel()
|
|
}
|
|
|
|
func (i *Imp) Start() error {
|
|
cfg, err := i.loadConfig()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
i.config = cfg
|
|
|
|
repoFactory := func(logger mlogger.Logger, conn *db.MongoConnection) (storage.Repository, error) {
|
|
return mongostorage.New(logger, conn)
|
|
}
|
|
|
|
serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
|
|
svc := oracle.NewService(logger, repo, producer)
|
|
i.service = svc
|
|
return svc, nil
|
|
}
|
|
|
|
app, err := grpcapp.NewApp(i.logger, "fx", cfg, i.debug, repoFactory, serviceFactory)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
i.app = app
|
|
|
|
return i.app.Start()
|
|
}
|
|
|
|
func (i *Imp) loadConfig() (*grpcapp.Config, error) {
|
|
data, err := os.ReadFile(i.file)
|
|
if err != nil {
|
|
i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
|
|
return nil, err
|
|
}
|
|
|
|
cfg := &grpcapp.Config{}
|
|
if err := yaml.Unmarshal(data, cfg); err != nil {
|
|
i.logger.Error("Failed to parse configuration", zap.Error(err))
|
|
return nil, err
|
|
}
|
|
|
|
if cfg.Runtime == nil {
|
|
cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
|
|
}
|
|
|
|
if cfg.GRPC == nil {
|
|
cfg.GRPC = &routers.GRPCConfig{
|
|
Network: "tcp",
|
|
Address: ":50051",
|
|
EnableReflection: true,
|
|
EnableHealth: true,
|
|
}
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|