aboutsummaryrefslogtreecommitdiff
path: root/backend/internal/store/postgres.go
blob: fb07bdcdaef2530febe43ddb137207af8912c800 (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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package store

import (
	"context"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"

	"yaum/internal/model"
)

type PostgresStore struct {
	pool *pgxpool.Pool
}

func NewPostgresStore(ctx context.Context, connString string) (*PostgresStore, error) {
	pool, err := pgxpool.New(ctx, connString)
	if err != nil {
		return nil, fmt.Errorf("erro ao conectar no postgres: %w", err)
	}
	if err := pool.Ping(ctx); err != nil {
		return nil, fmt.Errorf("erro ao pingar postgres: %w", err)
	}
	return &PostgresStore{pool: pool}, nil
}

func (s *PostgresStore) Close() {
	s.pool.Close()
}

// ---------------------------------------------------------------------------
// Services
// ---------------------------------------------------------------------------

func (s *PostgresStore) ListServices() ([]model.ServiceWithHeartbeat, error) {
	query := `
		SELECT
			s.id, s.name, s.url, s.group_name, s.interval_seconds, s.is_active, s.created_at,
			h.id     AS heartbeat_id,
			h.status_code,
			h.response_time_ms,
			h.is_up,
			h.error_message,
			h.tested_at
		FROM services s
		LEFT JOIN LATERAL (
			SELECT id, status_code, response_time_ms, is_up, error_message, tested_at
			FROM heartbeats
			WHERE service_id = s.id
			ORDER BY tested_at DESC
			LIMIT 1
		) h ON true
		ORDER BY s.id
	`

	rows, err := s.pool.Query(context.Background(), query)
	if err != nil {
		return nil, fmt.Errorf("list services: %w", err)
	}
	defer rows.Close()

	return pgx.CollectRows(rows, func(row pgx.CollectableRow) (model.ServiceWithHeartbeat, error) {
		var (
			swh            model.ServiceWithHeartbeat
			heartbeatID    *int
			statusCode     *int
			responseTimeMs *int64
			isUp           *bool
			errorMessage   *string
			testedAt       *time.Time
		)
		err := row.Scan(
			&swh.ID, &swh.Name, &swh.URL, &swh.GroupName, &swh.IntervalSeconds, &swh.IsActive, &swh.CreatedAt,
			&heartbeatID, &statusCode, &responseTimeMs, &isUp, &errorMessage, &testedAt,
		)
		if err != nil {
			return swh, err
		}
		if heartbeatID != nil {
			swh.LastHeartbeat = &model.Heartbeat{
				ID:             *heartbeatID,
				ServiceID:      swh.ID,
				StatusCode:     *statusCode,
				ResponseTimeMs: *responseTimeMs,
				IsUp:           *isUp,
				ErrorMessage:   *errorMessage,
				TestedAt:       *testedAt,
			}
		}
		return swh, nil
	})
}

func (s *PostgresStore) ListActiveServices() ([]model.Service, error) {
	query := `
		SELECT id, name, url, group_name, interval_seconds, is_active, discord_webhook_url, alert_email, keyword_to_find, created_at
		FROM services
		WHERE is_active = true
		ORDER BY id
	`

	rows, err := s.pool.Query(context.Background(), query)
	if err != nil {
		return nil, fmt.Errorf("list active services: %w", err)
	}
	defer rows.Close()

	return pgx.CollectRows(rows, func(row pgx.CollectableRow) (model.Service, error) {
		var svc model.Service
		err := row.Scan(&svc.ID, &svc.Name, &svc.URL, &svc.GroupName, &svc.IntervalSeconds, &svc.IsActive, &svc.DiscordWebhookURL, &svc.AlertEmail, &svc.KeywordToFind, &svc.CreatedAt)
		return svc, err
	})
}

func (s *PostgresStore) GetService(id int) (*model.Service, error) {
	query := `
		SELECT id, name, url, group_name, interval_seconds, is_active, discord_webhook_url, alert_email, keyword_to_find, created_at
		FROM services
		WHERE id = $1
	`
	var svc model.Service
	err := s.pool.QueryRow(context.Background(), query, id).
		Scan(&svc.ID, &svc.Name, &svc.URL, &svc.GroupName, &svc.IntervalSeconds, &svc.IsActive, &svc.DiscordWebhookURL, &svc.AlertEmail, &svc.KeywordToFind, &svc.CreatedAt)
	if err != nil {
		if err == pgx.ErrNoRows {
			return nil, nil
		}
		return nil, fmt.Errorf("get service: %w", err)
	}
	return &svc, nil
}

func (s *PostgresStore) AddService(svc model.Service) (*model.Service, error) {
	query := `
		INSERT INTO services (name, url, group_name, interval_seconds, discord_webhook_url, alert_email, keyword_to_find)
		VALUES ($1, $2, $3, $4, $5, $6, $7)
		RETURNING id, is_active, created_at
	`
	err := s.pool.QueryRow(context.Background(), query, svc.Name, svc.URL, svc.GroupName, svc.IntervalSeconds, svc.DiscordWebhookURL, svc.AlertEmail, svc.KeywordToFind).
		Scan(&svc.ID, &svc.IsActive, &svc.CreatedAt)
	if err != nil {
		return nil, fmt.Errorf("add service: %w", err)
	}
	return &svc, nil
}

func (s *PostgresStore) ToggleService(id int) (*model.Service, error) {
	query := `
		UPDATE services
		SET is_active = NOT is_active
		WHERE id = $1
		RETURNING id, name, url, group_name, interval_seconds, is_active, discord_webhook_url, alert_email, keyword_to_find, created_at
	`
	var svc model.Service
	err := s.pool.QueryRow(context.Background(), query, id).
		Scan(&svc.ID, &svc.Name, &svc.URL, &svc.GroupName, &svc.IntervalSeconds, &svc.IsActive, &svc.DiscordWebhookURL, &svc.AlertEmail, &svc.KeywordToFind, &svc.CreatedAt)
	if err != nil {
		if err == pgx.ErrNoRows {
			return nil, fmt.Errorf("servico nao encontrado")
		}
		return nil, fmt.Errorf("toggle service: %w", err)
	}
	return &svc, nil
}

func (s *PostgresStore) UpdateService(id int, svc model.Service) (*model.Service, error) {
	query := `
		UPDATE services
		SET name = $1, url = $2, group_name = $3, interval_seconds = $4, discord_webhook_url = $5, alert_email = $6, keyword_to_find = $7
		WHERE id = $8
		RETURNING id, name, url, group_name, interval_seconds, is_active, discord_webhook_url, alert_email, keyword_to_find, created_at
	`
	var updated model.Service
	err := s.pool.QueryRow(context.Background(), query,
		svc.Name, svc.URL, svc.GroupName, svc.IntervalSeconds, svc.DiscordWebhookURL, svc.AlertEmail, svc.KeywordToFind, id,
	).Scan(&updated.ID, &updated.Name, &updated.URL, &updated.GroupName, &updated.IntervalSeconds, &updated.IsActive, &updated.DiscordWebhookURL, &updated.AlertEmail, &updated.KeywordToFind, &updated.CreatedAt)
	if err != nil {
		if err == pgx.ErrNoRows {
			return nil, fmt.Errorf("servico nao encontrado")
		}
		return nil, fmt.Errorf("update service: %w", err)
	}
	return &updated, nil
}

func (s *PostgresStore) DeleteService(id int) error {
	tag, err := s.pool.Exec(context.Background(), "DELETE FROM services WHERE id = $1", id)
	if err != nil {
		return fmt.Errorf("delete service: %w", err)
	}
	if tag.RowsAffected() == 0 {
		return fmt.Errorf("servico nao encontrado")
	}
	return nil
}

// ---------------------------------------------------------------------------
// Heartbeats
// ---------------------------------------------------------------------------

func (s *PostgresStore) AddHeartbeat(hb model.Heartbeat) error {
	query := `
		INSERT INTO heartbeats (service_id, status_code, response_time_ms, is_up, error_message, tested_at)
		VALUES ($1, $2, $3, $4, $5, $6)
	`
	_, err := s.pool.Exec(context.Background(), query,
		hb.ServiceID, hb.StatusCode, hb.ResponseTimeMs, hb.IsUp, hb.ErrorMessage, hb.TestedAt)
	if err != nil {
		return fmt.Errorf("add heartbeat: %w", err)
	}
	return nil
}

func (s *PostgresStore) GetHistory(serviceID int, limit int, offset int) ([]model.Heartbeat, error) {
	query := `
		SELECT id, service_id, status_code, response_time_ms, is_up, error_message, tested_at
		FROM heartbeats
		WHERE service_id = $1
		ORDER BY tested_at DESC
		LIMIT $2
		OFFSET $3
	`
	rows, err := s.pool.Query(context.Background(), query, serviceID, limit, offset)
	if err != nil {
		return nil, fmt.Errorf("get history: %w", err)
	}
	defer rows.Close()

	return pgx.CollectRows(rows, func(row pgx.CollectableRow) (model.Heartbeat, error) {
		var hb model.Heartbeat
		err := row.Scan(&hb.ID, &hb.ServiceID, &hb.StatusCode, &hb.ResponseTimeMs, &hb.IsUp, &hb.ErrorMessage, &hb.TestedAt)
		return hb, err
	})
}

func (s *PostgresStore) CountHeartbeats(serviceID int) (int, error) {
	var count int
	err := s.pool.QueryRow(context.Background(),
		`SELECT COUNT(*) FROM heartbeats WHERE service_id = $1`,
		serviceID,
	).Scan(&count)
	if err != nil {
		return 0, fmt.Errorf("count heartbeats: %w", err)
	}
	return count, nil
}

func (s *PostgresStore) GetLastHeartbeat(serviceID int) (*model.Heartbeat, error) {
	query := `
		SELECT id, service_id, status_code, response_time_ms, is_up, error_message, tested_at
		FROM heartbeats
		WHERE service_id = $1
		ORDER BY tested_at DESC
		LIMIT 1
	`
	hb := &model.Heartbeat{}
	err := s.pool.QueryRow(context.Background(), query, serviceID).
		Scan(&hb.ID, &hb.ServiceID, &hb.StatusCode, &hb.ResponseTimeMs, &hb.IsUp, &hb.ErrorMessage, &hb.TestedAt)
	if err != nil {
		if err == pgx.ErrNoRows {
			return nil, nil
		}
		return nil, fmt.Errorf("get last heartbeat: %w", err)
	}
	return hb, nil
}

func (s *PostgresStore) GetServiceStats(serviceID int) (*model.ServiceStats, error) {
	query := `
		SELECT
			COALESCE(SUM(CASE WHEN tested_at >= NOW() - INTERVAL '24 hours' THEN 1 ELSE 0 END), 0),
			COALESCE(SUM(CASE WHEN tested_at >= NOW() - INTERVAL '24 hours' AND is_up THEN 1 ELSE 0 END), 0),
			COALESCE(AVG(response_time_ms) FILTER (WHERE tested_at >= NOW() - INTERVAL '24 hours'), 0),
			COALESCE(SUM(CASE WHEN tested_at >= NOW() - INTERVAL '7 days' THEN 1 ELSE 0 END), 0),
			COALESCE(SUM(CASE WHEN tested_at >= NOW() - INTERVAL '7 days' AND is_up THEN 1 ELSE 0 END), 0),
			COALESCE(AVG(response_time_ms) FILTER (WHERE tested_at >= NOW() - INTERVAL '7 days'), 0),
			COALESCE(SUM(CASE WHEN tested_at >= NOW() - INTERVAL '30 days' THEN 1 ELSE 0 END), 0),
			COALESCE(SUM(CASE WHEN tested_at >= NOW() - INTERVAL '30 days' AND is_up THEN 1 ELSE 0 END), 0),
			COALESCE(AVG(response_time_ms) FILTER (WHERE tested_at >= NOW() - INTERVAL '30 days'), 0)
		FROM heartbeats
		WHERE service_id = $1
	`
	var (
		t24, u24 int32
		a24      float64
		t7, u7   int32
		a7       float64
		t30, u30 int32
		a30      float64
	)
	err := s.pool.QueryRow(context.Background(), query, serviceID).
		Scan(&t24, &u24, &a24, &t7, &u7, &a7, &t30, &u30, &a30)
	if err != nil {
		return nil, fmt.Errorf("get service stats: %w", err)
	}

	pct := func(up, total int32) float64 {
		if total == 0 {
			return 0
		}
		return float64(up) / float64(total) * 100
	}

	return &model.ServiceStats{
		ServiceID:       serviceID,
		Uptime24h:       pct(u24, t24),
		Uptime7d:        pct(u7, t7),
		Uptime30d:       pct(u30, t30),
		AvgResponseMs24h: a24,
		AvgResponseMs7d:  a7,
		AvgResponseMs30d: a30,
		TotalChecks24h:  int(t24),
		TotalChecks7d:   int(t7),
		TotalChecks30d:  int(t30),
	}, nil
}

func (s *PostgresStore) GetActiveMaintenance(now time.Time) (*model.Maintenance, error) {
	query := `
		SELECT id, title, start_time, end_time, is_active
		FROM maintenances
		WHERE is_active = true AND start_time <= $1 AND end_time > $1
		LIMIT 1
	`
	var m model.Maintenance
	err := s.pool.QueryRow(context.Background(), query, now).
		Scan(&m.ID, &m.Title, &m.StartTime, &m.EndTime, &m.IsActive)
	if err != nil {
		if err == pgx.ErrNoRows {
			return nil, nil
		}
		return nil, fmt.Errorf("get active maintenance: %w", err)
	}
	return &m, nil
}

func (s *PostgresStore) ListMaintenances() ([]model.Maintenance, error) {
	query := `SELECT id, title, start_time, end_time, is_active FROM maintenances ORDER BY start_time DESC`
	rows, err := s.pool.Query(context.Background(), query)
	if err != nil {
		return nil, fmt.Errorf("list maintenances: %w", err)
	}
	defer rows.Close()
	return pgx.CollectRows(rows, func(row pgx.CollectableRow) (model.Maintenance, error) {
		var m model.Maintenance
		err := row.Scan(&m.ID, &m.Title, &m.StartTime, &m.EndTime, &m.IsActive)
		return m, err
	})
}

func (s *PostgresStore) AddMaintenance(m model.Maintenance) (*model.Maintenance, error) {
	query := `
		INSERT INTO maintenances (title, start_time, end_time, is_active)
		VALUES ($1, $2, $3, $4)
		RETURNING id
	`
	err := s.pool.QueryRow(context.Background(), query, m.Title, m.StartTime, m.EndTime, m.IsActive).
		Scan(&m.ID)
	if err != nil {
		return nil, fmt.Errorf("add maintenance: %w", err)
	}
	return &m, nil
}

func (s *PostgresStore) UpdateMaintenance(id int, m model.Maintenance) (*model.Maintenance, error) {
	query := `
		UPDATE maintenances
		SET title = $1, start_time = $2, end_time = $3, is_active = $4
		WHERE id = $5
		RETURNING id, title, start_time, end_time, is_active
	`
	var updated model.Maintenance
	err := s.pool.QueryRow(context.Background(), query, m.Title, m.StartTime, m.EndTime, m.IsActive, id).
		Scan(&updated.ID, &updated.Title, &updated.StartTime, &updated.EndTime, &updated.IsActive)
	if err != nil {
		if err == pgx.ErrNoRows {
			return nil, fmt.Errorf("manutencao nao encontrada")
		}
		return nil, fmt.Errorf("update maintenance: %w", err)
	}
	return &updated, nil
}

func (s *PostgresStore) DeleteMaintenance(id int) error {
	tag, err := s.pool.Exec(context.Background(), "DELETE FROM maintenances WHERE id = $1", id)
	if err != nil {
		return fmt.Errorf("delete maintenance: %w", err)
	}
	if tag.RowsAffected() == 0 {
		return fmt.Errorf("manutencao nao encontrada")
	}
	return nil
}

func (s *PostgresStore) GetSSLInfo(serviceID int) (*model.SSLInfo, error) {
	var info model.SSLInfo
	err := s.pool.QueryRow(context.Background(),
		`SELECT service_id, issuer, expires_at, days_remaining, checked_at FROM ssl_info WHERE service_id = $1`,
		serviceID,
	).Scan(&info.ServiceID, &info.Issuer, &info.ExpiresAt, &info.DaysRemaining, &info.CheckedAt)
	if err != nil {
		if err == pgx.ErrNoRows {
			return nil, nil
		}
		return nil, fmt.Errorf("get ssl info: %w", err)
	}
	return &info, nil
}

func (s *PostgresStore) SaveSSLInfo(info model.SSLInfo) error {
	_, err := s.pool.Exec(context.Background(),
		`INSERT INTO ssl_info (service_id, issuer, expires_at, days_remaining, checked_at)
		 VALUES ($1, $2, $3, $4, $5)
		 ON CONFLICT (service_id) DO UPDATE SET issuer=$2, expires_at=$3, days_remaining=$4, checked_at=$5`,
		info.ServiceID, info.Issuer, info.ExpiresAt, info.DaysRemaining, info.CheckedAt,
	)
	if err != nil {
		return fmt.Errorf("save ssl info: %w", err)
	}
	return nil
}