Вынос health-check-service в отдельный сервис

Тикер офлайн-детекции (internal/healthcheck) переехал из
device-control-service в новый самостоятельный Go-сервис — как и
планировалось с самого начала (см. изначальный README-заглушку).
Детекция online остаётся в device-control-service: она происходит
как побочный эффект уже имеющейся там MQTT-подписки на
devices/+/telemetry и devices/+/ack, заводить для этого отдельный
сервис с дублирующей MQTT-подпиской избыточно.

health-check-service — свой Go-модуль (без зависимости от proto/,
сборка из собственного контекста), читает только узкое
read+offline-подмножество Device Shadow keyspace в Redis
(devices:known, status, last_seen) — полный Shadow API с записью
desired/reported state остаётся только в device-control-service.

Метрика device_control_health_transitions_total переименована в
device_health_transitions_total и теперь публикуется с этим именем
из ДВУХ сервисов (device-control-service — direction=online,
health-check-service — direction=offline): Prometheus агрегирует
одноимённые метрики с разных таргетов прозрачно, поэтому Grafana-
дашборд адаптирован простой сменой имени метрики в запросе, без
переделки панели.

Проверено вживую через docker compose: реальный online→offline
переход (публикация тестовой телеметрии + ожидание таймаута)
корректно долетает до Redis и RabbitMQ (device.status_changed),
Prometheus видит новый scrape-таргет как up.
This commit is contained in:
2026-08-13 11:24:25 +05:00
parent be1f238f89
commit 17af76c159
20 changed files with 656 additions and 58 deletions
@@ -0,0 +1,84 @@
// Package config loads health-check-service settings from environment
// variables, matching the names used in the repo-root .env.example.
package config
import (
"fmt"
"os"
"strconv"
"time"
)
type Config struct {
RedisAddr string
RedisPassword string
RedisDB int
RabbitMQURL string
HealthCheckTimeout time.Duration
HealthCheckInterval time.Duration
MetricsPort int
}
func Load() (Config, error) {
cfg := Config{
RedisAddr: fmt.Sprintf("%s:%s", getEnv("REDIS_HOST", "localhost"), getEnv("REDIS_PORT", "6379")),
RedisPassword: getEnv("REDIS_PASSWORD", ""),
RabbitMQURL: fmt.Sprintf("amqp://%s:%s@%s:%s/",
getEnv("RABBITMQ_USER", "guest"),
getEnv("RABBITMQ_PASSWORD", "guest"),
getEnv("RABBITMQ_HOST", "localhost"),
getEnv("RABBITMQ_PORT", "5672"),
),
}
var err error
if cfg.RedisDB, err = getEnvInt("REDIS_DB", 0); err != nil {
return Config{}, err
}
if cfg.HealthCheckTimeout, err = getEnvDuration("HEALTH_CHECK_TIMEOUT", 60*time.Second); err != nil {
return Config{}, err
}
if cfg.HealthCheckInterval, err = getEnvDuration("HEALTH_CHECK_INTERVAL", 15*time.Second); err != nil {
return Config{}, err
}
if cfg.MetricsPort, err = getEnvInt("HEALTH_CHECK_METRICS_PORT", 9103); err != nil {
return Config{}, err
}
return cfg, nil
}
func getEnv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func getEnvInt(key string, fallback int) (int, error) {
v := os.Getenv(key)
if v == "" {
return fallback, nil
}
n, err := strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
return n, nil
}
func getEnvDuration(key string, fallback time.Duration) (time.Duration, error) {
v := os.Getenv(key)
if v == "" {
return fallback, nil
}
d, err := time.ParseDuration(v)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
return d, nil
}
@@ -0,0 +1,93 @@
// Package healthcheck periodically flips devices to offline when they stop
// sending telemetry/acks, per the platform's Device Shadow health-check
// design (a goroutine + graceful shutdown, deliberately simple).
package healthcheck
import (
"context"
"log/slog"
"time"
)
// DeviceStore is the subset of shadow.Store the checker needs, kept as an
// interface so tests don't require a real Redis.
type DeviceStore interface {
KnownDevices(ctx context.Context) ([]string, error)
MarkOfflineIfStale(ctx context.Context, deviceID string, timeout time.Duration) (bool, error)
}
// OnOfflineFunc is called once per device that just transitioned to offline.
type OnOfflineFunc func(deviceID string)
type Checker struct {
store DeviceStore
timeout time.Duration
interval time.Duration
onOffline OnOfflineFunc
logger *slog.Logger
stop chan struct{}
done chan struct{}
}
func New(store DeviceStore, timeout, interval time.Duration, onOffline OnOfflineFunc, logger *slog.Logger) *Checker {
return &Checker{
store: store,
timeout: timeout,
interval: interval,
onOffline: onOffline,
logger: logger,
}
}
// Start begins the periodic scan loop. Call once.
func (c *Checker) Start() {
c.stop = make(chan struct{})
c.done = make(chan struct{})
go c.loop()
}
// Stop signals the loop to exit and waits for it to finish.
func (c *Checker) Stop() {
close(c.stop)
<-c.done
}
func (c *Checker) loop() {
defer close(c.done)
ticker := time.NewTicker(c.interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.checkAll()
case <-c.stop:
return
}
}
}
func (c *Checker) checkAll() {
ctx, cancel := context.WithTimeout(context.Background(), c.interval)
defer cancel()
ids, err := c.store.KnownDevices(ctx)
if err != nil {
c.logger.Error("healthcheck: list known devices failed", "error", err)
return
}
for _, id := range ids {
changed, err := c.store.MarkOfflineIfStale(ctx, id, c.timeout)
if err != nil {
c.logger.Error("healthcheck: check device failed", "device_id", id, "error", err)
continue
}
if changed {
c.logger.Info("device marked offline", "device_id", id)
if c.onOffline != nil {
c.onOffline(id)
}
}
}
}
@@ -0,0 +1,76 @@
package healthcheck
import (
"context"
"io"
"log/slog"
"sync"
"testing"
"time"
)
type fakeStore struct {
mu sync.Mutex
known []string
stale map[string]bool // deviceID -> whether MarkOfflineIfStale should report a change
changes []string // devices actually marked changed, in call order
}
func (f *fakeStore) KnownDevices(context.Context) ([]string, error) {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.known...), nil
}
func (f *fakeStore) MarkOfflineIfStale(_ context.Context, deviceID string, _ time.Duration) (bool, error) {
f.mu.Lock()
defer f.mu.Unlock()
if !f.stale[deviceID] {
return false, nil
}
// Only report the transition once, like the real store would.
f.stale[deviceID] = false
f.changes = append(f.changes, deviceID)
return true, nil
}
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func TestChecker_FlipsStaleDevicesAndCallsOnOffline(t *testing.T) {
store := &fakeStore{
known: []string{"d1", "d2"},
stale: map[string]bool{"d1": true, "d2": false},
}
offline := make(chan string, 2)
c := New(store, time.Minute, 10*time.Millisecond, func(deviceID string) {
offline <- deviceID
}, discardLogger())
c.Start()
defer c.Stop()
select {
case id := <-offline:
if id != "d1" {
t.Fatalf("got offline callback for %q, want d1", id)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for onOffline callback")
}
select {
case id := <-offline:
t.Fatalf("unexpected second onOffline callback for %q (d2 was never stale)", id)
case <-time.After(50 * time.Millisecond):
// expected: no further callbacks
}
}
func TestChecker_StopWaitsForLoopExit(t *testing.T) {
store := &fakeStore{known: nil}
c := New(store, time.Minute, time.Hour, nil, discardLogger())
c.Start()
c.Stop() // must return without hanging
}
@@ -0,0 +1,21 @@
// Package metrics defines health-check-service's Prometheus metrics.
// Registered automatically (via promauto) into the default registry on
// import; served on /metrics.
//
// device_health_transitions_total is intentionally the same metric name
// device-control-service exposes for its "online" transitions (detected via
// MQTT touch) — this service only ever emits direction="offline". Prometheus
// aggregates same-named metrics across scrape targets/jobs transparently, so
// Grafana's `sum by (direction) (...)` panel keeps working across the split
// without a query change.
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var HealthTransitionsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "device_health_transitions_total",
Help: "Total number of device online/offline transitions detected.",
}, []string{"direction"})
@@ -0,0 +1,78 @@
// Package rabbitmq publishes device online/offline transitions for
// notification-service to consume. Delivery reliability matters more than
// latency here, so messages are persistent and the queue is durable.
package rabbitmq
import (
"context"
"encoding/json"
"fmt"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
const StatusChangedQueue = "device.status_changed"
type Publisher struct {
conn *amqp.Connection
ch *amqp.Channel
}
func Connect(url string) (*Publisher, error) {
conn, err := amqp.Dial(url)
if err != nil {
return nil, fmt.Errorf("dial rabbitmq: %w", err)
}
ch, err := conn.Channel()
if err != nil {
conn.Close()
return nil, fmt.Errorf("open channel: %w", err)
}
if _, err := ch.QueueDeclare(StatusChangedQueue, true, false, false, false, nil); err != nil {
ch.Close()
conn.Close()
return nil, fmt.Errorf("declare queue %s: %w", StatusChangedQueue, err)
}
return &Publisher{conn: conn, ch: ch}, nil
}
func (p *Publisher) Close() error {
if err := p.ch.Close(); err != nil {
p.conn.Close()
return err
}
return p.conn.Close()
}
type statusChangedEvent struct {
DeviceID string `json:"device_id"`
Status string `json:"status"`
At time.Time `json:"at"`
}
// PublishStatusChanged emits one event when a device transitions online or offline.
func (p *Publisher) PublishStatusChanged(ctx context.Context, deviceID, status string) error {
body, err := json.Marshal(statusChangedEvent{
DeviceID: deviceID,
Status: status,
At: time.Now(),
})
if err != nil {
return fmt.Errorf("marshal event: %w", err)
}
err = p.ch.PublishWithContext(ctx, "", StatusChangedQueue, false, false, amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
Timestamp: time.Now(),
Body: body,
})
if err != nil {
return fmt.Errorf("publish status change for device %s: %w", deviceID, err)
}
return nil
}
@@ -0,0 +1,91 @@
// Package shadow gives health-check-service read/offline-detection access
// to the Device Shadow keyspace in Redis. device-control-service owns the
// full Shadow API (desired/reported state patches, online-touch on
// telemetry/ack) — this is deliberately the narrow subset a periodic
// offline-scanner needs, kept as its own small copy rather than a shared
// module: the two services only overlap on reading/writing `status` and
// `last_seen`, and duplicating ~2 key-naming functions is cheaper than a
// fourth shared Go module for that.
package shadow
import (
"context"
"fmt"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
const knownDevicesKey = "devices:known"
func statusKey(deviceID string) string { return "device:" + deviceID + ":status" }
func lastSeenKey(deviceID string) string { return "device:" + deviceID + ":last_seen" }
const (
StatusOnline = "online"
StatusOffline = "offline"
)
type Store struct {
rdb *redis.Client
}
func New(rdb *redis.Client) *Store {
return &Store{rdb: rdb}
}
func Connect(ctx context.Context, addr, password string, db int) (*Store, error) {
rdb := redis.NewClient(&redis.Options{Addr: addr, Password: password, DB: db})
if err := rdb.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("ping redis: %w", err)
}
return New(rdb), nil
}
func (s *Store) Close() error {
return s.rdb.Close()
}
// KnownDevices lists every device ID device-control-service has heard from.
func (s *Store) KnownDevices(ctx context.Context) ([]string, error) {
ids, err := s.rdb.SMembers(ctx, knownDevicesKey).Result()
if err != nil {
return nil, fmt.Errorf("list known devices: %w", err)
}
return ids, nil
}
// MarkOfflineIfStale flips deviceID to offline if it is currently online and
// its last_seen is older than timeout. It reports whether a change was made.
func (s *Store) MarkOfflineIfStale(ctx context.Context, deviceID string, timeout time.Duration) (changed bool, err error) {
status, err := s.rdb.Get(ctx, statusKey(deviceID)).Result()
if err == redis.Nil || status != StatusOnline {
return false, nil
}
if err != nil {
return false, fmt.Errorf("get status for %s: %w", deviceID, err)
}
lastSeenRaw, err := s.rdb.Get(ctx, lastSeenKey(deviceID)).Result()
if err != nil && err != redis.Nil {
return false, fmt.Errorf("get last_seen for %s: %w", deviceID, err)
}
var lastSeen time.Time
if lastSeenRaw != "" {
sec, err := strconv.ParseInt(lastSeenRaw, 10, 64)
if err != nil {
return false, fmt.Errorf("parse last_seen for %s: %w", deviceID, err)
}
lastSeen = time.Unix(sec, 0)
}
if time.Since(lastSeen) <= timeout {
return false, nil
}
if err := s.rdb.Set(ctx, statusKey(deviceID), StatusOffline, 0).Err(); err != nil {
return false, fmt.Errorf("set status offline for %s: %w", deviceID, err)
}
return true, nil
}
@@ -0,0 +1,93 @@
package shadow
import (
"context"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
)
func newTestStore(t *testing.T) *Store {
t.Helper()
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { rdb.Close() })
return New(rdb)
}
// markOnline seeds Redis the way device-control-service's Touch() would,
// without depending on that service's code.
func markOnline(t *testing.T, s *Store, deviceID string, lastSeen time.Time) {
t.Helper()
ctx := context.Background()
if err := s.rdb.SAdd(ctx, knownDevicesKey, deviceID).Err(); err != nil {
t.Fatalf("seed known device: %v", err)
}
if err := s.rdb.Set(ctx, statusKey(deviceID), StatusOnline, 0).Err(); err != nil {
t.Fatalf("seed status: %v", err)
}
if err := s.rdb.Set(ctx, lastSeenKey(deviceID), lastSeen.Unix(), 0).Err(); err != nil {
t.Fatalf("seed last_seen: %v", err)
}
}
func TestKnownDevices_ListsSeededDevices(t *testing.T) {
ctx := context.Background()
s := newTestStore(t)
markOnline(t, s, "d1", time.Now())
markOnline(t, s, "d2", time.Now())
got, err := s.KnownDevices(ctx)
if err != nil {
t.Fatalf("known devices: %v", err)
}
if len(got) != 2 {
t.Fatalf("got %d known devices, want 2 (%v)", len(got), got)
}
}
func TestMarkOfflineIfStale(t *testing.T) {
ctx := context.Background()
s := newTestStore(t)
markOnline(t, s, "d1", time.Now())
changed, err := s.MarkOfflineIfStale(ctx, "d1", time.Hour)
if err != nil {
t.Fatalf("mark offline (not stale): %v", err)
}
if changed {
t.Fatal("device just touched should not be considered stale")
}
changed, err = s.MarkOfflineIfStale(ctx, "d1", -time.Second) // any age counts as stale
if err != nil {
t.Fatalf("mark offline (stale): %v", err)
}
if !changed {
t.Fatal("expected status to flip to offline")
}
// Already offline: a second call should report no further change.
changed, err = s.MarkOfflineIfStale(ctx, "d1", -time.Second)
if err != nil {
t.Fatalf("mark offline (already offline): %v", err)
}
if changed {
t.Fatal("expected no change once already offline")
}
}
func TestMarkOfflineIfStale_UnknownDeviceIsNoop(t *testing.T) {
ctx := context.Background()
s := newTestStore(t)
changed, err := s.MarkOfflineIfStale(ctx, "ghost", time.Second)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if changed {
t.Fatal("unknown device should never be reported as changed")
}
}