-
Notifications
You must be signed in to change notification settings - Fork 11
/
hydrophone.go
302 lines (272 loc) · 8.64 KB
/
hydrophone.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package main
import (
"context"
"crypto/tls"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/kelseyhightower/envconfig"
"go.uber.org/fx"
"go.uber.org/zap"
clinicsClient "github.com/tidepool-org/clinic/client"
"github.com/tidepool-org/go-common/clients"
"github.com/tidepool-org/go-common/clients/disc"
"github.com/tidepool-org/go-common/clients/highwater"
"github.com/tidepool-org/go-common/clients/shoreline"
ev "github.com/tidepool-org/go-common/events"
"github.com/tidepool-org/hydrophone/api"
sc "github.com/tidepool-org/hydrophone/clients"
"github.com/tidepool-org/hydrophone/events"
"github.com/tidepool-org/hydrophone/models"
"github.com/tidepool-org/hydrophone/templates"
"github.com/tidepool-org/platform/alerts"
"github.com/tidepool-org/platform/auth"
authclient "github.com/tidepool-org/platform/auth/client"
"github.com/tidepool-org/platform/client"
platformlog "github.com/tidepool-org/platform/log"
"github.com/tidepool-org/platform/platform"
)
var defaultStopTimeout = 60 * time.Second
type (
// OutboundConfig contains how to communicate with the dependent services
OutboundConfig struct {
Protocol string `default:"https"`
ServerSecret string `split_words:"true" required:"true"`
AuthClientAddress string `split_words:"true" required:"true"`
PermissionClientAddress string `split_words:"true" required:"true"`
MetricsClientAddress string `split_words:"true" required:"true"`
SeagullClientAddress string `split_words:"true" required:"true"`
ClinicClientAddress string `split_words:"true" required:"true"`
DataClientAddress string `split_words:"true" required:"true"`
}
//InboundConfig describes how to receive inbound communication
InboundConfig struct {
Protocol string `default:"http"`
SslKeyFile string `split_words:"true" default:""`
SslCertFile string `split_words:"true" default:""`
ListenAddress string `split_words:"true" required:"true"`
}
)
func shorelineProvider(config OutboundConfig, httpClient *http.Client) shoreline.Client {
return shoreline.NewShorelineClientBuilder().
WithHostGetter(disc.NewStaticHostGetterFromString(config.AuthClientAddress)).
WithHttpClient(httpClient).
WithName("hydrophone").
WithSecret(config.ServerSecret).
WithTokenRefreshInterval(time.Hour).
Build()
}
func gatekeeperProvider(config OutboundConfig, shoreline shoreline.Client, httpClient *http.Client) clients.Gatekeeper {
return clients.NewGatekeeperClientBuilder().
WithHostGetter(disc.NewStaticHostGetterFromString(config.PermissionClientAddress)).
WithHttpClient(httpClient).
WithTokenProvider(shoreline).
Build()
}
func highwaterProvider(config OutboundConfig, httpClient *http.Client) highwater.Client {
return highwater.NewHighwaterClientBuilder().
WithHostGetter(disc.NewStaticHostGetterFromString(config.MetricsClientAddress)).
WithHttpClient(httpClient).
WithName("highwater").
WithSource("hydrophone").
WithVersion("v0.0.1").
Build()
}
func seagullProvider(config OutboundConfig, httpClient *http.Client) clients.Seagull {
return clients.NewSeagullClientBuilder().
WithHostGetter(disc.NewStaticHostGetterFromString(config.SeagullClientAddress)).
WithHttpClient(httpClient).
Build()
}
func alertsProvider(config OutboundConfig, tokenProvider auth.ExternalAccessor, logger platformlog.Logger) (api.AlertsClient, error) {
cfg := client.NewConfig()
cfg.Address = config.DataClientAddress
platformCfg := platform.NewConfig()
platformCfg.Config = cfg
platformClient, err := platform.NewClient(platformCfg, platform.AuthorizeAsService)
if err != nil {
return nil, err
}
return alerts.NewClient(platformClient, tokenProvider, logger), nil
}
func zapPlatformAdapterProvider(zapper *zap.SugaredLogger) platformlog.Logger {
return NewZapPlatformAdapter(zapper)
}
func externalConfigLoaderProvider(loader platform.ConfigLoader) authclient.ExternalConfigLoader {
return authclient.NewExternalEnvconfigLoader(loader)
}
func platformConfigLoaderProvider(loader client.ConfigLoader) platform.ConfigLoader {
return platform.NewEnvconfigLoader(loader)
}
func clientConfigLoaderProvider() client.ConfigLoader {
return client.NewEnvconfigLoader()
}
func clinicProvider(config OutboundConfig, shoreline shoreline.Client) (clinicsClient.ClientWithResponsesInterface, error) {
opts := clinicsClient.WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
req.Header.Add(api.TP_SESSION_TOKEN, shoreline.TokenProvide())
return nil
})
return clinicsClient.NewClientWithResponses(config.ClinicClientAddress, opts)
}
func configProvider() (OutboundConfig, error) {
var config OutboundConfig
err := envconfig.Process("tidepool", &config)
if err != nil {
return OutboundConfig{}, err
}
return config, nil
}
func serviceConfigProvider() (InboundConfig, error) {
var config InboundConfig
err := envconfig.Process("service", &config)
if err != nil {
return InboundConfig{}, err
}
return config, nil
}
func httpClientProvider() *http.Client {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
return &http.Client{Transport: tr}
}
func emailTemplateProvider() (models.Templates, error) {
emailTemplates, err := templates.New()
return emailTemplates, err
}
func serverProvider(config InboundConfig, rtr *mux.Router) *http.Server {
return &http.Server{
Addr: config.ListenAddress,
Handler: rtr,
}
}
func cloudEventsConfigProvider() (*ev.CloudEventsConfig, error) {
cfg := ev.NewConfig()
if err := cfg.LoadFromEnv(); err != nil {
return nil, err
}
return cfg, nil
}
func faultTolerantConsumerProvider(config *ev.CloudEventsConfig, handler ev.EventHandler) (ev.EventConsumer, error) {
return ev.NewFaultTolerantConsumerGroup(config, func() (ev.MessageConsumer, error) {
handlers := []ev.EventHandler{handler}
return ev.NewCloudEventsMessageHandler(handlers)
})
}
func loggerProvider() (*zap.SugaredLogger, error) {
config := zap.NewProductionConfig()
config.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
config.EncoderConfig.FunctionKey = "function"
logger, err := config.Build()
if err != nil {
return nil, err
}
return logger.Sugar(), nil
}
// InvocationParams are the parameters need to kick off a service
type InvocationParams struct {
fx.In
Lifecycle fx.Lifecycle
Shutdowner fx.Shutdowner
Shoreline shoreline.Client
Config InboundConfig
Server *http.Server
Consumer ev.EventConsumer
Log *zap.SugaredLogger
}
func startEventConsumer(p InvocationParams) {
p.Lifecycle.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
go func() {
if err := p.Consumer.Start(); err != nil {
p.Log.With(zap.Error(err)).Error("starting cloud events consumer")
p.Log.Infof("shutting down the service")
if shutdownErr := p.Shutdowner.Shutdown(); shutdownErr != nil {
p.Log.With(zap.Error(shutdownErr)).Error("failed to shutdown")
}
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
return p.Consumer.Stop()
},
})
}
func startShoreline(p InvocationParams) {
p.Lifecycle.Append(
fx.Hook{
OnStart: func(ctx context.Context) error {
if err := p.Shoreline.Start(); err != nil {
p.Log.With(zap.Error(err)).Error("starting shoreline")
return err
}
return nil
},
OnStop: func(ctx context.Context) error {
p.Shoreline.Close()
return nil
},
},
)
}
func startServer(p InvocationParams) {
p.Lifecycle.Append(
fx.Hook{
OnStart: func(ctx context.Context) error {
go func() {
if err := p.Server.ListenAndServe(); err != nil {
p.Log.With(zap.Error(err)).Error("while listening")
p.Log.Infof("shutting down")
if shutdownErr := p.Shutdowner.Shutdown(); shutdownErr != nil {
p.Log.With(zap.Error(err)).Error("shutting down")
}
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
return p.Server.Shutdown(ctx)
},
},
)
}
func main() {
fx.New(
sc.SesModule,
sc.MongoModule,
api.RouterModule,
fx.Provide(
cloudEventsConfigProvider,
faultTolerantConsumerProvider,
events.NewHandler,
),
authclient.ExternalClientModule,
authclient.ProvideServiceName("hydrophone"),
fx.Provide(
externalConfigLoaderProvider,
platformConfigLoaderProvider,
clientConfigLoaderProvider,
zapPlatformAdapterProvider,
),
fx.Provide(
seagullProvider,
highwaterProvider,
gatekeeperProvider,
shorelineProvider,
configProvider,
serviceConfigProvider,
httpClientProvider,
emailTemplateProvider,
serverProvider,
clinicProvider,
loggerProvider,
alertsProvider,
api.NewApi,
),
fx.Invoke(startShoreline),
fx.Invoke(startEventConsumer),
fx.Invoke(startServer),
fx.StopTimeout(defaultStopTimeout),
).Run()
}