From 7ad4ffc7e0ee95f90b70934a50b2ec247bed7b63 Mon Sep 17 00:00:00 2001 From: Quaternions Date: Tue, 17 Dec 2024 18:12:00 -0800 Subject: [PATCH] openapi: generate --- pkg/internal/oas_client_gen.go | 580 ++++++++++++++ pkg/internal/oas_handlers_gen.go | 902 ++++++++++++++++++++++ pkg/internal/oas_json_gen.go | 702 +++++++++++++++++ pkg/internal/oas_operations_gen.go | 6 + pkg/internal/oas_parameters_gen.go | 368 +++++++++ pkg/internal/oas_request_decoders_gen.go | 147 ++++ pkg/internal/oas_request_encoders_gen.go | 37 + pkg/internal/oas_response_decoders_gen.go | 452 +++++++++++ pkg/internal/oas_response_encoders_gen.go | 70 ++ pkg/internal/oas_router_gen.go | 562 ++++++++++++-- pkg/internal/oas_schemas_gen.go | 202 +++++ pkg/internal/oas_server_gen.go | 36 + pkg/internal/oas_unimplemented_gen.go | 54 ++ pkg/internal/oas_validators_gen.go | 159 ++++ 14 files changed, 4195 insertions(+), 82 deletions(-) create mode 100644 pkg/internal/oas_validators_gen.go diff --git a/pkg/internal/oas_client_gen.go b/pkg/internal/oas_client_gen.go index 50ffab4..20e9d2e 100644 --- a/pkg/internal/oas_client_gen.go +++ b/pkg/internal/oas_client_gen.go @@ -23,6 +23,12 @@ import ( // Invoker invokes operations described by OpenAPI v3 specification. type Invoker interface { + // ActionSubmissionAccepted invokes actionSubmissionAccepted operation. + // + // (Internal endpoint) Role Validator changes status from Validating -> Accepted. + // + // POST /submissions/{SubmissionID}/status/validator-failed + ActionSubmissionAccepted(ctx context.Context, params ActionSubmissionAcceptedParams) error // ActionSubmissionReleased invokes actionSubmissionReleased operation. // // (Internal endpoint) Role Releaser changes status from releasing -> released. @@ -41,6 +47,36 @@ type Invoker interface { // // POST /submissions/{SubmissionID}/status/validator-validated ActionSubmissionValidated(ctx context.Context, params ActionSubmissionValidatedParams) error + // CreateScript invokes createScript operation. + // + // Create a new script. + // + // POST /scripts + CreateScript(ctx context.Context, request *ScriptCreate) (*ID, error) + // CreateScriptPolicy invokes createScriptPolicy operation. + // + // Create a new script policy. + // + // POST /script-policy + CreateScriptPolicy(ctx context.Context, request *ScriptPolicyCreate) (*ID, error) + // GetScript invokes getScript operation. + // + // Get the specified script by ID. + // + // GET /scripts/{ScriptID} + GetScript(ctx context.Context, params GetScriptParams) (*Script, error) + // GetScriptPolicyFromHash invokes getScriptPolicyFromHash operation. + // + // Get the policy for the given hash of script source code. + // + // GET /script-policy/hash/{FromScriptHash} + GetScriptPolicyFromHash(ctx context.Context, params GetScriptPolicyFromHashParams) (*ScriptPolicy, error) + // UpdateSubmissionModel invokes updateSubmissionModel operation. + // + // Update model following role restrictions. + // + // POST /submissions/{SubmissionID}/model + UpdateSubmissionModel(ctx context.Context, params UpdateSubmissionModelParams) error } // Client implements OAS client. @@ -95,6 +131,97 @@ func (c *Client) requestURL(ctx context.Context) *url.URL { return u } +// ActionSubmissionAccepted invokes actionSubmissionAccepted operation. +// +// (Internal endpoint) Role Validator changes status from Validating -> Accepted. +// +// POST /submissions/{SubmissionID}/status/validator-failed +func (c *Client) ActionSubmissionAccepted(ctx context.Context, params ActionSubmissionAcceptedParams) error { + _, err := c.sendActionSubmissionAccepted(ctx, params) + return err +} + +func (c *Client) sendActionSubmissionAccepted(ctx context.Context, params ActionSubmissionAcceptedParams) (res *ActionSubmissionAcceptedNoContent, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("actionSubmissionAccepted"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/submissions/{SubmissionID}/status/validator-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, ActionSubmissionAcceptedOperation, + 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] = "/submissions/" + { + // Encode "SubmissionID" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "SubmissionID", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.Int64ToString(params.SubmissionID)) + }(); 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] = "/status/validator-failed" + uri.AddPathParts(u, pathParts[:]...) + + 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 := decodeActionSubmissionAcceptedResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + // ActionSubmissionReleased invokes actionSubmissionReleased operation. // // (Internal endpoint) Role Releaser changes status from releasing -> released. @@ -388,3 +515,456 @@ func (c *Client) sendActionSubmissionValidated(ctx context.Context, params Actio return result, nil } + +// CreateScript invokes createScript operation. +// +// Create a new script. +// +// POST /scripts +func (c *Client) CreateScript(ctx context.Context, request *ScriptCreate) (*ID, error) { + res, err := c.sendCreateScript(ctx, request) + return res, err +} + +func (c *Client) sendCreateScript(ctx context.Context, request *ScriptCreate) (res *ID, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("createScript"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/scripts"), + } + + // 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, CreateScriptOperation, + 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] = "/scripts" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "POST", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + if err := encodeCreateScriptRequest(request, r); err != nil { + return res, errors.Wrap(err, "encode 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 := decodeCreateScriptResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// CreateScriptPolicy invokes createScriptPolicy operation. +// +// Create a new script policy. +// +// POST /script-policy +func (c *Client) CreateScriptPolicy(ctx context.Context, request *ScriptPolicyCreate) (*ID, error) { + res, err := c.sendCreateScriptPolicy(ctx, request) + return res, err +} + +func (c *Client) sendCreateScriptPolicy(ctx context.Context, request *ScriptPolicyCreate) (res *ID, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("createScriptPolicy"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/script-policy"), + } + + // 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, CreateScriptPolicyOperation, + 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] = "/script-policy" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "POST", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + if err := encodeCreateScriptPolicyRequest(request, r); err != nil { + return res, errors.Wrap(err, "encode 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 := decodeCreateScriptPolicyResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// GetScript invokes getScript operation. +// +// Get the specified script by ID. +// +// GET /scripts/{ScriptID} +func (c *Client) GetScript(ctx context.Context, params GetScriptParams) (*Script, error) { + res, err := c.sendGetScript(ctx, params) + return res, err +} + +func (c *Client) sendGetScript(ctx context.Context, params GetScriptParams) (res *Script, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("getScript"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/scripts/{ScriptID}"), + } + + // 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, GetScriptOperation, + 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 [2]string + pathParts[0] = "/scripts/" + { + // Encode "ScriptID" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "ScriptID", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.Int64ToString(params.ScriptID)) + }(); 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 + } + 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") + } + defer resp.Body.Close() + + stage = "DecodeResponse" + result, err := decodeGetScriptResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// GetScriptPolicyFromHash invokes getScriptPolicyFromHash operation. +// +// Get the policy for the given hash of script source code. +// +// GET /script-policy/hash/{FromScriptHash} +func (c *Client) GetScriptPolicyFromHash(ctx context.Context, params GetScriptPolicyFromHashParams) (*ScriptPolicy, error) { + res, err := c.sendGetScriptPolicyFromHash(ctx, params) + return res, err +} + +func (c *Client) sendGetScriptPolicyFromHash(ctx context.Context, params GetScriptPolicyFromHashParams) (res *ScriptPolicy, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("getScriptPolicyFromHash"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/script-policy/hash/{FromScriptHash}"), + } + + // 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, GetScriptPolicyFromHashOperation, + 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 [2]string + pathParts[0] = "/script-policy/hash/" + { + // Encode "FromScriptHash" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "FromScriptHash", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.StringToString(params.FromScriptHash)) + }(); 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 + } + 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") + } + defer resp.Body.Close() + + stage = "DecodeResponse" + result, err := decodeGetScriptPolicyFromHashResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// UpdateSubmissionModel invokes updateSubmissionModel operation. +// +// Update model following role restrictions. +// +// POST /submissions/{SubmissionID}/model +func (c *Client) UpdateSubmissionModel(ctx context.Context, params UpdateSubmissionModelParams) error { + _, err := c.sendUpdateSubmissionModel(ctx, params) + return err +} + +func (c *Client) sendUpdateSubmissionModel(ctx context.Context, params UpdateSubmissionModelParams) (res *UpdateSubmissionModelNoContent, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("updateSubmissionModel"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/submissions/{SubmissionID}/model"), + } + + // 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, UpdateSubmissionModelOperation, + 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] = "/submissions/" + { + // Encode "SubmissionID" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "SubmissionID", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.Int64ToString(params.SubmissionID)) + }(); 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] = "/model" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeQueryParams" + q := uri.NewQueryEncoder() + { + // Encode "ModelID" parameter. + cfg := uri.QueryParameterEncodingConfig{ + Name: "ModelID", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.Int64ToString(params.ModelID)) + }); err != nil { + return res, errors.Wrap(err, "encode query") + } + } + { + // Encode "VersionID" parameter. + cfg := uri.QueryParameterEncodingConfig{ + Name: "VersionID", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.Int64ToString(params.VersionID)) + }); 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 := decodeUpdateSubmissionModelResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} diff --git a/pkg/internal/oas_handlers_gen.go b/pkg/internal/oas_handlers_gen.go index 375a08d..c072c08 100644 --- a/pkg/internal/oas_handlers_gen.go +++ b/pkg/internal/oas_handlers_gen.go @@ -30,6 +30,155 @@ func (c *codeRecorder) WriteHeader(status int) { c.ResponseWriter.WriteHeader(status) } +// handleActionSubmissionAcceptedRequest handles actionSubmissionAccepted operation. +// +// (Internal endpoint) Role Validator changes status from Validating -> Accepted. +// +// POST /submissions/{SubmissionID}/status/validator-failed +func (s *Server) handleActionSubmissionAcceptedRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("actionSubmissionAccepted"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/submissions/{SubmissionID}/status/validator-failed"), + } + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ActionSubmissionAcceptedOperation, + 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: ActionSubmissionAcceptedOperation, + ID: "actionSubmissionAccepted", + } + ) + params, err := decodeActionSubmissionAcceptedParams(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 *ActionSubmissionAcceptedNoContent + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ActionSubmissionAcceptedOperation, + OperationSummary: "(Internal endpoint) Role Validator changes status from Validating -> Accepted", + OperationID: "actionSubmissionAccepted", + Body: nil, + Params: middleware.Parameters{ + { + Name: "SubmissionID", + In: "path", + }: params.SubmissionID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ActionSubmissionAcceptedParams + Response = *ActionSubmissionAcceptedNoContent + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackActionSubmissionAcceptedParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + err = s.h.ActionSubmissionAccepted(ctx, params) + return response, err + }, + ) + } else { + err = s.h.ActionSubmissionAccepted(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 := encodeActionSubmissionAcceptedResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleActionSubmissionReleasedRequest handles actionSubmissionReleased operation. // // (Internal endpoint) Role Releaser changes status from releasing -> released. @@ -480,3 +629,756 @@ func (s *Server) handleActionSubmissionValidatedRequest(args [1]string, argsEsca return } } + +// handleCreateScriptRequest handles createScript operation. +// +// Create a new script. +// +// POST /scripts +func (s *Server) handleCreateScriptRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("createScript"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/scripts"), + } + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateScriptOperation, + 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: CreateScriptOperation, + ID: "createScript", + } + ) + request, close, err := s.decodeCreateScriptRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response *ID + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateScriptOperation, + OperationSummary: "Create a new script", + OperationID: "createScript", + Body: request, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *ScriptCreate + Params = struct{} + Response = *ID + ) + 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.CreateScript(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.CreateScript(ctx, request) + } + 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 := encodeCreateScriptResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleCreateScriptPolicyRequest handles createScriptPolicy operation. +// +// Create a new script policy. +// +// POST /script-policy +func (s *Server) handleCreateScriptPolicyRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("createScriptPolicy"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/script-policy"), + } + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateScriptPolicyOperation, + 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: CreateScriptPolicyOperation, + ID: "createScriptPolicy", + } + ) + request, close, err := s.decodeCreateScriptPolicyRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response *ID + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateScriptPolicyOperation, + OperationSummary: "Create a new script policy", + OperationID: "createScriptPolicy", + Body: request, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *ScriptPolicyCreate + Params = struct{} + Response = *ID + ) + 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.CreateScriptPolicy(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.CreateScriptPolicy(ctx, request) + } + 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 := encodeCreateScriptPolicyResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetScriptRequest handles getScript operation. +// +// Get the specified script by ID. +// +// GET /scripts/{ScriptID} +func (s *Server) handleGetScriptRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("getScript"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/scripts/{ScriptID}"), + } + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetScriptOperation, + 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: GetScriptOperation, + ID: "getScript", + } + ) + params, err := decodeGetScriptParams(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 *Script + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetScriptOperation, + OperationSummary: "Get the specified script by ID", + OperationID: "getScript", + Body: nil, + Params: middleware.Parameters{ + { + Name: "ScriptID", + In: "path", + }: params.ScriptID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetScriptParams + Response = *Script + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetScriptParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetScript(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetScript(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 := encodeGetScriptResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetScriptPolicyFromHashRequest handles getScriptPolicyFromHash operation. +// +// Get the policy for the given hash of script source code. +// +// GET /script-policy/hash/{FromScriptHash} +func (s *Server) handleGetScriptPolicyFromHashRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("getScriptPolicyFromHash"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/script-policy/hash/{FromScriptHash}"), + } + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetScriptPolicyFromHashOperation, + 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: GetScriptPolicyFromHashOperation, + ID: "getScriptPolicyFromHash", + } + ) + params, err := decodeGetScriptPolicyFromHashParams(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 *ScriptPolicy + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetScriptPolicyFromHashOperation, + OperationSummary: "Get the policy for the given hash of script source code", + OperationID: "getScriptPolicyFromHash", + Body: nil, + Params: middleware.Parameters{ + { + Name: "FromScriptHash", + In: "path", + }: params.FromScriptHash, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetScriptPolicyFromHashParams + Response = *ScriptPolicy + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetScriptPolicyFromHashParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetScriptPolicyFromHash(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetScriptPolicyFromHash(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 := encodeGetScriptPolicyFromHashResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleUpdateSubmissionModelRequest handles updateSubmissionModel operation. +// +// Update model following role restrictions. +// +// POST /submissions/{SubmissionID}/model +func (s *Server) handleUpdateSubmissionModelRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("updateSubmissionModel"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/submissions/{SubmissionID}/model"), + } + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateSubmissionModelOperation, + 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: UpdateSubmissionModelOperation, + ID: "updateSubmissionModel", + } + ) + params, err := decodeUpdateSubmissionModelParams(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 *UpdateSubmissionModelNoContent + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: UpdateSubmissionModelOperation, + OperationSummary: "Update model following role restrictions", + OperationID: "updateSubmissionModel", + Body: nil, + Params: middleware.Parameters{ + { + Name: "SubmissionID", + In: "path", + }: params.SubmissionID, + { + Name: "ModelID", + In: "query", + }: params.ModelID, + { + Name: "VersionID", + In: "query", + }: params.VersionID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = UpdateSubmissionModelParams + Response = *UpdateSubmissionModelNoContent + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackUpdateSubmissionModelParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + err = s.h.UpdateSubmissionModel(ctx, params) + return response, err + }, + ) + } else { + err = s.h.UpdateSubmissionModel(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 := encodeUpdateSubmissionModelResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} diff --git a/pkg/internal/oas_json_gen.go b/pkg/internal/oas_json_gen.go index 71b3067..47793c8 100644 --- a/pkg/internal/oas_json_gen.go +++ b/pkg/internal/oas_json_gen.go @@ -124,3 +124,705 @@ func (s *Error) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } + +// Encode implements json.Marshaler. +func (s *ID) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ID) encodeFields(e *jx.Encoder) { + { + e.FieldStart("ID") + e.Int64(s.ID) + } +} + +var jsonFieldsNameOfID = [1]string{ + 0: "ID", +} + +// Decode decodes ID from json. +func (s *ID) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ID to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "ID": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int64() + s.ID = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ID\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ID") + } + // 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(jsonFieldsNameOfID) { + name = jsonFieldsNameOfID[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 *ID) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ID) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes int64 as json. +func (o OptInt64) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Int64(int64(o.Value)) +} + +// Decode decodes int64 from json. +func (o *OptInt64) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptInt64 to nil") + } + o.Set = true + v, err := d.Int64() + if err != nil { + return err + } + o.Value = int64(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptInt64) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptInt64) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *Script) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Script) encodeFields(e *jx.Encoder) { + { + e.FieldStart("ID") + e.Int64(s.ID) + } + { + e.FieldStart("Name") + e.Str(s.Name) + } + { + e.FieldStart("Hash") + e.Str(s.Hash) + } + { + e.FieldStart("Source") + e.Str(s.Source) + } + { + e.FieldStart("SubmissionID") + e.Int64(s.SubmissionID) + } +} + +var jsonFieldsNameOfScript = [5]string{ + 0: "ID", + 1: "Name", + 2: "Hash", + 3: "Source", + 4: "SubmissionID", +} + +// Decode decodes Script from json. +func (s *Script) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Script to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "ID": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int64() + s.ID = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ID\"") + } + case "Name": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Name = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"Name\"") + } + case "Hash": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Hash = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"Hash\"") + } + case "Source": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Str() + s.Source = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"Source\"") + } + case "SubmissionID": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := d.Int64() + s.SubmissionID = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"SubmissionID\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Script") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00011111, + } { + 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(jsonFieldsNameOfScript) { + name = jsonFieldsNameOfScript[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 *Script) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Script) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ScriptCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ScriptCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("Name") + e.Str(s.Name) + } + { + e.FieldStart("Source") + e.Str(s.Source) + } + { + if s.SubmissionID.Set { + e.FieldStart("SubmissionID") + s.SubmissionID.Encode(e) + } + } +} + +var jsonFieldsNameOfScriptCreate = [3]string{ + 0: "Name", + 1: "Source", + 2: "SubmissionID", +} + +// Decode decodes ScriptCreate from json. +func (s *ScriptCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ScriptCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "Name": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Name = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"Name\"") + } + case "Source": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Source = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"Source\"") + } + case "SubmissionID": + if err := func() error { + s.SubmissionID.Reset() + if err := s.SubmissionID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"SubmissionID\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ScriptCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + 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(jsonFieldsNameOfScriptCreate) { + name = jsonFieldsNameOfScriptCreate[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 *ScriptCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ScriptCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ScriptPolicy) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ScriptPolicy) encodeFields(e *jx.Encoder) { + { + e.FieldStart("ID") + e.Int64(s.ID) + } + { + e.FieldStart("FromScriptHash") + e.Str(s.FromScriptHash) + } + { + e.FieldStart("ToScriptID") + e.Int64(s.ToScriptID) + } + { + e.FieldStart("Policy") + e.Int32(s.Policy) + } +} + +var jsonFieldsNameOfScriptPolicy = [4]string{ + 0: "ID", + 1: "FromScriptHash", + 2: "ToScriptID", + 3: "Policy", +} + +// Decode decodes ScriptPolicy from json. +func (s *ScriptPolicy) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ScriptPolicy to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "ID": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int64() + s.ID = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ID\"") + } + case "FromScriptHash": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.FromScriptHash = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"FromScriptHash\"") + } + case "ToScriptID": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int64() + s.ToScriptID = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ToScriptID\"") + } + case "Policy": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.Policy = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"Policy\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ScriptPolicy") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + 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(jsonFieldsNameOfScriptPolicy) { + name = jsonFieldsNameOfScriptPolicy[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 *ScriptPolicy) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ScriptPolicy) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ScriptPolicyCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ScriptPolicyCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("FromScriptID") + e.Int64(s.FromScriptID) + } + { + e.FieldStart("ToScriptID") + e.Int64(s.ToScriptID) + } + { + e.FieldStart("Policy") + e.Int32(s.Policy) + } +} + +var jsonFieldsNameOfScriptPolicyCreate = [3]string{ + 0: "FromScriptID", + 1: "ToScriptID", + 2: "Policy", +} + +// Decode decodes ScriptPolicyCreate from json. +func (s *ScriptPolicyCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ScriptPolicyCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "FromScriptID": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int64() + s.FromScriptID = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"FromScriptID\"") + } + case "ToScriptID": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int64() + s.ToScriptID = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ToScriptID\"") + } + case "Policy": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Policy = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"Policy\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ScriptPolicyCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + 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(jsonFieldsNameOfScriptPolicyCreate) { + name = jsonFieldsNameOfScriptPolicyCreate[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 *ScriptPolicyCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ScriptPolicyCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/pkg/internal/oas_operations_gen.go b/pkg/internal/oas_operations_gen.go index fc1b72a..31c7a14 100644 --- a/pkg/internal/oas_operations_gen.go +++ b/pkg/internal/oas_operations_gen.go @@ -6,7 +6,13 @@ package api type OperationName = string const ( + ActionSubmissionAcceptedOperation OperationName = "ActionSubmissionAccepted" ActionSubmissionReleasedOperation OperationName = "ActionSubmissionReleased" ActionSubmissionUploadedOperation OperationName = "ActionSubmissionUploaded" ActionSubmissionValidatedOperation OperationName = "ActionSubmissionValidated" + CreateScriptOperation OperationName = "CreateScript" + CreateScriptPolicyOperation OperationName = "CreateScriptPolicy" + GetScriptOperation OperationName = "GetScript" + GetScriptPolicyFromHashOperation OperationName = "GetScriptPolicyFromHash" + UpdateSubmissionModelOperation OperationName = "UpdateSubmissionModel" ) diff --git a/pkg/internal/oas_parameters_gen.go b/pkg/internal/oas_parameters_gen.go index b3aa388..d75b26c 100644 --- a/pkg/internal/oas_parameters_gen.go +++ b/pkg/internal/oas_parameters_gen.go @@ -15,6 +15,72 @@ import ( "github.com/ogen-go/ogen/validate" ) +// ActionSubmissionAcceptedParams is parameters of actionSubmissionAccepted operation. +type ActionSubmissionAcceptedParams struct { + // The unique identifier for a submission. + SubmissionID int64 +} + +func unpackActionSubmissionAcceptedParams(packed middleware.Parameters) (params ActionSubmissionAcceptedParams) { + { + key := middleware.ParameterKey{ + Name: "SubmissionID", + In: "path", + } + params.SubmissionID = packed[key].(int64) + } + return params +} + +func decodeActionSubmissionAcceptedParams(args [1]string, argsEscaped bool, r *http.Request) (params ActionSubmissionAcceptedParams, _ error) { + // Decode path: SubmissionID. + 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: "SubmissionID", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt64(val) + if err != nil { + return err + } + + params.SubmissionID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "SubmissionID", + In: "path", + Err: err, + } + } + return params, nil +} + // ActionSubmissionReleasedParams is parameters of actionSubmissionReleased operation. type ActionSubmissionReleasedParams struct { // The unique identifier for a submission. @@ -264,3 +330,305 @@ func decodeActionSubmissionValidatedParams(args [1]string, argsEscaped bool, r * } return params, nil } + +// GetScriptParams is parameters of getScript operation. +type GetScriptParams struct { + // The unique identifier for a script. + ScriptID int64 +} + +func unpackGetScriptParams(packed middleware.Parameters) (params GetScriptParams) { + { + key := middleware.ParameterKey{ + Name: "ScriptID", + In: "path", + } + params.ScriptID = packed[key].(int64) + } + return params +} + +func decodeGetScriptParams(args [1]string, argsEscaped bool, r *http.Request) (params GetScriptParams, _ error) { + // Decode path: ScriptID. + 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: "ScriptID", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt64(val) + if err != nil { + return err + } + + params.ScriptID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "ScriptID", + In: "path", + Err: err, + } + } + return params, nil +} + +// GetScriptPolicyFromHashParams is parameters of getScriptPolicyFromHash operation. +type GetScriptPolicyFromHashParams struct { + FromScriptHash string +} + +func unpackGetScriptPolicyFromHashParams(packed middleware.Parameters) (params GetScriptPolicyFromHashParams) { + { + key := middleware.ParameterKey{ + Name: "FromScriptHash", + In: "path", + } + params.FromScriptHash = packed[key].(string) + } + return params +} + +func decodeGetScriptPolicyFromHashParams(args [1]string, argsEscaped bool, r *http.Request) (params GetScriptPolicyFromHashParams, _ error) { + // Decode path: FromScriptHash. + 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: "FromScriptHash", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.FromScriptHash = c + return nil + }(); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 16, + MinLengthSet: true, + MaxLength: 16, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(params.FromScriptHash)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "FromScriptHash", + In: "path", + Err: err, + } + } + return params, nil +} + +// UpdateSubmissionModelParams is parameters of updateSubmissionModel operation. +type UpdateSubmissionModelParams struct { + // The unique identifier for a submission. + SubmissionID int64 + ModelID int64 + VersionID int64 +} + +func unpackUpdateSubmissionModelParams(packed middleware.Parameters) (params UpdateSubmissionModelParams) { + { + key := middleware.ParameterKey{ + Name: "SubmissionID", + In: "path", + } + params.SubmissionID = packed[key].(int64) + } + { + key := middleware.ParameterKey{ + Name: "ModelID", + In: "query", + } + params.ModelID = packed[key].(int64) + } + { + key := middleware.ParameterKey{ + Name: "VersionID", + In: "query", + } + params.VersionID = packed[key].(int64) + } + return params +} + +func decodeUpdateSubmissionModelParams(args [1]string, argsEscaped bool, r *http.Request) (params UpdateSubmissionModelParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Decode path: SubmissionID. + 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: "SubmissionID", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt64(val) + if err != nil { + return err + } + + params.SubmissionID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "SubmissionID", + In: "path", + Err: err, + } + } + // Decode query: ModelID. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "ModelID", + 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.ToInt64(val) + if err != nil { + return err + } + + params.ModelID = c + return nil + }); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "ModelID", + In: "query", + Err: err, + } + } + // Decode query: VersionID. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "VersionID", + 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.ToInt64(val) + if err != nil { + return err + } + + params.VersionID = c + return nil + }); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "VersionID", + In: "query", + Err: err, + } + } + return params, nil +} diff --git a/pkg/internal/oas_request_decoders_gen.go b/pkg/internal/oas_request_decoders_gen.go index ae379a2..db79c40 100644 --- a/pkg/internal/oas_request_decoders_gen.go +++ b/pkg/internal/oas_request_decoders_gen.go @@ -1,3 +1,150 @@ // Code generated by ogen, DO NOT EDIT. package api + +import ( + "io" + "mime" + "net/http" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "go.uber.org/multierr" + + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/validate" +) + +func (s *Server) decodeCreateScriptRequest(r *http.Request) ( + req *ScriptCreate, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = multierr.Append(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = multierr.Append(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + if err != nil { + return req, close, err + } + + if len(buf) == 0 { + return req, close, validate.ErrBodyRequired + } + + d := jx.DecodeBytes(buf) + + var request ScriptCreate + if err := func() error { + if err := request.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 req, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, close, errors.Wrap(err, "validate") + } + return &request, close, nil + default: + return req, close, validate.InvalidContentType(ct) + } +} + +func (s *Server) decodeCreateScriptPolicyRequest(r *http.Request) ( + req *ScriptPolicyCreate, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = multierr.Append(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = multierr.Append(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + if err != nil { + return req, close, err + } + + if len(buf) == 0 { + return req, close, validate.ErrBodyRequired + } + + d := jx.DecodeBytes(buf) + + var request ScriptPolicyCreate + if err := func() error { + if err := request.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 req, close, err + } + return &request, close, nil + default: + return req, close, validate.InvalidContentType(ct) + } +} diff --git a/pkg/internal/oas_request_encoders_gen.go b/pkg/internal/oas_request_encoders_gen.go index ae379a2..a0e7305 100644 --- a/pkg/internal/oas_request_encoders_gen.go +++ b/pkg/internal/oas_request_encoders_gen.go @@ -1,3 +1,40 @@ // Code generated by ogen, DO NOT EDIT. package api + +import ( + "bytes" + "net/http" + + "github.com/go-faster/jx" + + ht "github.com/ogen-go/ogen/http" +) + +func encodeCreateScriptRequest( + req *ScriptCreate, + r *http.Request, +) error { + const contentType = "application/json" + e := new(jx.Encoder) + { + req.Encode(e) + } + encoded := e.Bytes() + ht.SetBody(r, bytes.NewReader(encoded), contentType) + return nil +} + +func encodeCreateScriptPolicyRequest( + req *ScriptPolicyCreate, + r *http.Request, +) error { + const contentType = "application/json" + e := new(jx.Encoder) + { + req.Encode(e) + } + encoded := e.Bytes() + ht.SetBody(r, bytes.NewReader(encoded), contentType) + return nil +} diff --git a/pkg/internal/oas_response_decoders_gen.go b/pkg/internal/oas_response_decoders_gen.go index 1feec44..6594497 100644 --- a/pkg/internal/oas_response_decoders_gen.go +++ b/pkg/internal/oas_response_decoders_gen.go @@ -14,6 +14,57 @@ import ( "github.com/ogen-go/ogen/validate" ) +func decodeActionSubmissionAcceptedResponse(resp *http.Response) (res *ActionSubmissionAcceptedNoContent, _ error) { + switch resp.StatusCode { + case 204: + // Code 204. + return &ActionSubmissionAcceptedNoContent{}, 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 decodeActionSubmissionReleasedResponse(resp *http.Response) (res *ActionSubmissionReleasedNoContent, _ error) { switch resp.StatusCode { case 204: @@ -166,3 +217,404 @@ func decodeActionSubmissionValidatedResponse(resp *http.Response) (res *ActionSu } return res, errors.Wrap(defRes, "error") } + +func decodeCreateScriptResponse(resp *http.Response) (res *ID, _ error) { + switch resp.StatusCode { + case 201: + // Code 201. + 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 ID + 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 &response, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // 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 decodeCreateScriptPolicyResponse(resp *http.Response) (res *ID, _ error) { + switch resp.StatusCode { + case 201: + // Code 201. + 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 ID + 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 &response, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // 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 decodeGetScriptResponse(resp *http.Response) (res *Script, _ 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 Script + 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) + } + } + // 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 decodeGetScriptPolicyFromHashResponse(resp *http.Response) (res *ScriptPolicy, _ 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 ScriptPolicy + 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) + } + } + // 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 decodeUpdateSubmissionModelResponse(resp *http.Response) (res *UpdateSubmissionModelNoContent, _ error) { + switch resp.StatusCode { + case 204: + // Code 204. + return &UpdateSubmissionModelNoContent{}, 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") +} diff --git a/pkg/internal/oas_response_encoders_gen.go b/pkg/internal/oas_response_encoders_gen.go index 182bdf1..1c2c959 100644 --- a/pkg/internal/oas_response_encoders_gen.go +++ b/pkg/internal/oas_response_encoders_gen.go @@ -13,6 +13,13 @@ import ( ht "github.com/ogen-go/ogen/http" ) +func encodeActionSubmissionAcceptedResponse(response *ActionSubmissionAcceptedNoContent, w http.ResponseWriter, span trace.Span) error { + w.WriteHeader(204) + span.SetStatus(codes.Ok, http.StatusText(204)) + + return nil +} + func encodeActionSubmissionReleasedResponse(response *ActionSubmissionReleasedNoContent, w http.ResponseWriter, span trace.Span) error { w.WriteHeader(204) span.SetStatus(codes.Ok, http.StatusText(204)) @@ -34,6 +41,69 @@ func encodeActionSubmissionValidatedResponse(response *ActionSubmissionValidated return nil } +func encodeCreateScriptResponse(response *ID, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(201) + span.SetStatus(codes.Ok, http.StatusText(201)) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil +} + +func encodeCreateScriptPolicyResponse(response *ID, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(201) + span.SetStatus(codes.Ok, http.StatusText(201)) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil +} + +func encodeGetScriptResponse(response *Script, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + span.SetStatus(codes.Ok, http.StatusText(200)) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil +} + +func encodeGetScriptPolicyFromHashResponse(response *ScriptPolicy, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + span.SetStatus(codes.Ok, http.StatusText(200)) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil +} + +func encodeUpdateSubmissionModelResponse(response *UpdateSubmissionModelNoContent, w http.ResponseWriter, span trace.Span) error { + w.WriteHeader(204) + span.SetStatus(codes.Ok, http.StatusText(204)) + + return nil +} + func encodeErrorResponse(response *ErrorStatusCode, w http.ResponseWriter, span trace.Span) error { w.Header().Set("Content-Type", "application/json; charset=utf-8") code := response.StatusCode diff --git a/pkg/internal/oas_router_gen.go b/pkg/internal/oas_router_gen.go index 829caf0..e8907bb 100644 --- a/pkg/internal/oas_router_gen.go +++ b/pkg/internal/oas_router_gen.go @@ -49,30 +49,21 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case '/': // Prefix: "/submissions/" + case '/': // Prefix: "/s" origElem := elem - if l := len("/submissions/"); len(elem) >= l && elem[0:l] == "/submissions/" { + if l := len("/s"); len(elem) >= l && elem[0:l] == "/s" { elem = elem[l:] } else { break } - // Param: "SubmissionID" - // 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: "/status/" + case 'c': // Prefix: "cript" origElem := elem - if l := len("/status/"); len(elem) >= l && elem[0:l] == "/status/" { + if l := len("cript"); len(elem) >= l && elem[0:l] == "cript" { elem = elem[l:] } else { break @@ -82,32 +73,133 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case 'r': // Prefix: "releaser-released" + case '-': // Prefix: "-policy" origElem := elem - if l := len("releaser-released"); len(elem) >= l && elem[0:l] == "releaser-released" { + if l := len("-policy"); len(elem) >= l && elem[0:l] == "-policy" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. switch r.Method { case "POST": - s.handleActionSubmissionReleasedRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) + s.handleCreateScriptPolicyRequest([0]string{}, elemIsEscaped, w, r) default: s.notAllowed(w, r, "POST") } return } + switch elem[0] { + case '/': // Prefix: "/hash/" + origElem := elem + if l := len("/hash/"); len(elem) >= l && elem[0:l] == "/hash/" { + elem = elem[l:] + } else { + break + } + + // Param: "FromScriptHash" + // Leaf parameter + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetScriptPolicyFromHashRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "GET") + } + + return + } + + elem = origElem + } elem = origElem - case 'v': // Prefix: "validator-" + case 's': // Prefix: "s" origElem := elem - if l := len("validator-"); len(elem) >= l && elem[0:l] == "validator-" { + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "POST": + s.handleCreateScriptRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "POST") + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + origElem := elem + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "ScriptID" + // Leaf parameter + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetScriptRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "GET") + } + + return + } + + elem = origElem + } + + elem = origElem + } + + elem = origElem + case 'u': // Prefix: "ubmissions/" + origElem := elem + if l := len("ubmissions/"); len(elem) >= l && elem[0:l] == "ubmissions/" { + elem = elem[l:] + } else { + break + } + + // Param: "SubmissionID" + // 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: "/" + origElem := elem + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { elem = elem[l:] } else { break @@ -117,9 +209,9 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case 'u': // Prefix: "uploaded" + case 'm': // Prefix: "model" origElem := elem - if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" { + if l := len("model"); len(elem) >= l && elem[0:l] == "model" { elem = elem[l:] } else { break @@ -129,7 +221,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Leaf node. switch r.Method { case "POST": - s.handleActionSubmissionUploadedRequest([1]string{ + s.handleUpdateSubmissionModelRequest([1]string{ args[0], }, elemIsEscaped, w, r) default: @@ -140,26 +232,125 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } elem = origElem - case 'v': // Prefix: "validated" + case 's': // Prefix: "status/" origElem := elem - if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" { + if l := len("status/"); len(elem) >= l && elem[0:l] == "status/" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "POST": - s.handleActionSubmissionValidatedRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, "POST") + break + } + switch elem[0] { + case 'r': // Prefix: "releaser-released" + origElem := elem + if l := len("releaser-released"); len(elem) >= l && elem[0:l] == "releaser-released" { + elem = elem[l:] + } else { + break } - return + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleActionSubmissionReleasedRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "POST") + } + + return + } + + elem = origElem + case 'v': // Prefix: "validator-" + origElem := elem + if l := len("validator-"); len(elem) >= l && elem[0:l] == "validator-" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'f': // Prefix: "failed" + origElem := elem + 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.handleActionSubmissionAcceptedRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "POST") + } + + return + } + + elem = origElem + case 'u': // Prefix: "uploaded" + origElem := elem + if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleActionSubmissionUploadedRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "POST") + } + + return + } + + elem = origElem + case 'v': // Prefix: "validated" + origElem := elem + if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleActionSubmissionValidatedRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, "POST") + } + + return + } + + elem = origElem + } + + elem = origElem } elem = origElem @@ -252,30 +443,21 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case '/': // Prefix: "/submissions/" + case '/': // Prefix: "/s" origElem := elem - if l := len("/submissions/"); len(elem) >= l && elem[0:l] == "/submissions/" { + if l := len("/s"); len(elem) >= l && elem[0:l] == "/s" { elem = elem[l:] } else { break } - // Param: "SubmissionID" - // 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: "/status/" + case 'c': // Prefix: "cript" origElem := elem - if l := len("/status/"); len(elem) >= l && elem[0:l] == "/status/" { + if l := len("cript"); len(elem) >= l && elem[0:l] == "cript" { elem = elem[l:] } else { break @@ -285,59 +467,50 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case 'r': // Prefix: "releaser-released" + case '-': // Prefix: "-policy" origElem := elem - if l := len("releaser-released"); len(elem) >= l && elem[0:l] == "releaser-released" { + if l := len("-policy"); len(elem) >= l && elem[0:l] == "-policy" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. switch method { case "POST": - r.name = ActionSubmissionReleasedOperation - r.summary = "(Internal endpoint) Role Releaser changes status from releasing -> released" - r.operationID = "actionSubmissionReleased" - r.pathPattern = "/submissions/{SubmissionID}/status/releaser-released" + r.name = CreateScriptPolicyOperation + r.summary = "Create a new script policy" + r.operationID = "createScriptPolicy" + r.pathPattern = "/script-policy" r.args = args - r.count = 1 + r.count = 0 return r, true default: return } } - - elem = origElem - case 'v': // Prefix: "validator-" - origElem := elem - if l := len("validator-"); len(elem) >= l && elem[0:l] == "validator-" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - break - } switch elem[0] { - case 'u': // Prefix: "uploaded" + case '/': // Prefix: "/hash/" origElem := elem - if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" { + if l := len("/hash/"); len(elem) >= l && elem[0:l] == "/hash/" { elem = elem[l:] } else { break } + // Param: "FromScriptHash" + // Leaf parameter + args[0] = elem + elem = "" + if len(elem) == 0 { // Leaf node. switch method { - case "POST": - r.name = ActionSubmissionUploadedOperation - r.summary = "(Internal endpoint) Role Validator changes status from Uploading -> Uploaded" - r.operationID = "actionSubmissionUploaded" - r.pathPattern = "/submissions/{SubmissionID}/status/validator-uploaded" + case "GET": + r.name = GetScriptPolicyFromHashOperation + r.summary = "Get the policy for the given hash of script source code" + r.operationID = "getScriptPolicyFromHash" + r.pathPattern = "/script-policy/hash/{FromScriptHash}" r.args = args r.count = 1 return r, true @@ -347,9 +520,104 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } elem = origElem - case 'v': // Prefix: "validated" + } + + elem = origElem + case 's': // Prefix: "s" + origElem := elem + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "POST": + r.name = CreateScriptOperation + r.summary = "Create a new script" + r.operationID = "createScript" + r.pathPattern = "/scripts" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" origElem := elem - if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" { + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "ScriptID" + // Leaf parameter + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetScriptOperation + r.summary = "Get the specified script by ID" + r.operationID = "getScript" + r.pathPattern = "/scripts/{ScriptID}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + elem = origElem + } + + elem = origElem + } + + elem = origElem + case 'u': // Prefix: "ubmissions/" + origElem := elem + if l := len("ubmissions/"); len(elem) >= l && elem[0:l] == "ubmissions/" { + elem = elem[l:] + } else { + break + } + + // Param: "SubmissionID" + // 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: "/" + origElem := elem + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'm': // Prefix: "model" + origElem := elem + if l := len("model"); len(elem) >= l && elem[0:l] == "model" { elem = elem[l:] } else { break @@ -359,10 +627,10 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { // Leaf node. switch method { case "POST": - r.name = ActionSubmissionValidatedOperation - r.summary = "(Internal endpoint) Role Validator changes status from Validating -> Validated" - r.operationID = "actionSubmissionValidated" - r.pathPattern = "/submissions/{SubmissionID}/status/validator-validated" + r.name = UpdateSubmissionModelOperation + r.summary = "Update model following role restrictions" + r.operationID = "updateSubmissionModel" + r.pathPattern = "/submissions/{SubmissionID}/model" r.args = args r.count = 1 return r, true @@ -371,6 +639,136 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } + elem = origElem + case 's': // Prefix: "status/" + origElem := elem + if l := len("status/"); len(elem) >= l && elem[0:l] == "status/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'r': // Prefix: "releaser-released" + origElem := elem + if l := len("releaser-released"); len(elem) >= l && elem[0:l] == "releaser-released" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ActionSubmissionReleasedOperation + r.summary = "(Internal endpoint) Role Releaser changes status from releasing -> released" + r.operationID = "actionSubmissionReleased" + r.pathPattern = "/submissions/{SubmissionID}/status/releaser-released" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + elem = origElem + case 'v': // Prefix: "validator-" + origElem := elem + if l := len("validator-"); len(elem) >= l && elem[0:l] == "validator-" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'f': // Prefix: "failed" + origElem := elem + 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 = ActionSubmissionAcceptedOperation + r.summary = "(Internal endpoint) Role Validator changes status from Validating -> Accepted" + r.operationID = "actionSubmissionAccepted" + r.pathPattern = "/submissions/{SubmissionID}/status/validator-failed" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + elem = origElem + case 'u': // Prefix: "uploaded" + origElem := elem + if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ActionSubmissionUploadedOperation + r.summary = "(Internal endpoint) Role Validator changes status from Uploading -> Uploaded" + r.operationID = "actionSubmissionUploaded" + r.pathPattern = "/submissions/{SubmissionID}/status/validator-uploaded" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + elem = origElem + case 'v': // Prefix: "validated" + origElem := elem + if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ActionSubmissionValidatedOperation + r.summary = "(Internal endpoint) Role Validator changes status from Validating -> Validated" + r.operationID = "actionSubmissionValidated" + r.pathPattern = "/submissions/{SubmissionID}/status/validator-validated" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + elem = origElem + } + + elem = origElem + } + elem = origElem } diff --git a/pkg/internal/oas_schemas_gen.go b/pkg/internal/oas_schemas_gen.go index 319dfb2..e3106c3 100644 --- a/pkg/internal/oas_schemas_gen.go +++ b/pkg/internal/oas_schemas_gen.go @@ -10,6 +10,9 @@ func (s *ErrorStatusCode) Error() string { return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) } +// ActionSubmissionAcceptedNoContent is response for ActionSubmissionAccepted operation. +type ActionSubmissionAcceptedNoContent struct{} + // ActionSubmissionReleasedNoContent is response for ActionSubmissionReleased operation. type ActionSubmissionReleasedNoContent struct{} @@ -72,6 +75,21 @@ func (s *ErrorStatusCode) SetResponse(val Error) { s.Response = val } +// Ref: #/components/schemas/Id +type ID struct { + ID int64 `json:"ID"` +} + +// GetID returns the value of ID. +func (s *ID) GetID() int64 { + return s.ID +} + +// SetID sets the value of ID. +func (s *ID) SetID(val int64) { + s.ID = val +} + // NewOptInt64 returns new OptInt64 with value set to v. func NewOptInt64(v int64) OptInt64 { return OptInt64{ @@ -117,3 +135,187 @@ func (o OptInt64) Or(d int64) int64 { } return d } + +// Ref: #/components/schemas/Script +type Script struct { + ID int64 `json:"ID"` + Name string `json:"Name"` + Hash string `json:"Hash"` + Source string `json:"Source"` + SubmissionID int64 `json:"SubmissionID"` +} + +// GetID returns the value of ID. +func (s *Script) GetID() int64 { + return s.ID +} + +// GetName returns the value of Name. +func (s *Script) GetName() string { + return s.Name +} + +// GetHash returns the value of Hash. +func (s *Script) GetHash() string { + return s.Hash +} + +// GetSource returns the value of Source. +func (s *Script) GetSource() string { + return s.Source +} + +// GetSubmissionID returns the value of SubmissionID. +func (s *Script) GetSubmissionID() int64 { + return s.SubmissionID +} + +// SetID sets the value of ID. +func (s *Script) SetID(val int64) { + s.ID = val +} + +// SetName sets the value of Name. +func (s *Script) SetName(val string) { + s.Name = val +} + +// SetHash sets the value of Hash. +func (s *Script) SetHash(val string) { + s.Hash = val +} + +// SetSource sets the value of Source. +func (s *Script) SetSource(val string) { + s.Source = val +} + +// SetSubmissionID sets the value of SubmissionID. +func (s *Script) SetSubmissionID(val int64) { + s.SubmissionID = val +} + +// Ref: #/components/schemas/ScriptCreate +type ScriptCreate struct { + Name string `json:"Name"` + Source string `json:"Source"` + SubmissionID OptInt64 `json:"SubmissionID"` +} + +// GetName returns the value of Name. +func (s *ScriptCreate) GetName() string { + return s.Name +} + +// GetSource returns the value of Source. +func (s *ScriptCreate) GetSource() string { + return s.Source +} + +// GetSubmissionID returns the value of SubmissionID. +func (s *ScriptCreate) GetSubmissionID() OptInt64 { + return s.SubmissionID +} + +// SetName sets the value of Name. +func (s *ScriptCreate) SetName(val string) { + s.Name = val +} + +// SetSource sets the value of Source. +func (s *ScriptCreate) SetSource(val string) { + s.Source = val +} + +// SetSubmissionID sets the value of SubmissionID. +func (s *ScriptCreate) SetSubmissionID(val OptInt64) { + s.SubmissionID = val +} + +// Ref: #/components/schemas/ScriptPolicy +type ScriptPolicy struct { + ID int64 `json:"ID"` + FromScriptHash string `json:"FromScriptHash"` + ToScriptID int64 `json:"ToScriptID"` + Policy int32 `json:"Policy"` +} + +// GetID returns the value of ID. +func (s *ScriptPolicy) GetID() int64 { + return s.ID +} + +// GetFromScriptHash returns the value of FromScriptHash. +func (s *ScriptPolicy) GetFromScriptHash() string { + return s.FromScriptHash +} + +// GetToScriptID returns the value of ToScriptID. +func (s *ScriptPolicy) GetToScriptID() int64 { + return s.ToScriptID +} + +// GetPolicy returns the value of Policy. +func (s *ScriptPolicy) GetPolicy() int32 { + return s.Policy +} + +// SetID sets the value of ID. +func (s *ScriptPolicy) SetID(val int64) { + s.ID = val +} + +// SetFromScriptHash sets the value of FromScriptHash. +func (s *ScriptPolicy) SetFromScriptHash(val string) { + s.FromScriptHash = val +} + +// SetToScriptID sets the value of ToScriptID. +func (s *ScriptPolicy) SetToScriptID(val int64) { + s.ToScriptID = val +} + +// SetPolicy sets the value of Policy. +func (s *ScriptPolicy) SetPolicy(val int32) { + s.Policy = val +} + +// Ref: #/components/schemas/ScriptPolicyCreate +type ScriptPolicyCreate struct { + FromScriptID int64 `json:"FromScriptID"` + ToScriptID int64 `json:"ToScriptID"` + Policy int32 `json:"Policy"` +} + +// GetFromScriptID returns the value of FromScriptID. +func (s *ScriptPolicyCreate) GetFromScriptID() int64 { + return s.FromScriptID +} + +// GetToScriptID returns the value of ToScriptID. +func (s *ScriptPolicyCreate) GetToScriptID() int64 { + return s.ToScriptID +} + +// GetPolicy returns the value of Policy. +func (s *ScriptPolicyCreate) GetPolicy() int32 { + return s.Policy +} + +// SetFromScriptID sets the value of FromScriptID. +func (s *ScriptPolicyCreate) SetFromScriptID(val int64) { + s.FromScriptID = val +} + +// SetToScriptID sets the value of ToScriptID. +func (s *ScriptPolicyCreate) SetToScriptID(val int64) { + s.ToScriptID = val +} + +// SetPolicy sets the value of Policy. +func (s *ScriptPolicyCreate) SetPolicy(val int32) { + s.Policy = val +} + +// UpdateSubmissionModelNoContent is response for UpdateSubmissionModel operation. +type UpdateSubmissionModelNoContent struct{} diff --git a/pkg/internal/oas_server_gen.go b/pkg/internal/oas_server_gen.go index 7333971..f266fc6 100644 --- a/pkg/internal/oas_server_gen.go +++ b/pkg/internal/oas_server_gen.go @@ -8,6 +8,12 @@ import ( // Handler handles operations described by OpenAPI v3 specification. type Handler interface { + // ActionSubmissionAccepted implements actionSubmissionAccepted operation. + // + // (Internal endpoint) Role Validator changes status from Validating -> Accepted. + // + // POST /submissions/{SubmissionID}/status/validator-failed + ActionSubmissionAccepted(ctx context.Context, params ActionSubmissionAcceptedParams) error // ActionSubmissionReleased implements actionSubmissionReleased operation. // // (Internal endpoint) Role Releaser changes status from releasing -> released. @@ -26,6 +32,36 @@ type Handler interface { // // POST /submissions/{SubmissionID}/status/validator-validated ActionSubmissionValidated(ctx context.Context, params ActionSubmissionValidatedParams) error + // CreateScript implements createScript operation. + // + // Create a new script. + // + // POST /scripts + CreateScript(ctx context.Context, req *ScriptCreate) (*ID, error) + // CreateScriptPolicy implements createScriptPolicy operation. + // + // Create a new script policy. + // + // POST /script-policy + CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (*ID, error) + // GetScript implements getScript operation. + // + // Get the specified script by ID. + // + // GET /scripts/{ScriptID} + GetScript(ctx context.Context, params GetScriptParams) (*Script, error) + // GetScriptPolicyFromHash implements getScriptPolicyFromHash operation. + // + // Get the policy for the given hash of script source code. + // + // GET /script-policy/hash/{FromScriptHash} + GetScriptPolicyFromHash(ctx context.Context, params GetScriptPolicyFromHashParams) (*ScriptPolicy, error) + // UpdateSubmissionModel implements updateSubmissionModel operation. + // + // Update model following role restrictions. + // + // POST /submissions/{SubmissionID}/model + UpdateSubmissionModel(ctx context.Context, params UpdateSubmissionModelParams) error // NewError creates *ErrorStatusCode from error returned by handler. // // Used for common default response. diff --git a/pkg/internal/oas_unimplemented_gen.go b/pkg/internal/oas_unimplemented_gen.go index 7430929..898a52c 100644 --- a/pkg/internal/oas_unimplemented_gen.go +++ b/pkg/internal/oas_unimplemented_gen.go @@ -13,6 +13,15 @@ type UnimplementedHandler struct{} var _ Handler = UnimplementedHandler{} +// ActionSubmissionAccepted implements actionSubmissionAccepted operation. +// +// (Internal endpoint) Role Validator changes status from Validating -> Accepted. +// +// POST /submissions/{SubmissionID}/status/validator-failed +func (UnimplementedHandler) ActionSubmissionAccepted(ctx context.Context, params ActionSubmissionAcceptedParams) error { + return ht.ErrNotImplemented +} + // ActionSubmissionReleased implements actionSubmissionReleased operation. // // (Internal endpoint) Role Releaser changes status from releasing -> released. @@ -40,6 +49,51 @@ func (UnimplementedHandler) ActionSubmissionValidated(ctx context.Context, param return ht.ErrNotImplemented } +// CreateScript implements createScript operation. +// +// Create a new script. +// +// POST /scripts +func (UnimplementedHandler) CreateScript(ctx context.Context, req *ScriptCreate) (r *ID, _ error) { + return r, ht.ErrNotImplemented +} + +// CreateScriptPolicy implements createScriptPolicy operation. +// +// Create a new script policy. +// +// POST /script-policy +func (UnimplementedHandler) CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (r *ID, _ error) { + return r, ht.ErrNotImplemented +} + +// GetScript implements getScript operation. +// +// Get the specified script by ID. +// +// GET /scripts/{ScriptID} +func (UnimplementedHandler) GetScript(ctx context.Context, params GetScriptParams) (r *Script, _ error) { + return r, ht.ErrNotImplemented +} + +// GetScriptPolicyFromHash implements getScriptPolicyFromHash operation. +// +// Get the policy for the given hash of script source code. +// +// GET /script-policy/hash/{FromScriptHash} +func (UnimplementedHandler) GetScriptPolicyFromHash(ctx context.Context, params GetScriptPolicyFromHashParams) (r *ScriptPolicy, _ error) { + return r, ht.ErrNotImplemented +} + +// UpdateSubmissionModel implements updateSubmissionModel operation. +// +// Update model following role restrictions. +// +// POST /submissions/{SubmissionID}/model +func (UnimplementedHandler) UpdateSubmissionModel(ctx context.Context, params UpdateSubmissionModelParams) error { + return ht.ErrNotImplemented +} + // NewError creates *ErrorStatusCode from error returned by handler. // // Used for common default response. diff --git a/pkg/internal/oas_validators_gen.go b/pkg/internal/oas_validators_gen.go new file mode 100644 index 0000000..2e52cc9 --- /dev/null +++ b/pkg/internal/oas_validators_gen.go @@ -0,0 +1,159 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "github.com/go-faster/errors" + + "github.com/ogen-go/ogen/validate" +) + +func (s *Script) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 64, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(s.Name)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Name", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 16, + MinLengthSet: true, + MaxLength: 16, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(s.Hash)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Hash", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1048576, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(s.Source)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ScriptCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 64, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(s.Name)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Name", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1048576, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(s.Source)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ScriptPolicy) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 16, + MinLengthSet: true, + MaxLength: 16, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + }).Validate(string(s.FromScriptHash)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "FromScriptHash", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +}