File size: 1,680 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package heartbeatmanager

import (
	"context"
	"database/sql"

	"github.com/target/goalert/alert"
	"github.com/target/goalert/engine/processinglock"
	"github.com/target/goalert/util"
)

// DB processes heartbeats.
type DB struct {
	lock *processinglock.Lock

	alertStore *alert.Store

	fetchFailed  *sql.Stmt
	fetchHealthy *sql.Stmt
}

// Name returns the name of the module.
func (db *DB) Name() string { return "Engine.HeartbeatManager" }

// NewDB creates a new DB.
func NewDB(ctx context.Context, db *sql.DB, a *alert.Store) (*DB, error) {
	lock, err := processinglock.NewLock(ctx, db, processinglock.Config{
		Type:    processinglock.TypeHeartbeat,
		Version: 2,
	})
	if err != nil {
		return nil, err
	}

	p := &util.Prepare{Ctx: ctx, DB: db}

	return &DB{
		lock:       lock,
		alertStore: a,

		// if checked is still false after processing, we can delete it
		fetchFailed: p.P(`
			with rows as (
				select id
				from heartbeat_monitors
				where
					last_state != 'unhealthy' and
					now() - last_heartbeat >= heartbeat_interval
				limit 250
				for update skip locked
			)
			update heartbeat_monitors mon
			set last_state = 'unhealthy'
			from rows
			where mon.id = rows.id
			returning mon.id, name, service_id, last_heartbeat, coalesce(additional_details, ''), coalesce(muted, '')
		`),
		fetchHealthy: p.P(`
			with rows as (
				select id
				from heartbeat_monitors
				where
					last_state != 'healthy' and
					now() - last_heartbeat < heartbeat_interval
				limit 250
				for update skip locked
			)
			update heartbeat_monitors mon
			set last_state = 'healthy'
			from rows
			where mon.id = rows.id
			returning mon.id, service_id
		`),
	}, p.Err
}