server

package
v0.16.5 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0

README

server

import "github.com/agentstation/starmap/server"

Package server provides the public Starmap HTTP server composition.

Index

type Config

Config configures an embeddable Starmap HTTP server.

type Config struct {
    // Host and Port form the informational HTTP server address. Serve uses the
    // caller-provided listener.
    Host string
    Port int

    // PathPrefix is the root for versioned API routes.
    PathPrefix string

    CORSEnabled bool
    CORSOrigins []string

    // AuthEnabled controls API-key middleware. AuthHeader names the request
    // header carrying the key.
    AuthEnabled bool
    AuthHeader  string

    // RateLimit is the per-IP requests-per-minute limit. Zero disables it.
    RateLimit int
    // CacheTTL bounds derived response-cache entries.
    CacheTTL time.Duration

    // ReadTimeout, WriteTimeout, and IdleTimeout configure net/http. Zero
    // delegates the corresponding timeout policy to the caller/network.
    ReadTimeout  time.Duration
    WriteTimeout time.Duration
    IdleTimeout  time.Duration

    // SSEHeartbeatInterval controls flushed comment heartbeats on publication
    // streams. SSEWriteTimeout bounds each event or heartbeat write and flush.
    SSEHeartbeatInterval time.Duration
    SSEWriteTimeout      time.Duration

    // ShutdownGracePeriod bounds internal service cleanup after HTTP draining.
    ShutdownGracePeriod time.Duration

    // MetricsEnabled exposes the process metrics endpoint.
    MetricsEnabled bool
}

func DefaultConfig
func DefaultConfig() Config

DefaultConfig returns production-oriented server defaults.

type ConnectedRuntime

ConnectedRuntime is the whole contract the server needs from a connected catalog runtime. The server reports the status and joins the shutdown, and it never reads a catalog source itself.

The narrow contract keeps the attested source machinery out of the public server dependency closure. A consumer that embeds the server around an offline client therefore pays for none of it. *runtime.Runtime in github.com/agentstation/starmap/runtime satisfies this contract.

type ConnectedRuntime interface {
    // Status reports the observable runtime state without a source read.
    Status() status.Status

    // Close ends the runtime background work under its own bounded join.
    Close() error
}

type Health

Health is an immutable snapshot of publisher catalog, callback, and stream delivery health. Only the active generation timestamp determines catalog generation timestamp. Heartbeat activity cannot refresh it.

type Health struct {
    State              State             `json:"state"`
    ActiveGenerationID string            `json:"active_generation_id,omitempty"`
    CatalogGeneratedAt time.Time         `json:"catalog_generated_at"`
    CatalogAgeSeconds  int64             `json:"catalog_age_seconds"`
    Publication        PublicationHealth `json:"publication"`
    Stream             StreamHealth      `json:"stream"`
}

type Option

Option configures a Server dependency.

type Option func(*options) error

func WithLogger
func WithLogger(logger *zerolog.Logger) Option

WithLogger configures server diagnostics. The default logger discards output.

func WithRuntime
func WithRuntime(connected ConnectedRuntime) Option

WithRuntime joins the server to one connected runtime. Readiness then reports the runtime status, and Shutdown joins the runtime shutdown.

func WithSyncer
func WithSyncer(syncer Syncer) Option

WithSyncer enables explicit source acquisition through the update endpoint.

type PublicationHealth

PublicationHealth reports post-commit callback delivery, including every pending generation coalesced by the bounded callback dispatcher.

type PublicationHealth struct {
    Completed   uint64        `json:"completed"`
    Failures    uint64        `json:"failures"`
    Panics      uint64        `json:"panics"`
    Coalesced   uint64        `json:"coalesced"`
    LastLatency time.Duration `json:"last_latency"`
    MaxLatency  time.Duration `json:"max_latency"`
}

type Server

Server serves one Starmap client's immutable catalog over HTTP.

Construction starts no listener or background goroutine. Serve starts the server-owned services and blocks until the listener fails or Shutdown drains the HTTP server.

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

func New
func New(client *starmap.Client, config Config, serverOptions ...Option) (*Server, error)

New constructs an embeddable server for client.

func (*Server) Handler
func (s *Server) Handler() http.Handler

Handler returns the configured HTTP handler. Call Start before serving this handler through a caller-owned http.Server. The caller must drain that http.Server before calling Shutdown to stop Starmap's background services.

func (*Server) Health
func (s *Server) Health() Health

Health returns current server health without performing I/O.

func (*Server) Serve
func (s *Server) Serve(listener net.Listener) error

Serve starts server-owned services and serves listener until Shutdown or a listener failure. A normal Shutdown returns nil.

func (*Server) Shutdown
func (s *Server) Shutdown(ctx context.Context) error

Shutdown drains the HTTP server used by Serve and then stops server-owned background services within ctx. It also closes a runtime joined with WithRuntime. A caller serving Handler through its own http.Server must drain that server first.

func (*Server) Start
func (s *Server) Start() error

Start starts server-owned background services exactly once.

type State

State is the embeddable server lifecycle state.

type State string

const (
    // StateIdle means construction succeeded but Start or Serve has not run.
    StateIdle State = "idle"
    // StateServing means server-owned services are active.
    StateServing State = "serving"
    // StateStopped means Shutdown completed and streaming is unavailable.
    StateStopped State = "stopped"
)

type StreamHealth

StreamHealth reports SSE liveness and delivery. BackpressureTerminated and Failed make every forced connection recovery observable.

type StreamHealth struct {
    State                  StreamState `json:"state"`
    Clients                int         `json:"clients"`
    LastHeartbeatAt        time.Time   `json:"last_heartbeat_at"`
    LastEventAt            time.Time   `json:"last_event_at"`
    LastGenerationID       string      `json:"last_generation_id,omitempty"`
    LastSequence           uint64      `json:"last_sequence"`
    LastErrorKind          string      `json:"last_error_kind,omitempty"`
    LastErrorAt            time.Time   `json:"last_error_at"`
    Published              uint64      `json:"published"`
    Sent                   uint64      `json:"sent"`
    Heartbeats             uint64      `json:"heartbeats"`
    Disconnected           uint64      `json:"disconnected"`
    BackpressureTerminated uint64      `json:"backpressure_terminated"`
    Failed                 uint64      `json:"failed"`
}

type StreamState

StreamState is the server-side SSE publication stream state.

type StreamState string

const (
    // StreamStateIdle means the broadcaster accepts streams but has no clients.
    StreamStateIdle StreamState = "idle"
    // StreamStateStreaming means the broadcaster has active clients.
    StreamStateStreaming StreamState = "streaming"
    // StreamStateStopped means the broadcaster rejects new streams.
    StreamStateStopped StreamState = "stopped"
)

type Syncer

Syncer is the optional acquisition capability used by the update endpoint. Read-only servers do not need one.

type Syncer interface {
    Sync(context.Context, ...pkgsync.Option) (*pkgsync.Result, error)
}

Generated by gomarkdoc

Documentation

Overview

Package server provides the public Starmap HTTP server composition.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Host and Port form the informational HTTP server address. Serve uses the
	// caller-provided listener.
	Host string
	Port int

	// PathPrefix is the root for versioned API routes.
	PathPrefix string

	CORSEnabled bool
	CORSOrigins []string

	// AuthEnabled controls API-key middleware. AuthHeader names the request
	// header carrying the key.
	AuthEnabled bool
	AuthHeader  string

	// RateLimit is the per-IP requests-per-minute limit. Zero disables it.
	RateLimit int
	// CacheTTL bounds derived response-cache entries.
	CacheTTL time.Duration

	// ReadTimeout, WriteTimeout, and IdleTimeout configure net/http. Zero
	// delegates the corresponding timeout policy to the caller/network.
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	IdleTimeout  time.Duration

	// SSEHeartbeatInterval controls flushed comment heartbeats on publication
	// streams. SSEWriteTimeout bounds each event or heartbeat write and flush.
	SSEHeartbeatInterval time.Duration
	SSEWriteTimeout      time.Duration

	// ShutdownGracePeriod bounds internal service cleanup after HTTP draining.
	ShutdownGracePeriod time.Duration

	// MetricsEnabled exposes the process metrics endpoint.
	MetricsEnabled bool
}

Config configures an embeddable Starmap HTTP server.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns production-oriented server defaults.

type ConnectedRuntime added in v0.16.0

type ConnectedRuntime interface {
	// Status reports the observable runtime state without a source read.
	Status() status.Status

	// Close ends the runtime background work under its own bounded join.
	Close() error
}

ConnectedRuntime is the whole contract the server needs from a connected catalog runtime. The server reports the status and joins the shutdown, and it never reads a catalog source itself.

The narrow contract keeps the attested source machinery out of the public server dependency closure. A consumer that embeds the server around an offline client therefore pays for none of it. *runtime.Runtime in github.com/agentstation/starmap/runtime satisfies this contract.

type Health

type Health struct {
	State              State             `json:"state"`
	ActiveGenerationID string            `json:"active_generation_id,omitempty"`
	CatalogGeneratedAt time.Time         `json:"catalog_generated_at"`
	CatalogAgeSeconds  int64             `json:"catalog_age_seconds"`
	Publication        PublicationHealth `json:"publication"`
	Stream             StreamHealth      `json:"stream"`
}

Health is an immutable snapshot of publisher catalog, callback, and stream delivery health. Only the active generation timestamp determines catalog generation timestamp. Heartbeat activity cannot refresh it.

type Option

type Option func(*options) error

Option configures a Server dependency.

func WithLogger

func WithLogger(logger *zerolog.Logger) Option

WithLogger configures server diagnostics. The default logger discards output.

func WithRuntime added in v0.16.0

func WithRuntime(connected ConnectedRuntime) Option

WithRuntime joins the server to one connected runtime. Readiness then reports the runtime status, and Shutdown joins the runtime shutdown.

func WithSyncer

func WithSyncer(syncer Syncer) Option

WithSyncer enables explicit source acquisition through the update endpoint.

type PublicationHealth

type PublicationHealth struct {
	Completed   uint64        `json:"completed"`
	Failures    uint64        `json:"failures"`
	Panics      uint64        `json:"panics"`
	Coalesced   uint64        `json:"coalesced"`
	LastLatency time.Duration `json:"last_latency"`
	MaxLatency  time.Duration `json:"max_latency"`
}

PublicationHealth reports post-commit callback delivery, including every pending generation coalesced by the bounded callback dispatcher.

type Server

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

Server serves one Starmap client's immutable catalog over HTTP.

Construction starts no listener or background goroutine. Serve starts the server-owned services and blocks until the listener fails or Shutdown drains the HTTP server.

func New

func New(client *starmap.Client, config Config, serverOptions ...Option) (*Server, error)

New constructs an embeddable server for client.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the configured HTTP handler. Call Start before serving this handler through a caller-owned http.Server. The caller must drain that http.Server before calling Shutdown to stop Starmap's background services.

func (*Server) Health

func (s *Server) Health() Health

Health returns current server health without performing I/O.

func (*Server) Serve

func (s *Server) Serve(listener net.Listener) error

Serve starts server-owned services and serves listener until Shutdown or a listener failure. A normal Shutdown returns nil.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown drains the HTTP server used by Serve and then stops server-owned background services within ctx. It also closes a runtime joined with WithRuntime. A caller serving Handler through its own http.Server must drain that server first.

func (*Server) Start

func (s *Server) Start() error

Start starts server-owned background services exactly once.

type State

type State string

State is the embeddable server lifecycle state.

const (
	// StateIdle means construction succeeded but Start or Serve has not run.
	StateIdle State = "idle"
	// StateServing means server-owned services are active.
	StateServing State = "serving"
	// StateStopped means Shutdown completed and streaming is unavailable.
	StateStopped State = "stopped"
)

type StreamHealth

type StreamHealth struct {
	State                  StreamState `json:"state"`
	Clients                int         `json:"clients"`
	LastHeartbeatAt        time.Time   `json:"last_heartbeat_at"`
	LastEventAt            time.Time   `json:"last_event_at"`
	LastGenerationID       string      `json:"last_generation_id,omitempty"`
	LastSequence           uint64      `json:"last_sequence"`
	LastErrorKind          string      `json:"last_error_kind,omitempty"`
	LastErrorAt            time.Time   `json:"last_error_at"`
	Published              uint64      `json:"published"`
	Sent                   uint64      `json:"sent"`
	Heartbeats             uint64      `json:"heartbeats"`
	Disconnected           uint64      `json:"disconnected"`
	BackpressureTerminated uint64      `json:"backpressure_terminated"`
	Failed                 uint64      `json:"failed"`
}

StreamHealth reports SSE liveness and delivery. BackpressureTerminated and Failed make every forced connection recovery observable.

type StreamState

type StreamState string

StreamState is the server-side SSE publication stream state.

const (
	// StreamStateIdle means the broadcaster accepts streams but has no clients.
	StreamStateIdle StreamState = "idle"
	// StreamStateStreaming means the broadcaster has active clients.
	StreamStateStreaming StreamState = "streaming"
	// StreamStateStopped means the broadcaster rejects new streams.
	StreamStateStopped StreamState = "stopped"
)

type Syncer

type Syncer interface {
	Sync(context.Context, ...pkgsync.Option) (*pkgsync.Result, error)
}

Syncer is the optional acquisition capability used by the update endpoint. Read-only servers do not need one.

Jump to

Keyboard shortcuts

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