heartbeat

package
v1.3.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2026 License: AGPL-3.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MinIntervalSeconds = 60     // 1 minute
	MaxIntervalSeconds = 604800 // 7 days
	MaxPayloadBytes    = 10240  // 10 KB
	MaxNameLength      = 255
)

Validation constants.

Variables

View Source
var (
	ErrHeartbeatNotFound = errors.New("heartbeat not found")
	ErrLimitReached      = errors.New("heartbeat limit reached")
	ErrInvalidInput      = errors.New("invalid input")
	ErrInvalidExitCode   = errors.New("invalid exit code")
)

Functions

func GenerateSnippets

func GenerateSnippets(baseURL, token string) map[string]string

GenerateSnippets returns integration code snippets for a heartbeat monitor. token is the heartbeat's ping token (its id).

Types

type AlertCallback

type AlertCallback func(h *Heartbeat, alertType string, details map[string]interface{})

AlertCallback is called when an alert or recovery event occurs.

type AlertState

type AlertState string

AlertState represents the alert state of a heartbeat monitor.

const (
	AlertNormal   AlertState = "normal"
	AlertAlerting AlertState = "alerting"
)

type CreateHeartbeatInput

type CreateHeartbeatInput struct {
	Name            string `json:"name"`
	IntervalSeconds int    `json:"interval_seconds"`
	GraceSeconds    int    `json:"grace_seconds"`
}

CreateHeartbeatInput contains the fields needed to create a heartbeat.

type DefaultLicenseChecker

type DefaultLicenseChecker struct {
	MaxHeartbeats int
}

DefaultLicenseChecker implements Community edition limits.

func (*DefaultLicenseChecker) CanCreateHeartbeat

func (c *DefaultLicenseChecker) CanCreateHeartbeat(currentCount int) bool

func (*DefaultLicenseChecker) CanStorePayload

func (c *DefaultLicenseChecker) CanStorePayload() bool

type Deps added in v1.1.0

type Deps struct {
	Store          HeartbeatStore // required
	Logger         *slog.Logger   // required
	LicenseChecker LicenseChecker // optional — defaults to community limits
	EventCallback  EventCallback  // optional — nil-safe
	AlertCallback  AlertCallback  // optional — nil-safe
	BaseURL        string         // optional
}

Deps holds all dependencies for the heartbeat Service.

type EventCallback

type EventCallback func(eventType string, data interface{})

EventCallback is called when a heartbeat event occurs (for SSE broadcasting).

type ExecutionOutcome

type ExecutionOutcome string

ExecutionOutcome represents the result of a job execution.

const (
	OutcomeSuccess    ExecutionOutcome = "success"
	OutcomeFailure    ExecutionOutcome = "failure"
	OutcomeTimeout    ExecutionOutcome = "timeout"
	OutcomeInProgress ExecutionOutcome = "in_progress"
)

type Heartbeat

type Heartbeat struct {
	ID                   string          `json:"id"`
	Name                 string          `json:"name"`
	Status               HeartbeatStatus `json:"status"`
	AlertState           AlertState      `json:"alert_state"`
	IntervalSeconds      int             `json:"interval_seconds"`
	GraceSeconds         int             `json:"grace_seconds"`
	LastPingAt           *time.Time      `json:"last_ping_at,omitempty"`
	NextDeadlineAt       *time.Time      `json:"next_deadline_at,omitempty"`
	CurrentRunStartedAt  *time.Time      `json:"current_run_started_at,omitempty"`
	LastExitCode         *int            `json:"last_exit_code,omitempty"`
	LastDurationMs       *int64          `json:"last_duration_ms,omitempty"`
	ConsecutiveFailures  int             `json:"consecutive_failures"`
	ConsecutiveSuccesses int             `json:"consecutive_successes"`
	Active               bool            `json:"active"`
	CreatedAt            time.Time       `json:"created_at"`
	UpdatedAt            time.Time       `json:"updated_at"`
	AgentID              string          `json:"agent_id"`
}

Heartbeat represents a passive heartbeat monitor. Its ID is the public ping token (a UUID), which doubles as the primary key.

func (*Heartbeat) PingURL

func (h *Heartbeat) PingURL() string

PingURL returns the relative ping URL for this heartbeat. The id is the token.

type HeartbeatExecution

type HeartbeatExecution struct {
	ID          string           `json:"id"`
	HeartbeatID string           `json:"heartbeat_id"`
	StartedAt   *time.Time       `json:"started_at,omitempty"`
	CompletedAt *time.Time       `json:"completed_at,omitempty"`
	DurationMs  *int64           `json:"duration_ms,omitempty"`
	ExitCode    *int             `json:"exit_code,omitempty"`
	Outcome     ExecutionOutcome `json:"outcome"`
	Payload     *string          `json:"payload,omitempty"`
}

HeartbeatExecution represents a logical job run.

type HeartbeatPing

type HeartbeatPing struct {
	ID          string    `json:"id"`
	HeartbeatID string    `json:"heartbeat_id"`
	PingType    PingType  `json:"ping_type"`
	ExitCode    *int      `json:"exit_code,omitempty"`
	SourceIP    string    `json:"source_ip"`
	HTTPMethod  string    `json:"http_method"`
	Payload     *string   `json:"payload,omitempty"`
	Timestamp   time.Time `json:"timestamp"`
}

HeartbeatPing represents a raw ping event.

type HeartbeatStatus

type HeartbeatStatus string

HeartbeatStatus represents the current state of a heartbeat monitor.

const (
	StatusNew     HeartbeatStatus = "new"
	StatusUp      HeartbeatStatus = "up"
	StatusDown    HeartbeatStatus = "down"
	StatusStarted HeartbeatStatus = "started"
	StatusPaused  HeartbeatStatus = "paused"
)

type HeartbeatStore

type HeartbeatStore interface {
	// Heartbeat CRUD
	CreateHeartbeat(ctx context.Context, h *Heartbeat) (string, error)
	GetHeartbeatByID(ctx context.Context, id string) (*Heartbeat, error)
	// GetHeartbeatByUUID looks up by the ping token (which is the id).
	GetHeartbeatByUUID(ctx context.Context, token string) (*Heartbeat, error)
	ListHeartbeats(ctx context.Context, opts ListHeartbeatsOpts) ([]*Heartbeat, error)
	UpdateHeartbeat(ctx context.Context, id string, input UpdateHeartbeatInput) error
	DeleteHeartbeat(ctx context.Context, id string) error

	// State updates
	UpdateHeartbeatState(ctx context.Context, id string, status HeartbeatStatus, alertState AlertState,
		lastPingAt *time.Time, nextDeadlineAt *time.Time, currentRunStartedAt *time.Time,
		lastExitCode *int, lastDurationMs *int64,
		consecutiveFailures, consecutiveSuccesses int) error
	PauseHeartbeat(ctx context.Context, id string) error
	ResumeHeartbeat(ctx context.Context, id string, nextDeadlineAt time.Time) error

	// Deadline scanning
	ListOverdueHeartbeats(ctx context.Context, now time.Time) ([]*Heartbeat, error)

	// License gating
	CountActiveHeartbeats(ctx context.Context) (int, error)

	// Pings
	InsertPing(ctx context.Context, p *HeartbeatPing) (string, error)
	ListPings(ctx context.Context, heartbeatID string, opts ListPingsOpts) ([]*HeartbeatPing, int, error)

	// Executions
	InsertExecution(ctx context.Context, e *HeartbeatExecution) (string, error)
	UpdateExecution(ctx context.Context, id string, completedAt *time.Time, durationMs *int64, exitCode *int, outcome ExecutionOutcome, payload *string) error
	GetCurrentExecution(ctx context.Context, heartbeatID string) (*HeartbeatExecution, error)
	ListExecutions(ctx context.Context, heartbeatID string, opts ListExecutionsOpts) ([]*HeartbeatExecution, int, error)

	// Retention
	DeletePingsBefore(ctx context.Context, before time.Time, batchSize int) (int64, error)
	DeleteExecutionsBefore(ctx context.Context, before time.Time, batchSize int) (int64, error)
}

HeartbeatStore defines the persistence interface for heartbeat monitoring data. A heartbeat's id is its public ping token; methods take that string.

type LicenseChecker

type LicenseChecker interface {
	CanCreateHeartbeat(currentCount int) bool
	CanStorePayload() bool
}

LicenseChecker determines license-gated capabilities.

type ListExecutionsOpts

type ListExecutionsOpts struct {
	Limit  int
	Offset int
}

ListExecutionsOpts configures execution listing queries.

type ListHeartbeatsOpts

type ListHeartbeatsOpts struct {
	Status          string
	IncludeInactive bool
	// AgentFilter filters by agent_id. Nil = no filter; "local" = the local
	// sentinel agent; UUID = specific agent.
	AgentFilter *string
}

ListHeartbeatsOpts configures heartbeat listing queries.

type ListPingsOpts

type ListPingsOpts struct {
	Limit  int
	Offset int
}

ListPingsOpts configures ping listing queries.

type PingType

type PingType string

PingType represents the type of a ping event.

const (
	PingSuccess  PingType = "success"
	PingStart    PingType = "start"
	PingExitCode PingType = "exit_code"
)

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service orchestrates heartbeat monitoring logic.

func NewService

func NewService(d Deps) *Service

NewService creates a new heartbeat service with all dependencies.

func (*Service) BaseURL

func (s *Service) BaseURL() string

BaseURL returns the configured base URL.

func (*Service) CountActiveHeartbeats added in v1.2.2

func (s *Service) CountActiveHeartbeats(ctx context.Context) (int, error)

CountActiveHeartbeats returns the count of all active heartbeat monitors.

func (*Service) CreateHeartbeat

func (s *Service) CreateHeartbeat(ctx context.Context, input CreateHeartbeatInput, token string) (*Heartbeat, error)

CreateHeartbeat creates a heartbeat whose id is the supplied ping token.

func (*Service) DeleteHeartbeat

func (s *Service) DeleteHeartbeat(ctx context.Context, id string) error

func (*Service) GetHeartbeat

func (s *Service) GetHeartbeat(ctx context.Context, id string) (*Heartbeat, error)

func (*Service) HandleAgentEvent added in v1.3.0

func (s *Service) HandleAgentEvent(ctx context.Context, agentID string, ev *agentpb.HeartbeatEvent) error

HandleAgentEvent processes a heartbeat ping forwarded by a remote agent. The agent_id tracks which agent relayed the ping, but the heartbeat monitor is identified by its ping token (heartbeat_token in the proto), which is its id.

func (*Service) ListExecutions

func (s *Service) ListExecutions(ctx context.Context, heartbeatID string, opts ListExecutionsOpts) ([]*HeartbeatExecution, int, error)

func (*Service) ListHeartbeats

func (s *Service) ListHeartbeats(ctx context.Context, opts ListHeartbeatsOpts) ([]*Heartbeat, error)

func (*Service) ListPings

func (s *Service) ListPings(ctx context.Context, heartbeatID string, opts ListPingsOpts) ([]*HeartbeatPing, int, error)

func (*Service) PauseHeartbeat

func (s *Service) PauseHeartbeat(ctx context.Context, id string) (*Heartbeat, error)

func (*Service) ProcessExitCodePing

func (s *Service) ProcessExitCodePing(ctx context.Context, token string, exitCode int, sourceIP, httpMethod string, payload *string) (*Heartbeat, error)

func (*Service) ProcessPing

func (s *Service) ProcessPing(ctx context.Context, token string, sourceIP, httpMethod string, payload *string, agentID *string) (*Heartbeat, error)

func (*Service) ProcessStartPing

func (s *Service) ProcessStartPing(ctx context.Context, token string, sourceIP, httpMethod string) (*Heartbeat, error)

func (*Service) ResumeHeartbeat

func (s *Service) ResumeHeartbeat(ctx context.Context, id string) (*Heartbeat, error)

func (*Service) SetAlertCallback

func (s *Service) SetAlertCallback(cb AlertCallback)

SetAlertCallback sets the callback for alert/recovery events.

func (*Service) SetBaseURL

func (s *Service) SetBaseURL(url string)

SetBaseURL sets the base URL for generating ping URLs and snippets.

func (*Service) SetEventCallback

func (s *Service) SetEventCallback(cb EventCallback)

SetEventCallback sets the callback for broadcasting heartbeat events.

func (*Service) StartDeadlineChecker

func (s *Service) StartDeadlineChecker(ctx context.Context)

func (*Service) UpdateHeartbeat

func (s *Service) UpdateHeartbeat(ctx context.Context, id string, input UpdateHeartbeatInput) (*Heartbeat, error)

type UpdateHeartbeatInput

type UpdateHeartbeatInput struct {
	Name            *string `json:"name,omitempty"`
	IntervalSeconds *int    `json:"interval_seconds,omitempty"`
	GraceSeconds    *int    `json:"grace_seconds,omitempty"`
}

UpdateHeartbeatInput contains the fields that can be updated.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL