// Package supportcase creates and reads account-owned support cases. package supportcase import ( "context" "encoding/json" "errors" "fmt" "log/slog" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) var ( ErrForbidden = errors.New("support case operation forbidden") ErrEmailNotVerified = errors.New("support case operation requires a confirmed email") ErrIdempotencyKeyReused = errors.New("support case idempotency key was reused") ErrInvalidIdempotencyKey = errors.New("invalid support case idempotency key") ErrInvalidCreateRequest = errors.New("invalid support case create request") ErrStateConflict = errors.New("support case conflicts with current state") ErrPolicyUnavailable = errors.New("support case policy is unavailable") ErrRateLimited = errors.New("support case request limit reached") ) const ( createOperation = "support.case.create" createLocation = "supportcase.Service.Create" maxIdempotencyKeySize = 255 maxCanonicalBodySize = 1 << 20 purgeExpiredBatch = 100 ) // Keyring computes scoped idempotency digests. identity.Keyring implements // this interface so support cases use the existing server secret and storage. type Keyring interface { IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte } // Dependencies are the collaborators of Service. type Dependencies struct { Transactor outbound.Transactor Keyring Keyring Clock func() time.Time } // Service applies support-case commands and reads. type Service struct { transactor outbound.Transactor keyring Keyring clock func() time.Time } func NewService(dependencies Dependencies) (*Service, error) { if dependencies.Transactor == nil || dependencies.Keyring == nil || dependencies.Clock == nil { return nil, errors.New("supportcase.NewService - every dependency must be set") } return &Service{ transactor: dependencies.Transactor, keyring: dependencies.Keyring, clock: dependencies.Clock, }, nil } // CreateCommand contains only user-stated fields and the authenticated actor. // Object data, policy decisions, status, response target, rubric, and staff // identities are resolved by the service. type CreateCommand struct { ActorID uuid.UUID IdempotencyKey string CanonicalBody []byte Type domain.SupportCaseType Description string Object *domain.SupportCaseReference AssessmentTarget *domain.SupportCaseAssessmentTarget ComplaintReason *domain.SupportCaseComplaintReason } func (CreateCommand) String() string { return "[support case create command]" } func (CreateCommand) GoString() string { return "[support case create command]" } func (CreateCommand) LogValue() slog.Value { return slog.StringValue("[support case create command]") } // CreateResult is the immutable response snapshot for a successful create. type CreateResult struct { Case domain.SupportCase Replayed bool TargetLate bool } type createRequest struct { command CreateCommand scope [outbound.IdempotencyDigestSize]byte fingerprint [outbound.IdempotencyDigestSize]byte record outbound.IdempotencyRecord now time.Time } type createAttempt struct { result CreateResult err error } // Create opens a support case and stores its stable result with the generic // idempotency record in one transaction. Domain rejections after the request // budget is consumed are returned only after the transaction commits. func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) { request, err := service.prepareCreateRequest(command) if err != nil { return CreateResult{}, err } var attempt createAttempt err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error attempt, err = service.createInTransaction(ctx, unit, request) return err }) if err != nil { return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err) } return attempt.result, attempt.err } func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) { const location = "supportcase.Service.prepareCreateRequest" if command.ActorID == uuid.Nil { return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden) } if !validIdempotencyKey(command.IdempotencyKey) { return createRequest{}, fmt.Errorf("%s - key must have 1 to 255 allowed bytes: %w", location, ErrInvalidIdempotencyKey) } canonicalBody := command.CanonicalBody if len(canonicalBody) == 0 { var err error canonicalBody, err = canonicalCreateBody(command) if err != nil { return createRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, ErrInvalidCreateRequest) } } if len(canonicalBody) > maxCanonicalBodySize { return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", location, ErrInvalidCreateRequest) } fingerprint := service.keyring.Fingerprint(canonicalBody) scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String()) return createRequest{ command: command, scope: scope, fingerprint: fingerprint, record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint}, }, nil } func (service *Service) createInTransaction( ctx context.Context, unit outbound.UnitOfWork, request createRequest, ) (createAttempt, error) { user, err := requireAccount(ctx, unit, request.command.ActorID, createLocation) if err != nil { return createAttempt{}, err } if user.Scenario == domain.ScenarioEmployer && request.command.Type != domain.SupportCaseTypeSupport { return createAttempt{}, ErrForbidden } repositories, attempts, err := supportCaseRepositories(unit) if err != nil { return createAttempt{}, err } latestRequestAt, err := repositories.SupportCaseRequestLimits().LockOwner(ctx, request.command.ActorID) if err != nil { return createAttempt{}, fmt.Errorf("%s - lock account request budget: %w", createLocation, err) } now := service.clock().UTC().Truncate(time.Microsecond) if now.IsZero() { return createAttempt{}, fmt.Errorf("%s - application time must be set", createLocation) } if latestRequestAt.After(now) { now = latestRequestAt.UTC().Truncate(time.Microsecond) } request.now = now request.record = outbound.IdempotencyRecord{ Scope: request.scope, Fingerprint: request.fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention), } version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, request.now) if err != nil { return createAttempt{}, fmt.Errorf("%s - read effective product policy: %w", createLocation, err) } policy := version.Policy().Support if policy == nil { return createAttempt{}, fmt.Errorf("%s - current policy has no support section: %w", createLocation, ErrPolicyUnavailable) } limit, err := repositories.SupportCaseRequestLimits().Consume( ctx, request.command.ActorID, request.now, policy.MaxRequestsPerWindow(), policy.RequestWindow(), ) if err != nil { return createAttempt{}, fmt.Errorf("%s - consume request budget: %w", createLocation, err) } if !limit.Allowed { return createAttempt{err: &RateLimitedError{RetryAfter: limit.RetryAfter}}, nil } prepared, attempt, finished, err := prepareCreateInTransaction(ctx, unit, repositories, policy, version.Version(), user, request) if err != nil || finished { return attempt, err } return createSupportCaseInTransaction(ctx, unit, repositories, attempts, user, prepared) } type preparedSupportCase struct { request createRequest fields domain.NewSupportCaseInput } func prepareCreateInTransaction( ctx context.Context, unit outbound.UnitOfWork, repositories outbound.SupportCaseRepositories, policy *domain.SupportPolicy, policyVersion int32, user domain.User, request createRequest, ) (preparedSupportCase, createAttempt, bool, error) { stored, err := unit.IdempotencyRecords().Find(ctx, request.scope, request.now) if err == nil { attempt, replayErr := replayCreateOutcome(ctx, repositories, request, stored) return preparedSupportCase{}, attempt, true, replayErr } if !errors.Is(err, outbound.ErrIdempotencyRecordNotFound) { return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - read idempotency record: %w", createLocation, err) } fields := newCaseInput(request.command, user.ID, domain.SupportResponseTarget{}, request.now) if validationErr := domain.ValidateSupportCaseRequest(fields); validationErr != nil { return rejectedCreateRequest(validationErr) } responseTarget, err := policy.ResponseTarget(request.command.Type, policyVersion, request.now) if err != nil { return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - fix response target: %w", createLocation, err) } fields.ResponseTarget = responseTarget stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) if err != nil { return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err) } if !created { attempt, replayErr := replayCreateOutcome(ctx, repositories, request, stored) return preparedSupportCase{}, attempt, true, replayErr } if err := repositories.SupportCaseCreateOutcomes().DeleteCreateOutcome(ctx, request.scope); err != nil { return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - remove expired create outcome: %w", createLocation, err) } return preparedSupportCase{request: request, fields: fields}, createAttempt{}, false, nil } func rejectedCreateRequest(validationErr error) (preparedSupportCase, createAttempt, bool, error) { return preparedSupportCase{}, createAttempt{err: validationErr}, true, nil } func createSupportCaseInTransaction( ctx context.Context, unit outbound.UnitOfWork, repositories outbound.SupportCaseRepositories, attempts outbound.AssessmentAttemptRepository, user domain.User, prepared preparedSupportCase, ) (createAttempt, error) { request, fields := prepared.request, prepared.fields if err := resolveReferences(ctx, unit, repositories.SupportCases(), attempts, user, fields); err != nil { return storeReferenceFailure(ctx, unit, repositories, request, err) } if err := resolveManualAssessmentRubric(ctx, repositories, &fields); err != nil { return createAttempt{}, err } number, err := repositories.SupportCases().NextNumber(ctx, request.now) if err != nil { return createAttempt{}, fmt.Errorf("%s - allocate case number: %w", createLocation, err) } fields.Number = number supportCase, err := domain.NewSupportCase(fields) if err != nil { return createAttempt{}, fmt.Errorf("%s - build validated case: %w", createLocation, err) } if err := repositories.SupportCases().Create(ctx, supportCase); err != nil { if errors.Is(err, outbound.ErrSupportCaseConflict) { return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseStateConflictOutcome(), ErrStateConflict) } return createAttempt{}, fmt.Errorf("%s - store case: %w", createLocation, err) } return storeCreatedCase(ctx, unit, repositories, request, supportCase) } func storeReferenceFailure( ctx context.Context, unit outbound.UnitOfWork, repositories outbound.SupportCaseRepositories, request createRequest, resolveErr error, ) (createAttempt, error) { switch { case errors.Is(resolveErr, ErrStateConflict): return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseStateConflictOutcome(), ErrStateConflict) case errors.Is(resolveErr, outbound.ErrSupportCaseNotFound): return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseNotFoundOutcome(), outbound.ErrSupportCaseNotFound) default: return createAttempt{}, resolveErr } } func storeCreatedCase( ctx context.Context, unit outbound.UnitOfWork, repositories outbound.SupportCaseRepositories, request createRequest, supportCase domain.SupportCase, ) (createAttempt, error) { outcome, err := domain.NewSupportCaseCreatedOutcome(supportCase) if err != nil { return createAttempt{}, fmt.Errorf("%s - build create outcome: %w", createLocation, err) } if err := repositories.SupportCaseCreateOutcomes().SaveCreateOutcome(ctx, request.scope, outcome, request.now); err != nil { return createAttempt{}, fmt.Errorf("%s - store create outcome: %w", createLocation, err) } if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { return createAttempt{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err) } result := CreateResult{Case: supportCase, TargetLate: supportCase.ResponseTarget().IsLate(request.now)} return createAttempt{result: result}, nil } func storeCreateFailure( ctx context.Context, unit outbound.UnitOfWork, repositories outbound.SupportCaseRepositories, request createRequest, outcome domain.SupportCaseCreateOutcome, responseErr error, ) (createAttempt, error) { if err := repositories.SupportCaseCreateOutcomes().SaveCreateOutcome(ctx, request.scope, outcome, request.now); err != nil { return createAttempt{}, fmt.Errorf("%s - store failure outcome: %w", createLocation, err) } if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { return createAttempt{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err) } return createAttempt{err: responseErr}, nil } func replayCreateOutcome( ctx context.Context, repositories outbound.SupportCaseRepositories, request createRequest, stored outbound.IdempotencyRecord, ) (createAttempt, error) { if stored.Fingerprint != request.fingerprint { return createAttempt{err: ErrIdempotencyKeyReused}, nil } outcome, err := repositories.SupportCaseCreateOutcomes().GetCreateOutcome(ctx, request.scope) if err != nil { return createAttempt{}, fmt.Errorf("%s - read immutable create outcome: %w", createLocation, err) } switch outcome.Kind() { case domain.SupportCaseCreateOutcomeCreated: supportCase, ok := outcome.Case() if !ok { return createAttempt{}, fmt.Errorf("%s - restore immutable create outcome: %w", createLocation, domain.ErrInvalidSupportCase) } late, ok := outcome.CreationTargetWasLate() if !ok { return createAttempt{}, fmt.Errorf("%s - read original response target state: %w", createLocation, domain.ErrInvalidSupportCase) } return createAttempt{result: CreateResult{Case: supportCase, Replayed: true, TargetLate: late}}, nil case domain.SupportCaseCreateOutcomeNotFound: return createAttempt{err: outbound.ErrSupportCaseNotFound}, nil case domain.SupportCaseCreateOutcomeStateConflict: return createAttempt{err: ErrStateConflict}, nil default: return createAttempt{}, fmt.Errorf("%s - stored outcome kind is invalid: %w", createLocation, domain.ErrInvalidSupportCase) } } func newCaseInput( command CreateCommand, ownerID uuid.UUID, responseTarget domain.SupportResponseTarget, createdAt time.Time, ) domain.NewSupportCaseInput { return domain.NewSupportCaseInput{ OwnerID: ownerID, Type: command.Type, Description: command.Description, Object: command.Object, AssessmentTarget: command.AssessmentTarget, ComplaintReason: command.ComplaintReason, ResponseTarget: responseTarget, CreatedAt: createdAt, } } func resolveReferences( ctx context.Context, unit outbound.UnitOfWork, cases outbound.SupportCaseRepository, attempts outbound.AssessmentAttemptRepository, user domain.User, input domain.NewSupportCaseInput, ) error { object := input.Object if object == nil { return nil } switch object.Type { case domain.SupportCaseObjectInvitation: return outbound.ErrSupportCaseNotFound case domain.SupportCaseObjectOrganization: return resolveOrganizationReference(ctx, unit, user, object.ID) case domain.SupportCaseObjectAssessmentAttempt: return resolveAttemptReference(ctx, attempts, user, object.ID, input) case domain.SupportCaseObjectSupportCase: return resolveSupportCaseReference(ctx, cases, user, object.ID, input.Type) default: return outbound.ErrSupportCaseNotFound } } func resolveOrganizationReference(ctx context.Context, unit outbound.UnitOfWork, user domain.User, id uuid.UUID) error { if user.Scenario != domain.ScenarioEmployer { return outbound.ErrSupportCaseNotFound } if _, _, err := unit.Organizations().GetForMember(ctx, id, user.ID); err != nil { if errors.Is(err, outbound.ErrOrganizationNotFound) { return outbound.ErrSupportCaseNotFound } return fmt.Errorf("%s - resolve organization reference: %w", createLocation, err) } return nil } func resolveAttemptReference( ctx context.Context, attempts outbound.AssessmentAttemptRepository, user domain.User, id uuid.UUID, input domain.NewSupportCaseInput, ) error { attempt, err := attempts.GetForCandidate(ctx, user.ID, domain.AssessmentAttemptID(id)) if err != nil { if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { return outbound.ErrSupportCaseNotFound } return fmt.Errorf("%s - resolve assessment attempt reference: %w", createLocation, err) } return validateAttemptReference(input, attempt) } func resolveSupportCaseReference( ctx context.Context, cases outbound.SupportCaseRepository, user domain.User, id uuid.UUID, caseType domain.SupportCaseType, ) error { referenced, err := cases.GetOwned(ctx, user.ID, domain.SupportCaseID(id)) if err != nil { return err } if caseType != domain.SupportCaseTypeGradeAppeal { return nil } decision := referenced.Decision() if referenced.Type() != domain.SupportCaseTypeManualAssessment || referenced.Status() != domain.SupportCaseStatusResolved || decision == nil || decision.Outcome() != domain.SupportCaseDecisionAssessed { return ErrStateConflict } return nil } func validateAttemptReference(input domain.NewSupportCaseInput, attempt domain.AssessmentAttempt) error { switch input.Type { case domain.SupportCaseTypeSupport, domain.SupportCaseTypeComplaint: return nil case domain.SupportCaseTypeManualAssessment: return validateManualAssessmentAttempt(input.AssessmentTarget, attempt) case domain.SupportCaseTypeGradeAppeal: if attempt.State() != domain.AssessmentAttemptStateCompleted { return ErrStateConflict } case domain.SupportCaseTypeAnticheatAppeal: // Anti-cheat review decisions are not implemented. An owned attempt // therefore has no appealable decision yet. return ErrStateConflict } return nil } func supportCaseRepositories( unit outbound.UnitOfWork, ) (outbound.SupportCaseRepositories, outbound.AssessmentAttemptRepository, error) { repositories, ok := unit.(outbound.SupportCaseRepositories) if !ok { return nil, nil, errors.New("supportcase.Service - unit of work does not expose support case repositories") } attempts, ok := unit.(outbound.AssessmentAttemptRepositories) if !ok { return nil, nil, errors.New("supportcase.Service - unit of work does not expose assessment attempts") } return repositories, attempts.AssessmentAttempts(), nil } func requireAccount(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) (domain.User, error) { user, err := unit.Users().GetByID(ctx, actorID) if err != nil { if errors.Is(err, outbound.ErrUserNotFound) { return domain.User{}, ErrForbidden } return domain.User{}, fmt.Errorf("%s - read account: %w", location, err) } if !user.EmailVerified() { return domain.User{}, ErrEmailNotVerified } if user.Scenario != domain.ScenarioCandidate && user.Scenario != domain.ScenarioEmployer { return domain.User{}, ErrForbidden } return user, nil } func validIdempotencyKey(value string) bool { if len(value) == 0 || len(value) > maxIdempotencyKeySize { 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 } func canonicalCreateBody(command CreateCommand) ([]byte, error) { var object any if command.Object != nil { object = []any{string(command.Object.Type), command.Object.ID.String()} } var target any if command.AssessmentTarget != nil { target = []any{string(command.AssessmentTarget.Specialization), string(command.AssessmentTarget.Grade)} } var reason any if command.ComplaintReason != nil { reason = string(*command.ComplaintReason) } return json.Marshal([]any{string(command.Type), command.Description, object, target, reason}) } // RateLimitedError carries the server-computed Retry-After interval. type RateLimitedError struct { RetryAfter time.Duration } func (RateLimitedError) Error() string { return ErrRateLimited.Error() } func (RateLimitedError) Unwrap() error { return ErrRateLimited } // GetMyCase returns one full case only to its account owner. func (service *Service) GetMyCase(ctx context.Context, actorID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) { const location = "supportcase.Service.GetMyCase" if actorID == uuid.Nil || caseID.IsZero() { return domain.SupportCase{}, fmt.Errorf("%s - identifiers must be set: %w", location, ErrForbidden) } var result domain.SupportCase err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if _, err := requireAccount(ctx, unit, actorID, location); err != nil { return err } repositories, _, err := supportCaseRepositories(unit) if err != nil { return err } result, err = repositories.SupportCases().GetOwned(ctx, actorID, caseID) if err != nil { return fmt.Errorf("%s - read owned case: %w", location, err) } return nil }) if err != nil { return domain.SupportCase{}, fmt.Errorf("%s - transaction: %w", location, err) } return result, nil } // ListCommand selects one owner-scoped page. type ListCommand struct { ActorID uuid.UUID After *outbound.SupportCaseListPosition Limit int32 } // ListMyCases returns summaries and never loads descriptions or history. func (service *Service) ListMyCases(ctx context.Context, command ListCommand) (outbound.SupportCaseListPage, error) { const location = "supportcase.Service.ListMyCases" if command.ActorID == uuid.Nil || command.Limit < 1 || command.Limit > outbound.MaxSupportCasePageSize || command.After != nil && (command.After.ID.IsZero() || command.After.CreatedAt.IsZero()) { return outbound.SupportCaseListPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidSupportCase) } var result outbound.SupportCaseListPage err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if _, err := requireAccount(ctx, unit, command.ActorID, location); err != nil { return err } repositories, _, err := supportCaseRepositories(unit) if err != nil { return err } result, err = repositories.SupportCases().ListOwned(ctx, outbound.SupportCaseListQuery{ OwnerID: command.ActorID, After: command.After, Limit: command.Limit, }) if err != nil { return fmt.Errorf("%s - list owned cases: %w", location, err) } return nil }) if err != nil { return outbound.SupportCaseListPage{}, fmt.Errorf("%s - transaction: %w", location, err) } return result, nil }