ucapi

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ucapi is a minimal client for the Pulsequorum REST API (api/openapi.yaml). It covers the operations the acceptance and chaos drivers need. Secrets (access token, password, join tokens) are never included in errors.

Index

Constants

View Source
const APIBasePath = "/api/v1"

APIBasePath is the REST prefix of a node (api/openapi.yaml, servers.url).

Variables

This section is empty.

Functions

func StatusCode

func StatusCode(err error) int

StatusCode returns the HTTP status of an error from this package, or 0.

Types

type APIError

type APIError struct {
	Status int
	Detail string
}

APIError is a non-2xx answer. Detail is the problem detail, truncated.

func (*APIError) Error

func (e *APIError) Error() string

type Assignment

type Assignment struct {
	Mode  string   `json:"mode"`
	Count int      `json:"count,omitempty"`
	Nodes []string `json:"nodes,omitempty"`
}

Assignment decides which nodes run a monitor's checks (api/openapi.yaml).

type Client

type Client struct {
	// Base is the node base URL without trailing slash, e.g. http://127.0.0.1:8080.
	Base     string
	HTTP     *http.Client
	Token    string
	User     string
	Password string
}

Client talks to one node. Token is the access token; when it is empty and a password is known, the client logs in before the first authenticated call and again after a 401 (the access token is short-lived).

func New

func New(base, user, password string) *Client

New returns a client for the node at base. The HTTP timeout is 15 s.

func (*Client) CreateChannel

func (c *Client) CreateChannel(ctx context.Context, name, shoutrrrURL string, events []string) (NotificationChannel, error)

CreateChannel creates a shoutrrr notification channel that is attached to new monitors by default.

func (*Client) CreateJoinToken

func (c *Client) CreateJoinToken(ctx context.Context, role string, ttlMinutes int) (JoinToken, error)

CreateJoinToken creates a one-time join token for a new node of the given role ("voter" or "probe") that is valid for ttlMinutes.

func (*Client) CreateMaintenance

func (c *Client) CreateMaintenance(ctx context.Context, in MaintenanceWindowInput) (MaintenanceWindow, error)

CreateMaintenance creates a maintenance window (POST /maintenance).

func (*Client) CreateMonitor

func (c *Client) CreateMonitor(ctx context.Context, name, targetURL string, intervalSeconds, retries int, channelIDs []string) (Monitor, error)

CreateMonitor creates an HTTP monitor with the given interval and retries.

func (*Client) CreateMonitorInput

func (c *Client) CreateMonitorInput(ctx context.Context, in MonitorInput) (Monitor, error)

CreateMonitorInput creates a monitor from a complete input.

func (*Client) CreateSystemChannel

func (c *Client) CreateSystemChannel(ctx context.Context, name, shoutrrrURL string, events []string) (NotificationChannel, error)

CreateSystemChannel creates a system notification channel (ADR 0025). The node forces the tenant to _system and adds the event system. Platform admins only.

func (*Client) DeleteMonitor

func (c *Client) DeleteMonitor(ctx context.Context, id string) error

DeleteMonitor deletes a monitor (DELETE /monitors/{id}, 204).

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body, out any) (int, error)

Do sends one request. method and path are relative to APIBasePath. On 401 it logs in again once when a password is known and retries. out may be nil.

func (*Client) DoRaw

func (c *Client) DoRaw(ctx context.Context, method, path string, query url.Values, body, out any) (int, []byte, error)

DoRaw is Do that also returns the raw body of the answer, error answers included. The body is nil when it could not be read. It can hold secrets (for example a token creation answer), so callers may inspect it but must never print or log it.

func (*Client) GetIncident

func (c *Client) GetIncident(ctx context.Context, id string) (Incident, error)

GetIncident reads one incident.

func (*Client) GetMonitor

func (c *Client) GetMonitor(ctx context.Context, id string) (Monitor, error)

GetMonitor reads one monitor including its consensus status.

func (*Client) Health

func (c *Client) Health(ctx context.Context) (Health, error)

Health checks GET /health.

func (*Client) ListChannels

func (c *Client) ListChannels(ctx context.Context) ([]NotificationChannel, error)

ListChannels lists the notification channels (secrets masked).

func (*Client) ListClusterNodes

func (c *Client) ListClusterNodes(ctx context.Context) (ClusterNodeList, error)

ListClusterNodes reads the cluster members (platform admins only).

func (*Client) ListHeartbeats

func (c *Client) ListHeartbeats(ctx context.Context, monitorID string, hq HeartbeatQuery) ([]Heartbeat, error)

ListHeartbeats lists the heartbeats of one monitor in the query window, following the cursor until the end.

func (*Client) ListIncidents

func (c *Client) ListIncidents(ctx context.Context, monitorID string, openOnly bool) ([]Incident, error)

ListIncidents lists incidents, optionally only those of one monitor and only unresolved ones.

func (*Client) ListMaintenance

func (c *Client) ListMaintenance(ctx context.Context) ([]MaintenanceWindow, error)

ListMaintenance lists the maintenance windows.

func (*Client) ListMonitors

func (c *Client) ListMonitors(ctx context.Context) ([]Monitor, error)

ListMonitors lists all monitors, following the cursor until the end.

func (*Client) ListSystemAlerts

func (c *Client) ListSystemAlerts(ctx context.Context, includeCleared bool) ([]SystemAlert, error)

ListSystemAlerts lists the active system alerts, or with includeCleared also the cleared ones (query active=false).

func (*Client) ListUsers

func (c *Client) ListUsers(ctx context.Context) ([]User, error)

ListUsers lists the users of the tenant.

func (*Client) Login

func (c *Client) Login(ctx context.Context) error

Login authenticates with the configured user and password.

func (*Client) OpenIncidents

func (c *Client) OpenIncidents(ctx context.Context, monitorID string) ([]Incident, error)

OpenIncidents lists unresolved incidents of one monitor.

func (*Client) RemoveClusterNode

func (c *Client) RemoveClusterNode(ctx context.Context, nodeID string) (NodeRemoval, error)

RemoveClusterNode removes a member and revokes its certificates.

func (*Client) Setup

func (c *Client) Setup(ctx context.Context, setupToken, displayName string) error

Setup creates the first admin with the one-time setup token (FA-AUTH-01). On success the returned access token is kept for later calls.

func (*Client) TestChannel

func (c *Client) TestChannel(ctx context.Context, channelID string) (DeliveryResult, error)

TestChannel sends the channel's test message synchronously.

func (*Client) TestSystemChannel

func (c *Client) TestSystemChannel(ctx context.Context, channelID string) (DeliveryResult, error)

TestSystemChannel sends the test message of a system channel synchronously.

func (*Client) UpdateMonitor

func (c *Client) UpdateMonitor(ctx context.Context, id string, in MonitorInput) (Monitor, error)

UpdateMonitor replaces the writable part of a monitor (PUT /monitors/{id}).

func (*Client) Uptime24h

func (c *Client) Uptime24h(ctx context.Context, monitorID string) (*float64, error)

Uptime24h returns the 24 h uptime percentage of a monitor, nil if no data.

type ClusterNode

type ClusterNode struct {
	ID                string   `json:"id"`
	Address           string   `json:"address"`
	Voter             bool     `json:"voter"`
	Leader            bool     `json:"leader"`
	Self              bool     `json:"self"`
	Name              string   `json:"name"`
	Version           string   `json:"version"`
	Capabilities      []string `json:"capabilities"`
	Healthy           *bool    `json:"healthy"`
	ReplicationLagMs  *int64   `json:"replicationLagMs"`
	ReplicationError  string   `json:"replicationError"`
	MaxCommandVersion int      `json:"maxCommandVersion"`
	// ConnectivityImpaired is the leader's decision on the node's connectivity (ADR 0022).
	ConnectivityImpaired bool   `json:"connectivityImpaired"`
	ConnectivityReason   string `json:"connectivityReason"`
}

ClusterNode is one member of the Raft configuration as seen by the node that answered the request.

type ClusterNodeList

type ClusterNodeList struct {
	Nodes          []ClusterNode `json:"nodes"`
	LeaderID       string        `json:"leaderId"`
	Warnings       []string      `json:"warnings"`
	CommandLevel   int           `json:"commandLevel"`
	UpgradePending bool          `json:"upgradePending"`
}

ClusterNodeList is the answer of GET /admin/nodes.

type DeliveryResult

type DeliveryResult struct {
	Delivered  bool   `json:"delivered"`
	Error      string `json:"error"`
	DurationMs int    `json:"durationMs"`
}

DeliveryResult is the answer of a synchronous channel test.

type Health

type Health struct {
	Status   string `json:"status"`
	Role     string `json:"role"`
	NodeName string `json:"nodeName"`
	Version  string `json:"version"`
	Commit   string `json:"commit"`
	// Degraded is true while the voter has known no leader for DEGRADED_AFTER (ADR 0024).
	Degraded bool `json:"degraded"`
	// Partition holds the node IDs of this voter and the reachable voters without a leader.
	Partition []string `json:"partition"`
}

Health is the answer of GET /health.

type Heartbeat

type Heartbeat struct {
	NodeID     string    `json:"nodeId"`
	TS         time.Time `json:"ts"`
	Status     string    `json:"status"`
	LatencyMs  int       `json:"latencyMs"`
	ErrorClass string    `json:"errorClass"`
	Message    string    `json:"message"`
}

Heartbeat is the result of one check on one node.

type HeartbeatPage

type HeartbeatPage struct {
	Items      []Heartbeat `json:"items"`
	NextCursor *string     `json:"nextCursor"`
}

HeartbeatPage is one page of heartbeats.

type HeartbeatQuery

type HeartbeatQuery struct {
	From time.Time
	To   time.Time
	Node string
}

HeartbeatQuery selects heartbeats of one monitor. A zero From or To leaves that side open; an empty Node means the consensus view.

type Incident

type Incident struct {
	ID          string     `json:"id"`
	MonitorID   string     `json:"monitorId"`
	MonitorName string     `json:"monitorName"`
	StartedAt   time.Time  `json:"startedAt"`
	ResolvedAt  *time.Time `json:"resolvedAt"`
	Cause       string     `json:"cause"`
	ErrorClass  string     `json:"errorClass"`
	Confirmed   bool       `json:"confirmed"`
}

Incident is an outage of one monitor.

type IncidentPage

type IncidentPage struct {
	Items      []Incident `json:"items"`
	NextCursor *string    `json:"nextCursor"`
}

IncidentPage is one page of incidents.

type JoinToken

type JoinToken struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expiresAt"`
	Role      string    `json:"role"`
	TenantID  string    `json:"tenantId"`
}

JoinToken is the one-time token of a new node. Token is a secret.

type MaintenanceWindow

type MaintenanceWindow struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	MonitorIDs  []string  `json:"monitorIds"`
	Schedule    any       `json:"schedule"`
	Active      bool      `json:"active"`
	NextStart   any       `json:"nextStart,omitempty"`
	InProgress  bool      `json:"inProgress,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

MaintenanceWindow is a maintenance window (MaintenanceWindow in the API).

type MaintenanceWindowInput

type MaintenanceWindowInput struct {
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	MonitorIDs  []string `json:"monitorIds"`
	Schedule    any      `json:"schedule"`
	Active      bool     `json:"active"`
}

MaintenanceWindowInput is the writable part of a maintenance window.

type Monitor

type Monitor struct {
	MonitorInput
	ID          string     `json:"id"`
	Status      string     `json:"status"`
	StatusSince time.Time  `json:"statusSince"`
	LastCheckAt *time.Time `json:"lastCheckAt"`
	LatencyMs   *int       `json:"lastLatencyMs"`
	Uptime24h   *float64   `json:"uptime24h"`
	CreatedAt   time.Time  `json:"createdAt"`
	UpdatedAt   time.Time  `json:"updatedAt"`
}

Monitor is a monitor including its consensus status.

type MonitorInput

type MonitorInput struct {
	Name                   string         `json:"name"`
	Description            string         `json:"description,omitempty"`
	Type                   string         `json:"type"`
	Config                 map[string]any `json:"config"`
	IntervalSeconds        int            `json:"intervalSeconds"`
	TimeoutSeconds         int            `json:"timeoutSeconds,omitempty"`
	Retries                int            `json:"retries"`
	RecoveryThreshold      int            `json:"recoveryThreshold,omitempty"`
	ResendIntervalMinutes  int            `json:"resendIntervalMinutes"`
	Assignment             *Assignment    `json:"assignment,omitempty"`
	ConsensusPolicy        string         `json:"consensusPolicy,omitempty"`
	Tags                   []string       `json:"tags,omitempty"`
	NotificationChannelIDs []string       `json:"notificationChannelIds"`
	Paused                 bool           `json:"paused"`
}

MonitorInput is the writable part of a monitor (MonitorInput in the API).

type MonitorPage

type MonitorPage struct {
	Items      []Monitor `json:"items"`
	NextCursor *string   `json:"nextCursor"`
}

MonitorPage is one page of monitors.

type NodeRemoval

type NodeRemoval struct {
	VotersLeft int      `json:"votersLeft"`
	Warnings   []string `json:"warnings"`
}

NodeRemoval is the answer of DELETE /admin/nodes/{id}.

type NotificationChannel

type NotificationChannel struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Kind      string    `json:"kind"`
	MaskedURL string    `json:"maskedUrl"`
	Webhook   any       `json:"webhook,omitempty"`
	Events    []string  `json:"events"`
	IsDefault bool      `json:"isDefault"`
	State     string    `json:"state"`
	CreatedAt time.Time `json:"createdAt"`
}

NotificationChannel is a notification channel (secrets masked by the node).

type SystemAlert

type SystemAlert struct {
	Kind    string         `json:"kind"`
	Subject string         `json:"subject"`
	Active  bool           `json:"active"`
	Level   int            `json:"level"`
	Since   time.Time      `json:"since"`
	Updated time.Time      `json:"updated"`
	Details map[string]any `json:"details"`
}

SystemAlert is one system alert (ADR 0025). Details hold measured values and node IDs only.

type TokenResponse

type TokenResponse struct {
	AccessToken string    `json:"accessToken"`
	ExpiresAt   time.Time `json:"expiresAt"`
}

TokenResponse is the answer of setup and login.

type UptimeStats

type UptimeStats struct {
	UptimePercent *float64 `json:"uptimePercent"`
}

UptimeStats is the answer of GET /monitors/{id}/uptime.

type User

type User struct {
	ID          string    `json:"id"`
	Username    string    `json:"username"`
	DisplayName string    `json:"displayName"`
	Role        string    `json:"role"`
	Disabled    bool      `json:"disabled"`
	CreatedAt   time.Time `json:"createdAt"`
}

User is a local user of the tenant.

Jump to

Keyboard shortcuts

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