feat(practice): store code submissions and practice states apart from attempts

This commit is contained in:
shira committed 2026-10-11 14:58:04 +03:00
1 parent d5e169e71b
commit 51770eea6c
61 files changed
+8584 -135

No files matched your search

@@ -1482,6 +1482,270 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca
}
}
// handleCreateMyAssessmentPracticeRunRequest handles CreateMyAssessmentPracticeRun operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// an allowed Origin, and an Idempotency-Key. The body names the practice item of the attempt and
// carries the language, the source, and up to ten tests of the candidate.
//
// A debug run executes the solution in the isolated sandbox against the public examples of the task
// and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes
// neither the practice state, the verdict, nor the attempt version; the graded solution is submitted
// with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed
// asynchronously: the response is 202 with the run `queued`, and the client polls
// GetMyAssessmentPracticeRun. The source is never echoed.
//
// The practice must be the current item: the attempt is in `practice_pending` for the main practice or
// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the
// server answers 409 state_conflict.
//
// Availability. When code practice is not enabled on this server, the server answers 503
// service_unavailable and stores nothing.
//
// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in
// its current state with 202, without starting another run. A different body with the same key answers
// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are
// evaluated again.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422,
// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of
// another candidate), the state (409), then the solution against the item (400 with a pointer such as
// `/language` or `/source_code`).
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs
func (s *Server) handleCreateMyAssessmentPracticeRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("CreateMyAssessmentPracticeRun"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/practice-runs"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMyAssessmentPracticeRunOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: CreateMyAssessmentPracticeRunOperation,
ID: "CreateMyAssessmentPracticeRun",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, CreateMyAssessmentPracticeRunOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, CreateMyAssessmentPracticeRunOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeCreateMyAssessmentPracticeRunParams(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 rawBody []byte
request, rawBody, close, err := s.decodeCreateMyAssessmentPracticeRunRequest(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 CreateMyAssessmentPracticeRunRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: CreateMyAssessmentPracticeRunOperation,
OperationSummary: "Start a debug run of a practice solution.",
OperationID: "CreateMyAssessmentPracticeRun",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *PracticeRunCreate
Params = CreateMyAssessmentPracticeRunParams
Response = CreateMyAssessmentPracticeRunRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackCreateMyAssessmentPracticeRunParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.CreateMyAssessmentPracticeRun(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.CreateMyAssessmentPracticeRun(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](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 := encodeCreateMyAssessmentPracticeRunResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCreateMySupportCaseRequest handles CreateMySupportCase operation.
//
// Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and
@@ -4265,6 +4529,217 @@ func (s *Server) handleGetMyAssessmentAvailabilityRequest(args [0]string, argsEs
}
}
// handleGetMyAssessmentPracticeRunRequest handles GetMyAssessmentPracticeRun operation.
//
// Requires the session cookie of a candidate account. Returns the state of a debug run started with
// CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of
// the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source.
// This GET is read-only.
//
// A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer
// 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is
// not readable here.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}
func (s *Server) handleGetMyAssessmentPracticeRunRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetMyAssessmentPracticeRun"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentPracticeRunOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetMyAssessmentPracticeRunOperation,
ID: "GetMyAssessmentPracticeRun",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentPracticeRunOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeGetMyAssessmentPracticeRunParams(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 rawBody []byte
var response GetMyAssessmentPracticeRunRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetMyAssessmentPracticeRunOperation,
OperationSummary: "Read a debug run of a practice solution.",
OperationID: "GetMyAssessmentPracticeRun",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "run_id",
In: "path",
}: params.RunID,
},
Raw: r,
}
type (
Request = struct{}
Params = GetMyAssessmentPracticeRunParams
Response = GetMyAssessmentPracticeRunRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetMyAssessmentPracticeRunParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetMyAssessmentPracticeRun(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetMyAssessmentPracticeRun(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](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 := encodeGetMyAssessmentPracticeRunResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetMyAssessmentResultRequest handles GetMyAssessmentResult operation.
//
// Requires the session cookie of a candidate account. Returns the immutable result of a terminal
@@ -25,6 +25,10 @@ type CreateMyAssessmentAttemptRes interface {
createMyAssessmentAttemptRes()
}
type CreateMyAssessmentPracticeRunRes interface {
createMyAssessmentPracticeRunRes()
}
type CreateMySupportCaseRes interface {
createMySupportCaseRes()
}
@@ -69,6 +73,10 @@ type GetMyAssessmentAvailabilityRes interface {
getMyAssessmentAvailabilityRes()
}
type GetMyAssessmentPracticeRunRes interface {
getMyAssessmentPracticeRunRes()
}
type GetMyAssessmentResultRes interface {
getMyAssessmentResultRes()
}
File diff suppressed because it is too large. Load diff
@@ -12,6 +12,7 @@ const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
ConfirmEmailByCodeOperation OperationName = "ConfirmEmailByCode"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMyAssessmentPracticeRunOperation OperationName = "CreateMyAssessmentPracticeRun"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
@@ -24,6 +25,7 @@ const (
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentPracticeRunOperation OperationName = "GetMyAssessmentPracticeRun"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyAssessmentSignalNoticeOperation OperationName = "GetMyAssessmentSignalNotice"
GetMyCardPreviewOperation OperationName = "GetMyCardPreview"
@@ -593,6 +593,155 @@ func decodeCreateMyAssessmentAttemptParams(args [0]string, argsEscaped bool, r *
return params, nil
}
// CreateMyAssessmentPracticeRunParams is parameters of CreateMyAssessmentPracticeRun operation.
type CreateMyAssessmentPracticeRunParams struct {
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
AttemptID uuid.UUID
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
// request by method, path, and body.
//
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
// not_found or 409 state_conflict. A replay does not repeat the side effect.
//
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
// precondition_required (nothing changed; read the resource again and retry), 422
// idempotency_key_reused, 429, and every 5xx.
//
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
// before any other key check; a running request with the same fingerprint returns 409
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
}
func unpackCreateMyAssessmentPracticeRunParams(packed middleware.Parameters) (params CreateMyAssessmentPracticeRunParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeCreateMyAssessmentPracticeRunParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateMyAssessmentPracticeRunParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode path: attempt_id.
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: "attempt_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.AttemptID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "attempt_id",
In: "path",
Err: err,
}
}
// Decode header: Idempotency-Key.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "Idempotency-Key",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.IdempotencyKey = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 255,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.IdempotencyKey)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "Idempotency-Key",
In: "header",
Err: err,
}
}
return params, nil
}
// CreateMySupportCaseParams is parameters of CreateMySupportCase operation.
type CreateMySupportCaseParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
@@ -1523,6 +1672,127 @@ func decodeGetMyAssessmentAttemptParams(args [1]string, argsEscaped bool, r *htt
return params, nil
}
// GetMyAssessmentPracticeRunParams is parameters of GetMyAssessmentPracticeRun operation.
type GetMyAssessmentPracticeRunParams struct {
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
AttemptID uuid.UUID
// Identifier of a debug run of this attempt.
RunID uuid.UUID
}
func unpackGetMyAssessmentPracticeRunParams(packed middleware.Parameters) (params GetMyAssessmentPracticeRunParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "run_id",
In: "path",
}
params.RunID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetMyAssessmentPracticeRunParams(args [2]string, argsEscaped bool, r *http.Request) (params GetMyAssessmentPracticeRunParams, _ error) {
// Decode path: attempt_id.
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: "attempt_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.AttemptID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "attempt_id",
In: "path",
Err: err,
}
}
// Decode path: run_id.
if err := func() error {
param := args[1]
if argsEscaped {
unescaped, err := url.PathUnescape(args[1])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "run_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.RunID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "run_id",
In: "path",
Err: err,
}
}
return params, nil
}
// GetMyAssessmentResultParams is parameters of GetMyAssessmentResult operation.
type GetMyAssessmentResultParams struct {
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
@@ -488,6 +488,85 @@ func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) (
}
}
func (s *Server) decodeCreateMyAssessmentPracticeRunRequest(r *http.Request) (
req *PracticeRunCreate,
rawBody []byte,
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 = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request PracticeRunCreate
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, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) (
req SupportCaseCreate,
rawBody []byte,
@@ -676,6 +676,146 @@ func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptR
}
}
func encodeCreateMyAssessmentPracticeRunResponse(response CreateMyAssessmentPracticeRunRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *PracticeRunHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(202)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateMyAssessmentPracticeRunBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateMyAssessmentPracticeRunUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateMyAssessmentPracticeRunForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateMyAssessmentPracticeRunNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateMyAssessmentPracticeRunConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateMyAssessmentPracticeRunUnprocessableEntity:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(422)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ServiceUnavailableHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(503)
span.SetStatus(codes.Error, http.StatusText(503))
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SupportCaseHeaders:
@@ -1758,6 +1898,77 @@ func encodeGetMyAssessmentAvailabilityResponse(response GetMyAssessmentAvailabil
}
}
func encodeGetMyAssessmentPracticeRunResponse(response GetMyAssessmentPracticeRunRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *PracticeRunHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyAssessmentPracticeRunUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyAssessmentPracticeRunForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyAssessmentPracticeRunNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentResultHeaders:
@@ -11,7 +11,7 @@ import (
)
var (
rn86AllowedHeaders = map[string]string{
rn89AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn9AllowedHeaders = map[string]string{
@@ -20,44 +20,47 @@ var (
rn10AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn81AllowedHeaders = map[string]string{
rn84AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn71AllowedHeaders = map[string]string{
rn74AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn28AllowedHeaders = map[string]string{
rn30AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn83AllowedHeaders = map[string]string{
rn86AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn97AllowedHeaders = map[string]string{
rn100AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token",
}
rn23AllowedHeaders = map[string]string{
rn25AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn96AllowedHeaders = map[string]string{
rn15AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn99AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token",
}
rn80AllowedHeaders = map[string]string{
rn83AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn58AllowedHeaders = map[string]string{
rn61AllowedHeaders = map[string]string{
"DELETE": "X-Attempt-Client,X-Csrf-Token",
"PUT": "X-Attempt-Client,X-Csrf-Token",
}
rn5AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn88AllowedHeaders = map[string]string{
rn91AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn54AllowedHeaders = map[string]string{
rn57AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "Content-Type,X-Csrf-Token",
}
@@ -67,68 +70,68 @@ var (
rn7AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn20AllowedHeaders = map[string]string{
rn23AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn98AllowedHeaders = map[string]string{
rn101AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn74AllowedHeaders = map[string]string{
rn77AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn57AllowedHeaders = map[string]string{
rn60AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn93AllowedHeaders = map[string]string{
rn96AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn94AllowedHeaders = map[string]string{
rn97AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn39AllowedHeaders = map[string]string{
rn42AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn84AllowedHeaders = map[string]string{
rn87AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn40AllowedHeaders = map[string]string{
rn43AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn13AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn14AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn16AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn17AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn47AllowedHeaders = map[string]string{
rn19AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn91AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn99AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn89AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn19AllowedHeaders = map[string]string{
rn20AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn50AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn77AllowedHeaders = map[string]string{
rn82AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn94AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn102AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn92AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn22AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn53AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn80AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
)
@@ -285,7 +288,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn86AllowedHeaders,
allowedHeaders: rn89AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -388,7 +391,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn81AllowedHeaders,
allowedHeaders: rn84AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -412,7 +415,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn71AllowedHeaders,
allowedHeaders: rn74AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -439,7 +442,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,GET",
allowedHeaders: rn28AllowedHeaders,
allowedHeaders: rn30AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -492,7 +495,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn83AllowedHeaders,
allowedHeaders: rn86AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -614,7 +617,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn97AllowedHeaders,
allowedHeaders: rn100AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -641,7 +644,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn23AllowedHeaders,
allowedHeaders: rn25AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -650,6 +653,71 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
case 'p': // Prefix: "practice-runs"
if l := len("practice-runs"); len(elem) >= l && elem[0:l] == "practice-runs" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "POST":
s.handleCreateMyAssessmentPracticeRunRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn15AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "run_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyAssessmentPracticeRunRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
case 'r': // Prefix: "result"
if l := len("result"); len(elem) >= l && elem[0:l] == "result" {
@@ -707,7 +775,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn96AllowedHeaders,
allowedHeaders: rn99AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -734,7 +802,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn80AllowedHeaders,
allowedHeaders: rn83AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -767,7 +835,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn58AllowedHeaders,
allowedHeaders: rn61AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -976,7 +1044,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn88AllowedHeaders,
allowedHeaders: rn91AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1010,7 +1078,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn54AllowedHeaders,
allowedHeaders: rn57AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1191,7 +1259,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn20AllowedHeaders,
allowedHeaders: rn23AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1218,7 +1286,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn98AllowedHeaders,
allowedHeaders: rn101AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1296,7 +1364,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn74AllowedHeaders,
allowedHeaders: rn77AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1474,7 +1542,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn57AllowedHeaders,
allowedHeaders: rn60AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1565,7 +1633,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn93AllowedHeaders,
allowedHeaders: rn96AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1592,7 +1660,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn94AllowedHeaders,
allowedHeaders: rn97AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1622,7 +1690,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn39AllowedHeaders,
allowedHeaders: rn42AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1647,7 +1715,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn84AllowedHeaders,
allowedHeaders: rn87AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1678,7 +1746,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn40AllowedHeaders,
allowedHeaders: rn43AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1704,7 +1772,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn13AllowedHeaders,
allowedHeaders: rn16AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1768,7 +1836,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn14AllowedHeaders,
allowedHeaders: rn17AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1807,7 +1875,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn16AllowedHeaders,
allowedHeaders: rn19AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -1915,7 +1983,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn17AllowedHeaders,
allowedHeaders: rn20AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1956,7 +2024,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn47AllowedHeaders,
allowedHeaders: rn50AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -2036,7 +2104,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn79AllowedHeaders,
allowedHeaders: rn82AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2064,7 +2132,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn91AllowedHeaders,
allowedHeaders: rn94AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2094,7 +2162,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn99AllowedHeaders,
allowedHeaders: rn102AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2127,7 +2195,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn89AllowedHeaders,
allowedHeaders: rn92AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2169,7 +2237,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn19AllowedHeaders,
allowedHeaders: rn22AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2211,7 +2279,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn50AllowedHeaders,
allowedHeaders: rn53AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -2288,7 +2356,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn77AllowedHeaders,
allowedHeaders: rn80AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -2899,6 +2967,66 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
}
case 'p': // Prefix: "practice-runs"
if l := len("practice-runs"); len(elem) >= l && elem[0:l] == "practice-runs" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "POST":
r.name = CreateMyAssessmentPracticeRunOperation
r.summary = "Start a debug run of a practice solution."
r.operationID = "CreateMyAssessmentPracticeRun"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/practice-runs"
r.args = args
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "run_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyAssessmentPracticeRunOperation
r.summary = "Read a debug run of a practice solution."
r.operationID = "GetMyAssessmentPracticeRun"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}"
r.args = args
r.count = 2
return r, true
default:
return
}
}
}
case 'r': // Prefix: "result"
if l := len("result"); len(elem) >= l && elem[0:l] == "result" {
@@ -9746,6 +9746,30 @@ type CreateMyAssessmentAttemptUnprocessableEntity Problem
func (*CreateMyAssessmentAttemptUnprocessableEntity) createMyAssessmentAttemptRes() {}
type CreateMyAssessmentPracticeRunBadRequest Problem
func (*CreateMyAssessmentPracticeRunBadRequest) createMyAssessmentPracticeRunRes() {}
type CreateMyAssessmentPracticeRunConflict Problem
func (*CreateMyAssessmentPracticeRunConflict) createMyAssessmentPracticeRunRes() {}
type CreateMyAssessmentPracticeRunForbidden Problem
func (*CreateMyAssessmentPracticeRunForbidden) createMyAssessmentPracticeRunRes() {}
type CreateMyAssessmentPracticeRunNotFound Problem
func (*CreateMyAssessmentPracticeRunNotFound) createMyAssessmentPracticeRunRes() {}
type CreateMyAssessmentPracticeRunUnauthorized Problem
func (*CreateMyAssessmentPracticeRunUnauthorized) createMyAssessmentPracticeRunRes() {}
type CreateMyAssessmentPracticeRunUnprocessableEntity Problem
func (*CreateMyAssessmentPracticeRunUnprocessableEntity) createMyAssessmentPracticeRunRes() {}
type CreateMySupportCaseBadRequest Problem
func (*CreateMySupportCaseBadRequest) createMySupportCaseRes() {}
@@ -10991,6 +11015,18 @@ type GetMyAssessmentAvailabilityUnauthorized Problem
func (*GetMyAssessmentAvailabilityUnauthorized) getMyAssessmentAvailabilityRes() {}
type GetMyAssessmentPracticeRunForbidden Problem
func (*GetMyAssessmentPracticeRunForbidden) getMyAssessmentPracticeRunRes() {}
type GetMyAssessmentPracticeRunNotFound Problem
func (*GetMyAssessmentPracticeRunNotFound) getMyAssessmentPracticeRunRes() {}
type GetMyAssessmentPracticeRunUnauthorized Problem
func (*GetMyAssessmentPracticeRunUnauthorized) getMyAssessmentPracticeRunRes() {}
type GetMyAssessmentResultConflict Problem
func (*GetMyAssessmentResultConflict) getMyAssessmentResultRes() {}
@@ -19952,6 +19988,51 @@ func (o NilPracticeFailureReason) Or(d PracticeFailureReason) PracticeFailureRea
return d
}
// NewNilPracticeRunResult returns new NilPracticeRunResult with value set to v.
func NewNilPracticeRunResult(v PracticeRunResult) NilPracticeRunResult {
return NilPracticeRunResult{
Value: v,
}
}
// NilPracticeRunResult is nullable PracticeRunResult.
type NilPracticeRunResult struct {
Value PracticeRunResult
Null bool
}
// SetTo sets value to v.
func (o *NilPracticeRunResult) SetTo(v PracticeRunResult) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilPracticeRunResult) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilPracticeRunResult) SetToNull() {
o.Null = true
var v PracticeRunResult
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilPracticeRunResult) Get() (v PracticeRunResult, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilPracticeRunResult) Or(d PracticeRunResult) PracticeRunResult {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilPracticeVerdict returns new NilPracticeVerdict with value set to v.
func NewNilPracticeVerdict(v PracticeVerdict) NilPracticeVerdict {
return NilPracticeVerdict{
@@ -25883,6 +25964,505 @@ func (s *PracticeKind) UnmarshalText(data []byte) error {
}
}
// Debug run of a practice solution. It shows only the public examples and the tests of the candidate;
// hidden checks are never run, listed, or scored by a debug run.
// Ref: #/components/schemas/PracticeRun
type PracticeRun struct {
// Identifier of the run.
ID uuid.UUID `json:"id"`
ItemID AssessmentItemId `json:"item_id"`
State PracticeRunState `json:"state"`
CreatedAt Timestamp `json:"created_at"`
// Time the run reached `finished` or `failed`, or null.
FinishedAt NilTimestamp `json:"finished_at"`
// `sandbox_error` when `state` is `failed`, otherwise null.
FailureReason NilPracticeFailureReason `json:"failure_reason"`
// The result when `state` is `finished`, otherwise null.
Result NilPracticeRunResult `json:"result"`
}
// GetID returns the value of ID.
func (s *PracticeRun) GetID() uuid.UUID {
return s.ID
}
// GetItemID returns the value of ItemID.
func (s *PracticeRun) GetItemID() AssessmentItemId {
return s.ItemID
}
// GetState returns the value of State.
func (s *PracticeRun) GetState() PracticeRunState {
return s.State
}
// GetCreatedAt returns the value of CreatedAt.
func (s *PracticeRun) GetCreatedAt() Timestamp {
return s.CreatedAt
}
// GetFinishedAt returns the value of FinishedAt.
func (s *PracticeRun) GetFinishedAt() NilTimestamp {
return s.FinishedAt
}
// GetFailureReason returns the value of FailureReason.
func (s *PracticeRun) GetFailureReason() NilPracticeFailureReason {
return s.FailureReason
}
// GetResult returns the value of Result.
func (s *PracticeRun) GetResult() NilPracticeRunResult {
return s.Result
}
// SetID sets the value of ID.
func (s *PracticeRun) SetID(val uuid.UUID) {
s.ID = val
}
// SetItemID sets the value of ItemID.
func (s *PracticeRun) SetItemID(val AssessmentItemId) {
s.ItemID = val
}
// SetState sets the value of State.
func (s *PracticeRun) SetState(val PracticeRunState) {
s.State = val
}
// SetCreatedAt sets the value of CreatedAt.
func (s *PracticeRun) SetCreatedAt(val Timestamp) {
s.CreatedAt = val
}
// SetFinishedAt sets the value of FinishedAt.
func (s *PracticeRun) SetFinishedAt(val NilTimestamp) {
s.FinishedAt = val
}
// SetFailureReason sets the value of FailureReason.
func (s *PracticeRun) SetFailureReason(val NilPracticeFailureReason) {
s.FailureReason = val
}
// SetResult sets the value of Result.
func (s *PracticeRun) SetResult(val NilPracticeRunResult) {
s.Result = val
}
// Debug run of a practice solution against the public examples of the task and up to ten tests of the
// candidate. It never runs a hidden check and never changes the practice state, the verdict, or the
// attempt version. Unknown fields are rejected.
// Ref: #/components/schemas/PracticeRunCreate
type PracticeRunCreate struct {
ItemID AssessmentItemId `json:"item_id"`
// One of the `languages` of the practice item, or null when the item offers none.
Language NilTaskLanguage `json:"language"`
SourceCode string `json:"source_code"`
// Tests of the candidate, run after the public examples.
Tests []PracticeRunTest `json:"tests"`
}
// GetItemID returns the value of ItemID.
func (s *PracticeRunCreate) GetItemID() AssessmentItemId {
return s.ItemID
}
// GetLanguage returns the value of Language.
func (s *PracticeRunCreate) GetLanguage() NilTaskLanguage {
return s.Language
}
// GetSourceCode returns the value of SourceCode.
func (s *PracticeRunCreate) GetSourceCode() string {
return s.SourceCode
}
// GetTests returns the value of Tests.
func (s *PracticeRunCreate) GetTests() []PracticeRunTest {
return s.Tests
}
// SetItemID sets the value of ItemID.
func (s *PracticeRunCreate) SetItemID(val AssessmentItemId) {
s.ItemID = val
}
// SetLanguage sets the value of Language.
func (s *PracticeRunCreate) SetLanguage(val NilTaskLanguage) {
s.Language = val
}
// SetSourceCode sets the value of SourceCode.
func (s *PracticeRunCreate) SetSourceCode(val string) {
s.SourceCode = val
}
// SetTests sets the value of Tests.
func (s *PracticeRunCreate) SetTests(val []PracticeRunTest) {
s.Tests = val
}
// PracticeRunHeaders wraps PracticeRun with response headers.
type PracticeRunHeaders struct {
CacheControl CacheControlNoStore
Response PracticeRun
}
// GetCacheControl returns the value of CacheControl.
func (s *PracticeRunHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *PracticeRunHeaders) GetResponse() PracticeRun {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *PracticeRunHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *PracticeRunHeaders) SetResponse(val PracticeRun) {
s.Response = val
}
func (*PracticeRunHeaders) createMyAssessmentPracticeRunRes() {}
func (*PracticeRunHeaders) getMyAssessmentPracticeRunRes() {}
// Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation
// error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a
// failed run instead.
// Ref: #/components/schemas/PracticeRunOutcome
type PracticeRunOutcome string
const (
PracticeRunOutcomeAccepted PracticeRunOutcome = "accepted"
PracticeRunOutcomeWrongAnswer PracticeRunOutcome = "wrong_answer"
PracticeRunOutcomeCompileError PracticeRunOutcome = "compile_error"
PracticeRunOutcomeTimeLimitExceeded PracticeRunOutcome = "time_limit_exceeded"
PracticeRunOutcomeMemoryLimitExceeded PracticeRunOutcome = "memory_limit_exceeded"
PracticeRunOutcomeOutputLimitExceeded PracticeRunOutcome = "output_limit_exceeded"
PracticeRunOutcomeRuntimeError PracticeRunOutcome = "runtime_error"
)
// AllValues returns all PracticeRunOutcome values.
func (PracticeRunOutcome) AllValues() []PracticeRunOutcome {
return []PracticeRunOutcome{
PracticeRunOutcomeAccepted,
PracticeRunOutcomeWrongAnswer,
PracticeRunOutcomeCompileError,
PracticeRunOutcomeTimeLimitExceeded,
PracticeRunOutcomeMemoryLimitExceeded,
PracticeRunOutcomeOutputLimitExceeded,
PracticeRunOutcomeRuntimeError,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s PracticeRunOutcome) MarshalText() ([]byte, error) {
switch s {
case PracticeRunOutcomeAccepted:
return []byte(s), nil
case PracticeRunOutcomeWrongAnswer:
return []byte(s), nil
case PracticeRunOutcomeCompileError:
return []byte(s), nil
case PracticeRunOutcomeTimeLimitExceeded:
return []byte(s), nil
case PracticeRunOutcomeMemoryLimitExceeded:
return []byte(s), nil
case PracticeRunOutcomeOutputLimitExceeded:
return []byte(s), nil
case PracticeRunOutcomeRuntimeError:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *PracticeRunOutcome) UnmarshalText(data []byte) error {
switch PracticeRunOutcome(data) {
case PracticeRunOutcomeAccepted:
*s = PracticeRunOutcomeAccepted
return nil
case PracticeRunOutcomeWrongAnswer:
*s = PracticeRunOutcomeWrongAnswer
return nil
case PracticeRunOutcomeCompileError:
*s = PracticeRunOutcomeCompileError
return nil
case PracticeRunOutcomeTimeLimitExceeded:
*s = PracticeRunOutcomeTimeLimitExceeded
return nil
case PracticeRunOutcomeMemoryLimitExceeded:
*s = PracticeRunOutcomeMemoryLimitExceeded
return nil
case PracticeRunOutcomeOutputLimitExceeded:
*s = PracticeRunOutcomeOutputLimitExceeded
return nil
case PracticeRunOutcomeRuntimeError:
*s = PracticeRunOutcomeRuntimeError
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Result of a debug run on the public examples and the tests of the candidate. It never contains a
// hidden check, its outcome, or the score.
// Ref: #/components/schemas/PracticeRunResult
type PracticeRunResult struct {
Outcome PracticeRunOutcome `json:"outcome"`
// The compiler message when `outcome` is `compile_error`, otherwise null.
CompileDiagnostic NilString `json:"compile_diagnostic"`
Tests []PracticeRunTestResult `json:"tests"`
}
// GetOutcome returns the value of Outcome.
func (s *PracticeRunResult) GetOutcome() PracticeRunOutcome {
return s.Outcome
}
// GetCompileDiagnostic returns the value of CompileDiagnostic.
func (s *PracticeRunResult) GetCompileDiagnostic() NilString {
return s.CompileDiagnostic
}
// GetTests returns the value of Tests.
func (s *PracticeRunResult) GetTests() []PracticeRunTestResult {
return s.Tests
}
// SetOutcome sets the value of Outcome.
func (s *PracticeRunResult) SetOutcome(val PracticeRunOutcome) {
s.Outcome = val
}
// SetCompileDiagnostic sets the value of CompileDiagnostic.
func (s *PracticeRunResult) SetCompileDiagnostic(val NilString) {
s.CompileDiagnostic = val
}
// SetTests sets the value of Tests.
func (s *PracticeRunResult) SetTests(val []PracticeRunTestResult) {
s.Tests = val
}
// State of a debug run.
//
// - queued: the run waits in the sandbox queue.
// - running: the sandbox runs it.
// - finished: `result` holds the outcome of the public examples and the tests of the candidate.
// - failed: the sandbox infrastructure could not run it, independently of the solution;
// `failure_reason` is `sandbox_error`. Start a new run.
//
// Adding a value is a contract change.
// Ref: #/components/schemas/PracticeRunState
type PracticeRunState string
const (
PracticeRunStateQueued PracticeRunState = "queued"
PracticeRunStateRunning PracticeRunState = "running"
PracticeRunStateFinished PracticeRunState = "finished"
PracticeRunStateFailed PracticeRunState = "failed"
)
// AllValues returns all PracticeRunState values.
func (PracticeRunState) AllValues() []PracticeRunState {
return []PracticeRunState{
PracticeRunStateQueued,
PracticeRunStateRunning,
PracticeRunStateFinished,
PracticeRunStateFailed,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s PracticeRunState) MarshalText() ([]byte, error) {
switch s {
case PracticeRunStateQueued:
return []byte(s), nil
case PracticeRunStateRunning:
return []byte(s), nil
case PracticeRunStateFinished:
return []byte(s), nil
case PracticeRunStateFailed:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *PracticeRunState) UnmarshalText(data []byte) error {
switch PracticeRunState(data) {
case PracticeRunStateQueued:
*s = PracticeRunStateQueued
return nil
case PracticeRunStateRunning:
*s = PracticeRunStateRunning
return nil
case PracticeRunStateFinished:
*s = PracticeRunStateFinished
return nil
case PracticeRunStateFailed:
*s = PracticeRunStateFailed
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// One test of the candidate for a debug run: an input and the output the candidate expects. It is
// compared with the checker of the task.
// Ref: #/components/schemas/PracticeRunTest
type PracticeRunTest struct {
Input string `json:"input"`
ExpectedOutput string `json:"expected_output"`
}
// GetInput returns the value of Input.
func (s *PracticeRunTest) GetInput() string {
return s.Input
}
// GetExpectedOutput returns the value of ExpectedOutput.
func (s *PracticeRunTest) GetExpectedOutput() string {
return s.ExpectedOutput
}
// SetInput sets the value of Input.
func (s *PracticeRunTest) SetInput(val string) {
s.Input = val
}
// SetExpectedOutput sets the value of ExpectedOutput.
func (s *PracticeRunTest) SetExpectedOutput(val string) {
s.ExpectedOutput = val
}
// Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of
// that source are not listed.
// Ref: #/components/schemas/PracticeRunTestResult
type PracticeRunTestResult struct {
Source PracticeRunTestSource `json:"source"`
// Position of the test in its source, from 1.
Index int32 `json:"index"`
Outcome PracticeRunOutcome `json:"outcome"`
TimeMs int64 `json:"time_ms"`
MemoryKB int64 `json:"memory_kb"`
// Truncated error output of a failed test, or null.
Diagnostic NilString `json:"diagnostic"`
}
// GetSource returns the value of Source.
func (s *PracticeRunTestResult) GetSource() PracticeRunTestSource {
return s.Source
}
// GetIndex returns the value of Index.
func (s *PracticeRunTestResult) GetIndex() int32 {
return s.Index
}
// GetOutcome returns the value of Outcome.
func (s *PracticeRunTestResult) GetOutcome() PracticeRunOutcome {
return s.Outcome
}
// GetTimeMs returns the value of TimeMs.
func (s *PracticeRunTestResult) GetTimeMs() int64 {
return s.TimeMs
}
// GetMemoryKB returns the value of MemoryKB.
func (s *PracticeRunTestResult) GetMemoryKB() int64 {
return s.MemoryKB
}
// GetDiagnostic returns the value of Diagnostic.
func (s *PracticeRunTestResult) GetDiagnostic() NilString {
return s.Diagnostic
}
// SetSource sets the value of Source.
func (s *PracticeRunTestResult) SetSource(val PracticeRunTestSource) {
s.Source = val
}
// SetIndex sets the value of Index.
func (s *PracticeRunTestResult) SetIndex(val int32) {
s.Index = val
}
// SetOutcome sets the value of Outcome.
func (s *PracticeRunTestResult) SetOutcome(val PracticeRunOutcome) {
s.Outcome = val
}
// SetTimeMs sets the value of TimeMs.
func (s *PracticeRunTestResult) SetTimeMs(val int64) {
s.TimeMs = val
}
// SetMemoryKB sets the value of MemoryKB.
func (s *PracticeRunTestResult) SetMemoryKB(val int64) {
s.MemoryKB = val
}
// SetDiagnostic sets the value of Diagnostic.
func (s *PracticeRunTestResult) SetDiagnostic(val NilString) {
s.Diagnostic = val
}
// Where a test of a debug run comes from: a public example of the task or a test of the candidate.
// Ref: #/components/schemas/PracticeRunTestSource
type PracticeRunTestSource string
const (
PracticeRunTestSourceExample PracticeRunTestSource = "example"
PracticeRunTestSourceCandidate PracticeRunTestSource = "candidate"
)
// AllValues returns all PracticeRunTestSource values.
func (PracticeRunTestSource) AllValues() []PracticeRunTestSource {
return []PracticeRunTestSource{
PracticeRunTestSourceExample,
PracticeRunTestSourceCandidate,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s PracticeRunTestSource) MarshalText() ([]byte, error) {
switch s {
case PracticeRunTestSourceExample:
return []byte(s), nil
case PracticeRunTestSourceCandidate:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *PracticeRunTestSource) UnmarshalText(data []byte) error {
switch PracticeRunTestSource(data) {
case PracticeRunTestSourceExample:
*s = PracticeRunTestSourceExample
return nil
case PracticeRunTestSourceCandidate:
*s = PracticeRunTestSourceCandidate
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// State of a practice.
//
// - not_started: no solution was submitted yet.
@@ -29631,6 +30211,34 @@ type SendOrganizationInvitationUnprocessableEntity Problem
func (*SendOrganizationInvitationUnprocessableEntity) sendOrganizationInvitationRes() {}
// ServiceUnavailableHeaders wraps Problem with response headers.
type ServiceUnavailableHeaders struct {
RetryAfter OptInt32
Response Problem
}
// GetRetryAfter returns the value of RetryAfter.
func (s *ServiceUnavailableHeaders) GetRetryAfter() OptInt32 {
return s.RetryAfter
}
// GetResponse returns the value of Response.
func (s *ServiceUnavailableHeaders) GetResponse() Problem {
return s.Response
}
// SetRetryAfter sets the value of RetryAfter.
func (s *ServiceUnavailableHeaders) SetRetryAfter(val OptInt32) {
s.RetryAfter = val
}
// SetResponse sets the value of Response.
func (s *ServiceUnavailableHeaders) SetResponse(val Problem) {
s.Response = val
}
func (*ServiceUnavailableHeaders) createMyAssessmentPracticeRunRes() {}
// Current session as the client may see it: the account and the CSRF token. The session identifier
// itself travels only in the HttpOnly session cookie and never appears in a body.
// Ref: #/components/schemas/Session
@@ -60,6 +60,7 @@ var operationRolesSessionCookie = map[string][]string{
AcknowledgeMyAssessmentSignalNoticeOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMyAssessmentPracticeRunOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
@@ -70,6 +71,7 @@ var operationRolesSessionCookie = map[string][]string{
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentPracticeRunOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyAssessmentSignalNoticeOperation: []string{},
GetMyCardPreviewOperation: []string{},
@@ -154,6 +156,7 @@ var operationRolesSessionCsrf = map[string][]string{
AcknowledgeMyAssessmentSignalNoticeOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMyAssessmentPracticeRunOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
@@ -230,6 +230,39 @@ type Handler interface {
//
// POST /api/v1/me/assessment-attempts
CreateMyAssessmentAttempt(ctx context.Context, req AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error)
// CreateMyAssessmentPracticeRun implements CreateMyAssessmentPracticeRun operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// an allowed Origin, and an Idempotency-Key. The body names the practice item of the attempt and
// carries the language, the source, and up to ten tests of the candidate.
//
// A debug run executes the solution in the isolated sandbox against the public examples of the task
// and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes
// neither the practice state, the verdict, nor the attempt version; the graded solution is submitted
// with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed
// asynchronously: the response is 202 with the run `queued`, and the client polls
// GetMyAssessmentPracticeRun. The source is never echoed.
//
// The practice must be the current item: the attempt is in `practice_pending` for the main practice or
// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the
// server answers 409 state_conflict.
//
// Availability. When code practice is not enabled on this server, the server answers 503
// service_unavailable and stores nothing.
//
// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in
// its current state with 202, without starting another run. A different body with the same key answers
// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are
// evaluated again.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422,
// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of
// another candidate), the state (409), then the solution against the item (400 with a pointer such as
// `/language` or `/source_code`).
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs
CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (CreateMyAssessmentPracticeRunRes, error)
// CreateMySupportCase implements CreateMySupportCase operation.
//
// Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and
@@ -627,6 +660,19 @@ type Handler interface {
//
// GET /api/v1/me/assessment-availability
GetMyAssessmentAvailability(ctx context.Context) (GetMyAssessmentAvailabilityRes, error)
// GetMyAssessmentPracticeRun implements GetMyAssessmentPracticeRun operation.
//
// Requires the session cookie of a candidate account. Returns the state of a debug run started with
// CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of
// the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source.
// This GET is read-only.
//
// A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer
// 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is
// not readable here.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}
GetMyAssessmentPracticeRun(ctx context.Context, params GetMyAssessmentPracticeRunParams) (GetMyAssessmentPracticeRunRes, error)
// GetMyAssessmentResult implements GetMyAssessmentResult operation.
//
// Requires the session cookie of a candidate account. Returns the immutable result of a terminal
@@ -253,6 +253,42 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req A
return r, ht.ErrNotImplemented
}
// CreateMyAssessmentPracticeRun implements CreateMyAssessmentPracticeRun operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// an allowed Origin, and an Idempotency-Key. The body names the practice item of the attempt and
// carries the language, the source, and up to ten tests of the candidate.
//
// A debug run executes the solution in the isolated sandbox against the public examples of the task
// and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes
// neither the practice state, the verdict, nor the attempt version; the graded solution is submitted
// with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed
// asynchronously: the response is 202 with the run `queued`, and the client polls
// GetMyAssessmentPracticeRun. The source is never echoed.
//
// The practice must be the current item: the attempt is in `practice_pending` for the main practice or
// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the
// server answers 409 state_conflict.
//
// Availability. When code practice is not enabled on this server, the server answers 503
// service_unavailable and stores nothing.
//
// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in
// its current state with 202, without starting another run. A different body with the same key answers
// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are
// evaluated again.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422,
// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of
// another candidate), the state (409), then the solution against the item (400 with a pointer such as
// `/language` or `/source_code`).
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs
func (UnimplementedHandler) CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (r CreateMyAssessmentPracticeRunRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateMySupportCase implements CreateMySupportCase operation.
//
// Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and
@@ -686,6 +722,22 @@ func (UnimplementedHandler) GetMyAssessmentAvailability(ctx context.Context) (r
return r, ht.ErrNotImplemented
}
// GetMyAssessmentPracticeRun implements GetMyAssessmentPracticeRun operation.
//
// Requires the session cookie of a candidate account. Returns the state of a debug run started with
// CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of
// the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source.
// This GET is read-only.
//
// A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer
// 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is
// not readable here.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}
func (UnimplementedHandler) GetMyAssessmentPracticeRun(ctx context.Context, params GetMyAssessmentPracticeRunParams) (r GetMyAssessmentPracticeRunRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyAssessmentResult implements GetMyAssessmentResult operation.
//
// Requires the session cookie of a candidate account. Returns the immutable result of a terminal
@@ -8873,6 +8873,54 @@ func (s *CreateMyAssessmentAttemptUnprocessableEntity) Validate() error {
return nil
}
func (s *CreateMyAssessmentPracticeRunBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMyAssessmentPracticeRunConflict) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMyAssessmentPracticeRunForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMyAssessmentPracticeRunNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMyAssessmentPracticeRunUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMyAssessmentPracticeRunUnprocessableEntity) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMySupportCaseBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -10072,6 +10120,30 @@ func (s *GetMyAssessmentAvailabilityUnauthorized) Validate() error {
return nil
}
func (s *GetMyAssessmentPracticeRunForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMyAssessmentPracticeRunNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMyAssessmentPracticeRunUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMyAssessmentResultConflict) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -19468,6 +19540,509 @@ func (s PracticeKind) Validate() error {
}
}
func (s *PracticeRun) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.State.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "state",
Error: err,
})
}
if err := func() error {
if value, ok := s.FailureReason.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "failure_reason",
Error: err,
})
}
if err := func() error {
if value, ok := s.Result.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "result",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *PracticeRunCreate) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if value, ok := s.Language.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "language",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 65536,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.SourceCode)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "source_code",
Error: err,
})
}
if err := func() error {
if s.Tests == nil {
return nil // optional
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10,
MaxLengthSet: true,
}).ValidateLength(len(s.Tests)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Tests {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "tests",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *PracticeRunHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s PracticeRunOutcome) Validate() error {
switch s {
case "accepted":
return nil
case "wrong_answer":
return nil
case "compile_error":
return nil
case "time_limit_exceeded":
return nil
case "memory_limit_exceeded":
return nil
case "output_limit_exceeded":
return nil
case "runtime_error":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *PracticeRunResult) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Outcome.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "outcome",
Error: err,
})
}
if err := func() error {
if value, ok := s.CompileDiagnostic.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 0,
MinLengthSet: false,
MaxLength: 4096,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "compile_diagnostic",
Error: err,
})
}
if err := func() error {
if s.Tests == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 20,
MaxLengthSet: true,
}).ValidateLength(len(s.Tests)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Tests {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "tests",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s PracticeRunState) Validate() error {
switch s {
case "queued":
return nil
case "running":
return nil
case "finished":
return nil
case "failed":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *PracticeRunTest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10000,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Input)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "input",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10000,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.ExpectedOutput)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "expected_output",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *PracticeRunTestResult) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Source.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "source",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 10,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.Index)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "index",
Error: err,
})
}
if err := func() error {
if err := s.Outcome.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "outcome",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: false,
Max: 0,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.TimeMs)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "time_ms",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: false,
Max: 0,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.MemoryKB)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "memory_kb",
Error: err,
})
}
if err := func() error {
if value, ok := s.Diagnostic.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 0,
MinLengthSet: false,
MaxLength: 2048,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "diagnostic",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s PracticeRunTestSource) Validate() error {
switch s {
case "example":
return nil
case "candidate":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s PracticeStatus) Validate() error {
switch s {
case "not_started":
@@ -23633,6 +24208,57 @@ func (s *SendOrganizationInvitationUnprocessableEntity) Validate() error {
return nil
}
func (s *ServiceUnavailableHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if value, ok := s.RetryAfter.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 86400,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "RetryAfter",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *Session) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -29,6 +29,7 @@ type Handler struct {
support *SupportHandler
assessment *AssessmentHandler
assessmentSignals *AssessmentSignalHandler
practice *PracticeHandler
privacy *PrivacyHandler
evidence *EvidenceHandler
matches *MatchHandler
@@ -96,6 +97,11 @@ func WithAssessmentSignals(signals *AssessmentSignalHandler) HandlerOption {
return func(handler *Handler) { handler.assessmentSignals = signals }
}
// WithPractice serves the debug runs of code practices.
func WithPractice(practice *PracticeHandler) HandlerOption {
return func(handler *Handler) { handler.practice = practice }
}
// WithPrivacy serves current publication and candidate-card visibility operations.
func WithPrivacy(privacy *PrivacyHandler) HandlerOption {
return func(handler *Handler) { handler.privacy = privacy }
@@ -0,0 +1,210 @@
package v1
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/practice"
)
// PracticeOperations serves the debug runs of code practices.
type PracticeOperations interface {
SubmitRun(ctx context.Context, command practice.RunCommand) (practice.RunResult, error)
GetRun(ctx context.Context, actorID uuid.UUID, attemptID domain.AssessmentAttemptID, runID uuid.UUID) (domain.PracticeRunView, error)
}
// PracticeHandler binds the practice usecases to the v1 API.
type PracticeHandler struct {
operations PracticeOperations
}
func NewPracticeHandler(operations PracticeOperations) *PracticeHandler {
if operations == nil {
panic("v1.NewPracticeHandler - operations must not be nil")
}
return &PracticeHandler{operations: operations}
}
func (handler *Handler) CreateMyAssessmentPracticeRun(
ctx context.Context,
request *api.PracticeRunCreate,
params api.CreateMyAssessmentPracticeRunParams,
) (api.CreateMyAssessmentPracticeRunRes, error) {
if handler.practice == nil {
return handler.UnimplementedHandler.CreateMyAssessmentPracticeRun(ctx, request, params)
}
return handler.practice.CreateMyAssessmentPracticeRun(ctx, request, params)
}
func (handler *Handler) GetMyAssessmentPracticeRun(
ctx context.Context,
params api.GetMyAssessmentPracticeRunParams,
) (api.GetMyAssessmentPracticeRunRes, error) {
if handler.practice == nil {
return handler.UnimplementedHandler.GetMyAssessmentPracticeRun(ctx, params)
}
return handler.practice.GetMyAssessmentPracticeRun(ctx, params)
}
func (handler *PracticeHandler) CreateMyAssessmentPracticeRun(
ctx context.Context,
request *api.PracticeRunCreate,
params api.CreateMyAssessmentPracticeRunParams,
) (api.CreateMyAssessmentPracticeRunRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateMyAssessmentPracticeRunUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
command := practice.RunCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
PracticeID: uuid.UUID(request.ItemID), IdempotencyKey: params.IdempotencyKey, Source: request.SourceCode,
Tests: make([]domain.PracticeTest, 0, len(request.Tests)),
}
if !request.Language.Null {
language := domain.TaskLanguageCode(request.Language.Value)
command.Language = &language
}
for _, test := range request.Tests {
command.Tests = append(command.Tests, domain.PracticeTest{Input: test.Input, ExpectedOutput: test.ExpectedOutput})
}
result, err := handler.operations.SubmitRun(ctx, command)
if err != nil {
return practiceRunFailure(ctx, err)
}
response, err := practiceRunResponse(result.Run)
if err != nil {
return nil, fmt.Errorf("PracticeHandler.CreateMyAssessmentPracticeRun - map run: %w", err)
}
return &api.PracticeRunHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *PracticeHandler) GetMyAssessmentPracticeRun(
ctx context.Context,
params api.GetMyAssessmentPracticeRunParams,
) (api.GetMyAssessmentPracticeRunRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyAssessmentPracticeRunUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
run, err := handler.operations.GetRun(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID), params.RunID)
switch {
case errors.Is(err, practice.ErrForbidden):
return (*api.GetMyAssessmentPracticeRunForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, practice.ErrNotFound):
return (*api.GetMyAssessmentPracticeRunNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case err != nil:
return nil, err
}
response, err := practiceRunResponse(run)
if err != nil {
return nil, fmt.Errorf("PracticeHandler.GetMyAssessmentPracticeRun - map run: %w", err)
}
return &api.PracticeRunHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func practiceRunFailure(ctx context.Context, err error) (api.CreateMyAssessmentPracticeRunRes, error) {
var fieldError *practice.FieldError
switch {
case errors.As(err, &fieldError):
return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/"+fieldError.Field).Response), nil
case errors.Is(err, practice.ErrInvalidKey):
return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, practice.ErrForbidden):
return (*api.CreateMyAssessmentPracticeRunForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, practice.ErrUnavailable):
unavailable := problem.New(ctx, api.ProblemCodeServiceUnavailable)
return &api.ServiceUnavailableHeaders{Response: unavailable.Response}, nil
case errors.Is(err, practice.ErrKeyReused):
return (*api.CreateMyAssessmentPracticeRunUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, practice.ErrNotFound):
return (*api.CreateMyAssessmentPracticeRunNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, practice.ErrStateConflict):
return (*api.CreateMyAssessmentPracticeRunConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
default:
return nil, err
}
}
// practiceRunResponse maps a run to its public form. It reads only the public
// groups of the result, so a hidden group could never reach the response
// even if one were stored with a debug run.
func practiceRunResponse(run domain.PracticeRunView) (api.PracticeRun, error) {
response := api.PracticeRun{
ID: run.ID, ItemID: api.AssessmentItemId(run.PracticeID), CreatedAt: api.Timestamp(run.CreatedAt.UTC()),
FinishedAt: api.NilTimestamp{Null: true}, FailureReason: api.NilPracticeFailureReason{Null: true},
Result: api.NilPracticeRunResult{Null: true},
}
switch run.State {
case domain.PracticeJobQueued:
response.State = api.PracticeRunStateQueued
case domain.PracticeJobRunning:
response.State = api.PracticeRunStateRunning
case domain.PracticeJobFinished:
response.State = api.PracticeRunStateFinished
case domain.PracticeJobFailed:
response.State = api.PracticeRunStateFailed
response.FailureReason = api.NewNilPracticeFailureReason(api.PracticeFailureReasonSandboxError)
default:
return api.PracticeRun{}, errors.New("v1.practiceRunResponse - run state is unknown")
}
if run.FinishedAt != nil {
response.FinishedAt = api.NewNilTimestamp(api.Timestamp(run.FinishedAt.UTC()))
}
if run.State == domain.PracticeJobFinished && run.Result != nil {
result, err := practiceRunResultResponse(run.Result.Public())
if err != nil {
return api.PracticeRun{}, err
}
response.Result = api.NewNilPracticeRunResult(result)
}
return response, nil
}
func practiceRunResultResponse(result domain.PracticeRunResult) (api.PracticeRunResult, error) {
response := api.PracticeRunResult{
Outcome: api.PracticeRunOutcome(result.Outcome), CompileDiagnostic: api.NilString{Null: true},
Tests: []api.PracticeRunTestResult{},
}
if result.CompileDiagnostic != "" {
response.CompileDiagnostic = api.NewNilString(result.CompileDiagnostic)
}
for _, group := range result.Groups {
var source api.PracticeRunTestSource
switch {
case group.Hidden:
continue
case group.ID == practice.PublicGroupID:
source = api.PracticeRunTestSourceExample
case group.ID == practice.CustomGroupID:
source = api.PracticeRunTestSourceCandidate
default:
return api.PracticeRunResult{}, errors.New("v1.practiceRunResultResponse - group is unknown")
}
for _, test := range group.Tests {
index, err := strconv.ParseInt(test.ID, 10, 32)
if err != nil || index < 1 {
return api.PracticeRunResult{}, errors.New("v1.practiceRunResultResponse - test index is invalid")
}
item := api.PracticeRunTestResult{
Source: source, Index: int32(index), Outcome: api.PracticeRunOutcome(test.Outcome),
TimeMs: test.TimeMs, MemoryKB: test.MemoryKB, Diagnostic: api.NilString{Null: true},
}
if diagnostic := strings.TrimSpace(test.Diagnostic); diagnostic != "" {
item.Diagnostic = api.NewNilString(test.Diagnostic)
}
response.Tests = append(response.Tests, item)
}
}
return response, nil
}
@@ -0,0 +1,285 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.AssessmentPracticeRepositories = (*UnitOfWork)(nil)
func (unit *UnitOfWork) AssessmentPractices() outbound.AssessmentPracticeRepository {
return assessmentPracticeRepository{queries: unit.queries}
}
type assessmentPracticeRepository struct {
queries *sqlc.Queries
}
func (repository assessmentPracticeRepository) Create(ctx context.Context, practice domain.AssessmentPractice) error {
const location = "assessmentPracticeRepository.Create"
if practice.Status != domain.AssessmentPracticeNotStarted {
return fmt.Errorf("%s - a new practice must not be started: %w", location, domain.ErrInvalidAssessmentPractice)
}
if err := practice.Validate(); err != nil {
return fmt.Errorf("%s - validate practice: %w", location, err)
}
task, err := json.Marshal(practice.Task)
if err != nil {
return fmt.Errorf("%s - encode task: %w", location, domain.ErrInvalidAssessmentPractice)
}
if err := repository.queries.InsertAssessmentPractice(ctx, sqlc.InsertAssessmentPracticeParams{
ID: pgUUID(practice.ID), AttemptID: pgUUID(practice.AttemptID.UUID()), UserID: pgUUID(practice.UserID),
Kind: string(practice.Kind), Task: task, CreatedAt: pgTime(practice.CreatedAt),
}); err != nil {
return fmt.Errorf("%s - insert practice: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentPracticeRepository) LockAttempt(
ctx context.Context,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
) (outbound.PracticeAttemptLock, error) {
const location = "assessmentPracticeRepository.LockAttempt"
row, err := repository.queries.LockAssessmentAttemptForPractice(ctx, sqlc.LockAssessmentAttemptForPracticeParams{
AttemptID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID),
})
if isNoRows(err) {
return outbound.PracticeAttemptLock{}, fmt.Errorf("%s - lock attempt: %w", location, outbound.ErrAssessmentAttemptNotFound)
}
if err != nil {
return outbound.PracticeAttemptLock{}, fmt.Errorf("%s - lock attempt: %w", location, mapAssessmentError(err))
}
if !row.ExpiresAt.Valid || !row.DatabaseTime.Valid {
return outbound.PracticeAttemptLock{}, errors.New(location + " - attempt deadline or database time is missing")
}
return outbound.PracticeAttemptLock{
State: domain.AssessmentAttemptState(row.State),
ExpiresAt: row.ExpiresAt.Time.UTC(),
DatabaseTime: row.DatabaseTime.Time.UTC().Truncate(time.Microsecond),
}, nil
}
func (repository assessmentPracticeRepository) LockPractice(
ctx context.Context,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
practiceID uuid.UUID,
) (domain.AssessmentPractice, error) {
const location = "assessmentPracticeRepository.LockPractice"
row, err := repository.queries.LockAssessmentPractice(ctx, sqlc.LockAssessmentPracticeParams{
ID: pgUUID(practiceID), AttemptID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID),
})
if isNoRows(err) {
return domain.AssessmentPractice{}, fmt.Errorf("%s - lock practice: %w", location, outbound.ErrAssessmentPracticeNotFound)
}
if err != nil {
return domain.AssessmentPractice{}, fmt.Errorf("%s - lock practice: %w", location, mapAssessmentError(err))
}
practice, err := restorePractice(practiceRow{
ID: row.ID, AttemptID: row.AttemptID, UserID: row.UserID, Kind: row.Kind, Task: row.Task, Status: row.Status,
FailureReason: row.FailureReason, SubmittedAt: row.SubmittedAt, CreatedAt: row.CreatedAt,
})
if err != nil {
return domain.AssessmentPractice{}, fmt.Errorf("%s - restore practice: %w", location, err)
}
return practice, nil
}
func (repository assessmentPracticeRepository) SaveState(ctx context.Context, practice domain.AssessmentPractice, updatedAt time.Time) error {
const location = "assessmentPracticeRepository.SaveState"
if err := practice.Validate(); err != nil {
return fmt.Errorf("%s - validate practice: %w", location, err)
}
if updatedAt.IsZero() {
return errors.New(location + " - update time is required")
}
submittedAt := pgtype.Timestamptz{}
if !practice.SubmittedAt.IsZero() {
submittedAt = pgTime(practice.SubmittedAt)
}
updated, err := repository.queries.UpdateAssessmentPracticeState(ctx, sqlc.UpdateAssessmentPracticeStateParams{
ID: pgUUID(practice.ID), Status: string(practice.Status), FailureReason: pgOptionalText(string(practice.FailureReason)),
SubmittedAt: submittedAt, UpdatedAt: pgTime(updatedAt),
})
if err != nil {
return fmt.Errorf("%s - update practice: %w", location, mapAssessmentError(err))
}
if updated != 1 {
return fmt.Errorf("%s - update practice: %w", location, outbound.ErrAssessmentPracticeNotFound)
}
return nil
}
func (repository assessmentPracticeRepository) FindByScope(
ctx context.Context,
userID uuid.UUID,
scope [outbound.IdempotencyDigestSize]byte,
) (outbound.PracticeSubmissionReplay, bool, error) {
const location = "assessmentPracticeRepository.FindByScope"
row, err := repository.queries.FindAssessmentPracticeSubmissionByScope(ctx, sqlc.FindAssessmentPracticeSubmissionByScopeParams{
UserID: pgUUID(userID), IdempotencyScope: scope[:],
})
if isNoRows(err) {
return outbound.PracticeSubmissionReplay{}, false, nil
}
if err != nil {
return outbound.PracticeSubmissionReplay{}, false, fmt.Errorf("%s - find submission: %w", location, mapAssessmentError(err))
}
if !row.ID.Valid || !row.PracticeID.Valid || !domain.PracticeSubmissionMode(row.Mode).IsKnown() {
return outbound.PracticeSubmissionReplay{}, false, fmt.Errorf("%s - stored submission is incomplete: %w", location, domain.ErrInvalidAssessmentPractice)
}
return outbound.PracticeSubmissionReplay{
ID: row.ID.Bytes, PracticeID: row.PracticeID.Bytes, Mode: domain.PracticeSubmissionMode(row.Mode),
}, true, nil
}
func (repository assessmentPracticeRepository) LatestFinal(ctx context.Context, practiceID uuid.UUID) (outbound.PracticeFinalSolution, bool, error) {
const location = "assessmentPracticeRepository.LatestFinal"
row, err := repository.queries.GetLatestFinalPracticeSubmission(ctx, pgUUID(practiceID))
if isNoRows(err) {
return outbound.PracticeFinalSolution{}, false, nil
}
if err != nil {
return outbound.PracticeFinalSolution{}, false, fmt.Errorf("%s - read latest final submission: %w", location, mapAssessmentError(err))
}
solution := outbound.PracticeFinalSolution{SubmissionID: row.ID.Bytes, Language: domain.TaskLanguageCode(row.Language)}
if !row.ID.Valid || !solution.Language.IsKnown() || len(row.SourceSha256) != len(solution.SourceDigest) {
return outbound.PracticeFinalSolution{}, false, fmt.Errorf("%s - stored submission is incomplete: %w", location, domain.ErrInvalidAssessmentPractice)
}
copy(solution.SourceDigest[:], row.SourceSha256)
return solution, true, nil
}
func (repository assessmentPracticeRepository) Submit(
ctx context.Context,
submission domain.PracticeSubmission,
scope [outbound.IdempotencyDigestSize]byte,
) error {
const location = "assessmentPracticeRepository.Submit"
if submission.ID == uuid.Nil || submission.PracticeID == uuid.Nil || submission.UserID == uuid.Nil ||
!submission.Mode.IsKnown() || !submission.Language.IsKnown() || submission.CreatedAt.IsZero() {
return fmt.Errorf("%s - submission is incomplete: %w", location, domain.ErrInvalidAssessmentPractice)
}
var customTests []byte
if len(submission.CustomTests) > 0 {
encoded, err := json.Marshal(submission.CustomTests)
if err != nil {
return fmt.Errorf("%s - encode custom tests: %w", location, domain.ErrInvalidAssessmentPractice)
}
customTests = encoded
}
digest := domain.DigestPracticeSource(submission.Source)
if err := repository.queries.InsertAssessmentPracticeSubmission(ctx, sqlc.InsertAssessmentPracticeSubmissionParams{
ID: pgUUID(submission.ID), PracticeID: pgUUID(submission.PracticeID), UserID: pgUUID(submission.UserID),
Mode: string(submission.Mode), Language: string(submission.Language), Source: submission.Source,
SourceSha256: digest[:], CustomTests: customTests, IdempotencyScope: scope[:], CreatedAt: pgTime(submission.CreatedAt),
}); err != nil {
return fmt.Errorf("%s - insert submission: %w", location, mapAssessmentError(err))
}
if err := repository.queries.InsertAssessmentPracticeJob(ctx, sqlc.InsertAssessmentPracticeJobParams{
SubmissionID: pgUUID(submission.ID), Mode: string(submission.Mode), CreatedAt: pgTime(submission.CreatedAt),
}); err != nil {
return fmt.Errorf("%s - queue job: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentPracticeRepository) GetRun(
ctx context.Context,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
runID uuid.UUID,
) (domain.PracticeRunView, error) {
const location = "assessmentPracticeRepository.GetRun"
row, err := repository.queries.GetAssessmentPracticeRun(ctx, sqlc.GetAssessmentPracticeRunParams{
ID: pgUUID(runID), UserID: pgUUID(userID), AttemptID: pgUUID(attemptID.UUID()),
})
if isNoRows(err) {
return domain.PracticeRunView{}, fmt.Errorf("%s - read run: %w", location, outbound.ErrPracticeRunNotFound)
}
if err != nil {
return domain.PracticeRunView{}, fmt.Errorf("%s - read run: %w", location, mapAssessmentError(err))
}
view := domain.PracticeRunView{
ID: row.ID.Bytes, PracticeID: row.PracticeID.Bytes, State: domain.PracticeJobState(row.State),
CreatedAt: row.CreatedAt.Time.UTC(),
}
if !row.ID.Valid || !row.PracticeID.Valid || !row.CreatedAt.Valid || !view.State.IsKnown() {
return domain.PracticeRunView{}, fmt.Errorf("%s - stored run is incomplete: %w", location, domain.ErrInvalidAssessmentPractice)
}
if row.FinishedAt.Valid {
finishedAt := row.FinishedAt.Time.UTC()
view.FinishedAt = &finishedAt
}
if len(row.Result) > 0 {
result, err := decodePracticeRunResult(row.Result)
if err != nil {
return domain.PracticeRunView{}, fmt.Errorf("%s - restore result: %w", location, err)
}
public := result.Public()
view.Result = &public
}
return view, nil
}
// practiceRow is the stored form of a practice that several queries read.
type practiceRow struct {
ID pgtype.UUID
AttemptID pgtype.UUID
UserID pgtype.UUID
Kind string
Task []byte
Status string
FailureReason pgtype.Text
SubmittedAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
}
func restorePractice(row practiceRow) (domain.AssessmentPractice, error) {
const location = "postgres.restorePractice"
if !row.ID.Valid || !row.AttemptID.Valid || !row.UserID.Valid || !row.CreatedAt.Valid {
return domain.AssessmentPractice{}, fmt.Errorf("%s - stored practice is incomplete: %w", location, domain.ErrInvalidAssessmentPractice)
}
var task domain.PracticeTask
if err := json.Unmarshal(row.Task, &task); err != nil {
return domain.AssessmentPractice{}, fmt.Errorf("%s - decode task: %w", location, domain.ErrInvalidAssessmentPractice)
}
practice := domain.AssessmentPractice{
ID: row.ID.Bytes, AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), UserID: row.UserID.Bytes,
Kind: domain.AssessmentPracticeKind(row.Kind), Task: task, Status: domain.AssessmentPracticeStatus(row.Status),
CreatedAt: row.CreatedAt.Time.UTC(),
}
if row.FailureReason.Valid {
practice.FailureReason = domain.AssessmentPracticeFailureReason(row.FailureReason.String)
}
if row.SubmittedAt.Valid {
practice.SubmittedAt = row.SubmittedAt.Time.UTC()
}
if err := practice.Validate(); err != nil {
return domain.AssessmentPractice{}, fmt.Errorf("%s - validate practice: %w", location, err)
}
return practice, nil
}
func decodePracticeRunResult(encoded []byte) (domain.PracticeRunResult, error) {
var result domain.PracticeRunResult
if err := json.Unmarshal(encoded, &result); err != nil {
return domain.PracticeRunResult{}, fmt.Errorf("postgres.decodePracticeRunResult - decode result: %w", domain.ErrInvalidAssessmentPractice)
}
if err := result.Validate(); err != nil {
return domain.PracticeRunResult{}, fmt.Errorf("postgres.decodePracticeRunResult - validate result: %w", err)
}
return result, nil
}
@@ -0,0 +1,377 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_practice.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const findAssessmentPracticeSubmissionByScope = `-- name: FindAssessmentPracticeSubmissionByScope :one
SELECT
submission.id,
submission.practice_id,
submission.mode
FROM assessment_practice_submissions AS submission
WHERE
submission.user_id = $1
AND submission.idempotency_scope = $2
ORDER BY submission.created_at DESC, submission.id DESC
LIMIT 1
`
type FindAssessmentPracticeSubmissionByScopeParams struct {
UserID pgtype.UUID
IdempotencyScope []byte
}
type FindAssessmentPracticeSubmissionByScopeRow struct {
ID pgtype.UUID
PracticeID pgtype.UUID
Mode string
}
// Finds the latest submission of the owner under an idempotency scope, which
// a replay returns.
func (q *Queries) FindAssessmentPracticeSubmissionByScope(ctx context.Context, arg FindAssessmentPracticeSubmissionByScopeParams) (FindAssessmentPracticeSubmissionByScopeRow, error) {
row := q.db.QueryRow(ctx, findAssessmentPracticeSubmissionByScope, arg.UserID, arg.IdempotencyScope)
var i FindAssessmentPracticeSubmissionByScopeRow
err := row.Scan(&i.ID, &i.PracticeID, &i.Mode)
return i, err
}
const getAssessmentPracticeRun = `-- name: GetAssessmentPracticeRun :one
SELECT
submission.id,
submission.practice_id,
submission.created_at,
submission.result,
job.state,
job.finished_at
FROM assessment_practice_submissions AS submission
INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id
INNER JOIN assessment_practice_jobs AS job ON submission.id = job.submission_id
WHERE
submission.id = $1
AND submission.user_id = $2
AND submission.mode = 'public'
AND practice.attempt_id = $3
`
type GetAssessmentPracticeRunParams struct {
ID pgtype.UUID
UserID pgtype.UUID
AttemptID pgtype.UUID
}
type GetAssessmentPracticeRunRow struct {
ID pgtype.UUID
PracticeID pgtype.UUID
CreatedAt pgtype.Timestamptz
Result []byte
State string
FinishedAt pgtype.Timestamptz
}
// Reads a debug run of the owner's attempt with the state of its job.
func (q *Queries) GetAssessmentPracticeRun(ctx context.Context, arg GetAssessmentPracticeRunParams) (GetAssessmentPracticeRunRow, error) {
row := q.db.QueryRow(ctx, getAssessmentPracticeRun, arg.ID, arg.UserID, arg.AttemptID)
var i GetAssessmentPracticeRunRow
err := row.Scan(
&i.ID,
&i.PracticeID,
&i.CreatedAt,
&i.Result,
&i.State,
&i.FinishedAt,
)
return i, err
}
const getLatestFinalPracticeSubmission = `-- name: GetLatestFinalPracticeSubmission :one
SELECT
submission.id,
submission.language,
submission.source_sha256
FROM assessment_practice_submissions AS submission
WHERE
submission.practice_id = $1
AND submission.mode = 'final'
ORDER BY submission.created_at DESC, submission.id DESC
LIMIT 1
`
type GetLatestFinalPracticeSubmissionRow struct {
ID pgtype.UUID
Language string
SourceSha256 []byte
}
// The latest final submission of a practice: the solution the practice
// state describes.
func (q *Queries) GetLatestFinalPracticeSubmission(ctx context.Context, practiceID pgtype.UUID) (GetLatestFinalPracticeSubmissionRow, error) {
row := q.db.QueryRow(ctx, getLatestFinalPracticeSubmission, practiceID)
var i GetLatestFinalPracticeSubmissionRow
err := row.Scan(&i.ID, &i.Language, &i.SourceSha256)
return i, err
}
const insertAssessmentPractice = `-- name: InsertAssessmentPractice :exec
INSERT INTO assessment_practices (
id,
attempt_id,
user_id,
kind,
task,
status,
failure_reason,
submitted_at,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
'not_started',
NULL,
NULL,
$6,
$6
)
`
type InsertAssessmentPracticeParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
UserID pgtype.UUID
Kind string
Task []byte
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertAssessmentPractice(ctx context.Context, arg InsertAssessmentPracticeParams) error {
_, err := q.db.Exec(ctx, insertAssessmentPractice,
arg.ID,
arg.AttemptID,
arg.UserID,
arg.Kind,
arg.Task,
arg.CreatedAt,
)
return err
}
const insertAssessmentPracticeJob = `-- name: InsertAssessmentPracticeJob :exec
INSERT INTO assessment_practice_jobs (
submission_id,
mode,
state,
created_at,
updated_at
) VALUES (
$1,
$2,
'queued',
$3,
$3
)
`
type InsertAssessmentPracticeJobParams struct {
SubmissionID pgtype.UUID
Mode string
CreatedAt pgtype.Timestamptz
}
// Queues the execution job of a submission in the transaction that stores
// the submission.
func (q *Queries) InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error {
_, err := q.db.Exec(ctx, insertAssessmentPracticeJob, arg.SubmissionID, arg.Mode, arg.CreatedAt)
return err
}
const insertAssessmentPracticeSubmission = `-- name: InsertAssessmentPracticeSubmission :exec
INSERT INTO assessment_practice_submissions (
id,
practice_id,
user_id,
mode,
language,
source,
source_sha256,
custom_tests,
idempotency_scope,
created_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10
)
`
type InsertAssessmentPracticeSubmissionParams struct {
ID pgtype.UUID
PracticeID pgtype.UUID
UserID pgtype.UUID
Mode string
Language string
Source string
SourceSha256 []byte
CustomTests []byte
IdempotencyScope []byte
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertAssessmentPracticeSubmission(ctx context.Context, arg InsertAssessmentPracticeSubmissionParams) error {
_, err := q.db.Exec(ctx, insertAssessmentPracticeSubmission,
arg.ID,
arg.PracticeID,
arg.UserID,
arg.Mode,
arg.Language,
arg.Source,
arg.SourceSha256,
arg.CustomTests,
arg.IdempotencyScope,
arg.CreatedAt,
)
return err
}
const lockAssessmentAttemptForPractice = `-- name: LockAssessmentAttemptForPractice :one
SELECT
attempt.state,
attempt.expires_at,
clock_timestamp()::timestamptz AS database_time
FROM assessment_attempts AS attempt
WHERE
attempt.id = $1
AND attempt.user_id = $2
FOR SHARE
`
type LockAssessmentAttemptForPracticeParams struct {
AttemptID pgtype.UUID
UserID pgtype.UUID
}
type LockAssessmentAttemptForPracticeRow struct {
State string
ExpiresAt pgtype.Timestamptz
DatabaseTime pgtype.Timestamptz
}
// Lock order of a practice command: the idempotency record, the attempt in
// share mode, then the practice row. The attempt flows lock the attempt
// first as well, so a practice command never waits for them in the opposite
// order.
// Locks the owner's attempt in share mode, so its state cannot change while
// a practice command decides on it, and reads the database time after the
// lock.
func (q *Queries) LockAssessmentAttemptForPractice(ctx context.Context, arg LockAssessmentAttemptForPracticeParams) (LockAssessmentAttemptForPracticeRow, error) {
row := q.db.QueryRow(ctx, lockAssessmentAttemptForPractice, arg.AttemptID, arg.UserID)
var i LockAssessmentAttemptForPracticeRow
err := row.Scan(&i.State, &i.ExpiresAt, &i.DatabaseTime)
return i, err
}
const lockAssessmentPractice = `-- name: LockAssessmentPractice :one
SELECT
practice.id,
practice.attempt_id,
practice.user_id,
practice.kind,
practice.task,
practice.status,
practice.failure_reason,
practice.submitted_at,
practice.created_at
FROM assessment_practices AS practice
WHERE
practice.id = $1
AND practice.attempt_id = $2
AND practice.user_id = $3
FOR UPDATE
`
type LockAssessmentPracticeParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
UserID pgtype.UUID
}
type LockAssessmentPracticeRow struct {
ID pgtype.UUID
AttemptID pgtype.UUID
UserID pgtype.UUID
Kind string
Task []byte
Status string
FailureReason pgtype.Text
SubmittedAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
}
// Locks one practice of the owner's attempt for a state change.
func (q *Queries) LockAssessmentPractice(ctx context.Context, arg LockAssessmentPracticeParams) (LockAssessmentPracticeRow, error) {
row := q.db.QueryRow(ctx, lockAssessmentPractice, arg.ID, arg.AttemptID, arg.UserID)
var i LockAssessmentPracticeRow
err := row.Scan(
&i.ID,
&i.AttemptID,
&i.UserID,
&i.Kind,
&i.Task,
&i.Status,
&i.FailureReason,
&i.SubmittedAt,
&i.CreatedAt,
)
return i, err
}
const updateAssessmentPracticeState = `-- name: UpdateAssessmentPracticeState :execrows
UPDATE assessment_practices
SET
status = $1,
failure_reason = $2,
submitted_at = $3,
updated_at = greatest(updated_at, $4::timestamptz)
WHERE id = $5
`
type UpdateAssessmentPracticeStateParams struct {
Status string
FailureReason pgtype.Text
SubmittedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
}
func (q *Queries) UpdateAssessmentPracticeState(ctx context.Context, arg UpdateAssessmentPracticeStateParams) (int64, error) {
result, err := q.db.Exec(ctx, updateAssessmentPracticeState,
arg.Status,
arg.FailureReason,
arg.SubmittedAt,
arg.UpdatedAt,
arg.ID,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
@@ -229,6 +229,43 @@ type AssessmentLeakTrace struct {
EvidenceBits int32
}
type AssessmentPractice struct {
ID pgtype.UUID
AttemptID pgtype.UUID
UserID pgtype.UUID
Kind string
Task []byte
Status string
FailureReason pgtype.Text
SubmittedAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type AssessmentPracticeJob struct {
SubmissionID pgtype.UUID
Mode string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
FinishedAt pgtype.Timestamptz
}
type AssessmentPracticeSubmission struct {
ID pgtype.UUID
PracticeID pgtype.UUID
UserID pgtype.UUID
Mode string
Language string
Source string
SourceSha256 []byte
CustomTests []byte
IdempotencyScope []byte
Result []byte
ResultAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
}
type AssessmentReviewRead struct {
ID pgtype.UUID
AttemptID pgtype.UUID
@@ -277,6 +277,9 @@ type Querier interface {
// NULL retry_at. due_at keeps the deadline. The same guard as the
// completion applies.
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
// Finds the latest submission of the owner under an idempotency scope, which
// a replay returns.
FindAssessmentPracticeSubmissionByScope(ctx context.Context, arg FindAssessmentPracticeSubmissionByScopeParams) (FindAssessmentPracticeSubmissionByScopeRow, error)
// The unmarked statements of real attempts whose text, with runs of white space
// collapsed, contains the fragment. The fragment is matched literally: position
// is not a pattern. The scan reads the stored variant of every item, which is
@@ -314,6 +317,8 @@ type Querier interface {
GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error)
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
// Reads a debug run of the owner's attempt with the state of its job.
GetAssessmentPracticeRun(ctx context.Context, arg GetAssessmentPracticeRunParams) (GetAssessmentPracticeRunRow, error)
// The attempt a review job works on: real attempts only.
GetAssessmentReviewSubject(ctx context.Context, attemptID pgtype.UUID) (pgtype.UUID, error)
// Counts eligible root attempts in a policy window and computes the instant
@@ -390,6 +395,9 @@ type Querier interface {
// for the account's own view of its mail. It selects no address and no
// content. The recipient index narrows the scan to the account's rows.
GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error)
// The latest final submission of a practice: the solution the practice
// state describes.
GetLatestFinalPracticeSubmission(ctx context.Context, practiceID pgtype.UUID) (GetLatestFinalPracticeSubmissionRow, error)
// The pending credentials of the newest token of a registration, for a
// resend, which issues its token with the same credentials.
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
@@ -487,6 +495,11 @@ type Querier interface {
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
InsertAssessmentLeakTrace(ctx context.Context, arg InsertAssessmentLeakTraceParams) error
InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error
InsertAssessmentPractice(ctx context.Context, arg InsertAssessmentPracticeParams) error
// Queues the execution job of a submission in the transaction that stores
// the submission.
InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error
InsertAssessmentPracticeSubmission(ctx context.Context, arg InsertAssessmentPracticeSubmissionParams) error
InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error
// The attempt row is already locked by the caller. Store a parent before its
// bounded child events, in the same transaction as the immutable receipt.
@@ -829,6 +842,14 @@ type Querier interface {
LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error)
// Locks one owner-scoped attempt while a session command performs its CAS.
LockAssessmentAttemptForCandidate(ctx context.Context, arg LockAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
// Lock order of a practice command: the idempotency record, the attempt in
// share mode, then the practice row. The attempt flows lock the attempt
// first as well, so a practice command never waits for them in the opposite
// order.
// Locks the owner's attempt in share mode, so its state cannot change while
// a practice command decides on it, and reads the database time after the
// lock.
LockAssessmentAttemptForPractice(ctx context.Context, arg LockAssessmentAttemptForPracticeParams) (LockAssessmentAttemptForPracticeRow, error)
// Serializes root quota checks for one candidate before taking its optional
// specialization or training lock. All callers acquire these locks in order.
LockAssessmentAttemptScope(ctx context.Context, arg LockAssessmentAttemptScopeParams) error
@@ -836,6 +857,8 @@ type Querier interface {
// published or open the category, until the transaction ends. The key is
// namespaced, so it cannot collide with another use of advisory locks.
LockAssessmentCategory(ctx context.Context, category string) error
// Locks one practice of the owner's attempt for a state change.
LockAssessmentPractice(ctx context.Context, arg LockAssessmentPracticeParams) (LockAssessmentPracticeRow, error)
// Serializes the evaluations of one review. A job takes these locks for every
// attempt it will write, in ascending attempt order, before it reads any fact,
// so what it reads is what the previous writer committed.
@@ -1220,6 +1243,7 @@ type Querier interface {
// Applies an answer, expiry, or finalization transition after the attempt row
// is locked. Session limits and all immutable pins remain unchanged.
UpdateAssessmentAttemptTransition(ctx context.Context, arg UpdateAssessmentAttemptTransitionParams) (AssessmentAttempt, error)
UpdateAssessmentPracticeState(ctx context.Context, arg UpdateAssessmentPracticeStateParams) (int64, error)
// Replaces the publication over the version the caller read and advances the
// version in the same statement. No row returns for a stale version, which
// the caller answers as a version conflict. The update time never moves back,
+2
View File
@@ -45,6 +45,7 @@ func newAPIHandler(
supportHandler *v1.SupportHandler,
assessmentHandler *v1.AssessmentHandler,
assessmentSignalHandler *v1.AssessmentSignalHandler,
practiceHandler *v1.PracticeHandler,
privacyHandler *v1.PrivacyHandler,
evidenceHandler *v1.EvidenceHandler,
notificationHandler *v1.NotificationHandler,
@@ -62,6 +63,7 @@ func newAPIHandler(
v1.WithSupport(supportHandler),
v1.WithAssessment(assessmentHandler),
v1.WithAssessmentSignals(assessmentSignalHandler),
v1.WithPractice(practiceHandler),
v1.WithPrivacy(privacyHandler),
v1.WithEvidence(evidenceHandler),
v1.WithNotifications(notificationHandler),
+49
View File
@@ -0,0 +1,49 @@
package bootstrap
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/practice"
)
// practicePoolMaxConns covers concurrent debug run requests; each holds one
// short transaction.
const practicePoolMaxConns = 4
// newPracticeHandler builds the debug run operations of code practice and the
// PostgreSQL pool they own. Nothing connects here. It returns no handler when
// DATABASE_URL is unset, and the operations then answer 501. Without a code
// runner (CODE_RUNNER_URL unset) the operations answer 503 and store nothing.
// The application clock is time.Now.
func newPracticeHandler(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
keyring *identity.Keyring,
) (*v1.PracticeHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("code practice operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
if keyring == nil {
return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring must be set")
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practicePoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create pool: %w", err)
}
service, err := practice.NewService(postgres.NewTransactor(pool), keyring, time.Now, settings.CodeRunner.Enabled())
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create service: %w", err)
}
return v1.NewPracticeHandler(service), pool.Close, nil
}
+1
View File
@@ -57,6 +57,7 @@ func initialize(
newSupportHandler,
newAssessmentHandler,
newAssessmentSignalHandler,
newPracticeHandler,
newPrivacyHandler,
newEvidenceHandler,
newNotificationHandler,
+83 -53
View File
@@ -184,7 +184,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
privacyHandler, cleanup15, err := newPrivacyHandler(ctx, config2, logger, keyring)
practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup14()
cleanup13()
@@ -202,7 +202,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
evidenceHandler, cleanup16, err := newEvidenceHandler(ctx, config2, logger, keyring)
privacyHandler, cleanup16, err := newPrivacyHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup15()
cleanup14()
@@ -221,7 +221,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
notificationHandler, cleanup17, err := newNotificationHandler(ctx, config2, logger)
evidenceHandler, cleanup17, err := newEvidenceHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup16()
cleanup15()
@@ -241,7 +241,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
matchHandler, cleanup18, err := newMatchHandler(ctx, config2, logger, keyring)
notificationHandler, cleanup18, err := newNotificationHandler(ctx, config2, logger)
if err != nil {
cleanup17()
cleanup16()
@@ -262,54 +262,32 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, invitationHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler)
matchHandler, cleanup19, err := newMatchHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, invitationHandler, supportHandler, assessmentHandler, assessmentSignalHandler, practiceHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
if err != nil {
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
relay, cleanup19, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup20, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup19()
cleanup18()
@@ -332,7 +310,30 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup21, err := newJobWorker(ctx, config2, logger, metrics)
relay, cleanup20, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup21, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup20()
cleanup19()
@@ -356,7 +357,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup22, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
worker, cleanup22, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup21()
cleanup20()
@@ -381,7 +382,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
bootstrapNotificationSendingWorker, cleanup23, err := newNotificationSenderWorker(ctx, config2, logger, metrics, mailSender)
mailsenderWorker, cleanup23, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup22()
cleanup21()
@@ -407,7 +408,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup24, err := newDeliveryMetrics(ctx, config2, logger, metrics)
bootstrapNotificationSendingWorker, cleanup24, err := newNotificationSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup23()
cleanup22()
@@ -434,8 +435,37 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup25, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup24()
cleanup23()
cleanup22()
cleanup21()
cleanup20()
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, bootstrapNotificationSendingWorker, sampler)
return application, func() {
cleanup25()
cleanup24()
cleanup23()
cleanup22()
@@ -0,0 +1,568 @@
package domain
import (
"crypto/sha256"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
// ErrInvalidAssessmentPractice reports practice content, a submission, or a
// run result that breaks the rules below.
var ErrInvalidAssessmentPractice = errors.New("invalid assessment practice")
// Bounds of practice content and submissions. The runner contract bounds the
// technical limits and the payload; these are the product bounds of a task.
const (
// PracticeHiddenGroups is the number of hidden test groups: the verdict
// scores one point for each group that passes.
PracticeHiddenGroups = 3
// MaxPracticeSourceBytes is the runner bound of a source, which is also
// the largest max_source_length a task may set in characters.
MaxPracticeSourceBytes = 65536
// MaxPracticePublicTests bounds the public examples of a task, and
// MaxPracticeCustomTests the candidate's own tests of one debug run.
MaxPracticePublicTests = 10
MaxPracticeCustomTests = 10
// MaxPracticeHiddenTests bounds the tests of one hidden group, as the
// runner bounds the tests of a group.
MaxPracticeHiddenTests = 50
// MaxPracticeExampleText bounds the input and the expected output of a
// public example and of a candidate test in characters.
MaxPracticeExampleText = 10000
// MaxPracticeHiddenText bounds the input and the expected output of a
// hidden test in bytes, as the runner bounds a test text.
MaxPracticeHiddenText = 262144
// maxPracticeLanguages is the number of task languages.
maxPracticeLanguages = 2
redactedPracticeTask = "[redacted practice task]"
redactedPracticeSubmission = "[redacted practice submission]"
)
// AssessmentPracticeKind is the role of a practice in its attempt.
type AssessmentPracticeKind string
const (
AssessmentPracticeMain AssessmentPracticeKind = "main"
AssessmentPracticeAdditional AssessmentPracticeKind = "additional"
)
func (kind AssessmentPracticeKind) IsKnown() bool {
return kind == AssessmentPracticeMain || kind == AssessmentPracticeAdditional
}
// AttemptState is the attempt state in which the practice is the current
// item: only then does it accept runs and submissions.
func (kind AssessmentPracticeKind) AttemptState() AssessmentAttemptState {
if kind == AssessmentPracticeAdditional {
return AssessmentAttemptStateAdditionalPracticePending
}
return AssessmentAttemptStatePracticePending
}
// AssessmentPracticeStatus is the state of a practice as the candidate sees it.
type AssessmentPracticeStatus string
const (
AssessmentPracticeNotStarted AssessmentPracticeStatus = "not_started"
AssessmentPracticePending AssessmentPracticeStatus = "pending"
AssessmentPracticeFinished AssessmentPracticeStatus = "finished"
AssessmentPracticeFailed AssessmentPracticeStatus = "failed"
)
func (status AssessmentPracticeStatus) IsKnown() bool {
switch status {
case AssessmentPracticeNotStarted, AssessmentPracticePending, AssessmentPracticeFinished, AssessmentPracticeFailed:
return true
default:
return false
}
}
// AcceptsFinalSubmission reports whether a new final solution may be
// submitted: nothing was submitted yet, or the sandbox failed the latest one.
func (status AssessmentPracticeStatus) AcceptsFinalSubmission() bool {
return status == AssessmentPracticeNotStarted || status == AssessmentPracticeFailed
}
// AssessmentPracticeFailureReason says why the sandbox gave no verdict. It
// never depends on the solution.
type AssessmentPracticeFailureReason string
const (
// AssessmentPracticeSandboxBusy: the practice queue was full.
AssessmentPracticeSandboxBusy AssessmentPracticeFailureReason = "sandbox_busy"
// AssessmentPracticeSandboxError: the infrastructure could not run it.
AssessmentPracticeSandboxError AssessmentPracticeFailureReason = "sandbox_error"
)
func (reason AssessmentPracticeFailureReason) IsKnown() bool {
return reason == AssessmentPracticeSandboxBusy || reason == AssessmentPracticeSandboxError
}
// PracticeSubmissionMode separates a debug run from the graded solution.
type PracticeSubmissionMode string
const (
// PracticeModePublic runs the public examples and the candidate's own
// tests. It never runs or reports a hidden group.
PracticeModePublic PracticeSubmissionMode = "public"
// PracticeModeFinal runs the hidden groups that grade the practice.
PracticeModeFinal PracticeSubmissionMode = "final"
)
func (mode PracticeSubmissionMode) IsKnown() bool {
return mode == PracticeModePublic || mode == PracticeModeFinal
}
// PracticeJobState is the state of the execution job of a submission.
type PracticeJobState string
const (
PracticeJobQueued PracticeJobState = "queued"
PracticeJobRunning PracticeJobState = "running"
PracticeJobFinished PracticeJobState = "finished"
// PracticeJobFailed means the infrastructure gave up on the job. It is
// never a verdict on the code.
PracticeJobFailed PracticeJobState = "failed"
)
func (state PracticeJobState) IsKnown() bool {
switch state {
case PracticeJobQueued, PracticeJobRunning, PracticeJobFinished, PracticeJobFailed:
return true
default:
return false
}
}
// PracticeCheckerKind says how the output of a test is compared.
type PracticeCheckerKind string
const (
PracticeCheckerExact PracticeCheckerKind = "exact"
PracticeCheckerTokens PracticeCheckerKind = "tokens"
PracticeCheckerNumbers PracticeCheckerKind = "numbers"
PracticeCheckerCustom PracticeCheckerKind = "custom"
)
// PracticeTest is one input with the output the checker expects.
type PracticeTest struct {
Input string `json:"input"`
ExpectedOutput string `json:"expected_output"`
}
// PracticeTestGroup is one hidden group of tests.
type PracticeTestGroup struct {
Tests []PracticeTest `json:"tests"`
}
// PracticeCheckerProgram is the checker program of a custom checker.
type PracticeCheckerProgram struct {
Language TaskLanguageCode `json:"language"`
Source string `json:"source"`
}
// PracticeChecker configures the comparison of every group of the task.
type PracticeChecker struct {
Kind PracticeCheckerKind `json:"kind"`
AbsTolerance float64 `json:"abs_tolerance,omitempty"`
RelTolerance float64 `json:"rel_tolerance,omitempty"`
Program *PracticeCheckerProgram `json:"program,omitempty"`
}
// PracticeTask is the private content of a practice item: what the runner
// needs to run a solution. The hidden groups are task secrets; they never
// reach a candidate, a log, or an error. The statement and the public
// projection of the item belong to the attempt item, not to this record.
//
// String, GoString, Format, and LogValue redact the whole task.
type PracticeTask struct {
// Languages lists the languages a solution may use, one or two.
Languages []TaskLanguageCode `json:"languages"`
// MaxSourceLength bounds the solution in characters.
MaxSourceLength int `json:"max_source_length"`
// TimeLimitMs, MemoryLimitMB, and OutputLimitKB apply to every test.
TimeLimitMs int32 `json:"time_limit_ms"`
MemoryLimitMB int32 `json:"memory_limit_mb"`
OutputLimitKB int32 `json:"output_limit_kb"`
Checker PracticeChecker `json:"checker"`
// PublicTests are the public examples the candidate sees.
PublicTests []PracticeTest `json:"public_tests"`
// HiddenGroups are the PracticeHiddenGroups groups that grade a final
// solution.
HiddenGroups []PracticeTestGroup `json:"hidden_groups"`
}
func (task PracticeTask) String() string { return redactedPracticeTask }
func (task PracticeTask) GoString() string { return redactedPracticeTask }
func (task PracticeTask) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedPracticeTask)
}
func (task PracticeTask) LogValue() slog.Value { return slog.StringValue(redactedPracticeTask) }
// Validate checks the product rules of the task. The runner rules (limit
// ranges, checker parameters, the CPU budget, the payload size) are checked
// when a run request is built from it. Errors never quote task content.
func (task PracticeTask) Validate() error {
const location = "PracticeTask.Validate"
if err := validatePracticeLanguages(task.Languages); err != nil {
return err
}
if task.MaxSourceLength < 1 || task.MaxSourceLength > MaxPracticeSourceBytes {
return practiceError(location, "max source length must be between 1 and 65536")
}
if task.TimeLimitMs <= 0 || task.MemoryLimitMB <= 0 || task.OutputLimitKB <= 0 {
return practiceError(location, "limits must be positive")
}
if err := task.Checker.validate(); err != nil {
return err
}
if len(task.PublicTests) < 1 || len(task.PublicTests) > MaxPracticePublicTests {
return practiceError(location, "public tests must have 1 to 10 entries")
}
for _, test := range task.PublicTests {
if err := test.validate(MaxPracticeExampleText, true); err != nil {
return err
}
}
return validatePracticeHiddenGroups(task.HiddenGroups)
}
func validatePracticeLanguages(languages []TaskLanguageCode) error {
const location = "domain.validatePracticeLanguages"
if len(languages) < 1 || len(languages) > maxPracticeLanguages {
return practiceError(location, "languages must have one or two entries")
}
seen := make(map[TaskLanguageCode]struct{}, len(languages))
for _, language := range languages {
if _, duplicate := seen[language]; duplicate || !language.IsKnown() {
return practiceError(location, "languages must be distinct known task languages")
}
seen[language] = struct{}{}
}
return nil
}
func validatePracticeHiddenGroups(groups []PracticeTestGroup) error {
const location = "domain.validatePracticeHiddenGroups"
if len(groups) != PracticeHiddenGroups {
return practiceError(location, "hidden groups must have exactly three entries")
}
for _, group := range groups {
if len(group.Tests) < 1 || len(group.Tests) > MaxPracticeHiddenTests {
return practiceError(location, "a hidden group must have 1 to 50 tests")
}
for _, test := range group.Tests {
if err := test.validate(MaxPracticeHiddenText, false); err != nil {
return err
}
}
}
return nil
}
// AllowsLanguage reports whether a solution may use the language.
func (task PracticeTask) AllowsLanguage(language TaskLanguageCode) bool {
for _, allowed := range task.Languages {
if allowed == language {
return true
}
}
return false
}
func (checker PracticeChecker) validate() error {
const location = "PracticeChecker.validate"
switch checker.Kind {
case PracticeCheckerExact, PracticeCheckerTokens, PracticeCheckerNumbers:
if checker.Program != nil {
return practiceError(location, "only a custom checker has a program")
}
case PracticeCheckerCustom:
if checker.Program == nil || !checker.Program.Language.IsKnown() || strings.TrimSpace(checker.Program.Source) == "" {
return practiceError(location, "a custom checker needs a program in a task language")
}
default:
return practiceError(location, "checker kind must be exact, tokens, numbers, or custom")
}
return nil
}
// validate checks one test. maxLength counts characters when byCharacters
// is set and bytes otherwise.
func (test PracticeTest) validate(maxLength int, byCharacters bool) error {
const location = "PracticeTest.validate"
for _, text := range []string{test.Input, test.ExpectedOutput} {
if !utf8.ValidString(text) || strings.ContainsRune(text, 0) {
return practiceError(location, "test texts must be valid UTF-8 without NUL")
}
length := len(text)
if byCharacters {
length = utf8.RuneCountInString(text)
}
if length > maxLength {
return practiceError(location, "a test text is too long")
}
}
return nil
}
// ValidatePracticeCustomTests checks the candidate's own tests of a debug run.
func ValidatePracticeCustomTests(tests []PracticeTest) error {
if len(tests) > MaxPracticeCustomTests {
return practiceError("domain.ValidatePracticeCustomTests", "at most 10 custom tests are allowed")
}
for _, test := range tests {
if err := test.validate(MaxPracticeExampleText, true); err != nil {
return err
}
}
return nil
}
// ValidatePracticeSource checks a solution source against the task bound in
// characters and the runner bound in bytes.
func ValidatePracticeSource(source string, maxLength int) error {
const location = "domain.ValidatePracticeSource"
switch {
case strings.TrimSpace(source) == "":
return practiceError(location, "source must not be blank")
case !utf8.ValidString(source) || strings.ContainsRune(source, 0):
return practiceError(location, "source must be valid UTF-8 without NUL")
case len(source) > MaxPracticeSourceBytes || utf8.RuneCountInString(source) > maxLength:
return practiceError(location, "source is too long")
}
return nil
}
// AssessmentPractice is one practice item of an attempt with its state.
type AssessmentPractice struct {
ID uuid.UUID
AttemptID AssessmentAttemptID
UserID uuid.UUID
Kind AssessmentPracticeKind
Task PracticeTask
Status AssessmentPracticeStatus
FailureReason AssessmentPracticeFailureReason
// SubmittedAt is the time of the latest final submission; zero before
// the first one.
SubmittedAt time.Time
CreatedAt time.Time
}
// Validate checks that the practice can be stored or was restored intact.
func (practice AssessmentPractice) Validate() error {
const location = "AssessmentPractice.Validate"
switch {
case practice.ID == uuid.Nil, practice.AttemptID.IsZero(), practice.UserID == uuid.Nil:
return practiceError(location, "practice, attempt, and owner IDs are required")
case !practice.Kind.IsKnown(), !practice.Status.IsKnown():
return practiceError(location, "kind and status must be known")
case (practice.Status == AssessmentPracticeFailed) != practice.FailureReason.IsKnown(),
practice.Status != AssessmentPracticeFailed && practice.FailureReason != "":
return practiceError(location, "only a failed practice has a failure reason")
case (practice.Status == AssessmentPracticeNotStarted) != practice.SubmittedAt.IsZero():
return practiceError(location, "only a submitted practice has a submission time")
case practice.CreatedAt.IsZero():
return practiceError(location, "creation time is required")
}
return practice.Task.Validate()
}
// View is the candidate's view of the practice state. It holds nothing of
// the task.
func (practice AssessmentPractice) View() AssessmentPracticeView {
view := AssessmentPracticeView{
Kind: practice.Kind, ItemID: practice.ID, Status: practice.Status, FailureReason: practice.FailureReason,
}
if !practice.SubmittedAt.IsZero() {
submittedAt := practice.SubmittedAt
view.SubmittedAt = &submittedAt
}
return view
}
// AssessmentPracticeView is the state of a practice that the candidate may
// see: never the task content, the hidden groups, or the source.
type AssessmentPracticeView struct {
Kind AssessmentPracticeKind
ItemID uuid.UUID
Status AssessmentPracticeStatus
SubmittedAt *time.Time
FailureReason AssessmentPracticeFailureReason
}
// PracticeSourceDigest is the SHA-256 of a source; two final submissions are
// the same solution when their languages and digests are equal.
type PracticeSourceDigest [sha256.Size]byte
// DigestPracticeSource returns the digest of a source.
func DigestPracticeSource(source string) PracticeSourceDigest {
return sha256.Sum256([]byte(source))
}
// PracticeSubmission is one stored submission of candidate code. Its request
// part is immutable.
//
// String, GoString, Format, and LogValue redact the source and the tests,
// which are candidate work.
type PracticeSubmission struct {
ID uuid.UUID
PracticeID uuid.UUID
UserID uuid.UUID
Mode PracticeSubmissionMode
Language TaskLanguageCode
Source string
CustomTests []PracticeTest
CreatedAt time.Time
}
func (submission PracticeSubmission) String() string { return redactedPracticeSubmission }
func (submission PracticeSubmission) GoString() string { return redactedPracticeSubmission }
func (submission PracticeSubmission) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedPracticeSubmission)
}
func (submission PracticeSubmission) LogValue() slog.Value {
return slog.GroupValue(
slog.String("submission_id", submission.ID.String()),
slog.String("mode", string(submission.Mode)),
slog.String("language", string(submission.Language)),
)
}
// Validate checks the submission against the task of its practice.
func (submission PracticeSubmission) Validate(task PracticeTask) error {
const location = "PracticeSubmission.Validate"
switch {
case submission.ID == uuid.Nil, submission.PracticeID == uuid.Nil, submission.UserID == uuid.Nil:
return practiceError(location, "submission, practice, and owner IDs are required")
case !submission.Mode.IsKnown():
return practiceError(location, "mode must be public or final")
case !task.AllowsLanguage(submission.Language):
return practiceError(location, "language is not offered by the task")
case submission.Mode == PracticeModeFinal && len(submission.CustomTests) > 0:
return practiceError(location, "a final submission has no custom tests")
case submission.CreatedAt.IsZero():
return practiceError(location, "creation time is required")
}
if err := ValidatePracticeSource(submission.Source, task.MaxSourceLength); err != nil {
return err
}
return ValidatePracticeCustomTests(submission.CustomTests)
}
// PracticeOutcome is the verdict of a test, a group, a compile step, or a
// run, as the runner reports it.
type PracticeOutcome string
const (
PracticeOutcomeAccepted PracticeOutcome = "accepted"
PracticeOutcomeWrongAnswer PracticeOutcome = "wrong_answer"
PracticeOutcomeCompileError PracticeOutcome = "compile_error"
PracticeOutcomeTimeLimitExceeded PracticeOutcome = "time_limit_exceeded"
PracticeOutcomeMemoryLimitExceeded PracticeOutcome = "memory_limit_exceeded"
PracticeOutcomeOutputLimitExceeded PracticeOutcome = "output_limit_exceeded"
PracticeOutcomeRuntimeError PracticeOutcome = "runtime_error"
)
func (outcome PracticeOutcome) IsKnown() bool {
switch outcome {
case PracticeOutcomeAccepted, PracticeOutcomeWrongAnswer, PracticeOutcomeCompileError,
PracticeOutcomeTimeLimitExceeded, PracticeOutcomeMemoryLimitExceeded,
PracticeOutcomeOutputLimitExceeded, PracticeOutcomeRuntimeError:
return true
default:
return false
}
}
// PracticeTestOutcome is the result of one evaluated public test.
type PracticeTestOutcome struct {
ID string `json:"id"`
Outcome PracticeOutcome `json:"outcome"`
TimeMs int64 `json:"time_ms"`
MemoryKB int64 `json:"memory_kb"`
Diagnostic string `json:"diagnostic,omitempty"`
}
// PracticeGroupOutcome is the result of one group. A hidden group keeps only
// its outcome and counts, never its tests.
type PracticeGroupOutcome struct {
ID string `json:"id"`
Hidden bool `json:"hidden"`
Outcome PracticeOutcome `json:"outcome"`
PassedTests int `json:"passed_tests"`
TotalTests int `json:"total_tests"`
Tests []PracticeTestOutcome `json:"tests,omitempty"`
}
// PracticeRunResult is the stored result of a run.
type PracticeRunResult struct {
Outcome PracticeOutcome `json:"outcome"`
// CompileDiagnostic is the compiler message of a compile error. It can
// quote the source, never test data.
CompileDiagnostic string `json:"compile_diagnostic,omitempty"`
Groups []PracticeGroupOutcome `json:"groups"`
DurationMs int64 `json:"duration_ms"`
}
// Validate checks that the result can be stored and shown.
func (result PracticeRunResult) Validate() error {
const location = "PracticeRunResult.Validate"
if !result.Outcome.IsKnown() || result.DurationMs < 0 {
return practiceError(location, "outcome must be known and duration not negative")
}
if result.CompileDiagnostic != "" && result.Outcome != PracticeOutcomeCompileError {
return practiceError(location, "only a compile error has a compile diagnostic")
}
for _, group := range result.Groups {
if group.ID == "" || !group.Outcome.IsKnown() || group.PassedTests < 0 || group.PassedTests > group.TotalTests {
return practiceError(location, "group outcome and counts are inconsistent")
}
if group.Hidden && len(group.Tests) > 0 {
return practiceError(location, "a hidden group keeps no test results")
}
for _, test := range group.Tests {
if test.ID == "" || !test.Outcome.IsKnown() {
return practiceError(location, "test outcome is unknown")
}
}
}
return nil
}
// Public returns the result without hidden groups. Only this projection may
// be shown for a debug run.
func (result PracticeRunResult) Public() PracticeRunResult {
public := result
public.Groups = make([]PracticeGroupOutcome, 0, len(result.Groups))
for _, group := range result.Groups {
if !group.Hidden {
public.Groups = append(public.Groups, group)
}
}
return public
}
// PracticeRunView is a debug run as the candidate sees it: its state and the
// public result. A debug run never runs a hidden group, and the view never
// carries one.
type PracticeRunView struct {
ID uuid.UUID
PracticeID uuid.UUID
State PracticeJobState
CreatedAt time.Time
FinishedAt *time.Time
Result *PracticeRunResult
}
func practiceError(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidAssessmentPractice)
}
@@ -0,0 +1,84 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrAssessmentPracticeNotFound reports a practice that is unknown or
// not a practice of the owner's attempt.
ErrAssessmentPracticeNotFound = errors.New("assessment practice not found")
// ErrPracticeRunNotFound reports a debug run that is unknown or not a
// run of the owner's attempt.
ErrPracticeRunNotFound = errors.New("practice run not found")
)
// PracticeAttemptLock is what a practice command reads about its attempt
// under the share lock.
type PracticeAttemptLock struct {
State domain.AssessmentAttemptState
ExpiresAt time.Time
// DatabaseTime is read after the lock was granted.
DatabaseTime time.Time
}
// PracticeSubmissionReplay identifies the stored submission that a replayed
// request returns.
type PracticeSubmissionReplay struct {
ID uuid.UUID
PracticeID uuid.UUID
Mode domain.PracticeSubmissionMode
}
// PracticeFinalSolution identifies the latest final submission of a practice
// without its source.
type PracticeFinalSolution struct {
SubmissionID uuid.UUID
Language domain.TaskLanguageCode
SourceDigest domain.PracticeSourceDigest
}
// AssessmentPracticeRepositories groups the practice repositories of a unit
// of work.
type AssessmentPracticeRepositories interface {
AssessmentPractices() AssessmentPracticeRepository
}
// AssessmentPracticeRepository keeps the practice items of attempts, their
// submissions, and the execution jobs of the submissions, separately from the
// attempt snapshot and the result. Every read is scoped by the owner, so an
// identifier of another candidate reads as not found.
type AssessmentPracticeRepository interface {
// Create stores a new practice of an attempt in the not_started state.
// The attempt flow that serves practice items calls it.
Create(ctx context.Context, practice domain.AssessmentPractice) error
// LockAttempt locks the owner's attempt in share mode and reads its
// state, deadline, and the database time. An unknown or foreign attempt
// returns ErrAssessmentAttemptNotFound.
LockAttempt(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (PracticeAttemptLock, error)
// LockPractice locks one practice of the owner's attempt for a state
// change. An unknown or foreign practice returns
// ErrAssessmentPracticeNotFound.
LockPractice(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID, practiceID uuid.UUID) (domain.AssessmentPractice, error)
// SaveState stores the status, failure reason, and submission time of a
// locked practice.
SaveState(ctx context.Context, practice domain.AssessmentPractice, updatedAt time.Time) error
// FindByScope returns the latest submission of the owner stored under
// the idempotency scope, if any.
FindByScope(ctx context.Context, userID uuid.UUID, scope [IdempotencyDigestSize]byte) (PracticeSubmissionReplay, bool, error)
// LatestFinal returns the latest final submission of a practice, if any.
LatestFinal(ctx context.Context, practiceID uuid.UUID) (PracticeFinalSolution, bool, error)
// Submit stores a submission under the idempotency scope and queues its
// execution job in the same transaction.
Submit(ctx context.Context, submission domain.PracticeSubmission, scope [IdempotencyDigestSize]byte) error
// GetRun reads a debug run of the owner's attempt with the state of its
// job. It never returns a final submission; an unknown, foreign, or final
// submission returns ErrPracticeRunNotFound.
GetRun(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID, runID uuid.UUID) (domain.PracticeRunView, error)
}
@@ -74,6 +74,7 @@ type UnitOfWork interface {
AssessmentAttemptRepositories
AssessmentSignalRepositories
AssessmentSignalNoticeRepositories
AssessmentPracticeRepositories
SupportCaseRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
@@ -0,0 +1,103 @@
package practice
import (
"fmt"
"strconv"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Group IDs of a run request. They are opaque labels for the runner and the
// stored result; the hidden ones never reach a candidate.
const (
// PublicGroupID holds the public examples of the task.
PublicGroupID = "public"
// CustomGroupID holds the candidate's own tests of a debug run.
CustomGroupID = "custom"
// hiddenGroupPrefix is followed by the group number, from 1.
hiddenGroupPrefix = "hidden-"
)
// RunRequest builds the runner request of a submission. A debug run carries
// the public examples and the candidate's own tests, never a hidden group; a
// final submission carries the hidden groups only, which grade it. The key
// binds the run to the practice item, the submission, and the generation, so
// a retry reuses the run and a new generation starts a new one.
func RunRequest(task domain.PracticeTask, submission domain.PracticeSubmission, generation uint32) (outbound.CodeRunRequest, error) {
const location = "practice.RunRequest"
language, err := runnerLanguage(submission.Language)
if err != nil {
return outbound.CodeRunRequest{}, fmt.Errorf("%s - map language: %w", location, err)
}
checker, err := runnerChecker(task.Checker)
if err != nil {
return outbound.CodeRunRequest{}, fmt.Errorf("%s - map checker: %w", location, err)
}
request := outbound.CodeRunRequest{
Key: outbound.CodeRunKey{AttemptItemID: submission.PracticeID, SubmissionID: submission.ID, Generation: generation},
Language: language,
Source: submission.Source,
Limits: outbound.CodeRunLimits{
TimeLimitMs: task.TimeLimitMs, MemoryLimitMB: task.MemoryLimitMB, OutputLimitKB: task.OutputLimitKB,
},
}
switch submission.Mode {
case domain.PracticeModePublic:
request.Groups = append(request.Groups, runnerGroup(PublicGroupID, outbound.CodeTestPublic, checker, task.PublicTests))
if len(submission.CustomTests) > 0 {
request.Groups = append(request.Groups, runnerGroup(CustomGroupID, outbound.CodeTestPublic, checker, submission.CustomTests))
}
case domain.PracticeModeFinal:
for index, group := range task.HiddenGroups {
id := hiddenGroupPrefix + strconv.Itoa(index+1)
request.Groups = append(request.Groups, runnerGroup(id, outbound.CodeTestHidden, checker, group.Tests))
}
default:
return outbound.CodeRunRequest{}, fmt.Errorf("%s - mode must be public or final: %w", location, domain.ErrInvalidAssessmentPractice)
}
if err := request.Validate(); err != nil {
return outbound.CodeRunRequest{}, fmt.Errorf("%s - validate request: %w", location, err)
}
return request, nil
}
func runnerGroup(
id string,
visibility outbound.CodeTestVisibility,
checker outbound.CodeChecker,
tests []domain.PracticeTest,
) outbound.CodeTestGroup {
group := outbound.CodeTestGroup{ID: id, Visibility: visibility, Checker: checker, Tests: make([]outbound.CodeTest, 0, len(tests))}
for index, test := range tests {
group.Tests = append(group.Tests, outbound.CodeTest{
ID: strconv.Itoa(index + 1), Input: test.Input, ExpectedOutput: test.ExpectedOutput,
})
}
return group
}
func runnerLanguage(language domain.TaskLanguageCode) (outbound.CodeLanguage, error) {
switch language {
case domain.TaskLanguageGo:
return outbound.CodeLanguageGo, nil
case domain.TaskLanguagePython:
return outbound.CodeLanguagePython3, nil
default:
return "", fmt.Errorf("practice.runnerLanguage - language is unknown: %w", domain.ErrInvalidAssessmentPractice)
}
}
func runnerChecker(checker domain.PracticeChecker) (outbound.CodeChecker, error) {
mapped := outbound.CodeChecker{
Kind: outbound.CodeCheckerKind(checker.Kind), AbsTolerance: checker.AbsTolerance, RelTolerance: checker.RelTolerance,
}
if checker.Program != nil {
language, err := runnerLanguage(checker.Program.Language)
if err != nil {
return outbound.CodeChecker{}, fmt.Errorf("practice.runnerChecker - map program language: %w", err)
}
mapped.Program = &outbound.CodeCheckerProgram{Language: language, Source: checker.Program.Source}
}
return mapped, nil
}
@@ -0,0 +1,72 @@
package practice
import (
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const hiddenMarker = "hidden-secret"
func TestRunRequestKeepsHiddenGroupsOutOfDebugRuns(t *testing.T) {
task := testTask()
submission := domain.PracticeSubmission{
ID: uuid.New(), PracticeID: uuid.New(), UserID: uuid.New(), Mode: domain.PracticeModePublic,
Language: domain.TaskLanguagePython, Source: "print(1)\n", CreatedAt: time.Now(),
CustomTests: []domain.PracticeTest{{Input: "1\n", ExpectedOutput: "1\n"}},
}
request, err := RunRequest(task, submission, 0)
if err != nil {
t.Fatalf("RunRequest(public) error = %v", err)
}
if len(request.Groups) != 2 || request.Groups[0].ID != PublicGroupID || request.Groups[1].ID != CustomGroupID {
t.Fatalf("public groups = %d, want the public and the custom group", len(request.Groups))
}
for _, group := range request.Groups {
if group.Visibility != outbound.CodeTestPublic {
t.Fatalf("group %s visibility = %s, want public", group.ID, group.Visibility)
}
for _, test := range group.Tests {
if strings.Contains(test.Input+test.ExpectedOutput, hiddenMarker) {
t.Fatalf("a debug run carries hidden test content in group %s", group.ID)
}
}
}
if request.Language != outbound.CodeLanguagePython3 || request.Key.AttemptItemID != submission.PracticeID ||
request.Key.SubmissionID != submission.ID {
t.Fatal("request language or key does not match the submission")
}
submission.Mode, submission.CustomTests = domain.PracticeModeFinal, nil
request, err = RunRequest(task, submission, 3)
if err != nil {
t.Fatalf("RunRequest(final) error = %v", err)
}
if len(request.Groups) != domain.PracticeHiddenGroups || request.Key.Generation != 3 {
t.Fatalf("final groups = %d with generation %d, want three hidden groups and generation 3", len(request.Groups), request.Key.Generation)
}
for index, group := range request.Groups {
if group.Visibility != outbound.CodeTestHidden || group.ID != hiddenGroupPrefix+string(rune('1'+index)) {
t.Fatalf("final group %d = %s %s, want a hidden group", index, group.ID, group.Visibility)
}
}
}
func testTask() domain.PracticeTask {
hidden := make([]domain.PracticeTestGroup, 0, domain.PracticeHiddenGroups)
for range domain.PracticeHiddenGroups {
hidden = append(hidden, domain.PracticeTestGroup{Tests: []domain.PracticeTest{{Input: hiddenMarker, ExpectedOutput: hiddenMarker}}})
}
return domain.PracticeTask{
Languages: []domain.TaskLanguageCode{domain.TaskLanguagePython},
MaxSourceLength: 100, TimeLimitMs: 1000, MemoryLimitMB: 64, OutputLimitKB: 64,
Checker: domain.PracticeChecker{Kind: domain.PracticeCheckerExact},
PublicTests: []domain.PracticeTest{{Input: "1\n", ExpectedOutput: "1\n"}},
HiddenGroups: hidden,
}
}
@@ -0,0 +1,509 @@
// Package practice stores code practice submissions and their execution
// jobs. It keeps practice state apart from the attempt snapshot and the
// result: a submission and its job commit together, and the practice queue
// worker runs the job later.
package practice
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Idempotency operations. Each scopes its keys separately.
const (
runOperation = "assessment_practice.run"
finalOperation = "assessment_practice.final"
// maxIdempotencyKeyBytes is the contract bound of Idempotency-Key.
maxIdempotencyKeyBytes = 255
)
// Request fields that a FieldError names. The HTTP adapter turns them into
// pointers of its own body.
const (
FieldLanguage = "language"
FieldSource = "source_code"
FieldTests = "tests"
)
var (
// ErrInvalidRequest reports a command that breaks the contract or the
// rules of the task; FieldError names the field.
ErrInvalidRequest = errors.New("invalid practice request")
// ErrInvalidKey reports a malformed Idempotency-Key.
ErrInvalidKey = errors.New("invalid practice idempotency key")
// ErrKeyReused reports an Idempotency-Key used with another request.
ErrKeyReused = errors.New("practice idempotency key reused")
// ErrForbidden reports an account that is not a verified candidate.
ErrForbidden = errors.New("practice is for verified candidates only")
// ErrNotFound reports an attempt, practice, or run that is unknown or
// belongs to another candidate.
ErrNotFound = errors.New("practice not found")
// ErrStateConflict reports a command that the attempt or the practice
// does not accept now: the attempt is not at this practice or past its
// deadline, or the practice already has another solution.
ErrStateConflict = errors.New("practice state conflict")
// ErrUnavailable reports that code practice cannot run now, for example
// because the code runner is disabled. Nothing was stored or graded.
ErrUnavailable = errors.New("code practice unavailable")
)
// FieldError names the request field that ErrInvalidRequest is about.
type FieldError struct {
Field string
}
func (fieldError *FieldError) Error() string {
return "invalid practice request field " + fieldError.Field
}
func (fieldError *FieldError) Unwrap() error { return ErrInvalidRequest }
// Keyring computes scoped idempotency digests with the server secret.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// Service accepts debug runs and final solutions of code practices.
type Service struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
// enabled is false when no code runner is configured: practice then
// answers unavailable and stores nothing.
enabled bool
}
func NewService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time, enabled bool) (*Service, error) {
if transactor == nil || keyring == nil || clock == nil {
return nil, errors.New("practice.NewService - transactor, keyring, and clock are required")
}
return &Service{transactor: transactor, keyring: keyring, clock: clock, enabled: enabled}, nil
}
// RunCommand asks for a debug run of a solution against the public examples
// and the candidate's own tests.
type RunCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
PracticeID uuid.UUID
IdempotencyKey string
// Language is nil when the task offers one language only.
Language *domain.TaskLanguageCode
Source string
Tests []domain.PracticeTest
}
// RunResult is the queued or replayed run.
type RunResult struct {
Run domain.PracticeRunView
Replayed bool
}
// FinalCommand submits the solution that the hidden groups grade.
type FinalCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
PracticeID uuid.UUID
IdempotencyKey string
Language *domain.TaskLanguageCode
Source string
}
// FinalResult is the practice state after the command.
type FinalResult struct {
Practice domain.AssessmentPracticeView
// Replayed reports a repeat of an earlier request with the same key.
Replayed bool
// Unchanged reports that the same solution was already submitted and
// nothing was stored.
Unchanged bool
}
type canonicalRequest struct {
PracticeID string `json:"item_id"`
Language *string `json:"language"`
Source string `json:"source_code"`
Tests []domain.PracticeTest `json:"tests,omitempty"`
}
// SubmitRun stores a debug run and queues its job in one transaction. A
// repeat with the same Idempotency-Key and request returns the stored run in
// its current state; refusals are not stored and are evaluated again.
func (service *Service) SubmitRun(ctx context.Context, command RunCommand) (RunResult, error) {
const location = "Service.SubmitRun"
if err := domain.ValidatePracticeCustomTests(command.Tests); err != nil {
return RunResult{}, fmt.Errorf("%s - validate tests: %w", location, &FieldError{Field: FieldTests})
}
request, err := service.prepare(runOperation, command.ActorID, command.AttemptID, command.PracticeID, command.IdempotencyKey,
canonicalRequest{Language: languageText(command.Language), Source: command.Source, Tests: command.Tests})
if err != nil {
return RunResult{}, fmt.Errorf("%s - prepare: %w", location, err)
}
var result RunResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var transactionErr error
result, transactionErr = service.submitRunInTransaction(ctx, unit, command, request)
return transactionErr
})
if err != nil {
return RunResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func (service *Service) submitRunInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command RunCommand,
request idempotentRequest,
) (RunResult, error) {
const location = "Service.submitRunInTransaction"
if err := requireCandidate(ctx, unit, command.ActorID); err != nil {
return RunResult{}, fmt.Errorf("%s - check account: %w", location, err)
}
if !service.enabled {
return RunResult{}, fmt.Errorf("%s - code runner is disabled: %w", location, ErrUnavailable)
}
replayed, err := reserve(ctx, unit, request)
if err != nil {
return RunResult{}, fmt.Errorf("%s - reserve key: %w", location, err)
}
repository := unit.AssessmentPractices()
if replayed {
stored, found, err := repository.FindByScope(ctx, command.ActorID, request.record.Scope)
if err != nil {
return RunResult{}, fmt.Errorf("%s - find replayed run: %w", location, err)
}
if !found || stored.Mode != domain.PracticeModePublic {
return RunResult{}, fmt.Errorf("%s - replayed key has no run: %w", location, ErrKeyReused)
}
run, err := repository.GetRun(ctx, command.ActorID, command.AttemptID, stored.ID)
if err != nil {
return RunResult{}, fmt.Errorf("%s - read replayed run: %w", location, mapNotFound(err))
}
return RunResult{Run: run, Replayed: true}, nil
}
practice, now, err := lockOpenPractice(ctx, repository, command.ActorID, command.AttemptID, command.PracticeID)
if err != nil {
return RunResult{}, fmt.Errorf("%s - lock practice: %w", location, err)
}
submission, err := newSubmission(practice, domain.PracticeModePublic, command.ActorID, command.Language, command.Source, command.Tests, now)
if err != nil {
return RunResult{}, fmt.Errorf("%s - build submission: %w", location, err)
}
if err := repository.Submit(ctx, submission, request.record.Scope); err != nil {
return RunResult{}, fmt.Errorf("%s - store run: %w", location, err)
}
return RunResult{Run: domain.PracticeRunView{
ID: submission.ID, PracticeID: practice.ID, State: domain.PracticeJobQueued, CreatedAt: now,
}}, nil
}
// SubmitFinal stores the final solution of a practice and queues its job in
// one transaction, and marks the practice pending. The same solution sent
// again stores nothing; a different one is refused while the practice is
// pending or finished, so the source of a graded solution never changes. A
// practice that failed in the sandbox accepts a solution again.
func (service *Service) SubmitFinal(ctx context.Context, command FinalCommand) (FinalResult, error) {
const location = "Service.SubmitFinal"
request, err := service.prepare(finalOperation, command.ActorID, command.AttemptID, command.PracticeID, command.IdempotencyKey,
canonicalRequest{Language: languageText(command.Language), Source: command.Source})
if err != nil {
return FinalResult{}, fmt.Errorf("%s - prepare: %w", location, err)
}
var result FinalResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var transactionErr error
result, transactionErr = service.submitFinalInTransaction(ctx, unit, command, request)
return transactionErr
})
if err != nil {
return FinalResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func (service *Service) submitFinalInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command FinalCommand,
request idempotentRequest,
) (FinalResult, error) {
const location = "Service.submitFinalInTransaction"
if err := requireCandidate(ctx, unit, command.ActorID); err != nil {
return FinalResult{}, fmt.Errorf("%s - check account: %w", location, err)
}
if !service.enabled {
return FinalResult{}, fmt.Errorf("%s - code runner is disabled: %w", location, ErrUnavailable)
}
replayed, err := reserve(ctx, unit, request)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - reserve key: %w", location, err)
}
repository := unit.AssessmentPractices()
if replayed {
if _, err := repository.LockAttempt(ctx, command.ActorID, command.AttemptID); err != nil {
return FinalResult{}, fmt.Errorf("%s - lock attempt of replay: %w", location, mapNotFound(err))
}
practice, err := repository.LockPractice(ctx, command.ActorID, command.AttemptID, command.PracticeID)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - read practice of replay: %w", location, mapNotFound(err))
}
return FinalResult{Practice: practice.View(), Replayed: true}, nil
}
practice, now, err := lockOpenPractice(ctx, repository, command.ActorID, command.AttemptID, command.PracticeID)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - lock practice: %w", location, err)
}
submission, err := newSubmission(practice, domain.PracticeModeFinal, command.ActorID, command.Language, command.Source, nil, now)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - build submission: %w", location, err)
}
if !practice.Status.AcceptsFinalSubmission() {
return finalRepeat(ctx, repository, practice, submission)
}
if err := repository.Submit(ctx, submission, request.record.Scope); err != nil {
return FinalResult{}, fmt.Errorf("%s - store final submission: %w", location, err)
}
practice.Status, practice.FailureReason, practice.SubmittedAt = domain.AssessmentPracticePending, "", now
if err := repository.SaveState(ctx, practice, now); err != nil {
return FinalResult{}, fmt.Errorf("%s - mark practice pending: %w", location, err)
}
return FinalResult{Practice: practice.View()}, nil
}
// finalRepeat answers a final submission to a pending or finished practice:
// the stored solution sent again changes nothing, anything else conflicts.
func finalRepeat(
ctx context.Context,
repository outbound.AssessmentPracticeRepository,
practice domain.AssessmentPractice,
submission domain.PracticeSubmission,
) (FinalResult, error) {
const location = "practice.finalRepeat"
stored, found, err := repository.LatestFinal(ctx, practice.ID)
if err != nil {
return FinalResult{}, fmt.Errorf("%s - read stored solution: %w", location, err)
}
if !found || stored.Language != submission.Language || stored.SourceDigest != domain.DigestPracticeSource(submission.Source) {
return FinalResult{}, fmt.Errorf("%s - practice already has another solution: %w", location, ErrStateConflict)
}
return FinalResult{Practice: practice.View(), Unchanged: true}, nil
}
// GetRun reads a debug run of the owner's attempt.
func (service *Service) GetRun(
ctx context.Context,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
runID uuid.UUID,
) (domain.PracticeRunView, error) {
const location = "Service.GetRun"
if actorID == uuid.Nil || attemptID.IsZero() || runID == uuid.Nil {
return domain.PracticeRunView{}, fmt.Errorf("%s - candidate, attempt, and run IDs are required: %w", location, ErrNotFound)
}
var run domain.PracticeRunView
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, actorID); err != nil {
return err
}
var readErr error
run, readErr = unit.AssessmentPractices().GetRun(ctx, actorID, attemptID, runID)
return mapNotFound(readErr)
})
if err != nil {
return domain.PracticeRunView{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return run, nil
}
type idempotentRequest struct {
record outbound.IdempotencyRecord
}
// prepare checks what a command needs before any database work and derives
// its idempotency record.
func (service *Service) prepare(
operation string,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
practiceID uuid.UUID,
key string,
body canonicalRequest,
) (idempotentRequest, error) {
const location = "Service.prepare"
if actorID == uuid.Nil || attemptID.IsZero() || practiceID == uuid.Nil {
return idempotentRequest{}, fmt.Errorf("%s - candidate, attempt, and practice IDs are required: %w", location, ErrNotFound)
}
if !validIdempotencyKey(key) {
return idempotentRequest{}, fmt.Errorf("%s - check key: %w", location, ErrInvalidKey)
}
if body.Language != nil && !domain.TaskLanguageCode(*body.Language).IsKnown() {
return idempotentRequest{}, fmt.Errorf("%s - check language: %w", location, &FieldError{Field: FieldLanguage})
}
body.PracticeID = practiceID.String()
canonical, err := json.Marshal(body)
if err != nil {
return idempotentRequest{}, fmt.Errorf("%s - encode request fingerprint: %w", location, ErrInvalidRequest)
}
now := service.clock().UTC().Truncate(time.Microsecond)
return idempotentRequest{record: outbound.IdempotencyRecord{
Scope: service.keyring.IdempotencyScope(operation, key, actorID.String()),
Fingerprint: service.keyring.Fingerprint(canonical),
CreatedAt: now,
ExpiresAt: now.Add(outbound.IdempotencyRetention),
}}, nil
}
// requireCandidate admits a verified candidate account only.
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
const location = "practice.requireCandidate"
user, err := unit.Users().GetByID(ctx, actorID)
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - account is missing: %w", location, ErrForbidden)
}
if err != nil {
return fmt.Errorf("%s - read account: %w", location, err)
}
if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate {
return fmt.Errorf("%s - require a verified candidate: %w", location, ErrForbidden)
}
return nil
}
// reserve takes the idempotency record in the transaction and reports a
// replay of the same request. A concurrent request with the same key waits
// for the first transaction.
func reserve(ctx context.Context, unit outbound.UnitOfWork, request idempotentRequest) (bool, error) {
const location = "practice.reserve"
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return false, fmt.Errorf("%s - reserve record: %w", location, err)
}
if created {
return false, nil
}
if stored.Fingerprint != request.record.Fingerprint {
return false, fmt.Errorf("%s - compare request fingerprint: %w", location, ErrKeyReused)
}
return true, nil
}
// lockOpenPractice locks the attempt and the practice and checks that the
// practice is the current item of a running attempt. It returns the database
// time read under the attempt lock.
func lockOpenPractice(
ctx context.Context,
repository outbound.AssessmentPracticeRepository,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
practiceID uuid.UUID,
) (domain.AssessmentPractice, time.Time, error) {
const location = "practice.lockOpenPractice"
attempt, err := repository.LockAttempt(ctx, actorID, attemptID)
if err != nil {
return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - lock attempt: %w", location, mapNotFound(err))
}
practice, err := repository.LockPractice(ctx, actorID, attemptID, practiceID)
if err != nil {
return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - lock practice: %w", location, mapNotFound(err))
}
if attempt.State != practice.Kind.AttemptState() || !attempt.DatabaseTime.Before(attempt.ExpiresAt) {
return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - attempt is not at this practice: %w", location, ErrStateConflict)
}
return practice, attempt.DatabaseTime, nil
}
// newSubmission builds a submission and checks it against the task and the
// runner contract, so the queue never holds a request the runner refuses.
func newSubmission(
practice domain.AssessmentPractice,
mode domain.PracticeSubmissionMode,
actorID uuid.UUID,
language *domain.TaskLanguageCode,
source string,
tests []domain.PracticeTest,
now time.Time,
) (domain.PracticeSubmission, error) {
const location = "practice.newSubmission"
resolved, err := resolveLanguage(practice.Task, language)
if err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - resolve language: %w", location, err)
}
if err := domain.ValidatePracticeSource(source, practice.Task.MaxSourceLength); err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - validate source: %w", location, &FieldError{Field: FieldSource})
}
id, err := uuid.NewV7()
if err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - generate submission ID: %w", location, err)
}
submission := domain.PracticeSubmission{
ID: id, PracticeID: practice.ID, UserID: actorID, Mode: mode, Language: resolved, Source: source,
CustomTests: tests, CreatedAt: now,
}
if err := submission.Validate(practice.Task); err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - validate submission: %w", location, err)
}
// A task the runner would refuse is a content bug, not the candidate's.
if _, err := RunRequest(practice.Task, submission, 0); err != nil {
return domain.PracticeSubmission{}, fmt.Errorf("%s - build run request: %w", location, err)
}
return submission, nil
}
// resolveLanguage returns the submitted language, or the only language of
// the task when none was sent.
func resolveLanguage(task domain.PracticeTask, language *domain.TaskLanguageCode) (domain.TaskLanguageCode, error) {
switch {
case language == nil && len(task.Languages) == 1:
return task.Languages[0], nil
case language != nil && task.AllowsLanguage(*language):
return *language, nil
default:
return "", &FieldError{Field: FieldLanguage}
}
}
func languageText(language *domain.TaskLanguageCode) *string {
if language == nil {
return nil
}
text := string(*language)
return &text
}
func mapNotFound(err error) error {
switch {
case err == nil:
return nil
case errors.Is(err, outbound.ErrAssessmentAttemptNotFound), errors.Is(err, outbound.ErrAssessmentPracticeNotFound),
errors.Is(err, outbound.ErrPracticeRunNotFound):
return fmt.Errorf("practice.mapNotFound - %w: %w", ErrNotFound, err)
default:
return err
}
}
func validIdempotencyKey(value string) bool {
if len(value) == 0 || len(value) > maxIdempotencyKeyBytes {
return false
}
for index := range len(value) {
character := value[index]
if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' ||
character >= '0' && character <= '9' || character == '.' || character == '_' || character == ':' || character == '-' {
continue
}
return false
}
return true
}