aboutsummaryrefslogtreecommitdiff
path: root/backend/internal/api/handler.go
blob: 5f934da2a0ff053baa3e354575815efe8d179514 (plain)
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
package api

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"yaum/internal/monitor"
	"yaum/internal/model"
	"yaum/internal/store"
)

type ServiceResponse struct {
	model.Service
	LastHeartbeat *model.Heartbeat `json:"last_heartbeat,omitempty"`
}

type Handler struct {
	store   store.Store
	timeout int
}

func NewHandler(s store.Store, timeoutSec int) *Handler {
	return &Handler{store: s, timeout: timeoutSec}
}

func (h *Handler) ListServices(w http.ResponseWriter, r *http.Request) {
	services, err := h.store.ListServices()
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	resp := make([]ServiceResponse, len(services))
	for i, svc := range services {
		resp[i] = ServiceResponse{
			Service:       svc.Service,
			LastHeartbeat: svc.LastHeartbeat,
		}
	}
	writeJSON(w, http.StatusOK, resp)
}

func (h *Handler) CreateService(w http.ResponseWriter, r *http.Request) {
	var svc model.Service
	if err := json.NewDecoder(r.Body).Decode(&svc); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "json invalido: " + err.Error()})
		return
	}
	if svc.Name == "" || svc.URL == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name e url sao obrigatorios"})
		return
	}
	created, err := h.store.AddService(svc)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusCreated, created)
}

func (h *Handler) ToggleService(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}
	svc, err := h.store.ToggleService(id)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, svc)
}

func (h *Handler) TestService(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}

	svc, err := h.store.GetService(id)
	if err != nil || svc == nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "servico nao encontrado"})
		return
	}

	ctx, cancel := context.WithTimeout(r.Context(), time.Duration(h.timeout)*time.Second)
	defer cancel()

	hb := monitor.CheckHTTP(ctx, svc.URL, svc.KeywordToFind)
	hb.ServiceID = svc.ID

	if saverr := h.store.AddHeartbeat(hb); saverr != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": saverr.Error()})
		return
	}

	writeJSON(w, http.StatusOK, hb)
}

func (h *Handler) UpdateService(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}

	var svc model.Service
	if err := json.NewDecoder(r.Body).Decode(&svc); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "json invalido: " + err.Error()})
		return
	}

	updated, err := h.store.UpdateService(id, svc)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, updated)
}

func (h *Handler) DeleteService(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}
	if err := h.store.DeleteService(id); err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *Handler) GetHistory(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}

	page, _ := strconv.Atoi(r.URL.Query().Get("page"))
	if page < 1 {
		page = 1
	}
	perPage, _ := strconv.Atoi(r.URL.Query().Get("per_page"))
	if perPage < 1 || perPage > 100 {
		perPage = 50
	}

	offset := (page - 1) * perPage
	history, err := h.store.GetHistory(id, perPage, offset)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}

	total, err := h.store.CountHeartbeats(id)
	if err != nil {
		total = len(history)
	}

	totalPages := (total + perPage - 1) / perPage
	if totalPages < 1 {
		totalPages = 1
	}

	writeJSON(w, http.StatusOK, map[string]any{
		"data":        history,
		"page":        page,
		"per_page":    perPage,
		"total":       total,
		"total_pages": totalPages,
	})
}

func (h *Handler) GetActiveMaintenance(w http.ResponseWriter, r *http.Request) {
	m, err := h.store.GetActiveMaintenance(time.Now())
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	if m == nil {
		writeJSON(w, http.StatusOK, map[string]any{"maintenance": nil})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"maintenance": m})
}

func (h *Handler) ListMaintenances(w http.ResponseWriter, r *http.Request) {
	maintenances, err := h.store.ListMaintenances()
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, maintenances)
}

func (h *Handler) CreateMaintenance(w http.ResponseWriter, r *http.Request) {
	var m model.Maintenance
	if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "json invalido: " + err.Error()})
		return
	}
	if m.Title == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "titulo obrigatorio"})
		return
	}
	created, err := h.store.AddMaintenance(m)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusCreated, created)
}

func (h *Handler) UpdateMaintenance(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}
	var m model.Maintenance
	if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "json invalido: " + err.Error()})
		return
	}
	updated, err := h.store.UpdateMaintenance(id, m)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, updated)
}

func (h *Handler) DeleteMaintenance(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}
	if err := h.store.DeleteMaintenance(id); err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *Handler) BadgeSVG(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		w.Header().Set("Content-Type", "image/svg+xml")
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(badgeSVG("ERRO", "#888")))
		return
	}

	svc, err := h.store.GetService(id)
	if err != nil || svc == nil {
		w.Header().Set("Content-Type", "image/svg+xml")
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte(badgeSVG("N/A", "#888")))
		return
	}

	stats, _ := h.store.GetServiceStats(id)
	lastHb, _ := h.store.GetLastHeartbeat(id)

	var label, color string
	if lastHb == nil {
		label = "AGUARDANDO"
		color = "#888"
	} else if lastHb.IsUp {
		if stats != nil && stats.Uptime30d > 0 {
			label = "UP " + fmt.Sprintf("%.1f", stats.Uptime30d) + "%"
		} else {
			label = "UP"
		}
		color = "#22f06a"
	} else {
		label = "DOWN"
		color = "#ff4060"
	}

	w.Header().Set("Content-Type", "image/svg+xml")
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Write([]byte(badgeSVG(label, color)))
}

func badgeSVG(label string, color string) string {
	textWidth := len(label) * 8
	if textWidth < 40 {
		textWidth = 40
	}
	totalWidth := 20 + textWidth + 8

	return fmt.Sprintf(
		`<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="20">
  <rect width="%d" height="20" rx="3" fill="#333"/>
  <rect x="%d" width="%d" height="20" rx="3" fill="%s"/>
  <text x="%d" y="14" font-family="monospace, sans-serif" font-size="11" font-weight="bold" fill="#fff" text-anchor="middle">%s</text>
</svg>`,
		totalWidth, totalWidth, totalWidth-textWidth-8, textWidth+8, color,
		10+(textWidth/2), label,
	)
}

func (h *Handler) GetStats(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id invalido"})
		return
	}
	stats, err := h.store.GetServiceStats(id)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, stats)
}

func writeJSON(w http.ResponseWriter, status int, data any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(data)
}