openapi

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package openapi provides a generic provider for OpenAPI/Swagger based services. This allows quick integration of any HTTP service that provides OpenAPI documentation.

Package openapi provides OpenAPI 3.0.3 specification validation and management

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIKeyAuth

type APIKeyAuth struct {
	// Name is the header or query parameter name (e.g., "X-API-Key")
	Name string `yaml:"name" json:"name"`

	// Value is the API key value
	Value string `yaml:"value" json:"value"`

	// In specifies where to put the key: "header" or "query"
	In string `yaml:"in" json:"in"`
}

APIKeyAuth defines API key authentication.

type APIMethod

type APIMethod struct {
	// Name is the method name used for calling (e.g., "get_role", "ban_user")
	// Falls back to operationId or generated from path if not set
	Name string `yaml:"name" json:"name"`

	// OperationId from OpenAPI spec (unique identifier for the operation)
	OperationID string `yaml:"operation_id" json:"operation_id"`

	// Summary is a short summary of what the operation does (from OpenAPI)
	Summary string `yaml:"summary" json:"summary"`

	// Description is a verbose explanation of the operation behavior (from OpenAPI)
	Description string `yaml:"description" json:"description"`

	// Path is the API path (e.g., "/api/role/{role_id}")
	Path string `yaml:"path" json:"path"`

	// Method is the HTTP method (GET, POST, PUT, DELETE, etc.)
	Method string `yaml:"method" json:"method"`

	// Tags for categorization (from OpenAPI tags)
	// Operations may be grouped by tags for UI organization
	Tags []string `yaml:"tags" json:"tags"`

	// Parameters defines how to map request parameters
	Parameters []ParameterMapping `yaml:"parameters" json:"parameters"`

	// RequestBody defines how to map the request body
	RequestBody *RequestBodyMapping `yaml:"request_body" json:"request_body"`

	// ResponseMapping defines how to transform the response
	ResponseMapping *ResponseMapping `yaml:"response_mapping" json:"response_mapping"`

	// Deprecated marks this operation as deprecated (from OpenAPI)
	Deprecated bool `yaml:"deprecated" json:"deprecated"`

	// OpenAPI 3.0.3 Extension fields (x-*)
	Category  string `yaml:"x-category" json:"x-category"`   // x-category: function category
	Risk      string `yaml:"x-risk" json:"x-risk"`           // x-risk: risk level
	Entity    string `yaml:"x-entity" json:"x-entity"`       // x-entity: associated entity type
	Operation string `yaml:"x-operation" json:"x-operation"` // x-operation: CRUD operation type
}

APIMethod defines a single API method that can be called. It closely follows OpenAPI 3.0 operation object structure.

type AuthConfig

type AuthConfig struct {
	// Type can be: "none", "bearer", "basic", "api_key", "custom"
	Type string `yaml:"type" json:"type"`

	// Bearer token for "bearer" type
	Token string `yaml:"token" json:"token"`

	// Username for "basic" type
	Username string `yaml:"username" json:"username"`

	// Password for "basic" type
	Password string `yaml:"password" json:"password"`

	// APIKey configuration for "api_key" type
	APIKey *APIKeyAuth `yaml:"api_key" json:"api_key"`

	// Custom header configuration for "custom" type
	CustomHeaders map[string]string `yaml:"custom_headers" json:"custom_headers"`
}

AuthConfig defines authentication methods.

type Config

type Config struct {
	// BaseURL is the base URL of the OpenAPI service (e.g., "http://api.example.com")
	BaseURL string `yaml:"base_url" json:"base_url"`

	// Auth specifies the authentication method
	Auth *AuthConfig `yaml:"auth" json:"auth"`

	// Methods defines the API methods available through this provider
	// If empty, will attempt to discover from OpenAPI spec
	Methods []APIMethod `yaml:"methods" json:"methods"`

	// OpenAPISpec is the URL or local path to a single OpenAPI/Swagger specification
	// If provided, the provider will auto-discover available methods
	OpenAPISpec string `yaml:"openapi_spec" json:"openapi_spec"`

	// OpenAPISpecs is a list of URLs or local paths to multiple OpenAPI specifications
	// If provided, the provider will merge all specs and auto-discover methods
	// Takes precedence over OpenAPISpec if both are set
	OpenAPISpecs []string `yaml:"openapi_specs" json:"openapi_specs"`

	// Timeout for HTTP requests (supports "10s", "1m", "500ms" or seconds as number)
	Timeout Duration `yaml:"timeout" json:"timeout"`

	// RetryCount specifies how many times to retry on failure
	RetryCount int `yaml:"retry_count" json:"retry_count"`

	// Headers are default headers to include in all requests
	Headers map[string]string `yaml:"headers" json:"headers"`

	// Transform allows response transformation
	Transform *TransformConfig `yaml:"transform" json:"transform"`
}

Config holds the OpenAPI provider specific configuration.

type Duration

type Duration time.Duration

Duration is a custom duration type that supports parsing from both human-readable strings (like "10s", "1m", "500ms") and integers (nanoseconds).

func (Duration) Duration

func (d Duration) Duration() time.Duration

Duration returns the time.Duration value.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for Duration.

type Entity added in v0.1.5

type Entity struct {
	ID          string
	Name        string
	Description string
	Operations  map[string]*openapi3.Operation
}

Entity represents a business entity with its operations

type EntityManager added in v0.1.5

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

EntityManager manages entity definitions and their operations

func NewEntityManager added in v0.1.5

func NewEntityManager() *EntityManager

NewEntityManager creates a new entity manager

func (*EntityManager) DeleteEntity added in v0.1.5

func (m *EntityManager) DeleteEntity(id string)

DeleteEntity removes an entity

func (*EntityManager) GetEntity added in v0.1.5

func (m *EntityManager) GetEntity(id string) (*Entity, bool)

GetEntity retrieves an entity by ID

func (*EntityManager) GetEntityOperation added in v0.1.5

func (m *EntityManager) GetEntityOperation(entityID, operationID string) (*openapi3.Operation, bool)

GetEntityOperation retrieves a specific operation from an entity

func (*EntityManager) ListEntities added in v0.1.5

func (m *EntityManager) ListEntities() []*Entity

ListEntities returns all registered entities

func (*EntityManager) RegisterEntity added in v0.1.5

func (m *EntityManager) RegisterEntity(entity *Entity) error

RegisterEntity registers or updates an entity definition

type FunctionDefinition added in v0.1.5

type FunctionDefinition struct {
	ID           string
	Summary      string
	Description  string
	Category     string
	Risk         string
	Entity       string
	Operation    string // create/read/update/delete/custom
	InputSchema  interface{}
	OutputSchema interface{}
}

FunctionDefinition represents a single function with all its metadata.

type FunctionDescriptor added in v0.1.5

type FunctionDescriptor struct {
	ID           string
	Name         string
	Summary      string
	Description  string
	InputSchema  string
	OutputSchema string
	Category     string
	Risk         string
	Entity       string
	Operation    string
}

FunctionDescriptor represents a generic function descriptor

type FunctionProvider added in v0.1.5

type FunctionProvider struct {
	Name      string
	Type      FunctionProviderType
	Version   string
	Functions map[string]*FunctionDefinition
}

FunctionProvider represents a function provider with metadata and functions. This is used for converting between different function definition formats. Note: This is different from provider.Provider which is for third-party platform integrations.

type FunctionProviderType added in v0.1.5

type FunctionProviderType int

FunctionProviderType represents the type of function provider (e.g., OpenAPI, Proto, Pack).

const (
	FunctionProviderTypeUnknown FunctionProviderType = iota
	FunctionProviderTypeOpenAPI
	FunctionProviderTypeProto
	FunctionProviderTypePack
)

func FunctionProviderTypeFromString added in v0.1.5

func FunctionProviderTypeFromString(s string) FunctionProviderType

FunctionProviderTypeFromString converts a string to FunctionProviderType.

func (FunctionProviderType) String added in v0.1.5

func (t FunctionProviderType) String() string

String returns the string representation of FunctionProviderType.

type MethodDetails

type MethodDetails struct {
	Name        string
	OperationID string
	Summary     string
	Description string
	Tags        []string
	Deprecated  bool
	Parameters  []ParameterMapping

	// OpenAPI 3.0.3 Extension fields (x-*)
	Category  string // x-category
	Risk      string // x-risk
	Entity    string // x-entity
	Operation string // x-operation
}

MethodDetails contains the metadata for a method extracted from OpenAPI. This is used when registering functions to the LocalStore.

type ParameterMapping

type ParameterMapping struct {
	// Name is the parameter name in the API request
	Name string `yaml:"name" json:"name"`

	// In specifies where the parameter goes: "path", "query", "header", "cookie"
	In string `yaml:"in" json:"in"`

	// Description of the parameter (from OpenAPI)
	Description string `yaml:"description" json:"description"`

	// From specifies the field name in the input JSON (e.g., "role_id")
	// If empty, uses Name
	From string `yaml:"from" json:"from"`

	// Required indicates if this parameter is required (from OpenAPI)
	Required bool `yaml:"required" json:"required"`

	// Deprecated marks this parameter as deprecated (from OpenAPI)
	Deprecated bool `yaml:"deprecated" json:"deprecated"`

	// Default value if not provided (from OpenAPI)
	Default interface{} `yaml:"default" json:"default"`

	// Type of the parameter: "string", "number", "integer", "boolean", "array", "object"
	Type string `yaml:"type" json:"type"`

	// Format of the parameter type: e.g., "int32", "int64", "float", "double", "date-time"
	Format string `yaml:"format" json:"format"`

	// Enum allowed values for this parameter (from OpenAPI)
	Enum []interface{} `yaml:"enum" json:"enum"`
}

ParameterMapping defines how to map a parameter. Follows OpenAPI 3.0 parameter object structure.

type Provider

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

Provider implements the provider.Provider interface for OpenAPI based services. It provides a generic way to call any HTTP API with configurable authentication, parameter mapping, and response transformation.

func NewProvider

func NewProvider() *Provider

NewProvider creates a new OpenAPI provider.

func (*Provider) Call

func (p *Provider) Call(ctx context.Context, method string, request []byte) ([]byte, error)

Call invokes an API method.

func (*Provider) Close

func (p *Provider) Close() error

Close closes the provider.

func (*Provider) GetMethodDetails

func (p *Provider) GetMethodDetails() map[string]*MethodDetails

GetMethodDetails returns the complete details for all methods. This is used by Agent to register functions with full metadata.

func (*Provider) GetOpenAPIDoc added in v0.1.5

func (p *Provider) GetOpenAPIDoc() json.RawMessage

GetOpenAPIDoc returns the raw OpenAPI document JSON. This can be used to store the complete OpenAPI specification for later retrieval.

func (*Provider) Init

func (p *Provider) Init(ctx context.Context, config provider.ProviderConfig) error

Init initializes the provider with configuration.

func (*Provider) IsEnabled

func (p *Provider) IsEnabled() bool

IsEnabled returns whether the provider is enabled.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name.

func (*Provider) SupportedMethods

func (p *Provider) SupportedMethods() []string

SupportedMethods returns the list of supported methods.

type ProviderConverter added in v0.1.5

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

ProviderConverter converts various function representations to OpenAPI Operations

func NewProviderConverter added in v0.1.5

func NewProviderConverter() *ProviderConverter

NewProviderConverter creates a new Provider converter

func (*ProviderConverter) ToOpenAPIOperation added in v0.1.5

func (c *ProviderConverter) ToOpenAPIOperation(desc *FunctionDescriptor) (*openapi3.Operation, error)

ToOpenAPIOperation converts a FunctionDescriptor to OpenAPI Operation

type RequestBodyMapping

type RequestBodyMapping struct {
	// Type specifies the body format: "json", "form", "text"
	Type string `yaml:"type" json:"type"`

	// Template is a Go template for building the body
	// Example: {"user_id": "{{ .user_id }}", "reason": "{{ .reason }}"}
	Template string `yaml:"template" json:"template"`

	// Fields defines field mappings (used when type is "json")
	Fields map[string]string `yaml:"fields" json:"fields"`
}

RequestBodyMapping defines how to map the request body.

type ResponseMapping

type ResponseMapping struct {
	// ExtractPath is a JSON path to extract from response (e.g., "data.items")
	ExtractPath string `yaml:"extract_path" json:"extract_path"`

	// Wrap indicates whether to wrap the response in a standard envelope
	Wrap bool `yaml:"wrap" json:"wrap"`

	// SuccessField is the field that indicates success (e.g., "code == 0")
	SuccessField string `yaml:"success_field" json:"success_field"`

	// SuccessValue is the value that indicates success
	SuccessValue interface{} `yaml:"success_value" json:"success_value"`
}

ResponseMapping defines how to transform the response.

type TransformConfig

type TransformConfig struct {
	// SuccessField specifies the field that indicates success
	SuccessField string `yaml:"success_field" json:"success_field"`

	// SuccessValue is the value that indicates success
	SuccessValue interface{} `yaml:"success_value" json:"success_value"`

	// DataField specifies the field containing the actual data
	DataField string `yaml:"data_field" json:"data_field"`

	// ErrorField specifies the field containing error message
	ErrorField string `yaml:"error_field" json:"error_field"`
}

TransformConfig defines global response transformation.

type Validator added in v0.1.5

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

Validator validates OpenAPI 3.0.3 specifications

func NewValidator added in v0.1.5

func NewValidator() *Validator

NewValidator creates a new OpenAPI validator instance

func (*Validator) ValidateExtensionFields added in v0.1.5

func (v *Validator) ValidateExtensionFields(extensions map[string]interface{}) error

ValidateExtensionFields validates Croupier-specific extension fields

func (*Validator) ValidateOperation added in v0.1.5

func (v *Validator) ValidateOperation(operation *openapi3.Operation) error

ValidateOperation validates a single OpenAPI 3.0.3 operation

func (*Validator) ValidateSpec added in v0.1.5

func (v *Validator) ValidateSpec(data []byte) (*openapi3.T, error)

ValidateSpec validates an OpenAPI 3.0.3 specification document

Jump to

Keyboard shortcuts

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