init project
This commit is contained in:
1 parent
d63cc8d9f5
commit
ee07869839
39 files changed
+1560
-622
No files matched your search
+146
-5
@@ -1,17 +1,158 @@
|
||||
package configs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.vitatech.com.cn/leo/proto.git/discovery"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func Load(path string, c interface{}) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
// Config 由各入口的 cmd/<name>/config 包定义。
|
||||
type Config interface {
|
||||
Validate() error
|
||||
}
|
||||
|
||||
type RegistryConfig struct {
|
||||
Etcd discovery.Config `mapstructure:"etcd"`
|
||||
ServiceName string `mapstructure:"service_name"`
|
||||
AdvertiseAddr string `mapstructure:"advertise_addr"`
|
||||
LeaseTTL int64 `mapstructure:"lease_ttl"`
|
||||
}
|
||||
|
||||
type AppConfig struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Env string `mapstructure:"env"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Addr string `mapstructure:"addr"`
|
||||
Reflection bool `mapstructure:"reflection"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"`
|
||||
}
|
||||
|
||||
type LogConfig struct {
|
||||
Level string `mapstructure:"level"`
|
||||
}
|
||||
|
||||
func Load(configFile string, cfg Config) error {
|
||||
loader := viper.New()
|
||||
loader.SetConfigType("yaml")
|
||||
loader.AllowEmptyEnv(true)
|
||||
loader.SetEnvPrefix("APP")
|
||||
loader.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
loader.AutomaticEnv()
|
||||
defaults := map[string]interface{}{
|
||||
"app.name": "micro_layout",
|
||||
"app.env": "local",
|
||||
"server.addr": ":50112",
|
||||
"server.reflection": false,
|
||||
"server.shutdown_timeout": "10s",
|
||||
"log.level": "info",
|
||||
"registry.etcd.endpoints": []string{"127.0.0.1:2379"},
|
||||
"registry.etcd.username": "",
|
||||
"registry.etcd.password": "",
|
||||
"registry.etcd.dial_timeout": "5s",
|
||||
"registry.service_name": "micro.micro_layout",
|
||||
"registry.advertise_addr": "",
|
||||
"registry.lease_ttl": 10,
|
||||
"storage.mysql.enabled": false,
|
||||
"storage.mysql.dsn": "",
|
||||
"storage.mysql.show_sql": false,
|
||||
"storage.mysql.max_open_conn": 10,
|
||||
"storage.mysql.max_idle_conn": 5,
|
||||
"storage.mysql.conn_max_lifetime": "1h",
|
||||
"storage.mysql.connect_timeout": "5s",
|
||||
"storage.redis.enabled": false,
|
||||
"storage.redis.addr": "127.0.0.1:6379",
|
||||
"storage.redis.password": "",
|
||||
"storage.redis.db": 0,
|
||||
"storage.redis.connect_timeout": "5s",
|
||||
"jetstream.enabled": false,
|
||||
"jetstream.addr": "nats://127.0.0.1:4222",
|
||||
"jetstream.token": "",
|
||||
"jetstream.connect_timeout": "5s",
|
||||
}
|
||||
for key, value := range defaults {
|
||||
loader.SetDefault(key, value)
|
||||
}
|
||||
if err := loader.BindEnv("app.name", "APP_NAME"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(data, c); err != nil {
|
||||
if err := loader.BindEnv("app.env", "APP_ENV"); err != nil {
|
||||
return err
|
||||
}
|
||||
if configFile == "" {
|
||||
configFile = strings.TrimSpace(os.Getenv("CONFIG_FILE"))
|
||||
}
|
||||
if configFile != "" {
|
||||
loader.SetConfigFile(configFile)
|
||||
} else {
|
||||
loader.SetConfigName("config")
|
||||
loader.AddConfigPath("./configs")
|
||||
}
|
||||
if err := loader.ReadInConfig(); err != nil {
|
||||
var notFound viper.ConfigFileNotFoundError
|
||||
if configFile != "" || !errors.As(err, ¬Found) {
|
||||
return errors.New("read configuration failed: check YAML syntax, file path and permissions")
|
||||
}
|
||||
}
|
||||
if err := loader.UnmarshalExact(cfg); err != nil {
|
||||
return errors.New("decode configuration failed: check field names and value types")
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return fmt.Errorf("validate configuration: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg RegistryConfig) Validate() error {
|
||||
if err := cfg.Etcd.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := discovery.ValidateService(cfg.ServiceName); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.LeaseTTL < 3 {
|
||||
return errors.New("registry.lease_ttl must be at least 3")
|
||||
}
|
||||
if cfg.AdvertiseAddr != "" {
|
||||
return discovery.ValidateAddress(cfg.AdvertiseAddr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg AppConfig) Validate() error {
|
||||
if strings.TrimSpace(cfg.Name) == "" || strings.TrimSpace(cfg.Env) == "" {
|
||||
return errors.New("app.name and app.env must not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg ServerConfig) Validate() error {
|
||||
_, port, err := net.SplitHostPort(cfg.Addr)
|
||||
if err != nil {
|
||||
return errors.New("server.addr must be host:port or :port")
|
||||
}
|
||||
number, err := strconv.Atoi(port)
|
||||
if err != nil || number < 1 || number > 65535 {
|
||||
return errors.New("server.addr port must be between 1 and 65535")
|
||||
}
|
||||
if cfg.ShutdownTimeout <= 0 {
|
||||
return errors.New("server.shutdown_timeout must be greater than zero")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg LogConfig) Validate() error {
|
||||
if _, err := log.ParseLevel(cfg.Level); err != nil {
|
||||
return errors.New("log.level must be a valid logrus level")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package configs_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
cronconfig "micro_layout/cmd/crontab/config"
|
||||
srvconfig "micro_layout/cmd/srv/config"
|
||||
"micro_layout/internal/configs"
|
||||
)
|
||||
|
||||
func TestLoadEntryConfigurations(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
selected := filepath.Join(dir, "local.ymal")
|
||||
if err := os.WriteFile(selected, []byte("app:\n name: from-file\nlog:\n level: debug\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("CONFIG_FILE", filepath.Join(dir, "missing.yaml"))
|
||||
t.Setenv("APP_NAME", "from-env")
|
||||
t.Setenv("APP_ENV", "test")
|
||||
t.Setenv("APP_STORAGE_MYSQL_ENABLED", "false")
|
||||
t.Setenv("APP_STORAGE_REDIS_ENABLED", "false")
|
||||
t.Setenv("APP_JETSTREAM_ENABLED", "false")
|
||||
var srv srvconfig.Config
|
||||
if err := configs.Load(selected, &srv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if srv.App.Name != "from-env" || srv.Log.Level != "debug" || srv.Server.ShutdownTimeout != 10*time.Second {
|
||||
t.Fatalf("environment, file and default precedence changed: app=%+v log=%+v server=%+v", srv.App, srv.Log, srv.Server)
|
||||
}
|
||||
var cron cronconfig.Config
|
||||
if err := configs.Load(selected, &cron); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cron.App != srv.App || cron.Log != srv.Log || cron.Server != srv.Server {
|
||||
t.Fatalf("srv and crontab disagree when reading the shared configuration")
|
||||
}
|
||||
if err := configs.Load("", &srv); err == nil {
|
||||
t.Fatal("explicit CONFIG_FILE pointing to a missing file was accepted")
|
||||
}
|
||||
t.Setenv("CONFIG_FILE", selected)
|
||||
if err := configs.Load("", &srv); err != nil {
|
||||
t.Fatalf("CONFIG_FILE was not used: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidConfiguration(t *testing.T) {
|
||||
t.Setenv("APP_STORAGE_MYSQL_ENABLED", "false")
|
||||
t.Setenv("APP_STORAGE_REDIS_ENABLED", "false")
|
||||
t.Setenv("APP_JETSTREAM_ENABLED", "false")
|
||||
for _, data := range []string{
|
||||
"unknown_key: value\n",
|
||||
"server:\n shutdown_timeout: 0s\n",
|
||||
"storage:\n mysql:\n enabled: true\n",
|
||||
} {
|
||||
t.Run(data, func(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), "invalid.yaml")
|
||||
if err := os.WriteFile(file, []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data == "storage:\n mysql:\n enabled: true\n" {
|
||||
t.Setenv("APP_STORAGE_MYSQL_ENABLED", "true")
|
||||
t.Setenv("APP_STORAGE_MYSQL_DSN", "")
|
||||
}
|
||||
var cfg srvconfig.Config
|
||||
if err := configs.Load(file, &cfg); err == nil {
|
||||
t.Fatal("invalid configuration was accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type serviceHook struct {
|
||||
name string
|
||||
env string
|
||||
}
|
||||
|
||||
func (hook serviceHook) Levels() []log.Level { return log.AllLevels }
|
||||
|
||||
func (hook serviceHook) Fire(entry *log.Entry) error {
|
||||
entry.Data["service"] = hook.name
|
||||
entry.Data["env"] = hook.env
|
||||
return nil
|
||||
}
|
||||
|
||||
func Setup(level, name, env string) error {
|
||||
parsed, err := log.ParseLevel(level)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.SetFormatter(&log.JSONFormatter{TimestampFormat: time.RFC3339Nano})
|
||||
log.SetLevel(parsed)
|
||||
log.AddHook(serviceHook{name: name, env: env})
|
||||
return nil
|
||||
}
|
||||
@@ -2,11 +2,12 @@ package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.xiaotuo.co/micro/skeleton/internal/queue/jetstream"
|
||||
"git.xiaotuo.co/pkg/go-plugins/logger"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"micro_layout/internal/logger"
|
||||
"micro_layout/internal/queue/jetstream"
|
||||
)
|
||||
|
||||
type MessageLogic struct {
|
||||
@@ -22,6 +23,9 @@ func (lgc MessageLogic) jetStreamPublish(ctx context.Context, topic string, body
|
||||
WithField("topic", topic).
|
||||
WithField("body", string(body)).
|
||||
Debug("start")
|
||||
if Resources == nil || Resources.JetStreamBroker == nil {
|
||||
return errors.New("jetstream is disabled")
|
||||
}
|
||||
ack, err := Resources.JetStreamBroker.PublishMsg(jetstream.NewMsg(ctx, topic, body))
|
||||
if err != nil {
|
||||
log.WithFields(logger.WithContext(ctx)).
|
||||
|
||||
+18
-35
@@ -1,68 +1,51 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"git.xiaotuo.co/micro/skeleton/internal/storage"
|
||||
"github.com/nats-io/nats.go"
|
||||
"micro_layout/internal/storage"
|
||||
)
|
||||
|
||||
var Resources *resources
|
||||
|
||||
type resources struct {
|
||||
Env string
|
||||
Server string
|
||||
Storage *storage.Storage
|
||||
JetStreamBroker nats.JetStreamContext
|
||||
|
||||
MessageLogic MessageLogic
|
||||
MessageLogic MessageLogic
|
||||
UserLogic *UserLogic
|
||||
}
|
||||
|
||||
func Init(opts ...Option) error {
|
||||
options := &Options{}
|
||||
for _, o := range opts {
|
||||
o(options)
|
||||
for _, option := range opts {
|
||||
option(options)
|
||||
}
|
||||
|
||||
Resources = &resources{
|
||||
Env: options.env,
|
||||
Server: options.server,
|
||||
|
||||
JetStreamBroker: options.jetStreamBr,
|
||||
Env: options.env,
|
||||
Storage: options.storage,
|
||||
JetStreamBroker: options.jetStream,
|
||||
MessageLogic: newMessageLogic(),
|
||||
UserLogic: newUserLogic(),
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Option func(o *Options)
|
||||
type Option func(*Options)
|
||||
|
||||
type Options struct {
|
||||
env string
|
||||
server string
|
||||
etcdServer string
|
||||
st *storage.Storage
|
||||
jetStreamBr nats.JetStreamContext
|
||||
tiktokAuthGateway string
|
||||
env string
|
||||
storage *storage.Storage
|
||||
jetStream nats.JetStreamContext
|
||||
}
|
||||
|
||||
func WithEnv(env string) Option {
|
||||
return func(o *Options) {
|
||||
o.env = env
|
||||
}
|
||||
return func(options *Options) { options.env = env }
|
||||
}
|
||||
|
||||
func WithStorage(st *storage.Storage) Option {
|
||||
return func(o *Options) {
|
||||
o.st = st
|
||||
}
|
||||
return func(options *Options) { options.storage = st }
|
||||
}
|
||||
|
||||
func WithEtcdServer(etcdServer string) Option {
|
||||
return func(o *Options) {
|
||||
o.etcdServer = etcdServer
|
||||
}
|
||||
}
|
||||
|
||||
func WithJetStreamBroker(br nats.JetStreamContext) Option {
|
||||
return func(o *Options) {
|
||||
o.jetStreamBr = br
|
||||
}
|
||||
func WithJetStreamBroker(broker nats.JetStreamContext) Option {
|
||||
return func(options *Options) { options.jetStream = broker }
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
|
||||
"micro_layout/internal/storage/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserLogic struct {
|
||||
mutex sync.RWMutex
|
||||
nextID int64
|
||||
users map[int64]model.User
|
||||
}
|
||||
|
||||
func newUserLogic() *UserLogic {
|
||||
return &UserLogic{
|
||||
nextID: 2,
|
||||
users: map[int64]model.User{1: {BaseModel: model.BaseModel{ID: 1}, Name: "demo", Status: "active"}},
|
||||
}
|
||||
}
|
||||
|
||||
var ErrInvalidUser = errors.New("name must contain between 1 and 100 characters")
|
||||
|
||||
func (logic *UserLogic) Create(ctx context.Context, name string) (model.User, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" || utf8.RuneCountInString(name) > 100 {
|
||||
return model.User{}, ErrInvalidUser
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
item := model.User{Name: name, Status: "active"}
|
||||
if database := Resources.Storage.DB(); database != nil {
|
||||
err := database.WithContext(ctx).Create(&item).Error
|
||||
return item, err
|
||||
}
|
||||
logic.mutex.Lock()
|
||||
defer logic.mutex.Unlock()
|
||||
item.ID = logic.nextID
|
||||
logic.nextID++
|
||||
logic.users[item.ID] = item
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (logic *UserLogic) QueryInfo(ctx context.Context, id int64) (model.User, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
if database := Resources.Storage.DB(); database != nil {
|
||||
var item model.User
|
||||
err := database.WithContext(ctx).First(&item, id).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
return item, err == nil, err
|
||||
}
|
||||
logic.mutex.RLock()
|
||||
defer logic.mutex.RUnlock()
|
||||
item, exists := logic.users[id]
|
||||
return item, exists, nil
|
||||
}
|
||||
@@ -1,15 +1,27 @@
|
||||
package jetstream
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
nats "github.com/nats-io/nats.go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Addr string `json:"addr"`
|
||||
Token string `json:"token"`
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
Addr string `mapstructure:"addr"`
|
||||
Token string `mapstructure:"token"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
|
||||
}
|
||||
|
||||
func (cfg Config) Validate() error {
|
||||
if cfg.Enabled && (strings.TrimSpace(cfg.Addr) == "" || cfg.ConnectTimeout <= 0) {
|
||||
return errors.New("enabled jetstream requires addr and positive connect_timeout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type JetStream struct {
|
||||
@@ -18,7 +30,7 @@ type JetStream struct {
|
||||
}
|
||||
|
||||
func NewJetStreamBroker(conf Config) (*JetStream, error) {
|
||||
nc, err := nats.Connect(conf.Addr, nats.Token(conf.Token),
|
||||
nc, err := nats.Connect(conf.Addr, nats.Token(conf.Token), nats.Timeout(conf.ConnectTimeout),
|
||||
nats.DisconnectErrHandler(func(conn *nats.Conn, err error) {
|
||||
log.Errorf("jetStream disconnect: %v", err)
|
||||
}),
|
||||
@@ -40,13 +52,14 @@ func NewJetStreamBroker(conf Config) (*JetStream, error) {
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.New("connect nats failed")
|
||||
}
|
||||
js, err := nc.JetStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
nc.Close()
|
||||
return nil, errors.New("initialize jetstream failed")
|
||||
}
|
||||
log.Infof("jetStream Addr: %s", conf.Addr)
|
||||
log.Info("jetstream connected")
|
||||
return &JetStream{
|
||||
nc: nc,
|
||||
JetStreamContext: js,
|
||||
|
||||
@@ -4,10 +4,10 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.xiaotuo.co/micro/skeleton/internal/runtime"
|
||||
"git.xiaotuo.co/micro/skeleton/pkg/util"
|
||||
"git.xiaotuo.co/pkg/tool/stringx"
|
||||
"github.com/google/uuid"
|
||||
"github.com/robfig/cron/v3"
|
||||
"micro_layout/internal/runtime"
|
||||
"micro_layout/pkg/util"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -20,7 +20,7 @@ type Crontab struct {
|
||||
func NewCrontab() *Crontab {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
opts := &runtime.Options{
|
||||
ID: stringx.MakeUUID(),
|
||||
ID: uuid.NewString(),
|
||||
Type: "crontab",
|
||||
Context: ctx,
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func (m *Crontab) Start() error {
|
||||
|
||||
<-m.options.Context.Done()
|
||||
log.Infof("crontab done")
|
||||
c.Stop()
|
||||
<-c.Stop().Done()
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.xiaotuo.co/micro/skeleton/internal/runtime"
|
||||
"git.xiaotuo.co/pkg/tool/stringx"
|
||||
"github.com/google/uuid"
|
||||
"micro_layout/internal/runtime"
|
||||
)
|
||||
|
||||
type monitor struct {
|
||||
@@ -16,7 +16,7 @@ type monitor struct {
|
||||
func NewMonitor() runtime.Runtime {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
opts := &runtime.Options{
|
||||
ID: stringx.MakeUUID(),
|
||||
ID: uuid.NewString(),
|
||||
Type: "monitor",
|
||||
Context: ctx,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime/debug"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func UnaryRecovery(ctx context.Context, request interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (response interface{}, err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
log.WithField("method", info.FullMethod).WithField("stack", string(debug.Stack())).Error("grpc handler panic")
|
||||
err = status.Error(codes.Internal, "internal server error")
|
||||
}
|
||||
}()
|
||||
return handler(ctx, request)
|
||||
}
|
||||
|
||||
func StreamRecovery(service interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
log.WithField("method", info.FullMethod).WithField("stack", string(debug.Stack())).Error("grpc stream panic")
|
||||
err = status.Error(codes.Internal, "internal server error")
|
||||
}
|
||||
}()
|
||||
return handler(service, stream)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"micro_layout/internal/logic"
|
||||
"micro_layout/internal/storage/model"
|
||||
|
||||
"git.vitatech.com.cn/leo/proto.git/micro_layout/proto/user"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type UserServer struct {
|
||||
user.UnimplementedUserServer
|
||||
}
|
||||
|
||||
func (server *UserServer) Create(ctx context.Context, request *user.CreateRequest) (*user.CreateResponse, error) {
|
||||
item, err := logic.Resources.UserLogic.Create(ctx, request.GetName())
|
||||
if errors.Is(err, logic.ErrInvalidUser) {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, rpcError(ctx, err)
|
||||
}
|
||||
return &user.CreateResponse{Item: userItem(item)}, nil
|
||||
}
|
||||
|
||||
func (server *UserServer) QueryInfo(ctx context.Context, request *user.QueryInfoRequest) (*user.QueryInfoResponse, error) {
|
||||
if request.GetId() <= 0 {
|
||||
return nil, status.Error(codes.InvalidArgument, "invalid user id")
|
||||
}
|
||||
item, exists, err := logic.Resources.UserLogic.QueryInfo(ctx, request.GetId())
|
||||
if err != nil {
|
||||
return nil, rpcError(ctx, err)
|
||||
}
|
||||
if !exists {
|
||||
return &user.QueryInfoResponse{Exists: false}, nil
|
||||
}
|
||||
return &user.QueryInfoResponse{Exists: true, Item: userItem(item)}, nil
|
||||
}
|
||||
|
||||
func userItem(item model.User) *user.UserItem {
|
||||
return &user.UserItem{Id: item.ID, Name: item.Name, Status: item.Status}
|
||||
}
|
||||
|
||||
func rpcError(ctx context.Context, err error) error {
|
||||
if ctx.Err() != nil {
|
||||
return status.FromContextError(ctx.Err()).Err()
|
||||
}
|
||||
log.WithError(err).Error("user operation failed")
|
||||
return status.Error(codes.Internal, "internal server error")
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"micro_layout/internal/logic"
|
||||
"micro_layout/internal/storage"
|
||||
|
||||
"git.vitatech.com.cn/leo/proto.git/micro_layout/proto/user"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestUserServerUsesRegisteredLogic(t *testing.T) {
|
||||
st, err := storage.NewStorage(storage.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
if err := logic.Init(logic.WithEnv("test"), logic.WithStorage(st)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
created, err := (&UserServer{}).Create(ctx, &user.CreateRequest{Name: " Alice "})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
queried, err := (&UserServer{}).QueryInfo(ctx, &user.QueryInfoRequest{Id: created.Item.Id})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !queried.Exists || queried.Item.Name != "Alice" {
|
||||
t.Fatalf("created user is not shared between handlers: %v", queried)
|
||||
}
|
||||
if _, err := (&UserServer{}).Create(ctx, &user.CreateRequest{Name: " "}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Fatalf("invalid name: got %v, want InvalidArgument", err)
|
||||
}
|
||||
}
|
||||
+11
-19
@@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"git.xiaotuo.co/pkg/go-plugins/grpc/metax"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
func GetBizId(ctx context.Context) (int64, error) {
|
||||
@@ -17,34 +17,26 @@ func GetBizId(ctx context.Context) (int64, error) {
|
||||
}
|
||||
|
||||
func NewContext(ctx context.Context) (context.Context, error) {
|
||||
ctx = metax.TransparentContext(ctx)
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
ctx = metadata.NewOutgoingContext(ctx, md)
|
||||
|
||||
reqId, exists, err := metax.GetReqId(ctx)
|
||||
if err != nil {
|
||||
return ctx, fmt.Errorf("req_id_parse_fail")
|
||||
}
|
||||
if !exists {
|
||||
reqIds := md.Get("req_id")
|
||||
if len(reqIds) == 0 {
|
||||
return ctx, fmt.Errorf("req_id_not_found")
|
||||
}
|
||||
ctx = context.WithValue(ctx, "req_id", reqId)
|
||||
ctx = context.WithValue(ctx, "req_id", reqIds[0])
|
||||
|
||||
bizId, exists, err := metax.GetBizId(ctx)
|
||||
if err != nil {
|
||||
return ctx, fmt.Errorf("biz_id_parse_fail")
|
||||
}
|
||||
if !exists {
|
||||
bizIds := md.Get("biz_id")
|
||||
if len(bizIds) == 0 {
|
||||
return ctx, fmt.Errorf("biz_id_not_found")
|
||||
}
|
||||
ctx = context.WithValue(ctx, "biz_id", bizId)
|
||||
|
||||
ctx = context.WithValue(ctx, "biz_id", bizIds[0])
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func getContextValue(ctx context.Context, keyword string) string {
|
||||
if ctx.Value(keyword) != nil {
|
||||
if v, ok := ctx.Value(keyword).(string); ok {
|
||||
return v
|
||||
}
|
||||
if value, ok := ctx.Value(keyword).(string); ok {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
func TestNewContextPreservesMetadata(t *testing.T) {
|
||||
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("req_id", "request-1", "biz_id", "42", "traceparent", "trace-1"))
|
||||
ctx, err := NewContext(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ctx.Value("req_id") != "request-1" {
|
||||
t.Fatal("request id was not added to the business context")
|
||||
}
|
||||
if id, err := GetBizId(ctx); err != nil || id != 42 {
|
||||
t.Fatalf("business id: got %d, %v", id, err)
|
||||
}
|
||||
md, _ := metadata.FromOutgoingContext(ctx)
|
||||
if values := md.Get("traceparent"); len(values) != 1 || values[0] != "trace-1" {
|
||||
t.Fatalf("outgoing metadata lost: %v", md)
|
||||
}
|
||||
if _, err := NewContext(context.Background()); err == nil {
|
||||
t.Fatal("missing request metadata was accepted")
|
||||
}
|
||||
}
|
||||
Vendored
+10
-10
@@ -5,8 +5,8 @@ import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.xiaotuo.co/micro/skeleton/internal/logger"
|
||||
"github.com/go-redis/redis"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"micro_layout/internal/logger"
|
||||
)
|
||||
|
||||
type BaseCache struct {
|
||||
@@ -15,7 +15,7 @@ type BaseCache struct {
|
||||
}
|
||||
|
||||
func (c *BaseCache) exists(ctx context.Context, key string) (bool, error) {
|
||||
value, err := c.rs.Exists(key).Result()
|
||||
value, err := c.rs.Exists(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
if c.isLog {
|
||||
logger.Debugf(ctx, "redis_exists", "key: %s, not_found", key)
|
||||
@@ -36,7 +36,7 @@ func (c *BaseCache) exists(ctx context.Context, key string) (bool, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) get(ctx context.Context, key string) (string, error) {
|
||||
value, err := c.rs.Get(key).Result()
|
||||
value, err := c.rs.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_get", "key: %s, err: %v", key, err)
|
||||
@@ -50,7 +50,7 @@ func (c *BaseCache) get(ctx context.Context, key string) (string, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) set(ctx context.Context, key string, value interface{}, expire time.Duration) (string, error) {
|
||||
result, err := c.rs.Set(key, value, expire).Result()
|
||||
result, err := c.rs.Set(ctx, key, value, expire).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_set", "key: %s, value: %v, err: %v", key, value, err)
|
||||
@@ -64,7 +64,7 @@ func (c *BaseCache) set(ctx context.Context, key string, value interface{}, expi
|
||||
}
|
||||
|
||||
func (c *BaseCache) del(ctx context.Context, key string) (int64, error) {
|
||||
affect, err := c.rs.Del(key).Result()
|
||||
affect, err := c.rs.Del(ctx, key).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_del", "key: %s, err: %v", key, err)
|
||||
@@ -78,7 +78,7 @@ func (c *BaseCache) del(ctx context.Context, key string) (int64, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) push(ctx context.Context, key string, values ...interface{}) (int64, error) {
|
||||
affect, err := c.rs.LPush(key, values...).Result()
|
||||
affect, err := c.rs.LPush(ctx, key, values...).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_lpush", "key: %s, err: %v", key, err)
|
||||
@@ -92,7 +92,7 @@ func (c *BaseCache) push(ctx context.Context, key string, values ...interface{})
|
||||
}
|
||||
|
||||
func (c *BaseCache) pop(ctx context.Context, key string) (string, error) {
|
||||
value, err := c.rs.RPop(key).Result()
|
||||
value, err := c.rs.RPop(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
if c.isLog {
|
||||
logger.Tracef(ctx, "redis_rpop", "key: %s null", key)
|
||||
@@ -112,7 +112,7 @@ func (c *BaseCache) pop(ctx context.Context, key string) (string, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) length(ctx context.Context, key string) (int64, error) {
|
||||
l, err := c.rs.LLen(key).Result()
|
||||
l, err := c.rs.LLen(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
if c.isLog {
|
||||
logger.Debugf(ctx, "redis_llen", "key: %s null", key)
|
||||
@@ -132,7 +132,7 @@ func (c *BaseCache) length(ctx context.Context, key string) (int64, error) {
|
||||
}
|
||||
|
||||
func (c *BaseCache) lock(ctx context.Context, key, value string, expire time.Duration) (bool, error) {
|
||||
result, err := c.rs.SetNX(key, value, expire).Result()
|
||||
result, err := c.rs.SetNX(ctx, key, value, expire).Result()
|
||||
if err != nil {
|
||||
if c.isLog {
|
||||
logger.Errorf(ctx, "redis_setnx", "key: %s, err: %v", key, err)
|
||||
|
||||
+44
-11
@@ -1,21 +1,54 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mysqldriver "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Mysql ConfigMysql `json:"mysql"`
|
||||
Redis ConfigRedis `json:"redis"`
|
||||
Mysql ConfigMysql `mapstructure:"mysql"`
|
||||
Redis ConfigRedis `mapstructure:"redis"`
|
||||
}
|
||||
|
||||
type ConfigMysql struct {
|
||||
DB string `json:"db"`
|
||||
Debug bool `json:"debug"`
|
||||
ShowSQL bool `json:"show_sql"`
|
||||
MaxOpenConn int `json:"max_open_conn"`
|
||||
MaxIdleConn int `json:"max_idle_conn"`
|
||||
ConnMaxLifetime int `json:"conn_max_life_time"`
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
DSN string `mapstructure:"dsn"`
|
||||
ShowSQL bool `mapstructure:"show_sql"`
|
||||
MaxOpenConn int `mapstructure:"max_open_conn"`
|
||||
MaxIdleConn int `mapstructure:"max_idle_conn"`
|
||||
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
|
||||
}
|
||||
|
||||
type ConfigRedis struct {
|
||||
Addr string `json:"addr"`
|
||||
Auth string `json:"auth"`
|
||||
DB int `json:"db"`
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
Addr string `mapstructure:"addr"`
|
||||
Password string `mapstructure:"password"`
|
||||
DB int `mapstructure:"db"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
|
||||
}
|
||||
|
||||
func (cfg Config) Validate() error {
|
||||
if cfg.Mysql.Enabled {
|
||||
mysql := cfg.Mysql
|
||||
if strings.TrimSpace(mysql.DSN) == "" {
|
||||
return errors.New("storage.mysql.dsn is required when mysql is enabled")
|
||||
}
|
||||
if _, err := mysqldriver.ParseDSN(mysql.DSN); err != nil {
|
||||
return errors.New("storage.mysql.dsn is invalid")
|
||||
}
|
||||
if mysql.MaxOpenConn <= 0 || mysql.MaxIdleConn < 0 || mysql.MaxIdleConn > mysql.MaxOpenConn {
|
||||
return errors.New("mysql connection pool requires max_open_conn > 0 and 0 <= max_idle_conn <= max_open_conn")
|
||||
}
|
||||
if mysql.ConnMaxLifetime <= 0 || mysql.ConnectTimeout <= 0 {
|
||||
return errors.New("mysql connection durations must be greater than zero")
|
||||
}
|
||||
}
|
||||
if cfg.Redis.Enabled && (strings.TrimSpace(cfg.Redis.Addr) == "" || cfg.Redis.DB < 0 || cfg.Redis.ConnectTimeout <= 0) {
|
||||
return errors.New("enabled redis requires addr, non-negative db and positive connect_timeout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package storage
|
||||
|
||||
import log "github.com/sirupsen/logrus"
|
||||
|
||||
type logWriter struct{}
|
||||
|
||||
func (logWriter) Printf(format string, args ...interface{}) {
|
||||
log.Infof(format, args...)
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package model
|
||||
|
||||
import "gorm.io/plugin/soft_delete"
|
||||
|
||||
type BaseModel struct {
|
||||
Id int64 `json:"id" xorm:"pk autoincr 'id'"`
|
||||
CreatedAt int64 `json:"created_at" xorm:"created"`
|
||||
UpdatedAt int64 `json:"updated_at" xorm:"updated"`
|
||||
DeletedAt int64 `json:"deleted_at" xorm:"deleted notnull"`
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt int64 `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"softDelete:second;not null;default:0;index"`
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package model
|
||||
|
||||
type User struct {
|
||||
BaseModel
|
||||
Name string `json:"name" gorm:"size:100;not null"`
|
||||
Status string `json:"status" gorm:"size:20;not null"`
|
||||
}
|
||||
+100
-54
@@ -1,74 +1,120 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis"
|
||||
|
||||
xormxlog "git.xiaotuo.co/pkg/go-plugins/xormx/log"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"xorm.io/xorm"
|
||||
mysqldriver "github.com/go-sql-driver/mysql"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
gormlog "gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultMaxOpenConn = 10
|
||||
DefaultMaxIdleConn = 5
|
||||
DefaultConnMaxLifetime = 1
|
||||
)
|
||||
var ErrDatabaseDisabled = errors.New("mysql is disabled")
|
||||
|
||||
type Storage struct {
|
||||
engine *xorm.Engine
|
||||
db *gorm.DB
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
func NewStorage(conf Config) (*Storage, error) {
|
||||
rs := redis.NewClient(&redis.Options{
|
||||
Addr: conf.Redis.Addr,
|
||||
Password: conf.Redis.Auth,
|
||||
DB: conf.Redis.DB,
|
||||
})
|
||||
if _, err := rs.Ping().Result(); err != nil {
|
||||
return nil, fmt.Errorf("redis.Ping: %v", err)
|
||||
st := &Storage{}
|
||||
if conf.Mysql.Enabled {
|
||||
driverConfig, err := mysqldriver.ParseDSN(conf.Mysql.DSN)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid mysql DSN")
|
||||
}
|
||||
driverConfig.ParseTime = true
|
||||
driverConfig.Timeout = conf.Mysql.ConnectTimeout
|
||||
driverConfig.ReadTimeout = conf.Mysql.ConnectTimeout
|
||||
driverConfig.WriteTimeout = conf.Mysql.ConnectTimeout
|
||||
if driverConfig.Params == nil {
|
||||
driverConfig.Params = map[string]string{}
|
||||
}
|
||||
driverConfig.Params["charset"] = "utf8mb4"
|
||||
sqlLogger := gormlog.Default.LogMode(gormlog.Silent)
|
||||
if conf.Mysql.ShowSQL {
|
||||
sqlLogger = gormlog.New(logWriter{}, gormlog.Config{
|
||||
SlowThreshold: time.Second,
|
||||
LogLevel: gormlog.Info,
|
||||
IgnoreRecordNotFoundError: true,
|
||||
ParameterizedQueries: false,
|
||||
})
|
||||
}
|
||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
||||
DSN: driverConfig.FormatDSN(),
|
||||
SkipInitializeWithVersion: true,
|
||||
}), &gorm.Config{Logger: sqlLogger, DisableAutomaticPing: true})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize mysql failed: %w", err)
|
||||
}
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get mysql connection pool: %w", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(conf.Mysql.MaxOpenConn)
|
||||
sqlDB.SetMaxIdleConns(conf.Mysql.MaxIdleConn)
|
||||
sqlDB.SetConnMaxLifetime(conf.Mysql.ConnMaxLifetime)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), conf.Mysql.ConnectTimeout)
|
||||
err = sqlDB.PingContext(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
_ = sqlDB.Close()
|
||||
return nil, fmt.Errorf("connect mysql failed: %w", err)
|
||||
}
|
||||
st.db = db
|
||||
}
|
||||
log.Infof("redis addr: %s, db: %d", conf.Redis.Addr, conf.Redis.DB)
|
||||
|
||||
if len(conf.Mysql.DB) == 0 {
|
||||
return nil, errors.New("db init failed: 数据库配置项为空")
|
||||
if conf.Redis.Enabled {
|
||||
st.redis = redis.NewClient(&redis.Options{
|
||||
Addr: conf.Redis.Addr,
|
||||
Password: conf.Redis.Password,
|
||||
DB: conf.Redis.DB,
|
||||
DialTimeout: conf.Redis.ConnectTimeout,
|
||||
ReadTimeout: conf.Redis.ConnectTimeout,
|
||||
WriteTimeout: conf.Redis.ConnectTimeout,
|
||||
ContextTimeoutEnabled: true,
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), conf.Redis.ConnectTimeout)
|
||||
err := st.redis.Ping(ctx).Err()
|
||||
cancel()
|
||||
if err != nil {
|
||||
_ = st.Close()
|
||||
return nil, errors.New("connect redis failed")
|
||||
}
|
||||
}
|
||||
if conf.Mysql.MaxIdleConn == 0 {
|
||||
conf.Mysql.MaxIdleConn = DefaultMaxIdleConn
|
||||
}
|
||||
if conf.Mysql.MaxOpenConn == 0 {
|
||||
conf.Mysql.MaxOpenConn = DefaultMaxOpenConn
|
||||
}
|
||||
if conf.Mysql.ConnMaxLifetime == 0 {
|
||||
conf.Mysql.ConnMaxLifetime = DefaultConnMaxLifetime
|
||||
}
|
||||
engine, err := xorm.NewEngine("mysql", conf.Mysql.DB)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("NewEngine: %v", err)
|
||||
}
|
||||
log.Infof("mysql addr: %s", xormxlog.SafeAddr(conf.Mysql.DB))
|
||||
|
||||
engine.SetMaxOpenConns(conf.Mysql.MaxOpenConn)
|
||||
engine.SetMaxIdleConns(conf.Mysql.MaxIdleConn)
|
||||
engine.SetConnMaxLifetime(time.Hour * time.Duration(conf.Mysql.ConnMaxLifetime))
|
||||
|
||||
if conf.Mysql.ShowSQL {
|
||||
engine.SetLogger(xormxlog.NewXormxLogger())
|
||||
engine.ShowSQL(true)
|
||||
}
|
||||
// redisLog := conf.Mysql.ShowSQL
|
||||
|
||||
return &Storage{
|
||||
engine: engine,
|
||||
}, nil
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func (s *Storage) NewSession() *xorm.Session {
|
||||
return s.engine.NewSession()
|
||||
func (st *Storage) DB() *gorm.DB {
|
||||
return st.db
|
||||
}
|
||||
|
||||
type TransactionClosure func(tx *xorm.Session) error
|
||||
func (st *Storage) Redis() *redis.Client {
|
||||
return st.redis
|
||||
}
|
||||
|
||||
func (st *Storage) Transaction(ctx context.Context, closure func(tx *gorm.DB) error) error {
|
||||
if st.db == nil {
|
||||
return ErrDatabaseDisabled
|
||||
}
|
||||
return st.db.WithContext(ctx).Transaction(closure)
|
||||
}
|
||||
|
||||
func (st *Storage) Close() error {
|
||||
var result error
|
||||
if st.redis != nil {
|
||||
result = errors.Join(result, st.redis.Close())
|
||||
}
|
||||
if st.db != nil {
|
||||
sqlDB, err := st.db.DB()
|
||||
if err != nil {
|
||||
result = errors.Join(result, err)
|
||||
} else {
|
||||
result = errors.Join(result, sqlDB.Close())
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
Reference in new issue
Block a user