-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
187 lines (151 loc) · 4.62 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package config
import (
"context"
"errors"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/redis/go-redis/v9"
"github.com/wearemojo/mojo-public-go/lib/db/mongodb"
"github.com/wearemojo/mojo-public-go/lib/merr"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)
// Redis configures a connection to a Redis database.
type Redis struct {
URI string `json:"uri"`
DialTimeout time.Duration `json:"dial_timeout"`
ReadTimeout time.Duration `json:"read_timeout"`
WriteTimeout time.Duration `json:"write_timeout"`
}
// Options returns a configured redis.Options structure.
func (r Redis) Options() (*redis.Options, error) {
opts, err := redis.ParseURL(r.URI)
if err != nil {
return nil, err
}
opts.DialTimeout = r.DialTimeout
opts.ReadTimeout = r.ReadTimeout
opts.WriteTimeout = r.WriteTimeout
return opts, nil
}
// Connect returns a connected redis.Client instance.
func (r Redis) Connect(ctx context.Context) (*redis.Client, error) {
opts, err := r.Options()
if err != nil {
return nil, err
}
client := redis.NewClient(opts)
if err := client.Ping(ctx).Err(); err != nil {
return client, err
}
return client, nil
}
// MongoDB configures a connection to a Mongo database.
type MongoDB struct {
URI string `json:"uri"`
ConnectTimeout time.Duration `json:"connect_timeout"`
MaxConnIdleTime *time.Duration `json:"max_conn_idle_time"`
MaxConnecting *uint64 `json:"max_connecting"`
MaxPoolSize *uint64 `json:"max_pool_size"`
MinPoolSize *uint64 `json:"min_pool_size"`
}
// Options returns the MongoDB client options and database name.
func (m MongoDB) Options(ctx context.Context) (opts *options.ClientOptions, dbName string, err error) {
opts = options.Client().ApplyURI(m.URI)
opts.MaxConnIdleTime = m.MaxConnIdleTime
opts.MaxConnecting = m.MaxConnecting
opts.MaxPoolSize = m.MaxPoolSize
opts.MinPoolSize = m.MinPoolSize
err = opts.Validate()
if err != nil {
return
}
// all Go services use majority reads/writes, and this is unlikely to change
// if it does change, switch to accepting as an argument
opts.SetReadConcern(readconcern.Majority())
opts.SetWriteConcern(writeconcern.Majority())
cs, err := connstring.Parse(m.URI)
if err != nil {
return
}
dbName = cs.Database
if dbName == "" {
err = merr.New(ctx, "mongo_db_name_missing", nil)
}
return
}
// Connect returns a connected mongo.Database instance.
func (m MongoDB) Connect(ctx context.Context) (*mongodb.Database, error) {
opts, dbName, err := m.Options(ctx)
if err != nil {
return nil, err
}
if m.ConnectTimeout == 0 {
m.ConnectTimeout = 10 * time.Second
}
// this package can only be used for service config
// so can only happen at init-time - no need to accept context input
ctx, cancel := context.WithTimeout(ctx, m.ConnectTimeout)
defer cancel()
return mongodb.Connect(ctx, opts, dbName)
}
// DefaultGraceful is the graceful shutdown timeout applied when no
// configuration value is given.
const DefaultGraceful = 5
// Server configures the binding and security of an HTTP server.
type Server struct {
Addr string `json:"addr"`
// Graceful enables graceful shutdown and is the time in seconds to wait
// for all outstanding requests to terminate before forceably killing the
// server. When no value is given, DefaultGraceful is used. Graceful
// shutdown is disabled when less than zero.
Graceful int `json:"graceful"`
}
// ListenAndServe configures a HTTP server and begins listening for clients.
func (cfg *Server) ListenAndServe(srv *http.Server) error {
// only set listen address if none is already configured
if srv.Addr == "" {
srv.Addr = cfg.Addr
}
if cfg.Graceful == 0 {
cfg.Graceful = DefaultGraceful
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
errs := make(chan error, 1)
go func() {
err := srv.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
errs <- err
}
}()
select {
case err := <-errs:
return err
case <-stop:
if cfg.Graceful > 0 {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(cfg.Graceful)*time.Second)
defer cancel()
return srv.Shutdown(ctx)
}
return nil
}
}
func ContextWithCancelOnSignal(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
go func() {
defer cancel()
select {
case <-stop:
case <-ctx.Done():
}
}()
return ctx
}