This repository has been archived by the owner on Mar 24, 2024. It is now read-only.
generated from yandex-praktikum/go-musthave-devops-tpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
381 lines (315 loc) · 10.1 KB
/
handlers.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package httpbackend
import (
"encoding/json"
"errors"
"html/template"
"io"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/alkurbatov/metrics-collector/internal/entity"
"github.com/alkurbatov/metrics-collector/internal/security"
"github.com/alkurbatov/metrics-collector/internal/services"
"github.com/alkurbatov/metrics-collector/internal/storage"
"github.com/alkurbatov/metrics-collector/internal/validators"
"github.com/alkurbatov/metrics-collector/pkg/metrics"
)
type metricsResource struct {
view *template.Template
recorder services.Recorder
signer *security.Signer
}
func parseUpdateMetricReqList(r *http.Request, signer *security.Signer) ([]storage.Record, error) {
req := make([]metrics.MetricReq, 0)
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, err
}
rv := make([]storage.Record, len(req))
for i := range req {
record, err := toRecord(r.Context(), &req[i], signer)
if err != nil {
return nil, err
}
rv[i] = record
}
if len(rv) == 0 {
return nil, entity.ErrIncompleteRequest
}
return rv, nil
}
func newMetricsResource(
view *template.Template,
recorder services.Recorder,
signer *security.Signer,
) metricsResource {
return metricsResource{view: view, recorder: recorder, signer: signer}
}
// Update godoc
// @Tags Metrics
// @Router /update/{type}/{name}/{value} [post]
// @Summary Push metric data.
// @ID metrics_update
// @Produce plain
// @Param type path string true "Metrics type (e.g. `counter`, `gauge`)."
// @Param name path string true "Metrics name."
// @Param value path string true "Metrics value, must be convertable to `int64` or `float64`."
// @Success 200 {string} string
// @Failure 400 {string} string http.StatusBadRequest
// @Failure 500 {string} string http.StatusInternalServerError
// @Failure 501 {string} string "Metric type is not supported"
func (h metricsResource) Update(w http.ResponseWriter, r *http.Request) {
req := metrics.MetricReq{
ID: chi.URLParam(r, "name"),
MType: chi.URLParam(r, "kind"),
}
rawValue := chi.URLParam(r, "value")
ctx := r.Context()
switch req.MType {
case metrics.KindCounter:
delta, err := metrics.ToCounter(rawValue)
if err != nil {
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
req.Delta = &delta
case metrics.KindGauge:
value, err := metrics.ToGauge(rawValue)
if err != nil {
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
req.Value = &value
}
record, err := toRecord(ctx, &req, nil)
if err != nil {
if errors.Is(err, entity.ErrMetricNotImplemented) {
writeErrorResponse(ctx, w, http.StatusNotImplemented, err)
return
}
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
recorded, err := h.recorder.Push(r.Context(), record)
if err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
if _, err = io.WriteString(w, recorded.Value.String()); err != nil {
writeErrorResponse(r.Context(), w, http.StatusInternalServerError, err)
return
}
}
// UpdateJSON godoc
// @Tags Metrics
// @Router /update [post]
// @Summary Push metric data as JSON
// @ID metrics_json_update
// @Accept json
// @Param request body metrics.MetricReq true "Request parameters."
// @Success 200 {object} metrics.MetricReq
// @Failure 400 {string} string http.StatusBadRequest
// @Failure 500 {string} string http.StatusInternalServerError
// @Failure 501 {string} string "Metric type is not supported"
func (h metricsResource) UpdateJSON(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req := new(metrics.MetricReq)
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
record, err := toRecord(ctx, req, h.signer)
if err != nil {
if errors.Is(err, entity.ErrMetricNotImplemented) {
writeErrorResponse(ctx, w, http.StatusNotImplemented, err)
return
}
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
recorded, err := h.recorder.Push(r.Context(), record)
if err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
resp, err := toMetricReq(recorded, h.signer)
if err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
}
// BatchUpdateJSON godoc
// @Tags Metrics
// @Router /updates [post]
// @Summary Push list of metrics data as JSON
// @ID metrics_json_update_list
// @Accept json
// @Param request body []metrics.MetricReq true "List of metrics to update."
// @Success 200 {object} []metrics.MetricReq
// @Failure 400 {string} string http.StatusBadRequest
// @Failure 500 {string} string http.StatusInternalServerError
// @Failure 501 {string} string "Metric type is not supported"
func (h metricsResource) BatchUpdateJSON(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req, err := parseUpdateMetricReqList(r, h.signer)
if err != nil {
if errors.Is(err, entity.ErrMetricNotImplemented) {
writeErrorResponse(ctx, w, http.StatusNotImplemented, err)
return
}
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
records, err := h.recorder.PushList(r.Context(), req)
if err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
resp, err := toMetricReqList(records, h.signer)
if err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
}
// Get godoc
// @Tags Metrics
// @Router /value/{type}/{name} [get]
// @Summary Get metrics value as string
// @ID metrics_info
// @Produce plain
// @Param type path string true "Metrics type (e.g. `counter`, `gauge`)."
// @Param name path string true "Metrics name."
// @Success 200 {string} string
// @Failure 400 {string} string http.StatusBadRequest
// @Failure 404 {string} string "Metric not found"
// @Failure 500 {string} string http.StatusInternalServerError
// @Failure 501 {string} string "Metric type is not supported"
func (h metricsResource) Get(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
kind := chi.URLParam(r, "kind")
name := chi.URLParam(r, "name")
if err := validators.ValidateMetricName(name, kind); err != nil {
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
if err := validators.ValidateMetricKind(kind); err != nil {
writeErrorResponse(ctx, w, http.StatusNotImplemented, err)
return
}
record, err := h.recorder.Get(r.Context(), kind, name)
if err != nil {
if errors.Is(err, entity.ErrMetricNotFound) {
writeErrorResponse(ctx, w, http.StatusNotFound, err)
return
}
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
if _, err := io.WriteString(w, record.Value.String()); err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
}
// GetJSON godoc
// @Tags Metrics
// @Router /value [post]
// @Summary Get metrics value as JSON
// @ID metrics_json_info
// @Accept json
// @Produce json
// @Param request body metrics.MetricReq true "Request parameters: `id` and `type` are required."
// @Success 200 {object} metrics.MetricReq
// @Failure 400 {string} string http.StatusBadRequest
// @Failure 404 {string} string "Metric not found"
// @Failure 500 {string} string http.StatusInternalServerError
// @Failure 501 {string} string "Metric type is not supported"
func (h metricsResource) GetJSON(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req := new(metrics.MetricReq)
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
if err := validators.ValidateMetricName(req.ID, req.MType); err != nil {
writeErrorResponse(ctx, w, http.StatusBadRequest, err)
return
}
if err := validators.ValidateMetricKind(req.MType); err != nil {
writeErrorResponse(ctx, w, http.StatusNotImplemented, err)
return
}
record, err := h.recorder.Get(r.Context(), req.MType, req.ID)
if err != nil {
if errors.Is(err, entity.ErrMetricNotFound) {
writeErrorResponse(ctx, w, http.StatusNotFound, err)
return
}
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
resp, err := toMetricReq(record, h.signer)
if err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
}
// List godoc
// @Tags Metrics
// @Router / [get]
// @Summary Get HTML page with full list of stored metrics
// @ID metrics_list
// @Produce html
// @Success 200
// @Failure 500 {string} string http.StatusInternalServerError
func (h metricsResource) List(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
records, err := h.recorder.List(r.Context())
if err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
if err := h.view.Execute(w, records); err != nil {
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
return
}
}
type livenessProbe struct {
healthcheck services.HealthCheck
}
func newLivenessProbe(healthcheck services.HealthCheck) livenessProbe {
return livenessProbe{healthcheck: healthcheck}
}
// Ping godoc
// @Tags Healthcheck
// @Router /ping [get]
// @Summary Verify connection to the database
// @ID health_info
// @Success 200
// @Failure 500 {string} string "Connection is broken"
// @Failure 501 {string} string "Server is not configured to use database"
func (h livenessProbe) Ping(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
err := h.healthcheck.CheckStorage(ctx)
if err == nil {
return
}
if errors.Is(err, entity.ErrHealthCheckNotSupported) {
writeErrorResponse(ctx, w, http.StatusNotImplemented, err)
return
}
writeErrorResponse(ctx, w, http.StatusInternalServerError, err)
}