apollo-backend/internal/cmdutil/cmdutil.go

87 lines
1.9 KiB
Go
Raw Normal View History

package cmdutil
import (
"context"
"fmt"
"os"
2022-07-13 15:09:06 +00:00
"time"
"github.com/DataDog/datadog-go/statsd"
2022-11-01 23:02:25 +00:00
"github.com/adjust/rmq/v5"
"github.com/go-redis/redis/v8"
"github.com/jackc/pgx/v4/pgxpool"
2022-05-23 18:17:25 +00:00
"go.uber.org/zap"
)
2022-05-23 18:29:15 +00:00
func NewLogger(service string) *zap.Logger {
env := os.Getenv("ENV")
logger, _ := zap.NewProduction(zap.Fields(
zap.String("env", env),
zap.String("service", service),
))
if env == "" || env == "development" {
2022-05-23 18:17:25 +00:00
logger, _ = zap.NewDevelopment()
}
return logger
}
func NewStatsdClient(tags ...string) (*statsd.Client, error) {
if env := os.Getenv("ENV"); env != "" {
tags = append(tags, fmt.Sprintf("env:%s", env))
}
2021-07-23 00:22:46 +00:00
return statsd.New(os.Getenv("STATSD_URL"), statsd.WithTags(tags))
}
2022-07-13 19:02:38 +00:00
func NewRedisClient(ctx context.Context, maxConns int) (*redis.Client, error) {
2021-07-23 00:22:46 +00:00
opt, err := redis.ParseURL(os.Getenv("REDIS_URL"))
if err != nil {
return nil, err
}
2022-07-13 19:02:38 +00:00
opt.PoolSize = maxConns
client := redis.NewClient(opt)
if err := client.Ping(ctx).Err(); err != nil {
return nil, err
}
return client, nil
}
2021-07-23 00:50:24 +00:00
func NewDatabasePool(ctx context.Context, maxConns int) (*pgxpool.Pool, error) {
2021-10-09 14:59:20 +00:00
if maxConns == 0 {
maxConns = 1
}
2021-07-15 17:47:22 +00:00
url := fmt.Sprintf(
2021-07-23 00:38:13 +00:00
"%s?pool_max_conns=%d&pool_min_conns=%d",
2021-07-15 17:47:22 +00:00
os.Getenv("DATABASE_CONNECTION_POOL_URL"),
2021-07-23 00:50:24 +00:00
maxConns,
2,
2021-07-15 17:47:22 +00:00
)
config, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, err
}
// Setting the build statement cache to nil helps this work with pgbouncer
config.ConnConfig.BuildStatementCache = nil
config.ConnConfig.PreferSimpleProtocol = true
2022-07-13 15:09:06 +00:00
config.MaxConnLifetime = 1 * time.Hour
config.MaxConnIdleTime = 30 * time.Second
return pgxpool.ConnectConfig(ctx, config)
}
2022-05-23 18:17:25 +00:00
func NewQueueClient(logger *zap.Logger, conn *redis.Client, identifier string) (rmq.Connection, error) {
errChan := make(chan error, 10)
go func() {
for err := range errChan {
2022-05-23 18:17:25 +00:00
logger.Error("error occurred within queue", zap.Error(err))
}
}()
return rmq.OpenConnectionWithRedisClient(identifier, conn, errChan)
}