system

package
v0.0.0-...-7477ae0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0

Documentation

Overview

Package system provides handlers for system-wide configuration endpoints.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrParameterNotFound = errors.New("parameter not found")
	ErrInvalidParameter  = errors.New("invalid parameter value")
	// ErrInvalidParameterKey is returned for a key that does not match
	// paramkeys.KeyPattern. Kept distinct from ErrInvalidParameter (which
	// covers a malformed value) because the two map to different response
	// fields — "key" versus "value".
	ErrInvalidParameterKey     = errors.New("invalid parameter key")
	ErrEmailInboxNotConfigured = errors.New("email inbox not configured")
	ErrEmailInboxDisabled      = errors.New("email inbox disabled")
	ErrEmailInboxNotAvailable  = errors.New("email inbox manager not initialized")
	// ErrOperatorNoticeUnavailable is returned when the operator-notice
	// transport was never wired into this process.
	ErrOperatorNoticeUnavailable = errors.New("operator notice transport not initialized")
)

Errors for system parameter operations.

View Source
var ErrUserNotFound = errors.New("user not found")

ErrUserNotFound is returned by GetUser for an unknown or deleted user.

Functions

func TestEmailData

func TestEmailData(loc i18n.Locale) map[string]any

TestEmailData is the test-email.html view model of the SMTP test, in loc. The email preview builds its fixture through it too.

Types

type ActivationFunnelResponse

type ActivationFunnelResponse struct {
	Data []*ActivationFunnelRow `json:"data"`
}

ActivationFunnelResponse wraps the funnel rows.

type ActivationFunnelRow

type ActivationFunnelRow struct {
	OrganizationUID string     `json:"organizationUid"`
	Slug            string     `json:"slug"`
	Name            string     `json:"name"`
	SignupAt        *time.Time `json:"signupAt,omitempty"`
	FirstCheckAt    *time.Time `json:"firstCheckAt,omitempty"`
	FirstResultAt   *time.Time `json:"firstResultAt,omitempty"`
	FirstNotifierAt *time.Time `json:"firstNotifierAt,omitempty"`
	FirstIncidentAt *time.Time `json:"firstIncidentAt,omitempty"`
	OrgCreatedAt    time.Time  `json:"orgCreatedAt"`
}

ActivationFunnelRow lists per-org timestamps for each activation milestone. Missing milestones leave the corresponding field nil.

type AdminOrgMembership

type AdminOrgMembership struct {
	UID      string     `json:"uid"`
	Slug     string     `json:"slug"`
	Name     string     `json:"name"`
	Role     string     `json:"role"`
	JoinedAt *time.Time `json:"joinedAt,omitempty"`
}

AdminOrgMembership is one organization a directory user belongs to.

type AdminUserRow

type AdminUserRow struct {
	UID                string               `json:"uid"`
	Email              string               `json:"email"`
	Name               string               `json:"name"`
	AvatarURL          string               `json:"avatarUrl"`
	SuperAdmin         bool                 `json:"superAdmin"`
	Demo               bool                 `json:"demo"`
	EmailVerified      bool                 `json:"emailVerified"`
	TOTPEnabled        bool                 `json:"totpEnabled"`
	MustChangePassword bool                 `json:"mustChangePassword"`
	HasPassword        bool                 `json:"hasPassword"`
	LastActiveAt       *time.Time           `json:"lastActiveAt,omitempty"`
	CreatedAt          time.Time            `json:"createdAt"`
	Orgs               []AdminOrgMembership `json:"orgs"`
}

AdminUserRow is one line of the superadmin user directory. It is a deliberate allow-list projection of models.User — never the struct itself, which also carries PasswordHash, TOTPSecret and TOTPRecoveryCodes.

type AdminUsersListResponse

type AdminUsersListResponse struct {
	Data []AdminUserRow `json:"data"`
	// Total is how many users matched the search, before paging.
	Total int `json:"total"`
}

AdminUsersListResponse wraps the page, per the repo's list convention.

type DiscordSetupResponse

type DiscordSetupResponse struct {
	BaseURL            string `json:"baseUrl"`
	BaseURLIsDefault   bool   `json:"baseUrlIsDefault"`
	LoginRedirectURI   string `json:"loginRedirectUri"`
	InstallRedirectURI string `json:"installRedirectUri"`
	InteractionsURL    string `json:"interactionsUrl"`
}

DiscordSetupResponse lists the values an operator pastes into the Discord developer portal, computed from the same helpers the login and install flows use to build their redirect URIs.

func DiscordSetupInfo

func DiscordSetupInfo(baseURL string) DiscordSetupResponse

DiscordSetupInfo builds the response for a base URL.

type EmailInboxConfigResponse

type EmailInboxConfigResponse struct {
	Enabled                bool   `json:"enabled"`
	SessionURL             string `json:"sessionUrl"`
	Username               string `json:"username"`
	AddressDomain          string `json:"addressDomain"`
	MailboxName            string `json:"mailboxName"`
	ProcessedMailboxName   string `json:"processedMailboxName"`
	PollIntervalSeconds    int    `json:"pollIntervalSeconds"`
	ProcessedRetentionDays int    `json:"processedRetentionDays"`
	FailedRetentionDays    int    `json:"failedRetentionDays"`
	RewriteBaseURL         string `json:"rewriteBaseUrl"`
	PasswordSet            bool   `json:"passwordSet"`
}

EmailInboxConfigResponse mirrors jmap.Config for the admin form, but never includes the password. PasswordSet tells the frontend whether to render the edit-password affordance.

type EmailInboxStatusResponse

type EmailInboxStatusResponse struct {
	Enabled       bool       `json:"enabled"`
	Connected     bool       `json:"connected"`
	Mode          string     `json:"mode,omitempty"`
	LastSyncedAt  *time.Time `json:"lastSyncedAt,omitempty"`
	LastError     string     `json:"lastError,omitempty"`
	AddressDomain string     `json:"addressDomain,omitempty"`
	AccountID     string     `json:"accountId,omitempty"`
}

EmailInboxStatusResponse mirrors jmap.Status for the API surface.

type EmailInboxTestRequest

type EmailInboxTestRequest struct {
	SessionURL    string `json:"sessionUrl,omitempty"`
	Username      string `json:"username,omitempty"`
	Password      string `json:"password,omitempty"`
	AddressDomain string `json:"addressDomain,omitempty"`
}

EmailInboxTestRequest is the optional request body for POST /email-inbox/test.

type Handler

type Handler struct {
	base.HandlerBase
	// contains filtered or unexported fields
}

Handler provides HTTP handlers for system parameter endpoints.

func NewHandler

func NewHandler(service *Service, cfg *config.Config) *Handler

NewHandler creates a new system handler.

func (*Handler) DeleteParameter

func (h *Handler) DeleteParameter(writer http.ResponseWriter, req *http.Request) error

DeleteParameter handles DELETE /api/v1/system/parameters/:key.

func (*Handler) DiscordSetup

func (h *Handler) DiscordSetup(writer http.ResponseWriter, _ *http.Request) error

DiscordSetup handles GET /api/v1/system/discord-setup. Super-admin only.

func (*Handler) EmailInboxConfig

func (h *Handler) EmailInboxConfig(writer http.ResponseWriter, req *http.Request) error

EmailInboxConfig handles GET /api/v1/system/email-inbox/config. Returns the saved JMAP config with the password elided. Used by the admin form to prefill its fields after navigating back to the page.

func (*Handler) EmailInboxPublic

func (h *Handler) EmailInboxPublic(writer http.ResponseWriter, req *http.Request) error

EmailInboxPublic handles GET /api/v1/system/parameters/email_inbox/public. Returns just the addressDomain so any authenticated user can render the per-check email address. Empty when the inbox isn't configured.

func (*Handler) EmailInboxStatus

func (h *Handler) EmailInboxStatus(writer http.ResponseWriter, _ *http.Request) error

EmailInboxStatus handles GET /api/v1/system/email-inbox/status.

func (*Handler) EmailInboxSync

func (h *Handler) EmailInboxSync(writer http.ResponseWriter, req *http.Request) error

EmailInboxSync handles POST /api/v1/system/email-inbox/sync.

func (*Handler) EmailInboxTest

func (h *Handler) EmailInboxTest(writer http.ResponseWriter, req *http.Request) error

EmailInboxTest handles POST /api/v1/system/email-inbox/test.

func (*Handler) GetOperatorNotifications

func (h *Handler) GetOperatorNotifications(writer http.ResponseWriter, req *http.Request) error

GetOperatorNotifications handles GET /api/v1/system/operator-notifications.

func (*Handler) GetParameter

func (h *Handler) GetParameter(writer http.ResponseWriter, req *http.Request) error

GetParameter handles GET /api/v1/system/parameters/:key.

func (*Handler) GetUser

func (h *Handler) GetUser(writer http.ResponseWriter, req *http.Request) error

GetUser handles GET /api/v1/system/users/:uid — superadmin only.

func (*Handler) LaneLoad

func (h *Handler) LaneLoad(writer http.ResponseWriter, req *http.Request) error

LaneLoad handles GET /api/v1/system/scheduling/lane-load. Super-admin only. Returns each worker's offered check load per lane (job counts, summed cost/delay EWMAs, summed duty cycle) so overload is visible server-side instead of being re-derived client-side from raw rows.

func (*Handler) ListActivationFunnel

func (h *Handler) ListActivationFunnel(writer http.ResponseWriter, req *http.Request) error

ListActivationFunnel handles GET /api/v1/system/activation. Super-admin only.

func (*Handler) ListParameters

func (h *Handler) ListParameters(writer http.ResponseWriter, req *http.Request) error

ListParameters handles GET /api/v1/system/parameters.

func (*Handler) ListUsers

func (h *Handler) ListUsers(writer http.ResponseWriter, req *http.Request) error

ListUsers handles GET /api/v1/system/users — superadmin only. See wiki/api-specification/system.md for the full contract.

func (*Handler) SendOperatorNoticeTest

func (h *Handler) SendOperatorNoticeTest(writer http.ResponseWriter, req *http.Request) error

SendOperatorNoticeTest handles POST /api/v1/system/operator-notifications/test.

It always targets the CALLER, never an arbitrary user: "send me a test" is a self-service confirmation, and letting a super admin push free text at somebody else's phone would be a messaging primitive, not a diagnostic.

func (*Handler) SetOperatorNotifications

func (h *Handler) SetOperatorNotifications(writer http.ResponseWriter, req *http.Request) error

SetOperatorNotifications handles PUT /api/v1/system/operator-notifications.

A dedicated endpoint rather than the raw parameter CRUD so the shape is validated as a document — an unknown event name or a non-super-admin recipient comes back as VALIDATION_ERROR while the operator is still looking at the form.

func (*Handler) SetParameter

func (h *Handler) SetParameter(writer http.ResponseWriter, req *http.Request) error

SetParameter handles PUT /api/v1/system/parameters/:key.

func (*Handler) TestEmail

func (h *Handler) TestEmail(writer http.ResponseWriter, req *http.Request) error

TestEmail handles POST /api/v1/system/test-email.

type JMAPInboxManager

type JMAPInboxManager interface {
	GetStatus() jmap.Status
	TriggerSync(ctx context.Context) error
	TestConnection(ctx context.Context, cfg *jmap.Config) (*jmap.Mailboxes, error)
}

JMAPInboxManager is the subset of *jmap.Manager that the system service depends on. Defined as an interface to keep the package decoupled from the jmap package and to make testing trivial.

type LaneLoadStats

type LaneLoadStats struct {
	// Jobs is the number of enabled check jobs in this lane the worker is
	// eligible to claim (region match).
	Jobs int `json:"jobs"`
	// CostEwmaSumMs is the sum of the jobs' cost EWMAs: the total wall-clock
	// milliseconds one full pass over the lane costs this worker.
	CostEwmaSumMs float64 `json:"costEwmaSumMs"`
	// DelayEwmaSumMs is the sum of the jobs' delay EWMAs — accumulated
	// start-lateness telemetry. A growing sum means the lane runs behind.
	DelayEwmaSumMs float64 `json:"delayEwmaSumMs"`
	// DutySumPct is the sum of per-job duty cycles (100 × cost EWMA / period):
	// how many runner slots this lane's steady-state demand occupies,
	// expressed in percent (100 ≈ one full-time slot). Comparing it against
	// the worker's pool capacity answers "is this worker overloaded?".
	DutySumPct float64 `json:"dutySumPct"`
}

LaneLoadStats aggregates one lane's offered load for a worker.

type ListParametersResponse

type ListParametersResponse struct {
	Data []*ParameterResponse `json:"data"`
	// EnvOverrides lists the known parameter keys whose effective value is
	// currently forced by an SP_* environment variable. Env wins over the
	// database in systemconfig.Service.Initialize, so without this an operator
	// editing one of these keys in Server Settings would see their edit saved
	// and then apparently ignored. Only key NAMES appear here — never values —
	// so it is safe regardless of a key's secrecy.
	EnvOverrides []string `json:"envOverrides"`
}

ListParametersResponse wraps the list of parameters.

type OperatorNoticeTestResponse

type OperatorNoticeTestResponse struct {
	Delivered int `json:"delivered"`
	Failed    int `json:"failed"`
	Skipped   int `json:"skipped"`
	Routes    int `json:"routes"`
}

OperatorNoticeTestResponse reports what the "Send me a test" button actually achieved. A bare 200 would be a lie: the transport succeeds as a call even when every route was skipped.

type OperatorNotificationRecipient

type OperatorNotificationRecipient struct {
	UserUID string `json:"userUid"`
	Email   string `json:"email"`
	Name    string `json:"name,omitempty"`
	// SuperAdmin is false only for a stale subscription — someone who was
	// subscribed and has since lost the flag. Their notices are already being
	// skipped at delivery time; the row exists so the operator can see why.
	SuperAdmin bool `json:"superAdmin"`
	// Events is what this user is currently subscribed to. Empty means "not a
	// recipient".
	Events []string `json:"events"`
	// Routes lists the distinct contact TYPES this user can be reached on,
	// across every org they belong to. Empty is the amber warning case:
	// subscribing them would deliver nothing.
	Routes []string `json:"routes"`
}

OperatorNotificationRecipient is one row of the tab.

type OperatorNotificationsRequest

type OperatorNotificationsRequest struct {
	Enabled bool `json:"enabled"`
	// Recipients is the FULL desired list. The dashboard sends every row it
	// rendered, including the ones with no event checked; the service drops
	// those (see normalizeRecipients) so unchecking the last box unsubscribes
	// rather than saving an inert row.
	Recipients []opsnotify.Recipient `json:"recipients"`
}

OperatorNotificationsRequest is the PUT body.

type OperatorNotificationsResponse

type OperatorNotificationsResponse struct {
	// Enabled is the master switch.
	Enabled bool `json:"enabled"`
	// Events is the subscribable vocabulary, in render order.
	Events []string `json:"events"`
	// Recipients is the candidate list: every super admin, plus anyone still
	// named in the parameter who has since lost the flag.
	Recipients []OperatorNotificationRecipient `json:"recipients"`
}

OperatorNotificationsResponse is the whole Server → Notifications tab in one document.

It deliberately ships the candidate list next to the configuration. The single most likely silent failure is "subscribed, but that person has no notification route", and an operator can only see that if the page knows which routes each candidate actually has — so the API resolves it rather than leaving the UI to make N extra calls it would probably skip.

type ParameterResponse

type ParameterResponse struct {
	Key       string    `json:"key"`
	Value     any       `json:"value"`
	Secret    bool      `json:"secret"`
	UpdatedAt time.Time `json:"updatedAt"`
}

ParameterResponse represents a system parameter in API responses.

type Service

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

Service provides business logic for system parameter operations.

func NewService

func NewService(dbService db.Service) *Service

NewService creates a new system service.

func (*Service) DeleteParameter

func (s *Service) DeleteParameter(ctx context.Context, key string) error

DeleteParameter soft-deletes a system parameter.

func (*Service) EmailInboxConfig

func (s *Service) EmailInboxConfig(ctx context.Context) (*EmailInboxConfigResponse, error)

EmailInboxConfig returns the stored email_inbox config with the password elided, suitable for prefilling the admin form. Returns a zero-valued response when the inbox has never been configured.

func (*Service) EmailInboxPublicAddressDomain

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

EmailInboxPublicAddressDomain returns the address domain configured on the shared inbox so authenticated users can render the per-check email address. Returns an empty string (not an error) when the inbox isn't configured — UIs use that to show the "configure first" placeholder.

func (*Service) EmailInboxStatus

func (s *Service) EmailInboxStatus() (jmap.Status, error)

EmailInboxStatus returns the JMAP inbox manager's current status, or an error if the manager has not been wired into the service.

func (*Service) EmailInboxSync

func (s *Service) EmailInboxSync(ctx context.Context) error

EmailInboxSync fires an immediate sync. Returns ErrEmailInboxNotConfigured if the system parameter is missing, or ErrEmailInboxDisabled if disabled.

func (*Service) EmailInboxTest

func (s *Service) EmailInboxTest(ctx context.Context, cfg *jmap.Config) (*jmap.Mailboxes, error)

EmailInboxTest validates a JMAP configuration end-to-end (session discovery, mailbox resolution). When cfg is nil, the stored email_inbox system parameter is used. Returns the resolved mailboxes on success.

func (*Service) GetOperatorNotifications

func (s *Service) GetOperatorNotifications(ctx context.Context) (*OperatorNotificationsResponse, error)

GetOperatorNotifications reads the configuration and resolves the candidate recipient list.

func (*Service) GetParameter

func (s *Service) GetParameter(ctx context.Context, key string) (*ParameterResponse, error)

GetParameter returns a single system parameter with secret masked.

func (*Service) GetUser

func (s *Service) GetUser(ctx context.Context, uid string) (*AdminUserRow, error)

GetUser returns one directory row (spec 2026-09-30-08, the edit page).

func (*Service) LaneLoad

func (s *Service) LaneLoad(ctx context.Context) ([]WorkerLaneLoad, error)

LaneLoad computes, server-side, each worker's offered check load per lane: job counts, summed cost and delay EWMAs, and the summed duty cycle. "Offered" means every enabled job the worker is eligible to claim (job region unset, or a prefix of the worker's region) — workers sharing a region therefore see the same jobs, which is the honest capacity view for "is this worker overloaded".

func (*Service) ListActivationFunnel

func (s *Service) ListActivationFunnel(ctx context.Context) (*ActivationFunnelResponse, error)

ListActivationFunnel returns one row per organization with the timestamps for each activation milestone. Used by the super-admin /admin/activation view to spot stalled funnels at a glance.

func (*Service) ListParameters

func (s *Service) ListParameters(ctx context.Context) (*ListParametersResponse, error)

ListParameters returns all system parameters with secrets masked.

func (*Service) SearchUsers

func (s *Service) SearchUsers(
	ctx context.Context, filter models.UserSearchFilter,
) (*AdminUsersListResponse, error)

SearchUsers pages the global user directory: one query for the page of users, one batched query for their memberships (never 1+N).

func (*Service) SendOperatorNoticeTest

func (s *Service) SendOperatorNoticeTest(
	ctx context.Context, user *models.User, baseURL string,
) (*OperatorNoticeTestResponse, error)

SendOperatorNoticeTest delivers a `test` notice to one user through the real transport — the one button an operator presses to confirm the setup works.

It runs SYNCHRONOUSLY, unlike the event hooks, precisely because its whole value is the answer: enqueueing it would report "accepted" and tell the operator nothing about whether Telegram actually carried it.

func (*Service) SetEmailConfigProvider

func (s *Service) SetEmailConfigProvider(p email.ConfigProvider)

SetEmailConfigProvider wires the effective-config resolver used by TestEmail.

func (*Service) SetEmailFormatter

func (s *Service) SetEmailFormatter(f email.Formatter)

SetEmailFormatter wires the shared email.Formatter into the service, used to render the admin test email through test-email.html instead of a hand-rolled string. Called from app/server.go alongside the other service wiring.

func (*Service) SetEmailInboxManager

func (s *Service) SetEmailInboxManager(m JMAPInboxManager)

SetEmailInboxManager wires a JMAP inbox manager into the service. Called from app/server.go after the manager has been constructed.

func (*Service) SetOperatorNoticeDeps

func (s *Service) SetOperatorNoticeDeps(deps opsnotify.Deps)

SetOperatorNoticeDeps wires the synchronous notice transport used by the test endpoint. Called from app/server.go; nil leaves the endpoint reporting "nothing delivered" rather than panicking.

func (*Service) SetOperatorNotifications

func (s *Service) SetOperatorNotifications(
	ctx context.Context, req *OperatorNotificationsRequest,
) (*OperatorNotificationsResponse, error)

SetOperatorNotifications validates and persists the configuration.

It goes through the same validators as the raw parameter CRUD — including the super-admin check — so the dashboard cannot save a document the delivery path would then refuse to act on.

func (*Service) SetParameter

func (s *Service) SetParameter(ctx context.Context, key string, value any, secret bool) (*ParameterResponse, error)

SetParameter creates or updates a system parameter. The auth.password.* keys are validated against the exact bounds enforced at config load (see config.ValidatePasswordParameter), and the live aggregation-retention keys against the floor the aggregation job requires (integer >= 1), so a value that would abort the next startup or be silently ignored by the job is rejected here with a validation error instead of being persisted.

func (*Service) TestEmail

func (s *Service) TestEmail(ctx context.Context, address string) (*TestEmailResponse, error)

TestEmail sends a test email using the currently saved SMTP parameters. It is written in the language of the account behind the address, else in the acting super admin's (the user the auth middleware put on ctx).

type SetParameterRequest

type SetParameterRequest struct {
	Value  any   `json:"value"`
	Secret *bool `json:"secret,omitempty"`
}

SetParameterRequest represents a request to set a parameter.

type TestEmailRequest

type TestEmailRequest struct {
	Recipient string `json:"recipient"`
}

TestEmailRequest represents a request to send a test email.

type TestEmailResponse

type TestEmailResponse struct {
	Sent    bool   `json:"sent"`
	Message string `json:"message"`
}

TestEmailResponse represents the result of sending a test email.

type WorkerLaneLoad

type WorkerLaneLoad struct {
	WorkerUID    string        `json:"workerUid"`
	Name         string        `json:"name"`
	Region       *string       `json:"region,omitempty"`
	LastActiveAt *time.Time    `json:"lastActiveAt,omitempty"`
	Fast         LaneLoadStats `json:"fast"`
	Slow         LaneLoadStats `json:"slow"`
}

WorkerLaneLoad is the per-worker lane-load report.

Jump to

Keyboard shortcuts

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