stuber

package
v3.23.8 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DumpFormatYAML = "yaml"
	DumpFormatJSON = "json"
)
View Source
const (
	// InternalStubIDGripmockHealthCheck is the reserved ID for internal gripmock health Check stub.
	InternalStubIDGripmockHealthCheck = "ffffffff-ffff-ffff-ffff-ffffffffffff"

	// InternalStubIDGripmockHealthWatch is the reserved ID for internal gripmock health Watch stub.
	InternalStubIDGripmockHealthWatch = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"
)
View Source
const (
	ListSortPriorityDesc = "priority_desc"
	ListSortPriorityAsc  = "priority_asc"
	ListSortServiceAsc   = "service_asc"
	ListSortMethodAsc    = "method_asc"
)
View Source
const (
	// RequestInternalFlag is a feature flag for internal requests.
	RequestInternalFlag features.Flag = iota

	// MatchInternalStubsFlag allows a query to match the reserved internal stubs
	// (the gripmock health status). It is set ONLY by the gRPC health service so
	// internal stubs stay invisible to user-facing search/inspect/list/MCP.
	MatchInternalStubsFlag
)
View Source
const (
	SourceFile  = "file"
	SourceRest  = "rest"
	SourceMCP   = "mcp"
	SourceProxy = "proxy"
)
View Source
const (
	EffectActionUpsert = "upsert"
	EffectActionDelete = "delete"
)
View Source
const GripMockKey = "_gripmock"

GripMockKey is the reserved map key for per-element stream metadata.

View Source
const PriorityMultiplier = 10.0

PriorityMultiplier is used to boost stub priority in ranking calculations. Higher values give more weight to explicit priority settings.

Variables

View Source
var (
	ErrUnknownDumpSource = errors.New("unknown dump source")
	ErrUnknownDumpFormat = errors.New("unknown dump format")
)
View Source
var ErrLeftNotFound = errors.New("left not found")

ErrLeftNotFound is returned when the left value is not found.

View Source
var ErrMethodNotFound = errors.New("method not found")

ErrMethodNotFound is returned when the method is not found.

View Source
var ErrRightNotFound = errors.New("right not found")

ErrRightNotFound is returned when the right value is not found.

View Source
var ErrServiceNotFound = errors.New("service not found")

ErrServiceNotFound is returned when the service is not found.

View Source
var ErrStubNotFound = errors.New("stub not found")

ErrStubNotFound is returned when the stub is not found.

Functions

func DumpFileKey added in v3.10.1

func DumpFileKey(stub *Stub) string

func DumpToDir added in v3.10.1

func DumpToDir(outDir string, stubs []*Stub, format string) (int, error)

func ExtractGripMockDelay added in v3.16.0

func ExtractGripMockDelay(m map[string]any) (types.Delay, bool)

func HandlerCandidate added in v3.20.0

func HandlerCandidate(stub *Stub, query QueryBidi) bool

func IsKnownSource added in v3.10.1

func IsKnownSource(source string) bool

func SetupGripmockHealthStubs added in v3.9.3

func SetupGripmockHealthStubs(storage InternalStubStorage)

SetupGripmockHealthStubs creates internal stubs for gripmock health service. These stubs are hidden from user APIs and take precedence in matching. The stubs are initially set to NOT_SERVING and should be updated via UpdateGripmockHealthStatus when the server becomes ready.

func SortForDump added in v3.10.1

func SortForDump(stubs []*Stub)

func SortStubs added in v3.18.0

func SortStubs(stubs []*Stub, mode string)

SortStubs sorts an already-materialized stub slice in place using the same modes as List (ListSort* constants). Exposed for callers that filter stubs outside the storage iterator (e.g. the MCP used/unused sets) yet want ordering consistent with the REST /stubs listing.

func UpdateGripmockHealthStatus added in v3.9.3

func UpdateGripmockHealthStatus(storage InternalStubStorage, status healthgrpc.HealthCheckResponse_ServingStatus)

UpdateGripmockHealthStatus updates the status by re-inserting stubs. This ensures thread-safe update via storage's internal locking.

func ValidateDumpFormat added in v3.10.1

func ValidateDumpFormat(format string) error

func ValidateDumpSource added in v3.10.1

func ValidateDumpSource(source string) error

func VisibleForSession added in v3.22.0

func VisibleForSession(stubSession, querySession string) bool

VisibleForSession reports whether a stub is visible to a caller in querySession: global stubs are visible to everyone, session stubs only to their own session.

func WriteDump added in v3.10.1

func WriteDump(writer io.Writer, stubs []*Stub, format string) error

Types

type Aliveness added in v3.9.3

type Aliveness interface {
	SetAlive()
}

type AnyOfElement added in v3.11.0

type AnyOfElement struct {
	IgnoreArrayOrder bool           `json:"ignoreArrayOrder,omitempty"`
	Equals           map[string]any `json:"equals"`
	Contains         map[string]any `json:"contains"`
	Matches          map[string]any `json:"matches"`
	Glob             map[string]any `json:"glob,omitempty"`
}

AnyOfElement is a flat alternative matcher inside InputData.

type AnyOfHeaderElement added in v3.11.0

type AnyOfHeaderElement struct {
	Equals   map[string]any `json:"equals"`
	Contains map[string]any `json:"contains"`
	Matches  map[string]any `json:"matches"`
	Glob     map[string]any `json:"glob,omitempty"`
}

AnyOfHeaderElement is a flat alternative matcher inside InputHeader.

type BidiResult

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

BidiResult holds matching stubs for bidirectional streaming.

func (*BidiResult) GetMessageIndex

func (br *BidiResult) GetMessageIndex() int

GetMessageIndex returns the current message index in the bidirectional stream (0-based).

func (*BidiResult) MatchNumber added in v3.21.0

func (br *BidiResult) MatchNumber() int

func (*BidiResult) Next

func (br *BidiResult) Next(messageData map[string]any) (*Stub, error)

Next processes the next message in the bidirectional stream and returns the matching stub.

type Budgerigar

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

func NewBudgerigar

func NewBudgerigar() *Budgerigar

func (*Budgerigar) All

func (b *Budgerigar) All() []*Stub

All returns all Stub values.

func (*Budgerigar) Clear

func (b *Budgerigar) Clear()

Clear removes all Stub values.

func (*Budgerigar) DeleteByID

func (b *Budgerigar) DeleteByID(ids ...uuid.UUID) int

DeleteByID deletes the Stub values with the given IDs from the Budgerigar's searcher.

func (*Budgerigar) DeleteSession added in v3.7.1

func (b *Budgerigar) DeleteSession(session string) int

DeleteSession deletes all stubs that belong to the provided session. Empty session is treated as global and is not deleted by this method.

func (*Budgerigar) FindBy

func (b *Budgerigar) FindBy(service, method string) ([]*Stub, error)

FindBy retrieves all Stub values that match the given service and method from the Budgerigar's searcher, sorted by priority score in descending order.

func (*Budgerigar) FindByID

func (b *Budgerigar) FindByID(id uuid.UUID) *Stub

FindByID retrieves the Stub value associated with the given ID.

func (*Budgerigar) FindByQuery

func (b *Budgerigar) FindByQuery(query Query) (*Result, error)

FindByQuery retrieves the Stub value associated with the given Query.

func (*Budgerigar) FindByQueryBidi

func (b *Budgerigar) FindByQueryBidi(query QueryBidi) (*BidiResult, error)

FindByQueryBidi retrieves a BidiResult for bidirectional streaming.

func (*Budgerigar) InspectQuery added in v3.8.2

func (b *Budgerigar) InspectQuery(query Query) InspectReport

func (*Budgerigar) List added in v3.10.1

func (b *Budgerigar) List(options ListOptions) ([]*Stub, int)

List returns filtered stubs and total before pagination.

func (*Budgerigar) PutMany

func (b *Budgerigar) PutMany(values ...*Stub) []uuid.UUID

PutMany inserts the given Stub values. Assigns UUIDs to stubs without IDs.

func (*Budgerigar) Sessions added in v3.8.2

func (b *Budgerigar) Sessions() []string

Sessions returns sorted non-empty session IDs known by storage.

func (*Budgerigar) SetAlive added in v3.9.3

func (b *Budgerigar) SetAlive()

SetAlive marks internal gripmock health stubs as SERVING.

func (*Budgerigar) Unused

func (b *Budgerigar) Unused() []*Stub

Unused returns all Stub values that have not been used.

func (*Budgerigar) UpdateMany

func (b *Budgerigar) UpdateMany(values ...*Stub) []uuid.UUID

UpdateMany updates stubs that have non-nil IDs.

func (*Budgerigar) Used

func (b *Budgerigar) Used() []*Stub

Used returns all Stub values that have been used.

func (*Budgerigar) UsedIDs added in v3.18.0

func (b *Budgerigar) UsedIDs() map[uuid.UUID]struct{}

UsedIDs returns the set of stub IDs that have matched at least once.

type ClientStreamHandler added in v3.20.0

type ClientStreamHandler func(ctx context.Context, messages []any) (any, error)

type Effect added in v3.11.0

type Effect struct {
	Action string         `json:"action"`
	ID     string         `json:"id,omitempty"`
	Stub   map[string]any `json:"stub,omitempty"`
}

Effect represents a side effect executed after stub match.

type GripMockElement added in v3.19.0

type GripMockElement struct {
	Delay    types.Delay
	HasDelay bool

	Error    string
	Code     *codes.Code
	Details  []map[string]any
	HasError bool
}

func ExtractGripMock added in v3.19.0

func ExtractGripMock(m map[string]any) GripMockElement

type InputData

type InputData struct {
	Equals           map[string]any `json:"equals"`
	Contains         map[string]any `json:"contains"`
	Matches          map[string]any `json:"matches"`
	Glob             map[string]any `json:"glob,omitempty"`
	AnyOf            []AnyOfElement `json:"anyOf,omitempty"`
	IgnoreArrayOrder bool           `json:"ignoreArrayOrder,omitempty"`
}

InputData represents the input data of a gRPC request.

func (InputData) GetContains

func (i InputData) GetContains() map[string]any

GetContains returns the data to match partially.

func (InputData) GetEquals

func (i InputData) GetEquals() map[string]any

GetEquals returns the data to match exactly.

func (InputData) GetMatches

func (i InputData) GetMatches() map[string]any

GetMatches returns the data to match using regular expressions.

type InputHeader

type InputHeader struct {
	Equals   map[string]any       `json:"equals"`
	Contains map[string]any       `json:"contains"`
	Matches  map[string]any       `json:"matches"`
	Glob     map[string]any       `json:"glob,omitempty"`
	AnyOf    []AnyOfHeaderElement `json:"anyOf,omitempty"`
}

InputHeader represents the headers of a gRPC request.

func (InputHeader) GetContains

func (i InputHeader) GetContains() map[string]any

GetContains returns the headers to match partially.

func (InputHeader) GetEquals

func (i InputHeader) GetEquals() map[string]any

GetEquals returns the headers to match exactly.

func (InputHeader) GetMatches

func (i InputHeader) GetMatches() map[string]any

GetMatches returns the headers to match using regular expressions.

func (InputHeader) Len

func (i InputHeader) Len() int

Len returns the total number of headers to match.

type InspectCandidate added in v3.8.2

type InspectCandidate struct {
	ID               uuid.UUID               `json:"id"`
	Service          string                  `json:"service"`
	Method           string                  `json:"method"`
	Session          string                  `json:"session,omitempty"`
	Priority         int                     `json:"priority"`
	Times            int                     `json:"times"`
	Used             int                     `json:"used"`
	VisibleBySession bool                    `json:"visibleBySession"`
	WithinTimes      bool                    `json:"withinTimes"`
	HeadersMatched   bool                    `json:"headersMatched"`
	InputMatched     bool                    `json:"inputMatched"`
	Matched          bool                    `json:"matched"`
	Specificity      int                     `json:"specificity"`
	Score            float64                 `json:"score"`
	ExcludedBy       []string                `json:"excludedBy,omitempty"`
	Events           []InspectCandidateEvent `json:"events,omitempty"`
}

type InspectCandidateEvent added in v3.8.2

type InspectCandidateEvent struct {
	Stage  string `json:"stage"`
	Result string `json:"result"`
	Reason string `json:"reason,omitempty"`
}

type InspectReport added in v3.8.2

type InspectReport struct {
	Service          string             `json:"service"`
	Method           string             `json:"method"`
	Session          string             `json:"session,omitempty"`
	FallbackToMethod bool               `json:"fallbackToMethod"`
	Error            *string            `json:"error,omitempty"`
	MatchedStubID    *uuid.UUID         `json:"matchedStubId,omitempty"`
	SimilarStubID    *uuid.UUID         `json:"similarStubId,omitempty"`
	Stages           []InspectStage     `json:"stages"`
	Candidates       []InspectCandidate `json:"candidates"`
}

type InspectStage added in v3.8.2

type InspectStage struct {
	Name    string `json:"name"`
	Before  int    `json:"before"`
	After   int    `json:"after"`
	Removed int    `json:"removed"`
}

type InternalStubStorage added in v3.9.3

type InternalStubStorage interface {
	// PutInternal adds stubs to the internal storage (hidden from users).
	// This is the ONLY way to add internal stubs.
	PutInternal(stubs ...*Stub) []uuid.UUID

	// FindAllAvailable finds stubs by service/method in internal storage.
	FindAllAvailable(service, method, session string) (iter.Seq[*Stub], error)
}

InternalStubStorage defines the interface for adding internal stubs. Internal stubs are hidden from user-facing APIs and take precedence in matching. Only ADD operation is allowed - no delete, no clear (controlled by Budgerigar internally).

type ListOptions added in v3.10.1

type ListOptions struct {
	Source  string
	Service string
	Method  string

	// Query is a case-insensitive substring matched against the stub's
	// service, method and ID. Empty means no text filter.
	Query string

	// Matchers keeps only stubs whose input declares at least one of the given
	// matcher kinds (equals/contains/matches/glob/anyOf) — OR semantics. Empty
	// means no matcher-kind filter.
	Matchers []string

	Session    string
	SessionSet bool

	Limit  int
	Offset int
	Sort   string
}

ListOptions controls filtering, sorting and pagination for stubs listing.

type Output

type Output struct {
	Headers  map[string]string `json:"headers"`
	Trailers map[string]string `json:"trailers,omitempty"`
	Data     any               `json:"data,omitempty"`
	Stream   any               `json:"stream,omitempty"`
	Template bool              `json:"template,omitempty"`
	Error    string            `json:"error"`
	Code     *codes.Code       `json:"code,omitempty"`
	Details  []map[string]any  `json:"details,omitempty"`
	Delay    types.Delay       `json:"delay,omitempty"`
}

Output represents the output data of a gRPC response. With Template set, Data or Stream holds a Go template instead of a literal payload; which of the two holds it decides whether the stub answers with one message or with a stream.

func (Output) Document added in v3.22.0

func (o Output) Document() (string, bool)

Document returns the template text and whether it renders the stream.

func (Output) HasTemplate added in v3.22.0

func (o Output) HasTemplate() bool

HasTemplate reports whether the output is computed from a template.

func (Output) IsServerStream added in v3.22.0

func (o Output) IsServerStream() bool

IsServerStream reports whether the stub answers with a stream. It is declared by the wire shape (stream vs data), never inferred from the payload.

func (Output) Messages added in v3.22.0

func (o Output) Messages() []any

Messages returns the response messages in one shape: a unary payload is the only element, a stream keeps its order, a template has none until it is rendered.

type Query

type Query struct {
	ID            *uuid.UUID       `json:"id,omitempty"`      // The unique identifier of the stub (optional).
	Service       string           `json:"service"`           // The service name to search for.
	Method        string           `json:"method"`            // The method name to search for.
	Session       string           `json:"session,omitempty"` // Session ID (empty = global only).
	Headers       map[string]any   `json:"headers"`           // The headers to match.
	Input         []map[string]any `json:"input"`             // The input data to match (unary or streaming).
	StrictService bool             `json:"strictService,omitempty"`
	// contains filtered or unexported fields
}

Query represents a query for finding stubs. Supports both unary (Input with one element) and streaming (Input with multiple elements). JSON accepts "data" (legacy, maps to Input[0]) or "input" (array). Prefer "input".

func NewQuery

func NewQuery(r *http.Request) (Query, error)

NewQuery creates a new Query from an HTTP request. Supports both legacy "data" (single object) and "input" (array) in JSON body.

func WithInternalStubs added in v3.18.0

func WithInternalStubs(q Query) Query

WithInternalStubs returns a copy of the query allowed to match internal stubs. Only the gRPC health service sets this; everyone else keeps internal stubs hidden (list/get/search/inspect/verify/MCP never see them).

func (*Query) Data

func (q *Query) Data() map[string]any

Data returns the first input element for backward compatibility with legacy unary API. Returns nil if Input is empty.

func (*Query) RequestInternal

func (q *Query) RequestInternal() bool

RequestInternal returns true if the query is marked as internal.

func (*Query) UnmarshalJSON added in v3.6.0

func (q *Query) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler to support both "data" and "input" in request body.

type QueryBidi

type QueryBidi struct {
	ID            *uuid.UUID     `json:"id,omitempty"`      // The unique identifier of the stub (optional).
	Service       string         `json:"service"`           // The service name to search for.
	Method        string         `json:"method"`            // The method name to search for.
	Session       string         `json:"session,omitempty"` // Session ID (empty = global only).
	Headers       map[string]any `json:"headers"`           // The headers to match.
	StrictService bool           `json:"strictService,omitempty"`
	// contains filtered or unexported fields
}

QueryBidi represents a query for bidirectional streaming. In bidirectional streaming, each message is treated as a separate unary request. The server can respond with multiple messages for each request.

func (QueryBidi) RequestInternal

func (q QueryBidi) RequestInternal() bool

RequestInternal returns true if the query is marked as internal.

type Result

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

Result holds the search result: exact match (Found) or best similar (Similar).

func (*Result) Found

func (r *Result) Found() *Stub

Found returns the exact match found in the search.

func (*Result) MatchNumber added in v3.21.0

func (r *Result) MatchNumber() int

func (*Result) Similar

func (r *Result) Similar() *Stub

Similar returns the most similar match found in the search.

type ServerStreamHandler added in v3.20.0

type ServerStreamHandler func(ctx context.Context, in any, stream any) error

ServerStreamHandler writes the response stream itself, given the decoded request.

type StreamHandler added in v3.16.0

type StreamHandler func(ctx context.Context, stream any) error

StreamHandler processes a bidirectional stream directly.

type Stub

type Stub struct {
	ID       uuid.UUID     `json:"id"`
	Service  string        `json:"service"           validate:"required"`
	Method   string        `json:"method"            validate:"required"`
	Session  string        `json:"session,omitempty"`
	Priority int           `json:"priority"`
	Options  StubOptions   `json:"options,omitempty"` //nolint:modernize
	Headers  InputHeader   `json:"headers"`
	Input    InputData     `json:"input"             validate:"valid_input_config"`
	Inputs   []InputData   `json:"inputs,omitempty"  validate:"valid_input_config"`
	Output   Output        `json:"output"            validate:"valid_output_config"`
	Effects  []Effect      `json:"effects,omitempty" validate:"valid_effects"`
	Source   string        `json:"source,omitempty"`
	Handler  StreamHandler `json:"-"`

	UnaryHandler        UnaryHandler        `json:"-"`
	ServerStreamHandler ServerStreamHandler `json:"-"`
	ClientStreamHandler ClientStreamHandler `json:"-"`

	Used bool `json:"used,omitempty"`
}

Stub represents a gRPC service method and its associated data.

func FilterForDump added in v3.10.1

func FilterForDump(stubs []*Stub, source string) []*Stub

func (*Stub) DeclaresStreamMatchers added in v3.22.0

func (s *Stub) DeclaresStreamMatchers() bool

DeclaresStreamMatchers reports whether the stub declared `inputs`, which selects the stream matcher: every message must match, and an empty list matches nothing.

func (*Stub) EffectiveTimes added in v3.7.0

func (s *Stub) EffectiveTimes() int

EffectiveTimes returns the stub's max match count; 0 means unlimited.

func (*Stub) IsBidirectional

func (s *Stub) IsBidirectional() bool

IsBidirectional returns true if this stub can handle bidirectional streaming.

func (*Stub) IsClientStream

func (s *Stub) IsClientStream() bool

IsClientStream returns true if this stub is for client streaming requests (has Inputs data).

func (*Stub) IsServerStream

func (s *Stub) IsServerStream() bool

IsServerStream returns true if this stub answers with a stream: literal messages in Output.Stream, or a template in that slot.

func (*Stub) Key

func (s *Stub) Key() uuid.UUID

Key returns the unique identifier of the stub.

func (*Stub) Matchers added in v3.22.0

func (s *Stub) Matchers() []InputData

Matchers returns the request matchers in one shape: a unary stub has exactly one, a client-streaming stub keeps the declared order.

func (*Stub) Score

func (s *Stub) Score() int

Score returns the priority score of the stub.

type StubOptions added in v3.7.0

type StubOptions struct {
	Times int `json:"times,omitempty" validate:"gte=0"`
}

StubOptions holds optional behavior settings for a stub.

type UnaryHandler added in v3.20.0

type UnaryHandler func(ctx context.Context, in any) (any, error)

Jump to

Keyboard shortcuts

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