handler

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 27 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HealthHandler

func HealthHandler(w http.ResponseWriter, r *http.Request)

healthHandler handles requests to the /health endpoint.

func LoadKeyManager added in v1.9.0

func LoadKeyManager(ctx context.Context, mgr PluginManager, registry definition.RegistryLookup, cfg *plugin.Config) (definition.KeyManager, error)

LoadKeyManager loads the KeyManager plugin using the provided PluginManager and registry.

func LoadPlugin added in v1.9.0

func LoadPlugin[T any](ctx context.Context, name string, cfg *plugin.Config, mgrFunc func(context.Context, *plugin.Config) (T, error)) (T, error)

LoadPlugin is a generic function to load and validate plugins.

func LoadPolicyChecker added in v1.9.0

func LoadPolicyChecker(ctx context.Context, mgr PluginManager, manifestLoader definition.ManifestLoader, cfg *plugin.Config) (definition.PolicyChecker, error)

func NewStdHandler

func NewStdHandler(ctx context.Context, mgr PluginManager, cfg *Config, moduleName string) (http.Handler, error)

NewStdHandler initializes a new processor with plugins and steps.

func RecordHTTPRequest added in v1.4.0

func RecordHTTPRequest(ctx context.Context, statusCode int, action, role, senderID, recipientID string)

func StatusClass added in v1.4.0

func StatusClass(statusCode int) string

StatusClass returns the HTTP status class string (e.g. 200 -> "2xx").

Types

type Config

type Config struct {
	Plugins          PluginCfg `yaml:"plugins"`
	Steps            []string
	Type             Type
	RegistryURL      string `yaml:"registryUrl"`
	Role             model.Role
	SubscriberID     string           `yaml:"subscriberId"`
	HttpClientConfig HttpClientConfig `yaml:"httpClientConfig"`
	// BasePath is the HTTP path prefix at which this module is mounted (e.g.
	// "/bap/receiver/"). Set by the module layer from module.Config.Path; not
	// read from YAML. Steps use it to strip the prefix before calling plugins.
	BasePath string `yaml:"-"`
	// OutputRoot previously named the catalogPublish handler's local output
	// directory directly. Storage is now supplied to the catalogPublisher
	// plugin via its own CatalogBlobStore plugin config
	// (Plugins.CatalogBlobStore, e.g. localcatalogblobstore's "root" key)
	// instead, so NewCatalogPublishHandler no longer reads this field. Kept
	// on Config only for backward-compat parsing of existing YAML that
	// still sets outputRoot -- YAML decoding in this package is not strict
	// (unknown keys are simply ignored), so removing the field entirely
	// would not break parsing, but that's a config-migration decision
	// better made deliberately, not as a side effect of this handler
	// change.
	OutputRoot string `yaml:"outputRoot,omitempty"`
	// AuthDisabled, when true, skips signature verification on handlers that
	// would otherwise require it (currently only catalogCrawlStatus). LOCAL
	// DEV / TESTING ONLY -- with this set, the caller's identity comes from
	// an unauthenticated subscriberId query param instead of a verified
	// Authorization header, so any caller can query any subscriber's crawl
	// status. Must stay false/unset for any network-facing deployment.
	AuthDisabled bool `yaml:"authDisabled,omitempty"`
}

Config holds the configuration for request processing handlers.

type EndpointHandler added in v1.9.0

type EndpointHandler[Req, Resp any] struct {
	Decode  func(ctx context.Context, r *http.Request) (Req, error)
	Execute func(ctx context.Context, req Req) (Resp, error)
	Encode  func(w http.ResponseWriter, r *http.Request, req Req, resp Resp, err error)
}

EndpointHandler is a generic HTTP handler shell: it does no domain-specific work itself, only sequencing Decode -> Execute -> Encode. Decode owns every HTTP-semantic decision (method check, header/query/body parsing, request validation) and always means a malformed/invalid request when it errors, surfaced as a transport-level 400. Execute failing means the operation ran but failed at a business level; only Encode (endpoint-specific) knows how to render that -- e.g. catalog/publish reports it as 200 + a FAILED body, not an HTTP error. Encode also receives the originally decoded request (not just the response), since an endpoint's rendering may legitimately need something only present on the request (e.g. catalog/publish's retire list for its bookkeeping) without resorting to a shared mutable capture across concurrent requests. This lets multiple unrelated plugin-backed endpoints (catalog/publish today, a future crawler trigger, etc.) share one handler core with no shared business logic.

func (*EndpointHandler[Req, Resp]) ServeHTTP added in v1.9.0

func (e *EndpointHandler[Req, Resp]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type HTTPMetrics added in v1.4.0

type HTTPMetrics struct {
	HttpRequestCount metric.Int64Counter
}

func GetHTTPMetrics added in v1.4.0

func GetHTTPMetrics(_ context.Context) (*HTTPMetrics, error)

GetHTTPMetrics returns HTTPMetrics bound to the current global MeterProvider, rebuilding only when the provider has been replaced since the last call.

type HandlerDirection added in v1.8.0

type HandlerDirection string

stdHandler orchestrates the execution of defined processing steps. HandlerDirection represents whether a handler is on the caller (outbound) or receiver (inbound) side of the Beckn adapter. Derived at runtime from role and payload action — not read from config.

const (
	DirectionCaller   HandlerDirection = "caller"
	DirectionReceiver HandlerDirection = "receiver"
)

type HandlerMetrics added in v1.3.0

type HandlerMetrics struct {
	SignatureValidationsTotal metric.Int64Counter
	SchemaValidationsTotal    metric.Int64Counter
	RoutingDecisionsTotal     metric.Int64Counter
}

HandlerMetrics exposes handler-related metric instruments.

func GetHandlerMetrics added in v1.3.0

func GetHandlerMetrics(_ context.Context) (*HandlerMetrics, error)

GetHandlerMetrics returns HandlerMetrics bound to the current global MeterProvider, rebuilding only when the provider has been replaced since the last call.

type HttpClientConfig

type HttpClientConfig struct {
	// MaxIdleConns controls the maximum number of idle (keep-alive)
	// connections across all hosts.
	MaxIdleConns int `yaml:"maxIdleConns"`

	// IdleConnTimeout is the maximum amount of time an idle
	// (keep-alive) connection will remain idle before closing itself.
	IdleConnTimeout time.Duration `yaml:"idleConnTimeout"`

	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host.
	MaxIdleConnsPerHost int `yaml:"maxIdleConnsPerHost"`

	// ResponseHeaderTimeout, if non-zero, specifies the amount of time to wait
	// for a server's response headers after fully writing the request.
	ResponseHeaderTimeout time.Duration `yaml:"responseHeaderTimeout"`
}

HttpClientConfig defines the configuration for the HTTP transport layer.

type InstrumentedResponseStep added in v1.7.0

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

InstrumentedResponseStep wraps a response processing step with telemetry instrumentation.

func NewInstrumentedResponseStep added in v1.7.0

func NewInstrumentedResponseStep(step ResponseStepRunner, stepName, moduleName string) (*InstrumentedResponseStep, error)

NewInstrumentedResponseStep returns a telemetry-enabled wrapper around a definition.ResponseStep.

func (*InstrumentedResponseStep) RunOnResponse added in v1.7.0

RunOnResponse executes the underlying response step and records RED style metrics.

Note: validateAckSign is a soft-failure step — it returns nil even on signature verification failures (degraded-trust design). onix_step_errors_total will never increment for that step; its own log.Warnf calls are the only signal for soft failures.

type InstrumentedStep added in v1.3.0

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

InstrumentedStep wraps a processing step with telemetry instrumentation.

func NewInstrumentedStep added in v1.3.0

func NewInstrumentedStep(step StepRunner, stepName, moduleName string) (*InstrumentedStep, error)

NewInstrumentedStep returns a telemetry enabled wrapper around a definition.Step.

func (*InstrumentedStep) Run added in v1.3.0

func (is *InstrumentedStep) Run(ctx *model.StepContext) error

Run executes the underlying step and records RED style metrics.

type PluginCfg

type PluginCfg struct {
	SchemaValidator       *plugin.Config  `yaml:"schemaValidator,omitempty"`
	PolicyChecker         *plugin.Config  `yaml:"checkPolicy,omitempty"`
	PayloadTransformer    *plugin.Config  `yaml:"payloadTransformer,omitempty"`
	SignValidator         *plugin.Config  `yaml:"signValidator,omitempty"`
	Publisher             *plugin.Config  `yaml:"publisher,omitempty"`
	Signer                *plugin.Config  `yaml:"signer,omitempty"`
	Router                *plugin.Config  `yaml:"router,omitempty"`
	Cache                 *plugin.Config  `yaml:"cache,omitempty"`
	Registry              *plugin.Config  `yaml:"registry,omitempty"`
	KeyManager            *plugin.Config  `yaml:"keyManager,omitempty"`
	ManifestLoader        *plugin.Config  `yaml:"manifestLoader,omitempty"`
	SchemaVersionMediator *plugin.Config  `yaml:"schemaVersionMediator,omitempty"`
	TransportWrapper      *plugin.Config  `yaml:"transportWrapper,omitempty"`
	PayloadStore          *plugin.Config  `yaml:"payloadStore,omitempty"`
	CatalogPublisher      *plugin.Config  `yaml:"catalogPublisher,omitempty"`
	CatalogBlobStore      *plugin.Config  `yaml:"catalogBlobStore,omitempty"`
	Middleware            []plugin.Config `yaml:"middleware,omitempty"`
	Steps                 []plugin.Config
}

PluginCfg holds the configuration for various plugins.

func (*PluginCfg) PluginEntries added in v1.6.0

func (p *PluginCfg) PluginEntries() []telemetry.PluginEntry

PluginEntries returns a flat list of all configured plugins in this PluginCfg. Each named slot contributes one entry; Steps and Middleware contribute one entry per item. Update this method whenever a new plugin slot is added to PluginCfg so that the onix_plugin_info gauge stays complete.

type PluginManager

type PluginManager interface {
	Middleware(ctx context.Context, cfg *plugin.Config) (func(http.Handler) http.Handler, error)
	SignValidator(ctx context.Context, cfg *plugin.Config) (definition.SignValidator, error)
	Validator(ctx context.Context, cfg *plugin.Config) (definition.SchemaValidator, error)
	Router(ctx context.Context, cfg *plugin.Config) (definition.Router, error)
	Publisher(ctx context.Context, cfg *plugin.Config) (definition.Publisher, error)
	Signer(ctx context.Context, cfg *plugin.Config) (definition.Signer, error)
	Step(ctx context.Context, cfg *plugin.Config) (definition.Step, error)
	PolicyChecker(ctx context.Context, manifestLoader definition.ManifestLoader, cfg *plugin.Config) (definition.PolicyChecker, error)
	SchemaVersionMediator(ctx context.Context, manifestLoader definition.ManifestLoader, cfg *plugin.Config) (definition.SchemaVersionMediator, error)
	Cache(ctx context.Context, cfg *plugin.Config) (definition.Cache, error)
	Registry(ctx context.Context, cache definition.Cache, cfg *plugin.Config) (definition.RegistryLookup, error)
	KeyManager(ctx context.Context, rLookup definition.RegistryLookup, cfg *plugin.Config) (definition.KeyManager, error)
	ManifestLoader(ctx context.Context, cache definition.Cache, lookup definition.RegistryMetadataLookup, cfg *plugin.Config) (definition.ManifestLoader, error)
	TransportWrapper(ctx context.Context, cfg *plugin.Config) (definition.TransportWrapper, error)
	SchemaValidator(ctx context.Context, cfg *plugin.Config) (definition.SchemaValidator, error)
	PayloadStore(ctx context.Context, cache definition.Cache, namespace string, cfg *plugin.Config) (definition.PayloadStore, error)
	CatalogPublisher(ctx context.Context, km definition.KeyManager, blobStore definition.CatalogBlobStore, registry definition.RegistryLookup, cfg *plugin.Config) (definition.CatalogPublisher, error)
	CatalogBlobStore(ctx context.Context, cfg *plugin.Config) (definition.CatalogBlobStore, error)
}

PluginManager defines an interface for managing plugins dynamically.

type ResponseStepRunner added in v1.7.0

type ResponseStepRunner interface {
	RunOnResponse(*model.StepContext, *model.ResponseStepContext) error
}

ResponseStepRunner is the minimal contract required for response step instrumentation.

type StatusError added in v1.9.0

type StatusError struct {
	Status int
	Err    error
}

StatusError lets a Decode implementation pick the transport-level HTTP status a decode failure is surfaced as -- e.g. http.StatusMethodNotAllowed for a wrong-method request, rather than always collapsing to 400. A Decode error that doesn't wrap a *StatusError still gets the default http.StatusBadRequest.

func (*StatusError) Error added in v1.9.0

func (e *StatusError) Error() string

func (*StatusError) Unwrap added in v1.9.0

func (e *StatusError) Unwrap() error

type StepMetrics added in v1.3.0

type StepMetrics struct {
	StepExecutionDuration metric.Float64Histogram
	StepExecutionTotal    metric.Int64Counter
	StepErrorsTotal       metric.Int64Counter
}

StepMetrics exposes step execution metric instruments.

func GetStepMetrics added in v1.3.0

func GetStepMetrics(_ context.Context) (*StepMetrics, error)

GetStepMetrics returns StepMetrics bound to the current global MeterProvider, rebuilding only when the provider has been replaced since the last call.

type StepRunner added in v1.3.0

type StepRunner interface {
	Run(*model.StepContext) error
}

StepRunner represents the minimal contract required for step instrumentation.

type Type

type Type string

Type defines different handler types for processing requests.

const (
	// HandlerTypeStd represents the standard handler type used for general request processing.
	HandlerTypeStd Type = "std"
	// HandlerTypeCatalogPublish handles DS-internal, unsigned catalog/publish
	// triggers: it invokes a CatalogPublisher synchronously with the
	// catalogs in the request body and writes the result to a local output
	// root, bypassing validateSign/signAck since the caller is the
	// operator's own tooling, not another network participant.
	HandlerTypeCatalogPublish Type = "catalogPublish"
	// HandlerTypeCatalogCrawl handles a DS-internal, unsigned on-demand
	// crawl trigger: it invokes the already-running Crawler plugin's
	// CrawlRegistry against caller-supplied networkIds and returns a run
	// ID. Unlike other handler types, its provider is registered at
	// runtime (see module.RegisterProvider, called from
	// catalogcrawler.RegisterHandler) rather than statically in
	// handlerProviders, because it closes over the single Crawler instance
	// main.go starts as a background job -- CrawlRegistry requires that
	// instance to already be running.
	// HandlerTypeCatalogCrawl handles the /crawl/* endpoint family: an
	// on-demand crawl trigger (invokes the already-running Crawler
	// plugin's CrawlRegistry) and a crawl/sync status query, both
	// sub-routed internally by catalogcrawler.NewHandler rather than
	// registered as separate handler types -- see that function's own doc
	// comment. Its provider is registered at runtime (see
	// module.RegisterProvider, called from catalogcrawler.RegisterHandler)
	// rather than statically in handlerProviders, because it closes over
	// the single Crawler instance main.go starts as a background job --
	// CrawlRegistry requires that instance to already be running.
	HandlerTypeCatalogCrawl Type = "catalogCrawl"
)

Jump to

Keyboard shortcuts

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