server

package
v0.15.0 Latest Latest
Warning

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

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

README

server

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

Package server provides an embeddable HTTP server for a Starmap catalog.

Alongside Starmap's native catalog and reactive-generation routes, the server exposes OpenRouter-compatible model discovery at /api/v1/model/{author}/{slug} and /api/v1/models/{author}/{slug}/endpoints. Those responses are server-local projections over the same immutable catalog; they do not create a second persisted catalog or make generated endpoints.yaml authoritative.

Storage is explicit caller composition before New. Standalone CLI serving uses storage.NewFilesystem by default. Embedding deployments without a persistent filesystem can pass a caller-owned AWS SDK v2 client to New in package github.com/agentstation/starmap/pkg/catalogs/storage/s3, wrap that backend with storage.NewObject, and inject the resulting store through starmap.WithCatalogStore when constructing the client. Server construction never discovers credentials, creates a storage client, or owns its lifecycle.

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 controls CORS middleware. CORSOrigins is the allowlist; an
    // empty allowlist permits every origin when CORS is enabled.
    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 Health

Health is an immutable snapshot of publisher catalog, callback, and stream delivery health. Catalog freshness is derived only from the active 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 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. 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 at least one SSE client is connected.
    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 an embeddable HTTP server for a Starmap catalog.

Alongside Starmap's native catalog and reactive-generation routes, the server exposes OpenRouter-compatible model discovery at /api/v1/model/{author}/{slug} and /api/v1/models/{author}/{slug}/endpoints. Those responses are server-local projections over the same immutable catalog; they do not create a second persisted catalog or make generated endpoints.yaml authoritative.

Storage is explicit caller composition before New. Standalone CLI serving uses storage.NewFilesystem by default. Embedding deployments without a persistent filesystem can pass a caller-owned AWS SDK v2 client to New in package github.com/agentstation/starmap/pkg/catalogs/storage/s3, wrap that backend with storage.NewObject, and inject the resulting store through starmap.WithCatalogStore when constructing the client. Server construction never discovers credentials, creates a storage client, or owns its lifecycle.

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 controls CORS middleware. CORSOrigins is the allowlist; an
	// empty allowlist permits every origin when CORS is enabled.
	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 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. Catalog freshness is derived only from the active 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 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. 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 at least one SSE client is connected.
	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