initial commit
This commit is contained in:
commit
88c14b627e
224 files changed
+17204
No files matched your search
@@ -0,0 +1,251 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
var (
|
||||
// Allocate option closure once.
|
||||
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
|
||||
)
|
||||
|
||||
type (
|
||||
optionFunc[C any] func(*C)
|
||||
otelOptionFunc func(*otelConfig)
|
||||
)
|
||||
|
||||
type otelConfig struct {
|
||||
TracerProvider trace.TracerProvider
|
||||
Tracer trace.Tracer
|
||||
MeterProvider metric.MeterProvider
|
||||
Meter metric.Meter
|
||||
Attributes []attribute.KeyValue
|
||||
}
|
||||
|
||||
func (cfg *otelConfig) initOTEL() {
|
||||
if cfg.TracerProvider == nil {
|
||||
cfg.TracerProvider = otel.GetTracerProvider()
|
||||
}
|
||||
if cfg.MeterProvider == nil {
|
||||
cfg.MeterProvider = otel.GetMeterProvider()
|
||||
}
|
||||
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
|
||||
trace.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||
)
|
||||
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name,
|
||||
metric.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||
)
|
||||
}
|
||||
|
||||
// ErrorHandler is error handler.
|
||||
type ErrorHandler = ogenerrors.ErrorHandler
|
||||
|
||||
type serverConfig struct {
|
||||
otelConfig
|
||||
NotFound http.HandlerFunc
|
||||
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
|
||||
ErrorHandler ErrorHandler
|
||||
Prefix string
|
||||
Middleware Middleware
|
||||
MaxMultipartMemory int64
|
||||
}
|
||||
|
||||
// ServerOption is server config option.
|
||||
type ServerOption interface {
|
||||
applyServer(*serverConfig)
|
||||
}
|
||||
|
||||
var _ ServerOption = (optionFunc[serverConfig])(nil)
|
||||
|
||||
func (o optionFunc[C]) applyServer(c *C) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
var _ ServerOption = (otelOptionFunc)(nil)
|
||||
|
||||
func (o otelOptionFunc) applyServer(c *serverConfig) {
|
||||
o(&c.otelConfig)
|
||||
}
|
||||
|
||||
func newServerConfig(opts ...ServerOption) serverConfig {
|
||||
cfg := serverConfig{
|
||||
NotFound: http.NotFound,
|
||||
MethodNotAllowed: nil,
|
||||
ErrorHandler: ogenerrors.DefaultErrorHandler,
|
||||
Middleware: nil,
|
||||
MaxMultipartMemory: 32 << 20, // 32 MB
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.applyServer(&cfg)
|
||||
}
|
||||
cfg.initOTEL()
|
||||
return cfg
|
||||
}
|
||||
|
||||
type baseServer struct {
|
||||
cfg serverConfig
|
||||
requests metric.Int64Counter
|
||||
errors metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
}
|
||||
|
||||
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
s.cfg.NotFound(w, r)
|
||||
}
|
||||
|
||||
type notAllowedParams struct {
|
||||
allowedMethods string
|
||||
allowedHeaders map[string]string
|
||||
acceptPost string
|
||||
acceptPatch string
|
||||
}
|
||||
|
||||
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, params notAllowedParams) {
|
||||
h := w.Header()
|
||||
isOptions := r.Method == "OPTIONS"
|
||||
if isOptions {
|
||||
h.Set("Access-Control-Allow-Methods", params.allowedMethods)
|
||||
if params.allowedHeaders != nil {
|
||||
m := r.Header.Get("Access-Control-Request-Method")
|
||||
if m != "" {
|
||||
allowedHeaders, ok := params.allowedHeaders[strings.ToUpper(m)]
|
||||
if ok {
|
||||
h.Set("Access-Control-Allow-Headers", allowedHeaders)
|
||||
}
|
||||
}
|
||||
}
|
||||
if params.acceptPost != "" {
|
||||
h.Set("Accept-Post", params.acceptPost)
|
||||
}
|
||||
if params.acceptPatch != "" {
|
||||
h.Set("Accept-Patch", params.acceptPatch)
|
||||
}
|
||||
}
|
||||
if s.cfg.MethodNotAllowed != nil {
|
||||
s.cfg.MethodNotAllowed(w, r, params.allowedMethods)
|
||||
return
|
||||
}
|
||||
status := http.StatusNoContent
|
||||
if !isOptions {
|
||||
h.Set("Allow", params.allowedMethods)
|
||||
status = http.StatusMethodNotAllowed
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (cfg serverConfig) baseServer() (s baseServer, err error) {
|
||||
s = baseServer{cfg: cfg}
|
||||
if s.requests, err = otelogen.ServerRequestCountCounter(s.cfg.Meter); err != nil {
|
||||
return s, err
|
||||
}
|
||||
if s.errors, err = otelogen.ServerErrorsCountCounter(s.cfg.Meter); err != nil {
|
||||
return s, err
|
||||
}
|
||||
if s.duration, err = otelogen.ServerDurationHistogram(s.cfg.Meter); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Option is config option.
|
||||
type Option interface {
|
||||
ServerOption
|
||||
}
|
||||
|
||||
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
|
||||
//
|
||||
// If none is specified, the global provider is used.
|
||||
func WithTracerProvider(provider trace.TracerProvider) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
if provider != nil {
|
||||
cfg.TracerProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMeterProvider specifies a meter provider to use for creating a meter.
|
||||
//
|
||||
// If none is specified, the otel.GetMeterProvider() is used.
|
||||
func WithMeterProvider(provider metric.MeterProvider) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
if provider != nil {
|
||||
cfg.MeterProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithAttributes specifies default otel attributes.
|
||||
func WithAttributes(attributes ...attribute.KeyValue) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
cfg.Attributes = attributes
|
||||
})
|
||||
}
|
||||
|
||||
// WithNotFound specifies Not Found handler to use.
|
||||
func WithNotFound(notFound http.HandlerFunc) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if notFound != nil {
|
||||
cfg.NotFound = notFound
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
|
||||
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if methodNotAllowed != nil {
|
||||
cfg.MethodNotAllowed = methodNotAllowed
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithErrorHandler specifies error handler to use.
|
||||
func WithErrorHandler(h ErrorHandler) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if h != nil {
|
||||
cfg.ErrorHandler = h
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithPathPrefix specifies server path prefix.
|
||||
func WithPathPrefix(prefix string) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
cfg.Prefix = prefix
|
||||
})
|
||||
}
|
||||
|
||||
// WithMiddleware specifies middlewares to use.
|
||||
func WithMiddleware(m ...Middleware) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
switch len(m) {
|
||||
case 0:
|
||||
cfg.Middleware = nil
|
||||
case 1:
|
||||
cfg.Middleware = m[0]
|
||||
default:
|
||||
cfg.Middleware = middleware.ChainMiddlewares(m...)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
|
||||
// File parts which can't be stored in memory will be stored on disk in temporary files.
|
||||
func WithMaxMultipartMemory(max int64) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if max > 0 {
|
||||
cfg.MaxMultipartMemory = max
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type codeRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (c *codeRecorder) WriteHeader(status int) {
|
||||
c.status = status
|
||||
c.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (c *codeRecorder) Unwrap() http.ResponseWriter {
|
||||
return c.ResponseWriter
|
||||
}
|
||||
|
||||
// handleGetHealthzRequest handles GetHealthz operation.
|
||||
//
|
||||
// Check whether the API process is responding.
|
||||
//
|
||||
// GET /api/v1/healthz
|
||||
func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetHealthz"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/healthz"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), GetHealthzOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
)
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response *HealthResponse
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: GetHealthzOperation,
|
||||
OperationSummary: "Check whether the API process is responding.",
|
||||
OperationID: "GetHealthz",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = struct{}
|
||||
Response = *HealthResponse
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
nil,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.GetHealthz(ctx)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.GetHealthz(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
defer recordError("Internal", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeGetHealthzResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *HealthResponse) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *HealthResponse) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("status")
|
||||
s.Status.Encode(e)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfHealthResponse = [1]string{
|
||||
0: "status",
|
||||
}
|
||||
|
||||
// Decode decodes HealthResponse from json.
|
||||
func (s *HealthResponse) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode HealthResponse to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "status":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
if err := s.Status.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"status\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode HealthResponse")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000001,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfHealthResponse) {
|
||||
name = jsonFieldsNameOfHealthResponse[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *HealthResponse) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *HealthResponse) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes HealthResponseStatus as json.
|
||||
func (s HealthResponseStatus) Encode(e *jx.Encoder) {
|
||||
e.Str(string(s))
|
||||
}
|
||||
|
||||
// Decode decodes HealthResponseStatus from json.
|
||||
func (s *HealthResponseStatus) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode HealthResponseStatus to nil")
|
||||
}
|
||||
v, err := d.StrBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Try to use constant string.
|
||||
switch HealthResponseStatus(v) {
|
||||
case HealthResponseStatusOk:
|
||||
*s = HealthResponseStatusOk
|
||||
default:
|
||||
*s = HealthResponseStatus(v)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s HealthResponseStatus) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *HealthResponseStatus) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
)
|
||||
|
||||
// Labeler is used to allow adding custom attributes to the server request metrics.
|
||||
type Labeler struct {
|
||||
attrs []attribute.KeyValue
|
||||
}
|
||||
|
||||
// Add attributes to the Labeler.
|
||||
func (l *Labeler) Add(attrs ...attribute.KeyValue) {
|
||||
l.attrs = append(l.attrs, attrs...)
|
||||
}
|
||||
|
||||
// AttributeSet returns the attributes added to the Labeler as an attribute.Set.
|
||||
func (l *Labeler) AttributeSet() attribute.Set {
|
||||
return attribute.NewSet(l.attrs...)
|
||||
}
|
||||
|
||||
type labelerContextKey struct{}
|
||||
|
||||
// LabelerFromContext retrieves the Labeler from the provided context, if present.
|
||||
//
|
||||
// If no Labeler was found in the provided context a new, empty Labeler is returned and the second
|
||||
// return value is false. In this case it is safe to use the Labeler but any attributes added to
|
||||
// it will not be used.
|
||||
func LabelerFromContext(ctx context.Context) (*Labeler, bool) {
|
||||
if l, ok := ctx.Value(labelerContextKey{}).(*Labeler); ok {
|
||||
return l, true
|
||||
}
|
||||
return &Labeler{}, false
|
||||
}
|
||||
|
||||
func contextWithLabeler(ctx context.Context, l *Labeler) context.Context {
|
||||
return context.WithValue(ctx, labelerContextKey{}, l)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
)
|
||||
|
||||
// Middleware is middleware type.
|
||||
type Middleware = middleware.Middleware
|
||||
@@ -0,0 +1,10 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
// OperationName is the ogen operation name
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
GetHealthzOperation OperationName = "GetHealthz"
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
@@ -0,0 +1,24 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
)
|
||||
|
||||
func (s *Server) cutPrefix(path string) (string, bool) {
|
||||
prefix := s.cfg.Prefix
|
||||
if prefix == "" {
|
||||
return path, true
|
||||
}
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
// Prefix doesn't match.
|
||||
return "", false
|
||||
}
|
||||
// Cut prefix from the path.
|
||||
return strings.TrimPrefix(path, prefix), true
|
||||
}
|
||||
|
||||
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
|
||||
// calling handler that matches the path or returning not found error.
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
elem := r.URL.Path
|
||||
elemIsEscaped := false
|
||||
if rawPath := r.URL.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
elemIsEscaped = strings.ContainsRune(elem, '%')
|
||||
}
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok || len(elem) == 0 {
|
||||
s.notFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/api/v1/healthz"
|
||||
|
||||
if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetHealthzRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
s.notFound(w, r)
|
||||
}
|
||||
|
||||
// Route is route object.
|
||||
type Route struct {
|
||||
name string
|
||||
summary string
|
||||
operationID string
|
||||
operationGroup string
|
||||
pathPattern string
|
||||
count int
|
||||
args [0]string
|
||||
}
|
||||
|
||||
// Name returns ogen operation name.
|
||||
//
|
||||
// It is guaranteed to be unique and not empty.
|
||||
func (r Route) Name() string {
|
||||
return r.name
|
||||
}
|
||||
|
||||
// Summary returns OpenAPI summary.
|
||||
func (r Route) Summary() string {
|
||||
return r.summary
|
||||
}
|
||||
|
||||
// OperationID returns OpenAPI operationId.
|
||||
func (r Route) OperationID() string {
|
||||
return r.operationID
|
||||
}
|
||||
|
||||
// OperationGroup returns the x-ogen-operation-group value.
|
||||
func (r Route) OperationGroup() string {
|
||||
return r.operationGroup
|
||||
}
|
||||
|
||||
// PathPattern returns OpenAPI path.
|
||||
func (r Route) PathPattern() string {
|
||||
return r.pathPattern
|
||||
}
|
||||
|
||||
// Args returns parsed arguments.
|
||||
func (r Route) Args() []string {
|
||||
return r.args[:r.count]
|
||||
}
|
||||
|
||||
// FindRoute finds Route for given method and path.
|
||||
//
|
||||
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
|
||||
func (s *Server) FindRoute(method, path string) (Route, bool) {
|
||||
return s.FindPath(method, &url.URL{Path: path})
|
||||
}
|
||||
|
||||
// FindPath finds Route for given method and URL.
|
||||
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
var (
|
||||
elem = u.Path
|
||||
args = r.args
|
||||
)
|
||||
if rawPath := u.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
}
|
||||
defer func() {
|
||||
for i, arg := range r.args[:r.count] {
|
||||
if unescaped, err := url.PathUnescape(arg); err == nil {
|
||||
r.args[i] = unescaped
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok {
|
||||
return r, false
|
||||
}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/api/v1/healthz"
|
||||
|
||||
if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetHealthzOperation
|
||||
r.summary = "Check whether the API process is responding."
|
||||
r.operationID = "GetHealthz"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/healthz"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return r, false
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-faster/errors"
|
||||
)
|
||||
|
||||
// Ref: #/components/schemas/HealthResponse
|
||||
type HealthResponse struct {
|
||||
Status HealthResponseStatus `json:"status"`
|
||||
}
|
||||
|
||||
// GetStatus returns the value of Status.
|
||||
func (s *HealthResponse) GetStatus() HealthResponseStatus {
|
||||
return s.Status
|
||||
}
|
||||
|
||||
// SetStatus sets the value of Status.
|
||||
func (s *HealthResponse) SetStatus(val HealthResponseStatus) {
|
||||
s.Status = val
|
||||
}
|
||||
|
||||
type HealthResponseStatus string
|
||||
|
||||
const (
|
||||
HealthResponseStatusOk HealthResponseStatus = "ok"
|
||||
)
|
||||
|
||||
// AllValues returns all HealthResponseStatus values.
|
||||
func (HealthResponseStatus) AllValues() []HealthResponseStatus {
|
||||
return []HealthResponseStatus{
|
||||
HealthResponseStatusOk,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s HealthResponseStatus) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case HealthResponseStatusOk:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *HealthResponseStatus) UnmarshalText(data []byte) error {
|
||||
switch HealthResponseStatus(data) {
|
||||
case HealthResponseStatusOk:
|
||||
*s = HealthResponseStatusOk
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Handler handles operations described by OpenAPI v3 specification.
|
||||
type Handler interface {
|
||||
// GetHealthz implements GetHealthz operation.
|
||||
//
|
||||
// Check whether the API process is responding.
|
||||
//
|
||||
// GET /api/v1/healthz
|
||||
GetHealthz(ctx context.Context) (*HealthResponse, error)
|
||||
}
|
||||
|
||||
// Server implements http server based on OpenAPI v3 specification and
|
||||
// calls Handler to handle requests.
|
||||
type Server struct {
|
||||
h Handler
|
||||
baseServer
|
||||
}
|
||||
|
||||
// NewServer creates new Server.
|
||||
func NewServer(h Handler, opts ...ServerOption) (*Server, error) {
|
||||
s, err := newServerConfig(opts...).baseServer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Server{
|
||||
h: h,
|
||||
baseServer: s,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
|
||||
type UnimplementedHandler struct{}
|
||||
|
||||
var _ Handler = UnimplementedHandler{}
|
||||
|
||||
// GetHealthz implements GetHealthz operation.
|
||||
//
|
||||
// Check whether the API process is responding.
|
||||
//
|
||||
// GET /api/v1/healthz
|
||||
func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *HealthResponse) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Status.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s HealthResponseStatus) Validate() error {
|
||||
switch s {
|
||||
case "ok":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/felixge/httpsnoop"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type RequestMetrics interface {
|
||||
ObserveRequest(method, route string, status int, duration time.Duration)
|
||||
}
|
||||
|
||||
func CollectMetrics(metrics RequestMetrics) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
captured := httpsnoop.CaptureMetrics(next, w, r)
|
||||
route := chi.RouteContext(r.Context()).RoutePattern()
|
||||
metrics.ObserveRequest(r.Method, route, captured.Code, captured.Duration)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
|
||||
|
||||
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
|
||||
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
)
|
||||
|
||||
func NewRouter(health *v1.HealthHandler, collector httpmiddleware.RequestMetrics, logger *slog.Logger) (http.Handler, error) {
|
||||
apiServer, err := apiadapter.NewServer(health)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
router := chi.NewRouter()
|
||||
router.Use(kitmiddleware.RequestID())
|
||||
router.Use(kitmiddleware.Recoverer(logger))
|
||||
router.Use(kitmiddleware.Logger(logger, nil, kitmiddleware.WithSkipPaths("/healthz", "/readyz")))
|
||||
router.Use(httpmiddleware.CollectMetrics(collector))
|
||||
router.Get("/healthz", health.Healthz)
|
||||
router.Get("/readyz", health.Readyz)
|
||||
router.Handle("/api/v1/*", apiServer)
|
||||
return router, nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
)
|
||||
|
||||
type readinessFunc func(context.Context) error
|
||||
|
||||
func (check readinessFunc) Check(ctx context.Context) error {
|
||||
return check(ctx)
|
||||
}
|
||||
|
||||
func TestOperationalHealthRoutes(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
check readinessFunc
|
||||
path string
|
||||
statusCode int
|
||||
bodyStatus string
|
||||
}{
|
||||
{name: "live", check: func(context.Context) error { return nil }, path: "/healthz", statusCode: http.StatusOK, bodyStatus: "ok"},
|
||||
{name: "ready", check: func(context.Context) error { return nil }, path: "/readyz", statusCode: http.StatusOK, bodyStatus: "ready"},
|
||||
{name: "not ready", check: func(context.Context) error { return context.DeadlineExceeded }, path: "/readyz", statusCode: http.StatusServiceUnavailable, bodyStatus: "not_ready"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
router := newTestRouter(t, test.check)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||
if response.Code != test.statusCode {
|
||||
t.Fatalf("status code = %d, want %d", response.Code, test.statusCode)
|
||||
}
|
||||
var body struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if body.Status != test.bodyStatus {
|
||||
t.Fatalf("status = %q, want %q", body.Status, test.bodyStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) {
|
||||
router := newTestRouter(t, func(context.Context) error { return context.DeadlineExceeded })
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if body.Status != "ok" {
|
||||
t.Fatalf("status = %q, want %q", body.Status, "ok")
|
||||
}
|
||||
}
|
||||
|
||||
func newTestRouter(t *testing.T, checker readinessFunc) http.Handler {
|
||||
t.Helper()
|
||||
readiness := health.NewReadiness(checker)
|
||||
healthHandler := v1.NewHealthHandler(readiness, time.Second)
|
||||
router, err := NewRouter(healthHandler, metrics.New(), slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return router
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
readiness inbound.Readiness
|
||||
readinessTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewHealthHandler(readiness inbound.Readiness, readinessTimeout time.Duration) *HealthHandler {
|
||||
return &HealthHandler{readiness: readiness, readinessTimeout: readinessTimeout}
|
||||
}
|
||||
|
||||
func (handler *HealthHandler) GetHealthz(context.Context) (*api.HealthResponse, error) {
|
||||
return &api.HealthResponse{Status: api.HealthResponseStatusOk}, nil
|
||||
}
|
||||
|
||||
func (handler *HealthHandler) Healthz(w http.ResponseWriter, _ *http.Request) {
|
||||
writeStatus(w, http.StatusOK, "ok")
|
||||
}
|
||||
|
||||
func (handler *HealthHandler) Readyz(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), handler.readinessTimeout)
|
||||
defer cancel()
|
||||
if err := handler.readiness.Check(ctx); err != nil {
|
||||
writeStatus(w, http.StatusServiceUnavailable, "not_ready")
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusOK, "ready")
|
||||
}
|
||||
|
||||
func writeStatus(w http.ResponseWriter, status int, value string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Status string `json:"status"`
|
||||
}{Status: value})
|
||||
}
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,144 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
var (
|
||||
// Allocate option closure once.
|
||||
clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
|
||||
)
|
||||
|
||||
type (
|
||||
optionFunc[C any] func(*C)
|
||||
otelOptionFunc func(*otelConfig)
|
||||
)
|
||||
|
||||
type otelConfig struct {
|
||||
TracerProvider trace.TracerProvider
|
||||
Tracer trace.Tracer
|
||||
MeterProvider metric.MeterProvider
|
||||
Meter metric.Meter
|
||||
Attributes []attribute.KeyValue
|
||||
}
|
||||
|
||||
func (cfg *otelConfig) initOTEL() {
|
||||
if cfg.TracerProvider == nil {
|
||||
cfg.TracerProvider = otel.GetTracerProvider()
|
||||
}
|
||||
if cfg.MeterProvider == nil {
|
||||
cfg.MeterProvider = otel.GetMeterProvider()
|
||||
}
|
||||
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
|
||||
trace.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||
)
|
||||
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name,
|
||||
metric.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||
)
|
||||
}
|
||||
|
||||
type clientConfig struct {
|
||||
otelConfig
|
||||
Client ht.Client
|
||||
}
|
||||
|
||||
// ClientOption is client config option.
|
||||
type ClientOption interface {
|
||||
applyClient(*clientConfig)
|
||||
}
|
||||
|
||||
var _ ClientOption = (optionFunc[clientConfig])(nil)
|
||||
|
||||
func (o optionFunc[C]) applyClient(c *C) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
var _ ClientOption = (otelOptionFunc)(nil)
|
||||
|
||||
func (o otelOptionFunc) applyClient(c *clientConfig) {
|
||||
o(&c.otelConfig)
|
||||
}
|
||||
|
||||
func newClientConfig(opts ...ClientOption) clientConfig {
|
||||
cfg := clientConfig{
|
||||
Client: http.DefaultClient,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.applyClient(&cfg)
|
||||
}
|
||||
cfg.initOTEL()
|
||||
return cfg
|
||||
}
|
||||
|
||||
type baseClient struct {
|
||||
cfg clientConfig
|
||||
requests metric.Int64Counter
|
||||
errors metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
}
|
||||
|
||||
func (cfg clientConfig) baseClient() (c baseClient, err error) {
|
||||
c = baseClient{cfg: cfg}
|
||||
if c.requests, err = otelogen.ClientRequestCountCounter(c.cfg.Meter); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if c.errors, err = otelogen.ClientErrorsCountCounter(c.cfg.Meter); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if c.duration, err = otelogen.ClientDurationHistogram(c.cfg.Meter); err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Option is config option.
|
||||
type Option interface {
|
||||
ClientOption
|
||||
}
|
||||
|
||||
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
|
||||
//
|
||||
// If none is specified, the global provider is used.
|
||||
func WithTracerProvider(provider trace.TracerProvider) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
if provider != nil {
|
||||
cfg.TracerProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMeterProvider specifies a meter provider to use for creating a meter.
|
||||
//
|
||||
// If none is specified, the otel.GetMeterProvider() is used.
|
||||
func WithMeterProvider(provider metric.MeterProvider) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
if provider != nil {
|
||||
cfg.MeterProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithAttributes specifies default otel attributes.
|
||||
func WithAttributes(attributes ...attribute.KeyValue) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
cfg.Attributes = attributes
|
||||
})
|
||||
}
|
||||
|
||||
// WithClient specifies http client to use.
|
||||
func WithClient(client ht.Client) ClientOption {
|
||||
return optionFunc[clientConfig](func(cfg *clientConfig) {
|
||||
if client != nil {
|
||||
cfg.Client = client
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func trimTrailingSlashes(u *url.URL) {
|
||||
u.Path = strings.TrimRight(u.Path, "/")
|
||||
u.RawPath = strings.TrimRight(u.RawPath, "/")
|
||||
}
|
||||
|
||||
// Invoker invokes operations described by OpenAPI v3 specification.
|
||||
type Invoker interface {
|
||||
// GetMLHealthz invokes GetMLHealthz operation.
|
||||
//
|
||||
// Check whether the ML process is responding.
|
||||
//
|
||||
// GET /healthz
|
||||
GetMLHealthz(ctx context.Context) (*MLHealthResponse, error)
|
||||
// GetMLReadyz invokes GetMLReadyz operation.
|
||||
//
|
||||
// Check whether an inference runtime is available.
|
||||
//
|
||||
// GET /readyz
|
||||
GetMLReadyz(ctx context.Context) (GetMLReadyzRes, error)
|
||||
}
|
||||
|
||||
// Client implements OAS client.
|
||||
type Client struct {
|
||||
serverURL *url.URL
|
||||
baseClient
|
||||
}
|
||||
|
||||
// NewClient initializes new Client defined by OAS.
|
||||
func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
|
||||
u, err := url.Parse(serverURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
trimTrailingSlashes(u)
|
||||
|
||||
c, err := newClientConfig(opts...).baseClient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Client{
|
||||
serverURL: u,
|
||||
baseClient: c,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type serverURLKey struct{}
|
||||
|
||||
// WithServerURL sets context key to override server URL.
|
||||
func WithServerURL(ctx context.Context, u *url.URL) context.Context {
|
||||
return context.WithValue(ctx, serverURLKey{}, u)
|
||||
}
|
||||
|
||||
func (c *Client) requestURL(ctx context.Context) *url.URL {
|
||||
u, ok := ctx.Value(serverURLKey{}).(*url.URL)
|
||||
if !ok {
|
||||
return c.serverURL
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// GetMLHealthz invokes GetMLHealthz operation.
|
||||
//
|
||||
// Check whether the ML process is responding.
|
||||
//
|
||||
// GET /healthz
|
||||
func (c *Client) GetMLHealthz(ctx context.Context) (*MLHealthResponse, error) {
|
||||
res, err := c.sendGetMLHealthz(ctx)
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (c *Client) sendGetMLHealthz(ctx context.Context) (res *MLHealthResponse, err error) {
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetMLHealthz"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.URLTemplateKey.String("/healthz"),
|
||||
}
|
||||
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
|
||||
}()
|
||||
|
||||
// Increment request counter.
|
||||
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, GetMLHealthzOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
clientSpanKind,
|
||||
)
|
||||
// Track stage for error reporting.
|
||||
var stage string
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, stage)
|
||||
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
stage = "BuildURL"
|
||||
u := uri.Clone(c.requestURL(ctx))
|
||||
var pathParts [1]string
|
||||
pathParts[0] = "/healthz"
|
||||
uri.AddPathParts(u, pathParts[:]...)
|
||||
|
||||
stage = "EncodeRequest"
|
||||
r, err := ht.NewRequest(ctx, "GET", u)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "create request")
|
||||
}
|
||||
|
||||
stage = "SendRequest"
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
body := resp.Body
|
||||
defer func() {
|
||||
// Drain the body to EOF before closing, so the underlying
|
||||
// connection can be reused by the Transport regardless of the
|
||||
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
|
||||
_, _ = io.Copy(io.Discard, body)
|
||||
_ = body.Close()
|
||||
}()
|
||||
|
||||
stage = "DecodeResponse"
|
||||
result, err := decodeGetMLHealthzResponse(resp)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetMLReadyz invokes GetMLReadyz operation.
|
||||
//
|
||||
// Check whether an inference runtime is available.
|
||||
//
|
||||
// GET /readyz
|
||||
func (c *Client) GetMLReadyz(ctx context.Context) (GetMLReadyzRes, error) {
|
||||
res, err := c.sendGetMLReadyz(ctx)
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (c *Client) sendGetMLReadyz(ctx context.Context) (res GetMLReadyzRes, err error) {
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetMLReadyz"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.URLTemplateKey.String("/readyz"),
|
||||
}
|
||||
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
|
||||
}()
|
||||
|
||||
// Increment request counter.
|
||||
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, GetMLReadyzOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
clientSpanKind,
|
||||
)
|
||||
// Track stage for error reporting.
|
||||
var stage string
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, stage)
|
||||
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
stage = "BuildURL"
|
||||
u := uri.Clone(c.requestURL(ctx))
|
||||
var pathParts [1]string
|
||||
pathParts[0] = "/readyz"
|
||||
uri.AddPathParts(u, pathParts[:]...)
|
||||
|
||||
stage = "EncodeRequest"
|
||||
r, err := ht.NewRequest(ctx, "GET", u)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "create request")
|
||||
}
|
||||
|
||||
stage = "SendRequest"
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
body := resp.Body
|
||||
defer func() {
|
||||
// Drain the body to EOF before closing, so the underlying
|
||||
// connection can be reused by the Transport regardless of the
|
||||
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
|
||||
_, _ = io.Copy(io.Discard, body)
|
||||
_ = body.Close()
|
||||
}()
|
||||
|
||||
stage = "DecodeResponse"
|
||||
result, err := decodeGetMLReadyzResponse(resp)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
package api
|
||||
|
||||
type GetMLReadyzRes interface {
|
||||
getMLReadyzRes()
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
// Encode encodes GetMLReadyzOK as json.
|
||||
func (s *GetMLReadyzOK) Encode(e *jx.Encoder) {
|
||||
unwrapped := (*MLReadinessResponse)(s)
|
||||
|
||||
unwrapped.Encode(e)
|
||||
}
|
||||
|
||||
// Decode decodes GetMLReadyzOK from json.
|
||||
func (s *GetMLReadyzOK) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode GetMLReadyzOK to nil")
|
||||
}
|
||||
var unwrapped MLReadinessResponse
|
||||
if err := func() error {
|
||||
if err := unwrapped.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "alias")
|
||||
}
|
||||
*s = GetMLReadyzOK(unwrapped)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *GetMLReadyzOK) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *GetMLReadyzOK) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes GetMLReadyzServiceUnavailable as json.
|
||||
func (s *GetMLReadyzServiceUnavailable) Encode(e *jx.Encoder) {
|
||||
unwrapped := (*MLReadinessResponse)(s)
|
||||
|
||||
unwrapped.Encode(e)
|
||||
}
|
||||
|
||||
// Decode decodes GetMLReadyzServiceUnavailable from json.
|
||||
func (s *GetMLReadyzServiceUnavailable) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode GetMLReadyzServiceUnavailable to nil")
|
||||
}
|
||||
var unwrapped MLReadinessResponse
|
||||
if err := func() error {
|
||||
if err := unwrapped.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "alias")
|
||||
}
|
||||
*s = GetMLReadyzServiceUnavailable(unwrapped)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *GetMLReadyzServiceUnavailable) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *GetMLReadyzServiceUnavailable) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *MLHealthResponse) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *MLHealthResponse) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("status")
|
||||
s.Status.Encode(e)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfMLHealthResponse = [1]string{
|
||||
0: "status",
|
||||
}
|
||||
|
||||
// Decode decodes MLHealthResponse from json.
|
||||
func (s *MLHealthResponse) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode MLHealthResponse to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "status":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
if err := s.Status.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"status\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode MLHealthResponse")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000001,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfMLHealthResponse) {
|
||||
name = jsonFieldsNameOfMLHealthResponse[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *MLHealthResponse) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *MLHealthResponse) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes MLHealthResponseStatus as json.
|
||||
func (s MLHealthResponseStatus) Encode(e *jx.Encoder) {
|
||||
e.Str(string(s))
|
||||
}
|
||||
|
||||
// Decode decodes MLHealthResponseStatus from json.
|
||||
func (s *MLHealthResponseStatus) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode MLHealthResponseStatus to nil")
|
||||
}
|
||||
v, err := d.StrBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Try to use constant string.
|
||||
switch MLHealthResponseStatus(v) {
|
||||
case MLHealthResponseStatusOk:
|
||||
*s = MLHealthResponseStatusOk
|
||||
default:
|
||||
*s = MLHealthResponseStatus(v)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s MLHealthResponseStatus) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *MLHealthResponseStatus) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *MLReadinessResponse) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *MLReadinessResponse) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("status")
|
||||
s.Status.Encode(e)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfMLReadinessResponse = [1]string{
|
||||
0: "status",
|
||||
}
|
||||
|
||||
// Decode decodes MLReadinessResponse from json.
|
||||
func (s *MLReadinessResponse) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode MLReadinessResponse to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "status":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
if err := s.Status.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"status\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode MLReadinessResponse")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000001,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfMLReadinessResponse) {
|
||||
name = jsonFieldsNameOfMLReadinessResponse[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *MLReadinessResponse) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *MLReadinessResponse) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes MLReadinessResponseStatus as json.
|
||||
func (s MLReadinessResponseStatus) Encode(e *jx.Encoder) {
|
||||
e.Str(string(s))
|
||||
}
|
||||
|
||||
// Decode decodes MLReadinessResponseStatus from json.
|
||||
func (s *MLReadinessResponseStatus) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode MLReadinessResponseStatus to nil")
|
||||
}
|
||||
v, err := d.StrBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Try to use constant string.
|
||||
switch MLReadinessResponseStatus(v) {
|
||||
case MLReadinessResponseStatusReady:
|
||||
*s = MLReadinessResponseStatusReady
|
||||
case MLReadinessResponseStatusNotReady:
|
||||
*s = MLReadinessResponseStatusNotReady
|
||||
default:
|
||||
*s = MLReadinessResponseStatus(v)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s MLReadinessResponseStatus) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *MLReadinessResponseStatus) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
// OperationName is the ogen operation name
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
GetMLHealthzOperation OperationName = "GetMLHealthz"
|
||||
GetMLReadyzOperation OperationName = "GetMLReadyz"
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
@@ -0,0 +1,158 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func decodeGetMLHealthzResponse(resp *http.Response) (res *MLHealthResponse, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
// Code 200.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response MLHealthResponse
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
return res, validate.UnexpectedStatusCodeWithResponse(resp)
|
||||
}
|
||||
|
||||
func decodeGetMLReadyzResponse(resp *http.Response) (res GetMLReadyzRes, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
// Code 200.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response GetMLReadyzOK
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 503:
|
||||
// Code 503.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response GetMLReadyzServiceUnavailable
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
return res, validate.UnexpectedStatusCodeWithResponse(resp)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-faster/errors"
|
||||
)
|
||||
|
||||
type GetMLReadyzOK MLReadinessResponse
|
||||
|
||||
func (*GetMLReadyzOK) getMLReadyzRes() {}
|
||||
|
||||
type GetMLReadyzServiceUnavailable MLReadinessResponse
|
||||
|
||||
func (*GetMLReadyzServiceUnavailable) getMLReadyzRes() {}
|
||||
|
||||
// Ref: #/components/schemas/MLHealthResponse
|
||||
type MLHealthResponse struct {
|
||||
Status MLHealthResponseStatus `json:"status"`
|
||||
}
|
||||
|
||||
// GetStatus returns the value of Status.
|
||||
func (s *MLHealthResponse) GetStatus() MLHealthResponseStatus {
|
||||
return s.Status
|
||||
}
|
||||
|
||||
// SetStatus sets the value of Status.
|
||||
func (s *MLHealthResponse) SetStatus(val MLHealthResponseStatus) {
|
||||
s.Status = val
|
||||
}
|
||||
|
||||
type MLHealthResponseStatus string
|
||||
|
||||
const (
|
||||
MLHealthResponseStatusOk MLHealthResponseStatus = "ok"
|
||||
)
|
||||
|
||||
// AllValues returns all MLHealthResponseStatus values.
|
||||
func (MLHealthResponseStatus) AllValues() []MLHealthResponseStatus {
|
||||
return []MLHealthResponseStatus{
|
||||
MLHealthResponseStatusOk,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s MLHealthResponseStatus) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case MLHealthResponseStatusOk:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *MLHealthResponseStatus) UnmarshalText(data []byte) error {
|
||||
switch MLHealthResponseStatus(data) {
|
||||
case MLHealthResponseStatusOk:
|
||||
*s = MLHealthResponseStatusOk
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/MLReadinessResponse
|
||||
type MLReadinessResponse struct {
|
||||
Status MLReadinessResponseStatus `json:"status"`
|
||||
}
|
||||
|
||||
// GetStatus returns the value of Status.
|
||||
func (s *MLReadinessResponse) GetStatus() MLReadinessResponseStatus {
|
||||
return s.Status
|
||||
}
|
||||
|
||||
// SetStatus sets the value of Status.
|
||||
func (s *MLReadinessResponse) SetStatus(val MLReadinessResponseStatus) {
|
||||
s.Status = val
|
||||
}
|
||||
|
||||
type MLReadinessResponseStatus string
|
||||
|
||||
const (
|
||||
MLReadinessResponseStatusReady MLReadinessResponseStatus = "ready"
|
||||
MLReadinessResponseStatusNotReady MLReadinessResponseStatus = "not_ready"
|
||||
)
|
||||
|
||||
// AllValues returns all MLReadinessResponseStatus values.
|
||||
func (MLReadinessResponseStatus) AllValues() []MLReadinessResponseStatus {
|
||||
return []MLReadinessResponseStatus{
|
||||
MLReadinessResponseStatusReady,
|
||||
MLReadinessResponseStatusNotReady,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s MLReadinessResponseStatus) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case MLReadinessResponseStatusReady:
|
||||
return []byte(s), nil
|
||||
case MLReadinessResponseStatusNotReady:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *MLReadinessResponseStatus) UnmarshalText(data []byte) error {
|
||||
switch MLReadinessResponseStatus(data) {
|
||||
case MLReadinessResponseStatusReady:
|
||||
*s = MLReadinessResponseStatusReady
|
||||
return nil
|
||||
case MLReadinessResponseStatusNotReady:
|
||||
*s = MLReadinessResponseStatusNotReady
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *GetMLReadyzOK) Validate() error {
|
||||
alias := (*MLReadinessResponse)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetMLReadyzServiceUnavailable) Validate() error {
|
||||
alias := (*MLReadinessResponse)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MLHealthResponse) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Status.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s MLHealthResponseStatus) Validate() error {
|
||||
switch s {
|
||||
case "ok":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MLReadinessResponse) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Status.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s MLReadinessResponseStatus) Validate() error {
|
||||
switch s {
|
||||
case "ready":
|
||||
return nil
|
||||
case "not_ready":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,44 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type HealthChecker struct {
|
||||
pool *pgxpool.Pool
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker, func(), error) {
|
||||
if config.DatabaseURL == "" {
|
||||
return &HealthChecker{}, func() {}, nil
|
||||
}
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(config.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
|
||||
return &HealthChecker{pool: pool, queries: sqlc.New(pool)}, pool.Close, nil
|
||||
}
|
||||
|
||||
func (checker *HealthChecker) Check(ctx context.Context) error {
|
||||
if checker.pool == nil || checker.queries == nil {
|
||||
return outbound.ErrNotReady
|
||||
}
|
||||
if _, err := checker.queries.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("PostgreSQL health query: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestHealthCheckerWithoutDatabaseIsNotReady(t *testing.T) {
|
||||
checker, closePool, err := NewHealthChecker(context.Background(), config.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHealthChecker() error = %v", err)
|
||||
}
|
||||
closePool()
|
||||
|
||||
if err := checker.Check(context.Background()); !errors.Is(err, outbound.ErrNotReady) {
|
||||
t.Fatalf("Check() error = %v, want ErrNotReady", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: health.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const ping = `-- name: Ping :one
|
||||
SELECT 1::int4 AS alive
|
||||
`
|
||||
|
||||
func (q *Queries) Ping(ctx context.Context) (int32, error) {
|
||||
row := q.db.QueryRow(ctx, ping)
|
||||
var alive int32
|
||||
err := row.Scan(&alive)
|
||||
return alive, err
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
@@ -0,0 +1,15 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
Ping(ctx context.Context) (int32, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
@@ -0,0 +1,49 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
client "github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
type Metrics struct {
|
||||
registry *client.Registry
|
||||
requests *client.CounterVec
|
||||
latency *client.HistogramVec
|
||||
}
|
||||
|
||||
func New() *Metrics {
|
||||
registry := client.NewRegistry()
|
||||
requests := client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_http_requests_total",
|
||||
Help: "Total number of HTTP requests served by the API.",
|
||||
}, []string{"method", "route", "status"})
|
||||
latency := client.NewHistogramVec(client.HistogramOpts{
|
||||
Name: "lincodex_http_request_duration_seconds",
|
||||
Help: "HTTP request duration in seconds.",
|
||||
Buckets: client.DefBuckets,
|
||||
}, []string{"method", "route"})
|
||||
registry.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), requests, latency)
|
||||
return &Metrics{registry: registry, requests: requests, latency: latency}
|
||||
}
|
||||
|
||||
func (metrics *Metrics) ObserveRequest(method, route string, status int, duration time.Duration) {
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodOptions:
|
||||
default:
|
||||
method = "OTHER"
|
||||
}
|
||||
metrics.requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc()
|
||||
metrics.latency.WithLabelValues(method, route).Observe(duration.Seconds())
|
||||
}
|
||||
|
||||
func (metrics *Metrics) Handler() http.Handler {
|
||||
return promhttp.HandlerFor(metrics.registry, promhttp.HandlerOpts{})
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.ObserveRequest("CUSTOM", "", 599, 25*time.Millisecond)
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
|
||||
body := response.Body.String()
|
||||
if !strings.Contains(body, `lincodex_http_requests_total{method="OTHER",route="unmatched",status="599"} 1`) {
|
||||
t.Fatalf("metrics output is missing bounded request labels:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(body, `lincodex_http_request_duration_seconds_bucket{method="OTHER",route="unmatched",le="0.05"} 1`) {
|
||||
t.Fatalf("metrics output is missing request duration:\n%s", body)
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
Reference in new issue
Block a user