serve

package
v0.27.1 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: Apache-2.0 Imports: 33 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

Index

Constants

View Source
const SessionOpenTimeout = 10 * time.Second

SessionOpenTimeout is the maximum amount of time that the service will wait while attempting to open a database connection before returning an error.

Variables

View Source
var (
	// ErrNoActiveClient is returned when a request is attempted but no browser
	// client is connected to drive it.
	ErrNoActiveClient = errors.New("no active browser client is connected")
	// ErrClientDisconnected is returned when the active client disconnects
	// while a request is in flight.
	ErrClientDisconnected = errors.New("browser client disconnected")
	// ErrClientSuperseded is returned when control is taken over by another
	// client while a request was in flight.
	ErrClientSuperseded = errors.New("another browser tab took over control")
	// ErrAgentIdleTimeout is returned when the active client sends no message
	// (heartbeat or response) within agentIdleTimeout.
	ErrAgentIdleTimeout = errors.New("timed out waiting for the browser; is the tab still open?")
)

Bridge errors surfaced to MCP tools (and ultimately the agent).

Functions

This section is empty.

Types

type AgentActivateRequest added in v0.24.0

type AgentActivateRequest struct {
	ClientID string `json:"clientId"`
}

AgentActivateRequest is the request body of POST /api/agent/activate. A browser tab posts its own client ID to become the active controlling tab (the "take over" action).

func (AgentActivateRequest) Validate added in v0.24.0

func (r AgentActivateRequest) Validate() error

Validate returns an error if a required field is missing.

type AgentActivateResponse added in v0.24.0

type AgentActivateResponse struct {
	Success bool `json:"success"`
}

AgentActivateResponse is the response body of POST /api/agent/activate.

type AgentCommand added in v0.24.0

type AgentCommand struct {
	ID      string          `json:"id"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

AgentCommand is a single command dispatched to the browser to execute (e.g. run a query, reconfigure the chart, read UI state). Payload is an opaque JSON blob whose shape depends on Type; the MCP tools and the web orchestrator agree on it.

type AgentRespondRequest added in v0.24.0

type AgentRespondRequest struct {
	ClientID  string            `json:"clientId"`
	RequestID string            `json:"requestId"`
	Type      agentResponseType `json:"type"`
	Data      json.RawMessage   `json:"data,omitempty"`
	Error     string            `json:"error,omitempty"`
}

AgentRespondRequest is the request body of POST /api/agent/respond. The browser posts heartbeats, command results, and errors back over this endpoint, keyed by the originating client and request IDs.

func (AgentRespondRequest) Validate added in v0.24.0

func (r AgentRespondRequest) Validate() error

Validate returns an error if a required field is missing.

type AgentRespondResponse added in v0.24.0

type AgentRespondResponse struct {
	Success bool `json:"success"`
}

AgentRespondResponse is the response body of POST /api/agent/respond.

type ArrowResultsRequest

type ArrowResultsRequest struct {
	ServiceRequest
	RunID uuid.UUID `json:"runId"`
}

ArrowResultsRequest is the request body of POST /api/arrowResults.

func (ArrowResultsRequest) Validate

func (r ArrowResultsRequest) Validate() error

Validate returns an error if a required field is missing.

type Bridge added in v0.24.0

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

Bridge is the communication channel between MCP tools (server side) and the browser UI (client side). Browser tabs subscribe to a Server-Sent Events stream; MCP tools dispatch commands to the single active client and await a response delivered back over a separate HTTP endpoint.

At most one command is in flight at a time (callers serialize via Request). Exactly one connected client is "active" at any moment; commands are only dispatched to it and responses are only accepted from it.

func NewBridge added in v0.24.0

func NewBridge() *Bridge

NewBridge creates an empty Bridge.

func (*Bridge) Activate added in v0.24.0

func (b *Bridge) Activate(clientID string) bool

Activate makes the given client the active one (the "take over" action). Any in-flight request dispatched to the previously-active client is failed. It is a no-op (returning false) if the client ID is unknown.

func (*Bridge) HasActiveClient added in v0.24.0

func (b *Bridge) HasActiveClient() bool

HasActiveClient reports whether a client is currently connected and active.

func (*Bridge) Request added in v0.24.0

func (b *Bridge) Request(ctx context.Context, commandType string, payload any) (json.RawMessage, error)

Request dispatches a command of the given type (with the given JSON- serializable payload) to the active browser client and waits for its response. Calls are serialized: a second Request blocks until the first completes. The request fails if the active client disconnects, another tab takes over, or no message (heartbeat or response) arrives within agentIdleTimeout.

func (*Bridge) WaitForActiveClient added in v0.24.0

func (b *Bridge) WaitForActiveClient(ctx context.Context) error

WaitForActiveClient blocks until an active client is connected, the context is canceled, or agentIdleTimeout elapses with no client. Returns nil once a client is active.

type CancelQueryRequest

type CancelQueryRequest struct {
	ServiceRequest
	RunID uuid.UUID `json:"runId"`
}

CancelQueryRequest is the request body of POST /api/cancelQuery.

func (CancelQueryRequest) Validate

func (r CancelQueryRequest) Validate() error

Validate returns an error if a required field is missing.

type CancelQueryResponse

type CancelQueryResponse struct {
	Success bool `json:"success"`
}

CancelQueryResponse is the response body of the POST /api/cancelQuery endpoint.

type ChartConfigHistoryEntry added in v0.24.0

type ChartConfigHistoryEntry struct {
	Config    string `json:"config"`
	Timestamp int64  `json:"ts"`
}

ChartConfigHistoryEntry is one entry in the chart config history: the full chart config source and when it was last recorded (epoch milliseconds). The web client owns dedup (identical configs are promoted, not duplicated).

type CloseSessionRequest

type CloseSessionRequest struct {
	ServiceRequest
	SessionID uuid.UUID `json:"sessionId"`
}

CloseSessionRequest is the request body of POST /api/closeSession.

func (CloseSessionRequest) Validate

func (r CloseSessionRequest) Validate() error

Validate returns an error if a required field is missing.

type CloseSessionResponse

type CloseSessionResponse struct {
	Success bool `json:"success"`
}

CloseSessionResponse is the response body of the POST /api/closeSession endpoint.

type CreateSessionRequest

type CreateSessionRequest struct {
	ServiceRequest
}

CreateSessionRequest is the request body of POST /api/createSession.

type CreateSessionResponse

type CreateSessionResponse struct {
	Success bool      `json:"success"`
	ID      uuid.UUID `json:"id"`
}

CreateSessionResponse is the response body of the POST /api/createSession endpoint.

type Database

type Database struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status string `json:"status"`
	Type   string `json:"type"`
}

Database is a single entry in a DatabasesResponse.

type DatabasesResponse

type DatabasesResponse struct {
	Databases []Database `json:"databases"`
}

DatabasesResponse is the response body of the GET /api/databases endpoint.

type EditorHistoryEntry added in v0.25.0

type EditorHistoryEntry struct {
	SQL       string `json:"sql"`
	Timestamp int64  `json:"ts"`
}

EditorHistoryEntry is one entry in the editor history: the full editor contents at the time it was recorded and when (epoch milliseconds). The web client owns dedup (identical contents are promoted, not duplicated).

type ExecuteQueryRequest

type ExecuteQueryRequest struct {
	ExecuteRequest
}

ExecuteQueryRequest is the request body of POST /api/executeQuery.

type ExecuteRequest

type ExecuteRequest struct {
	ServiceRequest
	RunID      uuid.UUID `json:"runId"`
	Query      string    `json:"query"`
	Statements []string  `json:"statements"`
}

ExecuteRequest holds the fields common to the executeQuery and executeSessionQuery endpoints. Clients send both a top-level query (legacy) and a statements array (the editor text split by the client's SQL parser); statements is preferred when present.

func (ExecuteRequest) Validate

func (r ExecuteRequest) Validate() error

Validate returns an error if a required field is missing.

type ExecuteSessionQueryRequest

type ExecuteSessionQueryRequest struct {
	ExecuteRequest
	SessionID uuid.UUID `json:"sessionId"`
}

ExecuteSessionQueryRequest is the request body of POST /api/executeSessionQuery.

func (ExecuteSessionQueryRequest) Validate

func (r ExecuteSessionQueryRequest) Validate() error

Validate returns an error if a required field is missing.

type GetBootstrapResponse

type GetBootstrapResponse struct {
	// ProjectID keeps the legacy "projectId" JSON key (rather than a space-based
	// name) for backwards-compatibility with the local web UI that consumes it.
	ProjectID string `json:"projectId"`
	Version   string `json:"version"`
	// ReadOnly reflects the read_only config option. When true, queries run by
	// this server use an immutable read-only connection, so the UI surfaces a
	// read-only indicator to the user.
	ReadOnly bool `json:"readOnly"`
	// UIQueryHistoryLimit reflects the ui_query_history_limit config option:
	// the maximum number of recent query runs (and their results) the UI keeps
	// in the in-memory results cache before evicting the oldest.
	UIQueryHistoryLimit int `json:"uiQueryHistoryLimit"`
}

GetBootstrapResponse is the response body of the GET /api/bootstrap endpoint.

type GetStateResponse

type GetStateResponse struct {
	State
}

GetStateResponse is the response body of the GET /api/state endpoint.

type Handler

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

func NewHandler

func NewHandler(config HandlerConfig) *Handler

func (*Handler) Handler

func (h *Handler) Handler() http.Handler

func (*Handler) NewSession

func (h *Handler) NewSession(ctx context.Context, dsn string) (session *Session, err error)

NewSession opens new database Session given a DSN. It returns an api.NormalizedError if the database connection could not be established, or if the connection attempt took longer than SessionOpenTimeout.

type HandlerConfig

type HandlerConfig struct {
	App    *common.App
	Store  *Store
	Logger *slog.Logger
	// Bridge is the optional agent communication channel. When non-nil, the
	// agent SSE/respond/activate endpoints are served, letting MCP tools drive
	// this UI. It is nil for a plain `ghost serve` (no MCP-driven control).
	Bridge *Bridge
}

type HealthResponse

type HealthResponse struct {
	Success bool `json:"success"`
}

HealthResponse is the response body of the GET /health endpoint.

type InvalidBoolQueryParamError

type InvalidBoolQueryParamError struct {
	ParamName string
	Value     string
}

InvalidBoolQueryParamError is returned when a query param expected to be a boolean cannot be parsed as one.

func (*InvalidBoolQueryParamError) Error

type InvalidContentTypeError

type InvalidContentTypeError struct {
	Required string
}

func (*InvalidContentTypeError) Error

func (e *InvalidContentTypeError) Error() string

type InvalidJSONBodyError

type InvalidJSONBodyError struct {
	Err error
}

func (*InvalidJSONBodyError) Error

func (e *InvalidJSONBodyError) Error() string

type InvalidRunIDError

type InvalidRunIDError struct {
	ID uuid.UUID
}

func (*InvalidRunIDError) Error

func (e *InvalidRunIDError) Error() string

type InvalidSessionIDError

type InvalidSessionIDError struct {
	ID uuid.UUID
}

func (*InvalidSessionIDError) Error

func (e *InvalidSessionIDError) Error() string

type Middleware

type Middleware func(handler http.Handler) http.Handler

type RequiredFieldError

type RequiredFieldError struct {
	Field string
}

RequiredFieldError is the error type returned when a required request body field is missing.

func (*RequiredFieldError) Error

func (e *RequiredFieldError) Error() string

Error implements the error interface.

type RequiredQueryParamError

type RequiredQueryParamError struct {
	ParamName string
}

RequiredQueryParamError is returned when a required query param is missing or empty.

func (*RequiredQueryParamError) Error

func (e *RequiredQueryParamError) Error() string

type ResultsUnavailableError

type ResultsUnavailableError struct {
	RunID uuid.UUID
}

func (*ResultsUnavailableError) Error

func (e *ResultsUnavailableError) Error() string

type Router

type Router struct {
	*httprouter.Router
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter(middleware ...Middleware) *Router

func (*Router) DELETE

func (r *Router) DELETE(path string, handler http.HandlerFunc, middleware ...Middleware)

func (*Router) GET

func (r *Router) GET(path string, handler http.HandlerFunc, middleware ...Middleware)

func (*Router) MethodNotAllowed

func (r *Router) MethodNotAllowed(handler http.HandlerFunc, middleware ...Middleware)

func (*Router) NotFound

func (r *Router) NotFound(handler http.HandlerFunc, middleware ...Middleware)

func (*Router) PATCH

func (r *Router) PATCH(path string, handler http.HandlerFunc, middleware ...Middleware)

func (*Router) POST

func (r *Router) POST(path string, handler http.HandlerFunc, middleware ...Middleware)

func (*Router) PUT

func (r *Router) PUT(path string, handler http.HandlerFunc, middleware ...Middleware)

type Run

type Run struct {
	// Unique identifier for the run.
	ID uuid.UUID

	// The list of SQL statements that the run is executing. Either this field
	// or Query will be present, but not both.
	Statements []string

	// The text of the SQL query that the run is executing. Either this field
	// or Statements will be present, but not both.
	Query string

	// Destinations and formats to write arrow records to.
	Outputs writer.Outputs

	// A function which, when called, triggers cancellation of the run.
	Cancel context.CancelFunc
}

Run represents an in-progress query. After being created via NewRun, it is passed to Session.Query, which executes the query against the database. All runs are stored in the Store until they complete or are canceled.

func NewRun

func NewRun(ctx context.Context, req ExecuteRequest) (*Run, context.Context)

NewRun creates a new Run from an ExecuteRequest, configured to stream results as Arrow over the results endpoint. It returns the fully initialized run, along with a context that is canceled when the run is canceled (via Run.Cancel or Run.Close). Runs do not time out.

func (*Run) Close

func (r *Run) Close()

Close cancels the run if it's still in progress, and cleans up associated resources.

func (*Run) FinalQuery

func (r *Run) FinalQuery() string

FinalQuery returns the run's query (or final statement in the statement list), which should be passed to driver.Driver.Query to execute the query. If there are additional statements in the statement list, they should be executed via Run.LeadingStatements before this query is executed.

func (*Run) LeadingStatements

func (r *Run) LeadingStatements() []string

LeadingStatements returns all of the statements in the run's statement list except the last (which is returned from Run.FinalQuery instead). Returns an empty list if the statement list is empty (because the Query field is being used instead) or only contains a single statement. The intention is for these statements to be executed sequentially via driver.Driver.Query, but without returning any results, before the run's final query is executed.

type RunFormatError

type RunFormatError struct {
	RunID  uuid.UUID
	Format api.OutputFormat
}

func (*RunFormatError) Error

func (e *RunFormatError) Error() string

type RunIDConflictError

type RunIDConflictError struct {
	ID uuid.UUID
}

func (*RunIDConflictError) Error

func (e *RunIDConflictError) Error() string

type SaveStateRequest

type SaveStateRequest struct {
	State
}

SaveStateRequest is the request body of the PUT /api/state endpoint.

type Server

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

Server is a wrapper around http.Server that encapsulates some standard configuration and boilerplate for starting and stopping the server.

func NewServer

func NewServer(host string, port int, handler http.Handler, logger *slog.Logger) *Server

NewServer creates a new instance of Server. The host may be empty to bind all interfaces, though callers should generally pass a loopback address (e.g. "localhost"). To start the server, call Server.Start.

func (*Server) Close

func (s *Server) Close() error

Close immediately shuts down the HTTP server started by Server.Start, closing all active connections without waiting for in-flight requests to complete. If Server.Start has not been called successfully, or if the HTTP server has already been closed, Close is a no-op. Note that it is not safe to call this method concurrently with itself or Server.Start.

func (*Server) Errors

func (s *Server) Errors() <-chan error

Errors returns a channel on which server errors are returned. Returns a nil channel if the server is not running (e.g. Server.Start has not yet been called or if Server.Close has already been called).

func (*Server) Start

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

Start starts listening for incoming HTTP requests on the configured host and port. If the port is 0, an ephemeral port is chosen, and the stored port is subsequently updated to the chosen port (useful in automated tests). Note that the context argument only controls the cancellation of this function itself - once started, the server can only be stopped by calling Server.Close.

func (*Server) URL

func (s *Server) URL() string

URL returns the http URL clients should connect to (with the OS-chosen port if the configured port was 0). Only accurate after Server.Start has been called.

type ServiceRequest

type ServiceRequest struct {
	// ProjectID keeps the legacy "projectId" JSON key (rather than a space-based
	// name) for backwards-compatibility with the local web UI that sends it.
	ProjectID string `json:"projectId"`
	ServiceID string `json:"serviceId"`
}

ServiceRequest holds the fields common to every query endpoint: the space and database ("service") the request targets.

func (ServiceRequest) Validate

func (r ServiceRequest) Validate() error

Validate returns an error if a required field is missing.

type Session

type Session struct {
	// Unique identifier for the session, which is automatically generated when
	// the session is created.
	ID uuid.UUID
	// contains filtered or unexported fields
}

Session represents a user's database connection. Ephemeral sessions are closed automatically after a run, but long-lived sessions are stored in the Store until explicitly removed, or until the session times out.

func (*Session) Broken

func (s *Session) Broken() bool

Broken reports whether the underlying database connection has been broken, at which point the session can no longer be used. This is set to true after a query using the session returns a fatal error, or if a database ping fails.

func (*Session) Close

func (s *Session) Close() error

Close attempts to close the underlying database connection. It will wait for any in-progress queries to finish before closing the connection and returning.

func (*Session) Events

func (s *Session) Events(ctx context.Context) <-chan api.Event

Events returns a channel on which session status events are returned. Pings the database periodically to check the health of the connection and generate status events. The channel is closed when the context is canceled, the session is closed, or a connection ping fails. In the future, this could return other types of session events as well (e.g. NOTICE or LISTEN/NOTIFY messages).

func (*Session) Query

func (s *Session) Query(ctx context.Context, run *Run) <-chan api.Result

Executes a query on the session and streams the results back via a channel. It is the caller's responsibility to fully drain the channel (even when the run has been canceled) or it could result in a leaked goroutine and database connection.

func (*Session) SetBroken

func (s *Session) SetBroken()

SetBroken marks the underlying database connection as broken, which signals for it to be closed and deleted from the store.

type SessionEventsRequest

type SessionEventsRequest struct {
	ServiceRequest
	SessionID uuid.UUID `json:"sessionId"`
}

SessionEventsRequest is the request body of POST /api/sessionEvents.

func (SessionEventsRequest) Validate

func (r SessionEventsRequest) Validate() error

Validate returns an error if a required field is missing.

type SessionIDConflictError

type SessionIDConflictError struct {
	ID uuid.UUID
}

func (*SessionIDConflictError) Error

func (e *SessionIDConflictError) Error() string

type State

type State struct {
	SelectedDatabaseID string `json:"selectedDatabaseId,omitempty"`
	EditorHeight       int    `json:"editorHeight,omitempty"`
	EditorSQL          string `json:"editorSql,omitempty"`
	SchemaPaneWidth    int    `json:"schemaPaneWidth,omitempty"`
	// SchemaPaneVisible is a pointer so that an explicit false (pane hidden) is
	// persisted; the web client defaults a missing value to true.
	SchemaPaneVisible  *bool               `json:"schemaPaneVisible,omitempty"`
	SchemaTreeExpanded map[string][]string `json:"schemaTreeExpanded,omitempty"`
	// ShowInternalObjects controls whether the schema browser includes system
	// schemas and extension-owned objects. Defaults to false (a plain bool, not
	// a pointer, since the web client also defaults a missing value to false).
	ShowInternalObjects bool `json:"showInternalObjects,omitempty"`
	// ResultView selects what's shown below the query editor: the results table,
	// the rendered chart, or the chart config editor.
	ResultView string `json:"resultView,omitempty"`
	// ChartConfig is the user's chart config source (the body of the chart
	// function), persisted so it survives reloads.
	ChartConfig string `json:"chartConfig,omitempty"`
	// ChartEditorWidth is the width (px) of the chart config editor pane in the
	// editor/preview split.
	ChartEditorWidth int `json:"chartEditorWidth,omitempty"`
	// EditorHistory is the list of past editor drafts (full editor contents
	// recorded as the user edits), newest first. Each PUT replaces it wholesale;
	// the web client owns dedup and capping. (Query history — distinct runs and
	// their results — is kept in-memory only by the web client and never
	// persisted here.)
	EditorHistory []EditorHistoryEntry `json:"editorHistory,omitempty"`
	// ChartConfigHistory is the list of previously used chart configs, newest
	// first. Like EditorHistory, each PUT replaces it wholesale; the web client
	// owns dedup and capping.
	ChartConfigHistory []ChartConfigHistoryEntry `json:"chartConfigHistory,omitempty"`
}

State is the persisted UI state for `ghost serve`, shared by the GET and PUT /api/state endpoints. A PUT replaces the stored state wholesale, so clients send the full snapshot; omitempty just keeps zero-valued fields out of the JSON.

type Store

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

Store maintains in-memory lookups of all current sessions and in-progress runs (keyed by ID), and persists the serve UI state to disk.

func NewStore

func NewStore(configDir string, logger *slog.Logger) *Store

NewStore initializes and returns a new Store instance. configDir is the directory in which the serve UI state file is persisted.

func (*Store) AcquireSession

func (s *Store) AcquireSession(sessionID uuid.UUID) (*Session, error)

AcquireSession retrieves a session from the store and returns it. It also pauses the session timeout, if active (i.e. if it was not already paused by another acquisition). ReleaseSession should be called when the session is done being used to reset the timeout.

func (*Store) Close

func (s *Store) Close()

Close attempts to close all outstanding database sessions and remove them from the store. It waits for any in-progress queries to complete before returning. Errors closing or removing database connections are logged.

func (*Store) DeleteRun

func (s *Store) DeleteRun(run *Run)

func (*Store) DeleteSession

func (s *Store) DeleteSession(session *Session)

func (*Store) GetRun

func (s *Store) GetRun(runID uuid.UUID) (*Run, error)

func (*Store) GetSession

func (s *Store) GetSession(sessionID uuid.UUID) (*Session, error)

GetSession retrieves a session from the store and returns it. It does not pause or extend the session timeout. If the session is being retrieved in order to be used by an end-user (e.g. in order to run a query or listen for session status events), Store.AcquireSession should be used instead.

func (*Store) InsertRun

func (s *Store) InsertRun(run *Run) error

func (*Store) InsertSession

func (s *Store) InsertSession(session *Session) error

func (*Store) LoadState

func (s *Store) LoadState() (State, error)

LoadState reads the persisted serve UI state from the store's state file. A missing file is not an error - it yields a zero State.

func (*Store) ReleaseSession

func (s *Store) ReleaseSession(session *Session)

ReleaseSession resets the session timeout that was paused by a call to Store.AcquireSession, if there are no other callers still using the session. It should always be called when a session obtained via that method is done being used. Failure to call it could create a leaked session that is never closed.

func (*Store) SaveState

func (s *Store) SaveState(state State) error

SaveState persists the serve UI state to the store's state file. Writes are atomic (temp file + rename) and serialized via stateLock so concurrent PUTs can't interleave.

func (*Store) TryCloseSession

func (s *Store) TryCloseSession(ctx context.Context, session *Session)

func (*Store) TryDeleteRun

func (s *Store) TryDeleteRun(ctx context.Context, run *Run)

func (*Store) TryDeleteSession

func (s *Store) TryDeleteSession(ctx context.Context, session *Session)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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