From ae6633163627108b90c463fee956741adea23ab5 Mon Sep 17 00:00:00 2001 From: Quaternions <krakow20@gmail.com> Date: Wed, 2 Apr 2025 17:59:41 -0700 Subject: [PATCH] openapi: generate --- pkg/internal/oas_client_gen.go | 115 ++++++++++++++++ pkg/internal/oas_handlers_gen.go | 153 ++++++++++++++++++++++ pkg/internal/oas_operations_gen.go | 1 + pkg/internal/oas_parameters_gen.go | 127 ++++++++++++++++++ pkg/internal/oas_response_decoders_gen.go | 51 ++++++++ pkg/internal/oas_response_encoders_gen.go | 7 + pkg/internal/oas_router_gen.go | 92 +++++++++++++ pkg/internal/oas_schemas_gen.go | 3 + pkg/internal/oas_server_gen.go | 6 + pkg/internal/oas_unimplemented_gen.go | 9 ++ 10 files changed, 564 insertions(+) diff --git a/pkg/internal/oas_client_gen.go b/pkg/internal/oas_client_gen.go index 9095d81..21152b2 100644 --- a/pkg/internal/oas_client_gen.go +++ b/pkg/internal/oas_client_gen.go @@ -46,6 +46,12 @@ type Invoker interface { // // POST /mapfixes/{MapfixID}/status/validator-validated ActionMapfixValidated(ctx context.Context, params ActionMapfixValidatedParams) error + // ActionOperationFailed invokes actionOperationFailed operation. + // + // (Internal endpoint) Fail an operation and write a StatusMessage. + // + // POST /operations/{OperationID}/failed + ActionOperationFailed(ctx context.Context, params ActionOperationFailedParams) error // ActionSubmissionAccepted invokes actionSubmissionAccepted operation. // // (Internal endpoint) Role Validator changes status from Validating -> Accepted. @@ -458,6 +464,115 @@ func (c *Client) sendActionMapfixValidated(ctx context.Context, params ActionMap return result, nil } +// ActionOperationFailed invokes actionOperationFailed operation. +// +// (Internal endpoint) Fail an operation and write a StatusMessage. +// +// POST /operations/{OperationID}/failed +func (c *Client) ActionOperationFailed(ctx context.Context, params ActionOperationFailedParams) error { + _, err := c.sendActionOperationFailed(ctx, params) + return err +} + +func (c *Client) sendActionOperationFailed(ctx context.Context, params ActionOperationFailedParams) (res *ActionOperationFailedNoContent, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("actionOperationFailed"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/operations/{OperationID}/failed"), + } + + // 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, ActionOperationFailedOperation, + 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 [3]string + pathParts[0] = "/operations/" + { + // Encode "OperationID" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "OperationID", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.Int32ToString(params.OperationID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + pathParts[2] = "/failed" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeQueryParams" + q := uri.NewQueryEncoder() + { + // Encode "StatusMessage" parameter. + cfg := uri.QueryParameterEncodingConfig{ + Name: "StatusMessage", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(params.StatusMessage)) + }); err != nil { + return res, errors.Wrap(err, "encode query") + } + } + u.RawQuery = q.Values().Encode() + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "POST", 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") + } + defer resp.Body.Close() + + stage = "DecodeResponse" + result, err := decodeActionOperationFailedResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + // ActionSubmissionAccepted invokes actionSubmissionAccepted operation. // // (Internal endpoint) Role Validator changes status from Validating -> Accepted. diff --git a/pkg/internal/oas_handlers_gen.go b/pkg/internal/oas_handlers_gen.go index 5a77b23..99977b4 100644 --- a/pkg/internal/oas_handlers_gen.go +++ b/pkg/internal/oas_handlers_gen.go @@ -481,6 +481,159 @@ func (s *Server) handleActionMapfixValidatedRequest(args [1]string, argsEscaped } } +// handleActionOperationFailedRequest handles actionOperationFailed operation. +// +// (Internal endpoint) Fail an operation and write a StatusMessage. +// +// POST /operations/{OperationID}/failed +func (s *Server) handleActionOperationFailedRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("actionOperationFailed"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/operations/{OperationID}/failed"), + } + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ActionOperationFailedOperation, + 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(codeAttr) + } + 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 + opErrContext = ogenerrors.OperationContext{ + Name: ActionOperationFailedOperation, + ID: "actionOperationFailed", + } + ) + params, err := decodeActionOperationFailedParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var response *ActionOperationFailedNoContent + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ActionOperationFailedOperation, + OperationSummary: "(Internal endpoint) Fail an operation and write a StatusMessage", + OperationID: "actionOperationFailed", + Body: nil, + Params: middleware.Parameters{ + { + Name: "OperationID", + In: "path", + }: params.OperationID, + { + Name: "StatusMessage", + In: "query", + }: params.StatusMessage, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ActionOperationFailedParams + Response = *ActionOperationFailedNoContent + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackActionOperationFailedParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + err = s.h.ActionOperationFailed(ctx, params) + return response, err + }, + ) + } else { + err = s.h.ActionOperationFailed(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ErrorStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeActionOperationFailedResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleActionSubmissionAcceptedRequest handles actionSubmissionAccepted operation. // // (Internal endpoint) Role Validator changes status from Validating -> Accepted. diff --git a/pkg/internal/oas_operations_gen.go b/pkg/internal/oas_operations_gen.go index 6fafed1..9e4ecd3 100644 --- a/pkg/internal/oas_operations_gen.go +++ b/pkg/internal/oas_operations_gen.go @@ -9,6 +9,7 @@ const ( ActionMapfixAcceptedOperation OperationName = "ActionMapfixAccepted" ActionMapfixUploadedOperation OperationName = "ActionMapfixUploaded" ActionMapfixValidatedOperation OperationName = "ActionMapfixValidated" + ActionOperationFailedOperation OperationName = "ActionOperationFailed" ActionSubmissionAcceptedOperation OperationName = "ActionSubmissionAccepted" ActionSubmissionUploadedOperation OperationName = "ActionSubmissionUploaded" ActionSubmissionValidatedOperation OperationName = "ActionSubmissionValidated" diff --git a/pkg/internal/oas_parameters_gen.go b/pkg/internal/oas_parameters_gen.go index 5ce0a6b..9d171fc 100644 --- a/pkg/internal/oas_parameters_gen.go +++ b/pkg/internal/oas_parameters_gen.go @@ -274,6 +274,133 @@ func decodeActionMapfixValidatedParams(args [1]string, argsEscaped bool, r *http return params, nil } +// ActionOperationFailedParams is parameters of actionOperationFailed operation. +type ActionOperationFailedParams struct { + // The unique identifier for a long-running operation. + OperationID int32 + StatusMessage string +} + +func unpackActionOperationFailedParams(packed middleware.Parameters) (params ActionOperationFailedParams) { + { + key := middleware.ParameterKey{ + Name: "OperationID", + In: "path", + } + params.OperationID = packed[key].(int32) + } + { + key := middleware.ParameterKey{ + Name: "StatusMessage", + In: "query", + } + params.StatusMessage = packed[key].(string) + } + return params +} + +func decodeActionOperationFailedParams(args [1]string, argsEscaped bool, r *http.Request) (params ActionOperationFailedParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Decode path: OperationID. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "OperationID", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt32(val) + if err != nil { + return err + } + + params.OperationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "OperationID", + In: "path", + Err: err, + } + } + // Decode query: StatusMessage. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "StatusMessage", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.StatusMessage = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: true, + MaxLength: 4096, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(params.StatusMessage)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "StatusMessage", + In: "query", + Err: err, + } + } + return params, nil +} + // ActionSubmissionAcceptedParams is parameters of actionSubmissionAccepted operation. type ActionSubmissionAcceptedParams struct { // The unique identifier for a submission. diff --git a/pkg/internal/oas_response_decoders_gen.go b/pkg/internal/oas_response_decoders_gen.go index a667917..1c492e1 100644 --- a/pkg/internal/oas_response_decoders_gen.go +++ b/pkg/internal/oas_response_decoders_gen.go @@ -168,6 +168,57 @@ func decodeActionMapfixValidatedResponse(resp *http.Response) (res *ActionMapfix return res, errors.Wrap(defRes, "error") } +func decodeActionOperationFailedResponse(resp *http.Response) (res *ActionOperationFailedNoContent, _ error) { + switch resp.StatusCode { + case 204: + // Code 204. + return &ActionOperationFailedNoContent{}, nil + } + // Convenient error response. + defRes, err := func() (res *ErrorStatusCode, err error) { + 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 Error + 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 + } + return &ErrorStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} + func decodeActionSubmissionAcceptedResponse(resp *http.Response) (res *ActionSubmissionAcceptedNoContent, _ error) { switch resp.StatusCode { case 204: diff --git a/pkg/internal/oas_response_encoders_gen.go b/pkg/internal/oas_response_encoders_gen.go index f8a52bd..ab1b12d 100644 --- a/pkg/internal/oas_response_encoders_gen.go +++ b/pkg/internal/oas_response_encoders_gen.go @@ -34,6 +34,13 @@ func encodeActionMapfixValidatedResponse(response *ActionMapfixValidatedNoConten return nil } +func encodeActionOperationFailedResponse(response *ActionOperationFailedNoContent, w http.ResponseWriter, span trace.Span) error { + w.WriteHeader(204) + span.SetStatus(codes.Ok, http.StatusText(204)) + + return nil +} + func encodeActionSubmissionAcceptedResponse(response *ActionSubmissionAcceptedNoContent, w http.ResponseWriter, span trace.Span) error { w.WriteHeader(204) span.SetStatus(codes.Ok, http.StatusText(204)) diff --git a/pkg/internal/oas_router_gen.go b/pkg/internal/oas_router_gen.go index 0d71206..0531e26 100644 --- a/pkg/internal/oas_router_gen.go +++ b/pkg/internal/oas_router_gen.go @@ -221,6 +221,51 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } + case 'o': // Prefix: "operations/" + + if l := len("operations/"); len(elem) >= l && elem[0:l] == "operations/" { + elem = elem[l:] + } else { + break + } + + // Param: "OperationID" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + break + } + switch elem[0] { + case '/': // Prefix: "/failed" + + if l := len("/failed"); len(elem) >= l && elem[0:l] == "/failed" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleActionOperationFailedRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "POST") + } + + return + } + + } + case 's': // Prefix: "s" if l := len("s"); len(elem) >= l && elem[0:l] == "s" { @@ -751,6 +796,53 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } + case 'o': // Prefix: "operations/" + + if l := len("operations/"); len(elem) >= l && elem[0:l] == "operations/" { + elem = elem[l:] + } else { + break + } + + // Param: "OperationID" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + break + } + switch elem[0] { + case '/': // Prefix: "/failed" + + if l := len("/failed"); len(elem) >= l && elem[0:l] == "/failed" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ActionOperationFailedOperation + r.summary = "(Internal endpoint) Fail an operation and write a StatusMessage" + r.operationID = "actionOperationFailed" + r.pathPattern = "/operations/{OperationID}/failed" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + case 's': // Prefix: "s" if l := len("s"); len(elem) >= l && elem[0:l] == "s" { diff --git a/pkg/internal/oas_schemas_gen.go b/pkg/internal/oas_schemas_gen.go index 86270ec..cc5c4ed 100644 --- a/pkg/internal/oas_schemas_gen.go +++ b/pkg/internal/oas_schemas_gen.go @@ -19,6 +19,9 @@ type ActionMapfixUploadedNoContent struct{} // ActionMapfixValidatedNoContent is response for ActionMapfixValidated operation. type ActionMapfixValidatedNoContent struct{} +// ActionOperationFailedNoContent is response for ActionOperationFailed operation. +type ActionOperationFailedNoContent struct{} + // ActionSubmissionAcceptedNoContent is response for ActionSubmissionAccepted operation. type ActionSubmissionAcceptedNoContent struct{} diff --git a/pkg/internal/oas_server_gen.go b/pkg/internal/oas_server_gen.go index 0ca4100..0423592 100644 --- a/pkg/internal/oas_server_gen.go +++ b/pkg/internal/oas_server_gen.go @@ -26,6 +26,12 @@ type Handler interface { // // POST /mapfixes/{MapfixID}/status/validator-validated ActionMapfixValidated(ctx context.Context, params ActionMapfixValidatedParams) error + // ActionOperationFailed implements actionOperationFailed operation. + // + // (Internal endpoint) Fail an operation and write a StatusMessage. + // + // POST /operations/{OperationID}/failed + ActionOperationFailed(ctx context.Context, params ActionOperationFailedParams) error // ActionSubmissionAccepted implements actionSubmissionAccepted operation. // // (Internal endpoint) Role Validator changes status from Validating -> Accepted. diff --git a/pkg/internal/oas_unimplemented_gen.go b/pkg/internal/oas_unimplemented_gen.go index c4ac65a..0f56dad 100644 --- a/pkg/internal/oas_unimplemented_gen.go +++ b/pkg/internal/oas_unimplemented_gen.go @@ -40,6 +40,15 @@ func (UnimplementedHandler) ActionMapfixValidated(ctx context.Context, params Ac return ht.ErrNotImplemented } +// ActionOperationFailed implements actionOperationFailed operation. +// +// (Internal endpoint) Fail an operation and write a StatusMessage. +// +// POST /operations/{OperationID}/failed +func (UnimplementedHandler) ActionOperationFailed(ctx context.Context, params ActionOperationFailedParams) error { + return ht.ErrNotImplemented +} + // ActionSubmissionAccepted implements actionSubmissionAccepted operation. // // (Internal endpoint) Role Validator changes status from Validating -> Accepted.