connector

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2025 License: Apache-2.0 Imports: 49 Imported by: 18

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetLogger

func GetLogger(ctx context.Context) *slog.Logger

GetLogger gets the logger instance from context.

func IsSensitiveHeader added in v1.6.4

func IsSensitiveHeader(name string) bool

IsSensitiveHeader checks if the header name is sensitive.

func MaskString added in v1.6.4

func MaskString(input string) string

MaskString masks the string value for security.

func NewTelemetryHeaders added in v1.6.4

func NewTelemetryHeaders(httpHeaders http.Header, allowedHeaders ...string) http.Header

NewTelemetryHeaders creates a new header map with sensitive values masked.

func SetSpanHeaderAttributes added in v1.6.4

func SetSpanHeaderAttributes(span traceapi.Span, prefix string, httpHeaders http.Header, allowedHeaders ...string)

SetSpanHeaderAttributes sets header attributes to the otel span.

func Start

func Start[Configuration any, State any](connector Connector[Configuration, State], options ...ServeOption) error

Starts the connector. Will read command line arguments or environment variables to determine runtime configuration.

This should be the entrypoint of your connector.

func StartCustom added in v0.2.0

func StartCustom[Configuration any, State any](cli ConnectorCLI, connector Connector[Configuration, State], options ...ServeOption) error

Starts the connector with custom CLI. Will read command line arguments or environment variables to determine runtime configuration.

This should be the entrypoint of your connector.

Types

type Connector

type Connector[Configuration any, State any] interface {
	// ParseConfiguration validates the configuration files provided by the user, returning a validated 'Configuration',
	// or throwing an error to prevents Connector startup.
	ParseConfiguration(ctx context.Context, configurationDir string) (*Configuration, error)

	// TryInitState initializes the connector's in-memory state.
	//
	// For example, any connection pools, prepared queries,
	// or other managed resources would be allocated here.
	//
	// In addition, this function should register any
	// connector-specific metrics with the metrics registry.
	TryInitState(ctx context.Context, configuration *Configuration, metrics *TelemetryState) (*State, error)

	// HealthCheck checks the health of the connector.
	//
	// For example, this function should check that the connector
	// is able to reach its data source over the network.
	//
	// Should throw if the check fails, else resolve.
	HealthCheck(ctx context.Context, configuration *Configuration, state *State) error

	// GetCapabilities get the connector's capabilities.
	//
	// This function implements the [capabilities endpoint] from the NDC specification.
	//
	// This function should be synchronous.
	//
	// [capabilities endpoint]: https://hasura.github.io/ndc-spec/specification/capabilities.html
	GetCapabilities(configuration *Configuration) schema.CapabilitiesResponseMarshaler

	// GetSchema gets the connector's schema.
	//
	// This function implements the [schema endpoint] from the NDC specification.
	//
	// [schema endpoint]: https://hasura.github.io/ndc-spec/specification/schema/index.html
	GetSchema(ctx context.Context, configuration *Configuration, state *State) (schema.SchemaResponseMarshaler, error)

	// QueryExplain explains a query by creating an execution plan.
	// This function implements the [explain endpoint] from the NDC specification.
	//
	// [explain endpoint]: https://hasura.github.io/ndc-spec/specification/explain.html
	QueryExplain(ctx context.Context, configuration *Configuration, state *State, request *schema.QueryRequest) (*schema.ExplainResponse, error)

	// MutationExplain explains a mutation by creating an execution plan.
	// This function implements the [explain endpoint] from the NDC specification.
	//
	// [explain endpoint]: https://hasura.github.io/ndc-spec/specification/explain.html
	MutationExplain(ctx context.Context, configuration *Configuration, state *State, request *schema.MutationRequest) (*schema.ExplainResponse, error)

	// Mutation executes a mutation.
	//
	// This function implements the [mutation endpoint] from the NDC specification.
	//
	// [mutation endpoint]: https://hasura.github.io/ndc-spec/specification/mutations/index.html
	Mutation(ctx context.Context, configuration *Configuration, state *State, request *schema.MutationRequest) (*schema.MutationResponse, error)

	// Query executes a query.
	//
	// This function implements the [query endpoint] from the NDC specification.
	//
	// [query endpoint]: https://hasura.github.io/ndc-spec/specification/queries/index.html
	Query(ctx context.Context, configuration *Configuration, state *State, request *schema.QueryRequest) (schema.QueryResponse, error)
}

Connector abstracts an interface with required methods for the NDC Specification.

type ConnectorCLI added in v0.2.0

type ConnectorCLI interface {
	GetServeCLI() *ServeCLI
	Execute(ctx context.Context, command string) error
}

ConnectorCLI abstracts the connector CLI so NDC authors can extend it.

type HTTPServerConfig added in v1.5.0

type HTTPServerConfig struct {
	ServerReadTimeout        time.Duration `` /* 164-byte string literal not displayed */
	ServerReadHeaderTimeout  time.Duration `` /* 136-byte string literal not displayed */
	ServerWriteTimeout       time.Duration `` /* 155-byte string literal not displayed */
	ServerIdleTimeout        time.Duration `` /* 163-byte string literal not displayed */
	ServerMaxHeaderKilobytes int           `` /* 184-byte string literal not displayed */
	ServerTLSCertFile        string        `help:"Path of the TLS certificate file" env:"HASURA_SERVER_TLS_CERT_FILE"`
	ServerTLSKeyFile         string        `help:"Path of the TLS key file" env:"HASURA_SERVER_TLS_KEY_FILE"`
}

HTTPServerConfig the configuration of the HTTP server.

type LogHandler added in v1.6.4

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

LogHandler wraps slog logger with the OpenTelemetry logs exporter handler.

func (LogHandler) Enabled added in v1.6.4

func (l LogHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (LogHandler) Handle added in v1.6.4

func (l LogHandler) Handle(ctx context.Context, record slog.Record) error

Handle handles the Record. It will only be called when Enabled returns true.

func (LogHandler) WithAttrs added in v1.6.4

func (l LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Handler whose attributes consist of both the receiver's attributes and the arguments. The Handler owns the slice: it may retain, modify or discard it.

func (LogHandler) WithGroup added in v1.6.4

func (l LogHandler) WithGroup(name string) slog.Handler

WithGroup returns a new Handler with the given group appended to the receiver's existing groups.

type OTLPConfig added in v0.3.0

type OTLPConfig struct {
	ServiceName            string `help:"OpenTelemetry service name." env:"OTEL_SERVICE_NAME"`
	OtlpEndpoint           string `help:"OpenTelemetry receiver endpoint that is set as default for all types." env:"OTEL_EXPORTER_OTLP_ENDPOINT"`
	OtlpTracesEndpoint     string `help:"OpenTelemetry endpoint for traces." env:"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"`
	OtlpMetricsEndpoint    string `help:"OpenTelemetry endpoint for metrics." env:"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"`
	OtlpLogsEndpoint       string `help:"OpenTelemetry endpoint for logs." env:"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"`
	OtlpInsecure           *bool  `help:"Disable LTS for OpenTelemetry exporters." env:"OTEL_EXPORTER_OTLP_INSECURE"`
	OtlpTracesInsecure     *bool  `help:"Disable LTS for OpenTelemetry traces exporter." env:"OTEL_EXPORTER_OTLP_TRACES_INSECURE"`
	OtlpMetricsInsecure    *bool  `help:"Disable LTS for OpenTelemetry metrics exporter." env:"OTEL_EXPORTER_OTLP_METRICS_INSECURE"`
	OtlpLogsInsecure       *bool  `help:"Disable LTS for OpenTelemetry logs exporter." env:"OTEL_EXPORTER_OTLP_LOGS_INSECURE"`
	OtlpProtocol           string `help:"OpenTelemetry receiver protocol for all types." env:"OTEL_EXPORTER_OTLP_PROTOCOL"`
	OtlpTracesProtocol     string `help:"OpenTelemetry receiver protocol for traces." env:"OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"`
	OtlpMetricsProtocol    string `help:"OpenTelemetry receiver protocol for metrics." env:"OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"`
	OtlpLogsProtocol       string `help:"OpenTelemetry receiver protocol for logs." env:"OTEL_EXPORTER_OTLP_LOGS_PROTOCOL"`
	OtlpCompression        string `` /* 133-byte string literal not displayed */
	OtlpTraceCompression   string `` /* 146-byte string literal not displayed */
	OtlpMetricsCompression string `` /* 148-byte string literal not displayed */
	OtlpLogsCompression    string `` /* 142-byte string literal not displayed */

	MetricsExporter  string `` /* 129-byte string literal not displayed */
	LogsExporter     string `help:"Logs export type. Accept: none, otlp" enum:"none,otlp" env:"OTEL_LOGS_EXPORTER" default:"none"`
	PrometheusPort   *uint  `` /* 145-byte string literal not displayed */
	DisableGoMetrics *bool  `help:"Disable internal Go and process metrics"`
}

OTLPConfig contains configuration for OpenTelemetry exporter.

type ServeCLI added in v0.2.0

type ServeCLI struct {
	LogLevel string                `help:"Log level." env:"HASURA_LOG_LEVEL" enum:"trace,debug,info,warn,error" default:"info"`
	Serve    ServeCommandArguments `cmd:"" help:"Serve the NDC connector."`
}

ServeCLI is used for CLI argument binding.

func (*ServeCLI) Execute added in v0.2.0

func (cli *ServeCLI) Execute(ctx context.Context, command string) error

Execute executes the command.

func (*ServeCLI) GetServeCLI added in v0.2.0

func (cli *ServeCLI) GetServeCLI() *ServeCLI

GetServeCLI returns the inner serve cli.

type ServeCommandArguments added in v0.2.0

type ServeCommandArguments struct {
	OTLPConfig
	HTTPServerConfig

	Configuration      string `help:"Configuration directory" env:"HASURA_CONFIGURATION_DIRECTORY"`
	Port               uint   `help:"Serve Port" env:"HASURA_CONNECTOR_PORT" default:"8080"`
	ServiceTokenSecret string `help:"Service token secret" env:"HASURA_SERVICE_TOKEN_SECRET"`
}

ServeCommandArguments contains argument flags of the serve command.

type ServeOption

type ServeOption func(*serveOptions)

ServeOption abstracts a public interface to update server options.

func WithDefaultServiceName

func WithDefaultServiceName(name string) ServeOption

WithDefaultServiceName sets the default service name option.

func WithLogger

func WithLogger(logger *slog.Logger) ServeOption

WithLogger sets a custom logger option.

func WithLoggerFunc added in v0.3.1

func WithLoggerFunc(fn func(level slog.Level) *slog.Logger) ServeOption

WithLoggerFunc sets a custom logger option with a constructor function.

func WithMetricsPrefix

func WithMetricsPrefix(prefix string) ServeOption

WithMetricsPrefix sets the custom metrics prefix option.

func WithVersion

func WithVersion(version string) ServeOption

WithVersion sets the custom version option.

func WithoutRecovery

func WithoutRecovery() ServeOption

WithoutRecovery disables recovery on panic.

type Server

type Server[Configuration any, State any] struct {
	// contains filtered or unexported fields
}

Server implements the NDC API specification for the connector

func NewServer

func NewServer[Configuration any, State any](connector Connector[Configuration, State], options *ServerOptions, others ...ServeOption) (*Server[Configuration, State], error)

NewServer creates a Server instance.

func (*Server[Configuration, State]) BuildTestServer

func (s *Server[Configuration, State]) BuildTestServer() *httptest.Server

BuildTestServer builds an http test server for testing purpose.

func (*Server[Configuration, State]) GetCapabilities

func (s *Server[Configuration, State]) GetCapabilities(w http.ResponseWriter, r *http.Request)

GetCapabilities get the connector's capabilities. Implement a handler for the /capabilities endpoint, GET method.

func (*Server[Configuration, State]) GetSchema

func (s *Server[Configuration, State]) GetSchema(w http.ResponseWriter, r *http.Request)

GetSchema implements a handler for the /schema endpoint, GET method.

func (*Server[Configuration, State]) Health

func (s *Server[Configuration, State]) Health(w http.ResponseWriter, r *http.Request)

Health checks the health of the connector. Implement a handler for the /health endpoint, GET method.

func (*Server[Configuration, State]) ListenAndServe

func (s *Server[Configuration, State]) ListenAndServe(port uint) error

ListenAndServe serves the configuration server with the standard http server. You can also replace this method with any router or web framework that is compatible with net/http.

func (*Server[Configuration, State]) Mutation

func (s *Server[Configuration, State]) Mutation(w http.ResponseWriter, r *http.Request)

Mutation implements a handler for the /mutation endpoint, POST method that executes a mutation.

func (*Server[Configuration, State]) MutationExplain

func (s *Server[Configuration, State]) MutationExplain(w http.ResponseWriter, r *http.Request)

MutationExplain implements a handler for the /mutation/explain endpoint, POST method that explains a mutation by creating an execution plan.

func (*Server[Configuration, State]) Query

func (s *Server[Configuration, State]) Query(w http.ResponseWriter, r *http.Request)

Query implements a handler for the /query endpoint, POST method that executes a query.

func (*Server[Configuration, State]) QueryExplain

func (s *Server[Configuration, State]) QueryExplain(w http.ResponseWriter, r *http.Request)

QueryExplain implements a handler for the /query/explain endpoint, POST method that explains a query by creating an execution plan.

type ServerOptions

type ServerOptions struct {
	OTLPConfig
	HTTPServerConfig

	Configuration      string
	InlineConfig       bool
	ServiceTokenSecret string
}

ServerOptions presents the configuration object of the connector http server.

type TelemetryState

type TelemetryState struct {
	Tracer   *Tracer
	Meter    metricapi.Meter
	Logger   *slog.Logger
	Shutdown func(context.Context) error
	// contains filtered or unexported fields
}

TelemetryState contains OpenTelemetry exporters and basic connector metrics.

func SetupOTelExporters added in v0.3.1

func SetupOTelExporters(ctx context.Context, config *OTLPConfig, serviceVersion, metricsPrefix string, logger *slog.Logger) (*TelemetryState, error)

SetupOTelExporters set up OpenTelemetry exporters from configuration.

type Tracer

type Tracer struct {
	traceapi.Tracer
}

Tracer is the wrapper of traceapi.Tracer with user visibility on Hasura Console.

func NewTracer added in v1.4.0

func NewTracer(name string, opts ...traceapi.TracerOption) *Tracer

NewTracer creates a new OpenTelemetry tracer.

func (*Tracer) Start

func (t *Tracer) Start(ctx context.Context, spanName string, opts ...traceapi.SpanStartOption) (context.Context, traceapi.Span)

Start creates a span and a context.Context containing the newly-created span with `internal.visibility: "user"` so that it shows up in the Hasura Console.

func (*Tracer) StartInternal

func (t *Tracer) StartInternal(ctx context.Context, spanName string, opts ...traceapi.SpanStartOption) (context.Context, traceapi.Span)

StartInternal creates a span and a context.Context containing the newly-created span. It won't show up in the Hasura Console.

Jump to

Keyboard shortcuts

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