adminapi

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package adminapi is what a mock server and its admin API share: what the server gives the admin API, its Capabilities, and the API that serves them. Mock servers import it, never the admin API itself, so a server without an admin API links neither the admin server nor what it serves with, such as MCP.

Index

Constants

View Source
const (
	// EventMatched is a request a mock answered.
	EventMatched = "matched"
	// EventUnmatched is a request no mock matched.
	EventUnmatched = "unmatched"
	// EventProxied is a request the server proxied.
	EventProxied = "proxied"
	// EventWarning is something that went wrong, but didn't fail the request, such as a webhook that failed.
	EventWarning = "warning"
	// EventError is a request that failed.
	EventError = "error"
	// EventScenario is a move of a scenario: by the mock a request picked, or by the server's SetScenario,
	// ResetScenario or ResetScenarios, which the admin API calls. Target names the scenario, in any case.
	EventScenario = "scenario"
)

Types of the events of a mock server.

View Source
const (
	// FileStoreFormat is the format of the mock files a FileStore writes.
	FileStoreFormat = "yaml"

	// FileStoreTempPattern names the files a FileStore is writing: never *.mock.*, so reading the store skips them.
	FileStoreTempPattern = ".admin-*.tmp"
)
View Source
const Origin = "admin"

Origin is the origin of the mocks the admin API adds. A mock server's builder gives it to the mocks it builds for the admin API, so the admin API tells them from mocks of files and code.

Variables

View Source
var ErrForeignMock = errors.New("admin: the mock isn't of the server's type")

ErrForeignMock is the error of a mock that isn't of the type of the mocks of the server, such as an HTTP mock given to a gRPC server.

View Source
var ErrNotDescribed = errors.New("admin: the mock can't be described as a mock file")

ErrNotDescribed is the error of a mock that can't be described as a mock file, such as one with a Handler reply.

Functions

This section is empty.

Types

type API

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

API is the handle of the built-in admin API. Only its constructor in package admin initializes it.

func NewAPI

func NewAPI(serve func(Capabilities) (Server, error), serveMCP func(context.Context, io.Reader, io.Writer) error) *API

NewAPI makes the handle of the built-in admin API, whose implementation binds capabilities with serve and serves MCP over stdio with serveMCP. It imports neither implementation into a mock server.

func (*API) ServeMCP

func (api *API) ServeMCP(ctx context.Context, in io.Reader, out io.Writer) error

ServeMCP serves the admin operations over MCP on in and out, newline-delimited JSON-RPC, until in ends or ctx is done. Nothing else may write to out, such as logs. It needs the MCP option and a mock server created with the admin API; the mock server's Close waits for the calls it serves.

type Capabilities

type Capabilities struct {
	// Kind is the kind of the mock server, such as http.
	Kind string

	// URL returns where the server serves its mocks: its URL, or its address for gRPC.
	URL func() string

	// Logger logs the admin API's internal errors. Nil logs nothing.
	Logger *zerolog.Logger

	// Mocks are the mocks of the server. The admin API needs them.
	Mocks Mocks

	Files     Files
	Recorder  Recorder
	Scenarios Scenarios
	Events    *Events
	Logs      *Logs
	Journal   Journal

	// KV is the key-value store the server's templates read. POST /kv/reload reloads it when it is a
	// [vlatte.KVReloader].
	KV vlatte.KV

	// Pattern makes the filter of the request part of a mock of the server's protocol, for a query of the journal.
	// Nil, for a protocol that has none, takes no request part.
	Pattern RequestPattern

	// Matchers builds the matcher lists of a query of the journal, as it does the server's mock files. Nil builds the
	// built-in matchers only.
	Matchers *matchbuild.Registry

	// MockSchema is the JSON Schema of the server's mock files, a JSON document, for clients that write them.
	MockSchema []byte
}

Capabilities are what a mock server gives its admin API. A nil one is one it lacks: the operations that need it answer that the server can't do them.

type Event

type Event struct {
	Type      string    `json:"type"`
	Time      time.Time `json:"time"`
	RequestID string    `json:"request_id,omitempty"`
	Method    string    `json:"method,omitempty"`
	Target    string    `json:"target,omitempty"`
	MockID    string    `json:"mock_id,omitempty"`
	Status    int       `json:"status,omitzero"`
	Message   string    `json:"message,omitempty"`
}

Event is something that happened on a mock server, as GET /events streams it.

type Events

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

Events are the events of a mock server, which it publishes and GET /events streams. It keeps none: the journal, GET /requests, keeps the requests.

func NewEvents

func NewEvents() *Events

NewEvents creates the events of a mock server.

func (*Events) Close

func (e *Events) Close()

Close ends the streams of GET /events.

func (*Events) Publish

func (e *Events) Publish(event Event)

Publish sends e to the clients of GET /events. It never waits for them.

func (*Events) ServeHTTP

func (e *Events) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP streams the events of the mock server, as they happen, as Server-Sent Events: GET /events. Each event is a JSON Event, of the event type its type names.

type FileStore

type FileStore[M vlatte.Mock] struct {
	// contains filtered or unexported fields
}

FileStore keeps the mocks of the admin API as mock files, <id>.mock.yaml in a directory: a persistent store of a mock server's admin mocks. Its changes are serialized, and change its files all or nothing. Pick, PickAll and List build new mocks from the files each time. A mock whose description doesn't load back is refused: its file would fail every later start.

func NewFileStore

func NewFileStore[M vlatte.Mock](
	dir string,
	encode func(mock M) ([]byte, error),
	decode func(origin string, data []byte, format string) (M, error),
	remove func(name string) error,
) *FileStore[M]

NewFileStore returns the store of the mock files of dir. encode describes a mock as its file holds it, in FileStoreFormat. decode builds a mock the admin API added from data, a mock file in format: origin is where its problems point, such as "file <path>". remove removes a file: os.Remove, or one that fails, as a file system can.

func (*FileStore[M]) Clear

func (s *FileStore[M]) Clear(context.Context) error

Clear removes every file of the store.

func (*FileStore[M]) Delete

func (s *FileStore[M]) Delete(_ context.Context, ids ...string) error

Delete removes the files of the mocks of ids.

func (*FileStore[M]) Health

func (s *FileStore[M]) Health(context.Context) error

Health returns an error when the store's directory can't be read. A directory that doesn't exist yet is ready: the first mock the store keeps makes it.

func (*FileStore[M]) List

func (s *FileStore[M]) List(ctx context.Context) (iter.Seq[M], error)

List returns the enabled mocks of the files.

func (*FileStore[M]) Pick

func (s *FileStore[M]) Pick(_ context.Context, id string) (M, error)

Pick builds the mock of id from its file.

func (*FileStore[M]) PickAll

func (s *FileStore[M]) PickAll(context.Context) ([]M, error)

PickAll builds the mocks of every file, in file name order. When a file has problems, it builds none, and reports every file with problems.

func (*FileStore[M]) Replace

func (s *FileStore[M]) Replace(_ context.Context, old []M, mocks ...M) error

Replace writes the files of mocks, then removes those of the mocks of old it doesn't write again. Every mock is described and checked first: when one fails, nothing is written. When a file can't be written or removed, the files it changed are put back.

func (*FileStore[M]) Store

func (s *FileStore[M]) Store(ctx context.Context, mocks ...M) error

Store writes the files of mocks.

type Files

type Files interface {
	// Reload loads the mocks of the server's sources again, its mock files and its persistent store, in place of the
	// mocks they gave before.
	Reload() error

	// SaveMocks writes the mocks the admin API added as mock files, in format, into dir, a local path that starts at
	// the server's root directory, then serves them from the files, which load from then on. Empty dir and format are
	// the server's defaults. It returns the files' paths. An error that wraps ErrNotDescribed wrote nothing, and one
	// of files that failed to load put them back as they were.
	SaveMocks(ctx context.Context, dir, format string) ([]string, error)
}

Files is a mock server that serves mock files.

type Journal

type Journal interface {
	verify.Journal
	Get(id string) (*journal.Entry, error)
	Clear() error
}

Journal is the journal of the requests a mock server serves, such as a *journal.Journal.

type Logs

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

Logs are the log lines of a mock server, which its logger writes and GET /logs streams. It keeps none.

func NewLogs

func NewLogs() *Logs

NewLogs creates the logs of a mock server.

func (*Logs) Close

func (l *Logs) Close()

Close ends the streams of GET /logs.

func (*Logs) ServeHTTP

func (l *Logs) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP streams the log lines of the mock server, as it writes them, as Server-Sent Events of type log: GET /logs.

func (*Logs) Write

func (l *Logs) Write(p []byte) (int, error)

Write sends p, a log line, to the clients of GET /logs. It never waits for them, and never fails, so the logger it writes for never does either.

type Mocks

type Mocks interface {
	Pick(ctx context.Context, id string) (vlatte.Mock, error)
	PickAll(ctx context.Context) ([]vlatte.Mock, error)

	// Store and Replace fail with ErrForeignMock, changing nothing, for a mock of another type than the server's.
	Store(ctx context.Context, mocks ...vlatte.Mock) error
	Replace(ctx context.Context, old []vlatte.Mock, mocks ...vlatte.Mock) error

	Clear(ctx context.Context) error
	Health(ctx context.Context) error

	// Build builds the mock of doc, a mock file in format. It needs a server that builds mocks: see Builds.
	Build(doc []byte, format string) (vlatte.Mock, error)

	// Builds reports whether the server builds mocks from mock files.
	Builds() bool
}

Mocks are the mocks of a mock server, whatever their type: the admin API works on them as vlatte.Mock. Its methods are those of vlatte.Store, and Build builds a mock of the server's type from a mock file.

func MocksOf

func MocksOf[M vlatte.Mock](store vlatte.Store[M], build vlatte.MockBuilder[M]) Mocks

MocksOf returns the mocks of store, which build makes from mock files. With a nil build, the server makes no mocks from mock files.

type Recorder

type Recorder interface {
	// StartRecording starts a recording with the settings of doc, a document in format with the keys of the record
	// section of the server's settings; an empty one keeps them. It returns vlatte.ErrRecording while a recording runs,
	// and a *config.Error when doc has problems.
	StartRecording(doc []byte, format string) error

	// StopRecording stops the recording, waits until it wrote what it took, and serves it. It returns
	// vlatte.ErrNotRecording when none runs. A result with an error tells what wasn't recorded or served.
	StopRecording(ctx context.Context) (*vlatte.RecordResult, error)

	// RecordingStatus counts the calls of the recording, or is zero when none runs.
	RecordingStatus() vlatte.RecordStatus
}

Recorder is a mock server that records what it proxies as mock files.

type RequestPattern

type RequestPattern func(v config.Value) (verify.Pattern, error)

RequestPattern makes the pattern of the request part of a mock of the server's protocol, v, as a mock file writes it: the request key of a query.

type Scenarios

type Scenarios interface {
	// Scenarios returns every scenario, by name, with its state, the states its mocks name, and their moves.
	Scenarios(ctx context.Context) ([]matchscenario.Scenario, error)

	// SetScenario moves the scenario name to state: its shared instance, or the one in picks. It returns an error that
	// wraps matchscenario.ErrUnknownState when no mock of the scenario names state.
	SetScenario(ctx context.Context, name, state string, in ...matchscenario.Instance) error

	// ResetScenario moves the scenario name back to where it started: every instance of it, or the one in picks.
	ResetScenario(name string, in ...matchscenario.Instance)

	// ResetScenarios moves every scenario back to where it started.
	ResetScenarios()
}

Scenarios is a mock server that keeps the state of scenarios: mocks that match in turn.

type Server

type Server interface {
	// Start serves the admin API. It starts once.
	Start() error

	// URL returns the base URL of the admin API, or "" before it starts.
	URL() string

	// Close stops the admin API, and waits for the operations it runs. A closed server doesn't start again.
	Close() error
}

Server is the admin API of one mock server.

func Serve

func Serve(api *API, caps Capabilities) (Server, error)

Serve binds api to the mock server of caps, returning its admin server, not started yet.

type Store

type Store[M vlatte.Mock] struct {
	// contains filtered or unexported fields
}

Store is the store the admin API changes mocks through, when the mock server keeps them in a persistent store too, such as files or a database. It serves from the server's store, which holds every mock and keeps their state, such as their hits, and writes each change through to the persistent store at once, so the mocks the admin API adds outlive the server. Reload picks up what the persistent store holds, such as changes made to it directly.

The persistent store tells mocks apart by ID: it keeps their descriptions, not the mocks themselves. The mocks the server has from elsewhere, such as mock files and code, never reach it: the server stores them in its store directly.

func NewStore

func NewStore[M vlatte.Mock](serving, durable vlatte.Store[M], logger *zerolog.Logger) *Store[M]

NewStore returns the store of the admin API of a mock server whose store is serving, and whose persistent store is durable. logger tells which mocks of durable give way to mocks the server has from elsewhere; nil logs nothing.

func (*Store[M]) Clear

func (s *Store[M]) Clear(ctx context.Context) error

Clear deletes every mock from the persistent store, then from the server's, those of mock files and code too.

func (*Store[M]) Delete

func (s *Store[M]) Delete(ctx context.Context, ids ...string) error

Delete deletes the mocks of ids from the persistent store, then from the server's.

func (*Store[M]) Health

func (s *Store[M]) Health(ctx context.Context) error

Health returns the errors of the persistent store and of the server's.

func (*Store[M]) List

func (s *Store[M]) List(ctx context.Context) (iter.Seq[M], error)

List returns the enabled mocks the server serves.

func (*Store[M]) Pick

func (s *Store[M]) Pick(ctx context.Context, id string) (M, error)

Pick returns the mock of id the server serves.

func (*Store[M]) PickAll

func (s *Store[M]) PickAll(ctx context.Context) ([]M, error)

PickAll returns every mock the server serves.

func (*Store[M]) Reload

func (s *Store[M]) Reload(ctx context.Context, load func(swap vlatte.Swap[M]) error) error

Reload serves what the persistent store holds now, in place of the mocks it served from it: the changes made to it directly take effect. load, when not nil, loads the server's mock files, with swap: it swaps the mocks of the persistent store in the same step as those of the files, so a request finds the old ones or the new ones, never a mix. A load that doesn't call swap, such as one with no mock files to load, leaves Reload to swap them on its own. A mock whose ID a mock the server has from elsewhere holds, such as a mock file's, gives way to it, as mocks the admin API adds do. Reload is all or nothing: when the persistent store can't be read, load doesn't run, and when load fails, the server serves what it served before.

func (*Store[M]) Replace

func (s *Store[M]) Replace(ctx context.Context, old []M, mocks ...M) error

Replace replaces old with mocks in the persistent store, then in the server's. A mock of old that mocks holds again is written again, as an edit of its state, such as its enabled state, is persisted, and keeps its place. A mock of old the server no longer serves, such as one a reload replaced since it was picked, is left out, as the server's store leaves it out: the mock that took its id since, and its description, stay. When the server's store refuses mocks, the persistent store gets back the mocks of old it held.

func (*Store[M]) Store

func (s *Store[M]) Store(ctx context.Context, mocks ...M) error

Store stores mocks in the persistent store, then serves them. When the server's store refuses them, such as for an ID a mock file's mock holds, the persistent store doesn't keep them either.

Jump to

Keyboard shortcuts

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