487 lines
19 KiB
Go
487 lines
19 KiB
Go
package domain
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
var (
|
|
// ErrInvalidCandidateQuestionnaire reports a questionnaire value that
|
|
// breaks its contract or cannot be restored from storage.
|
|
ErrInvalidCandidateQuestionnaire = errors.New("invalid candidate questionnaire")
|
|
|
|
// ErrCandidateQuestionnaireVersionConflict reports that the saved
|
|
// questionnaire changed after the caller read it.
|
|
ErrCandidateQuestionnaireVersionConflict = errors.New("candidate questionnaire changed concurrently")
|
|
)
|
|
|
|
const (
|
|
maxQuestionnaireSpecializations = 2
|
|
maxQuestionnaireTaskLanguages = 2
|
|
maxQuestionnaireStackItems = 20
|
|
maxQuestionnaireStackTagRunes = 50
|
|
maxQuestionnaireExperienceMonth = 600
|
|
)
|
|
|
|
const redactedQuestionnaire = "[redacted candidate questionnaire]"
|
|
|
|
// CandidateQuestionnaireFieldError describes one invalid request field. The
|
|
// reason is fixed text and never includes the submitted value.
|
|
type CandidateQuestionnaireFieldError struct {
|
|
Pointer string
|
|
Reason string
|
|
}
|
|
|
|
func (fieldError *CandidateQuestionnaireFieldError) Error() string {
|
|
return "candidate questionnaire field " + fieldError.Pointer + " " + fieldError.Reason
|
|
}
|
|
|
|
func (fieldError *CandidateQuestionnaireFieldError) Unwrap() error {
|
|
return ErrInvalidCandidateQuestionnaire
|
|
}
|
|
|
|
func invalidQuestionnaireField(location, pointer, reason string) error {
|
|
return fmt.Errorf("%s - %w", location, &CandidateQuestionnaireFieldError{Pointer: pointer, Reason: reason})
|
|
}
|
|
|
|
// TaskLanguageCode identifies a language actually offered by a published
|
|
// assessment bank. The catalog projection, not this enum, decides which one
|
|
// is currently valid for a specialization.
|
|
type TaskLanguageCode string
|
|
|
|
const (
|
|
TaskLanguagePython TaskLanguageCode = "python"
|
|
TaskLanguageGo TaskLanguageCode = "go"
|
|
)
|
|
|
|
func (language TaskLanguageCode) IsKnown() bool {
|
|
return language == TaskLanguagePython || language == TaskLanguageGo
|
|
}
|
|
|
|
// QuestionnaireWorkFormat is an acceptable work format.
|
|
type QuestionnaireWorkFormat string
|
|
|
|
const (
|
|
QuestionnaireWorkFormatRemote QuestionnaireWorkFormat = "remote"
|
|
QuestionnaireWorkFormatOffice QuestionnaireWorkFormat = "office"
|
|
QuestionnaireWorkFormatHybrid QuestionnaireWorkFormat = "hybrid"
|
|
)
|
|
|
|
func (format QuestionnaireWorkFormat) IsKnown() bool {
|
|
switch format {
|
|
case QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatOffice, QuestionnaireWorkFormatHybrid:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// QuestionnaireExperience contains self-reported month totals. It does not
|
|
// contribute assessment points and has no field for a confirmed grade.
|
|
type QuestionnaireExperience struct {
|
|
CommercialMonths int32
|
|
AcademicMonths int32
|
|
}
|
|
|
|
func (QuestionnaireExperience) String() string { return redactedQuestionnaire }
|
|
func (QuestionnaireExperience) GoString() string { return redactedQuestionnaire }
|
|
func (QuestionnaireExperience) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedQuestionnaire)
|
|
}
|
|
func (QuestionnaireExperience) LogValue() slog.Value {
|
|
return slog.StringValue(redactedQuestionnaire)
|
|
}
|
|
|
|
// QuestionnaireSpecialization is one self-assessed specialization. Its grade
|
|
// is a candidate claim, never a confirmed grade or category.
|
|
type QuestionnaireSpecialization struct {
|
|
Specialization SpecializationCode
|
|
SelfAssessedGrade GradeCode
|
|
TaskLanguages []TaskLanguageCode
|
|
Stack []string
|
|
Experience *QuestionnaireExperience
|
|
}
|
|
|
|
func (QuestionnaireSpecialization) String() string { return redactedQuestionnaire }
|
|
func (QuestionnaireSpecialization) GoString() string { return redactedQuestionnaire }
|
|
func (QuestionnaireSpecialization) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedQuestionnaire)
|
|
}
|
|
func (QuestionnaireSpecialization) LogValue() slog.Value {
|
|
return slog.StringValue(redactedQuestionnaire)
|
|
}
|
|
|
|
// CandidateQuestionnaireInput is the complete replacement sent by a
|
|
// candidate. It contains personal data and must not be logged.
|
|
type CandidateQuestionnaireInput struct {
|
|
Specializations []QuestionnaireSpecialization
|
|
WorkFormats []QuestionnaireWorkFormat
|
|
}
|
|
|
|
func (CandidateQuestionnaireInput) String() string { return redactedQuestionnaire }
|
|
func (CandidateQuestionnaireInput) GoString() string { return redactedQuestionnaire }
|
|
func (CandidateQuestionnaireInput) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedQuestionnaire)
|
|
}
|
|
func (CandidateQuestionnaireInput) LogValue() slog.Value {
|
|
return slog.StringValue(redactedQuestionnaire)
|
|
}
|
|
|
|
// SpecializationAvailability is the current published-bank projection shared
|
|
// by the public catalog and questionnaire validation. Empty grades and
|
|
// languages mean that the specialization is not currently available.
|
|
type SpecializationAvailability struct {
|
|
Specialization SpecializationCode
|
|
Grades []GradeCode
|
|
TaskLanguages []TaskLanguageCode
|
|
}
|
|
|
|
// CandidateQuestionnaire is the private questionnaire of one candidate.
|
|
// Version zero means no questionnaire has been saved yet.
|
|
type CandidateQuestionnaire struct {
|
|
userID uuid.UUID
|
|
version int64
|
|
specializations []QuestionnaireSpecialization
|
|
workFormats []QuestionnaireWorkFormat
|
|
createdAt time.Time
|
|
updatedAt time.Time
|
|
}
|
|
|
|
// EmptyCandidateQuestionnaire returns the unsaved questionnaire of userID.
|
|
func EmptyCandidateQuestionnaire(userID uuid.UUID) (CandidateQuestionnaire, error) {
|
|
if userID == uuid.Nil {
|
|
return CandidateQuestionnaire{}, fmt.Errorf("domain.EmptyCandidateQuestionnaire - user ID must not be nil: %w", ErrInvalidCandidateQuestionnaire)
|
|
}
|
|
return CandidateQuestionnaire{userID: userID}, nil
|
|
}
|
|
|
|
func (questionnaire CandidateQuestionnaire) UserID() uuid.UUID { return questionnaire.userID }
|
|
func (questionnaire CandidateQuestionnaire) Version() int64 { return questionnaire.version }
|
|
func (questionnaire CandidateQuestionnaire) CreatedAt() time.Time {
|
|
return questionnaire.createdAt
|
|
}
|
|
func (questionnaire CandidateQuestionnaire) UpdatedAt() time.Time {
|
|
return questionnaire.updatedAt
|
|
}
|
|
|
|
func (questionnaire CandidateQuestionnaire) Specializations() []QuestionnaireSpecialization {
|
|
return cloneQuestionnaireSpecializations(questionnaire.specializations)
|
|
}
|
|
|
|
func (questionnaire CandidateQuestionnaire) WorkFormats() []QuestionnaireWorkFormat {
|
|
return slices.Clone(questionnaire.workFormats)
|
|
}
|
|
|
|
func (questionnaire CandidateQuestionnaire) IsZero() bool { return questionnaire.userID == uuid.Nil }
|
|
|
|
// SameContent reports whether two questionnaires for the same candidate have
|
|
// identical validated answers, without comparing versions or timestamps.
|
|
func (questionnaire CandidateQuestionnaire) SameContent(other CandidateQuestionnaire) bool {
|
|
return !questionnaire.IsZero() && questionnaire.userID == other.userID &&
|
|
equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, questionnaireContent{
|
|
specializations: other.specializations,
|
|
workFormats: other.workFormats,
|
|
})
|
|
}
|
|
|
|
func (questionnaire CandidateQuestionnaire) String() string { return redactedQuestionnaire }
|
|
func (questionnaire CandidateQuestionnaire) GoString() string { return redactedQuestionnaire }
|
|
func (questionnaire CandidateQuestionnaire) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedQuestionnaire)
|
|
}
|
|
func (questionnaire CandidateQuestionnaire) LogValue() slog.Value {
|
|
return slog.GroupValue(
|
|
slog.String("user_id", questionnaire.userID.String()),
|
|
slog.Int64("version", questionnaire.version),
|
|
)
|
|
}
|
|
|
|
// StoredCandidateQuestionnaire is the database projection used to restore a
|
|
// saved questionnaire. A missing row is represented by EmptyCandidateQuestionnaire.
|
|
type StoredCandidateQuestionnaire struct {
|
|
UserID uuid.UUID
|
|
Version int64
|
|
Specializations []QuestionnaireSpecialization
|
|
WorkFormats []QuestionnaireWorkFormat
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
}
|
|
|
|
// RestoreCandidateQuestionnaire validates a saved questionnaire before it is
|
|
// exposed to a usecase. Current bank availability is intentionally not part
|
|
// of restoration; a later bank change must not make saved answers unreadable.
|
|
func RestoreCandidateQuestionnaire(stored StoredCandidateQuestionnaire) (CandidateQuestionnaire, error) {
|
|
const location = "domain.RestoreCandidateQuestionnaire"
|
|
if stored.UserID == uuid.Nil || stored.Version < 1 || stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt) {
|
|
return CandidateQuestionnaire{}, fmt.Errorf("%s - stored identity, version, or time is invalid: %w", location, ErrInvalidCandidateQuestionnaire)
|
|
}
|
|
content, err := validateQuestionnaireInput(CandidateQuestionnaireInput{
|
|
Specializations: stored.Specializations,
|
|
WorkFormats: stored.WorkFormats,
|
|
}, location)
|
|
if err != nil {
|
|
return CandidateQuestionnaire{}, fmt.Errorf("%s - validate stored content: %w", location, err)
|
|
}
|
|
return CandidateQuestionnaire{
|
|
userID: stored.UserID, version: stored.Version,
|
|
specializations: content.specializations, workFormats: content.workFormats,
|
|
createdAt: stored.CreatedAt, updatedAt: stored.UpdatedAt,
|
|
}, nil
|
|
}
|
|
|
|
// Replace validates a complete replacement and reports whether it changes
|
|
// the current questionnaire. Identical retries are no-ops even with an older
|
|
// expected version; a changed stale request conflicts.
|
|
func (questionnaire CandidateQuestionnaire) Replace(
|
|
input CandidateQuestionnaireInput,
|
|
expectedVersion int64,
|
|
at time.Time,
|
|
availability []SpecializationAvailability,
|
|
) (CandidateQuestionnaire, bool, error) {
|
|
const location = "CandidateQuestionnaire.Replace"
|
|
if questionnaire.IsZero() {
|
|
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - questionnaire was not built by EmptyCandidateQuestionnaire or RestoreCandidateQuestionnaire: %w", location, ErrInvalidCandidateQuestionnaire)
|
|
}
|
|
conflict := fmt.Errorf("%s - expected version is not current: %w", location, ErrCandidateQuestionnaireVersionConflict)
|
|
if expectedVersion < 0 || expectedVersion > questionnaire.version {
|
|
return CandidateQuestionnaire{}, false, conflict
|
|
}
|
|
if at.IsZero() {
|
|
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateQuestionnaire)
|
|
}
|
|
content, err := validateQuestionnaireInput(input, location)
|
|
if err != nil {
|
|
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - validate content: %w", location, err)
|
|
}
|
|
if equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, content) {
|
|
return questionnaire, false, nil
|
|
}
|
|
if expectedVersion != questionnaire.version {
|
|
return CandidateQuestionnaire{}, false, conflict
|
|
}
|
|
if err := validateQuestionnaireTaskLanguages(content.specializations, availability, location); err != nil {
|
|
return CandidateQuestionnaire{}, false, err
|
|
}
|
|
updated := questionnaire
|
|
updated.specializations = content.specializations
|
|
updated.workFormats = content.workFormats
|
|
updated.updatedAt = at
|
|
if at.Before(questionnaire.updatedAt) {
|
|
updated.updatedAt = questionnaire.updatedAt
|
|
}
|
|
if updated.createdAt.IsZero() {
|
|
updated.createdAt = updated.updatedAt
|
|
}
|
|
return updated, true, nil
|
|
}
|
|
|
|
type questionnaireContent struct {
|
|
specializations []QuestionnaireSpecialization
|
|
workFormats []QuestionnaireWorkFormat
|
|
}
|
|
|
|
func validateQuestionnaireInput(input CandidateQuestionnaireInput, location string) (questionnaireContent, error) {
|
|
if len(input.Specializations) < 1 || len(input.Specializations) > maxQuestionnaireSpecializations {
|
|
return questionnaireContent{}, invalidQuestionnaireField(location, "/specializations", "must contain one or two items")
|
|
}
|
|
if len(input.WorkFormats) < 1 || len(input.WorkFormats) > 3 {
|
|
return questionnaireContent{}, invalidQuestionnaireField(location, "/work_context/work_formats", "must contain one to three items")
|
|
}
|
|
content := questionnaireContent{
|
|
specializations: make([]QuestionnaireSpecialization, 0, len(input.Specializations)),
|
|
workFormats: slices.Clone(input.WorkFormats),
|
|
}
|
|
var err error
|
|
content.specializations, err = validateQuestionnaireSpecializations(input.Specializations, location)
|
|
if err != nil {
|
|
return questionnaireContent{}, err
|
|
}
|
|
if err := validateQuestionnaireWorkFormats(content.workFormats, location); err != nil {
|
|
return questionnaireContent{}, err
|
|
}
|
|
return content, nil
|
|
}
|
|
|
|
func validateQuestionnaireSpecializations(
|
|
answers []QuestionnaireSpecialization,
|
|
location string,
|
|
) ([]QuestionnaireSpecialization, error) {
|
|
validated := make([]QuestionnaireSpecialization, 0, len(answers))
|
|
seenSpecializations := make(map[SpecializationCode]struct{}, len(answers))
|
|
for index, answer := range answers {
|
|
pointer := fmt.Sprintf("/specializations/%d", index)
|
|
if !answer.Specialization.IsKnown() {
|
|
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must be a specialization of the catalog")
|
|
}
|
|
if _, exists := seenSpecializations[answer.Specialization]; exists {
|
|
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must not repeat an earlier item")
|
|
}
|
|
seenSpecializations[answer.Specialization] = struct{}{}
|
|
validatedAnswer, err := validateQuestionnaireSpecialization(answer, pointer, location)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
validated = append(validated, validatedAnswer)
|
|
}
|
|
return validated, nil
|
|
}
|
|
|
|
func validateQuestionnaireSpecialization(
|
|
answer QuestionnaireSpecialization,
|
|
pointer, location string,
|
|
) (QuestionnaireSpecialization, error) {
|
|
if !answer.SelfAssessedGrade.IsKnown() {
|
|
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/self_assessed_grade", "must be a grade of the catalog")
|
|
}
|
|
if len(answer.TaskLanguages) > maxQuestionnaireTaskLanguages {
|
|
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/task_languages", "must have at most two items")
|
|
}
|
|
if len(answer.Stack) > maxQuestionnaireStackItems {
|
|
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/stack", "must have at most twenty items")
|
|
}
|
|
answer.TaskLanguages = slices.Clone(answer.TaskLanguages)
|
|
if err := validateQuestionnaireTaskLanguageInputs(answer.TaskLanguages, pointer, location); err != nil {
|
|
return QuestionnaireSpecialization{}, err
|
|
}
|
|
answer.Stack = slices.Clone(answer.Stack)
|
|
if err := validateQuestionnaireStack(answer.Stack, pointer, location); err != nil {
|
|
return QuestionnaireSpecialization{}, err
|
|
}
|
|
if answer.Experience != nil {
|
|
experience := *answer.Experience
|
|
if experience.CommercialMonths < 0 || experience.CommercialMonths > maxQuestionnaireExperienceMonth {
|
|
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/commercial_months", "must be between zero and 600")
|
|
}
|
|
if experience.AcademicMonths < 0 || experience.AcademicMonths > maxQuestionnaireExperienceMonth {
|
|
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/academic_months", "must be between zero and 600")
|
|
}
|
|
answer.Experience = &experience
|
|
}
|
|
return answer, nil
|
|
}
|
|
|
|
func validateQuestionnaireTaskLanguageInputs(languages []TaskLanguageCode, pointer, location string) error {
|
|
seen := make(map[TaskLanguageCode]struct{}, len(languages))
|
|
for index, language := range languages {
|
|
languagePointer := fmt.Sprintf("%s/task_languages/%d", pointer, index)
|
|
if !language.IsKnown() {
|
|
return invalidQuestionnaireField(location, languagePointer, "must be a task language of the catalog")
|
|
}
|
|
if _, exists := seen[language]; exists {
|
|
return invalidQuestionnaireField(location, languagePointer, "must not repeat an earlier item")
|
|
}
|
|
seen[language] = struct{}{}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateQuestionnaireStack(tags []string, pointer, location string) error {
|
|
seen := make(map[string]struct{}, len(tags))
|
|
for index, tag := range tags {
|
|
tagPointer := fmt.Sprintf("%s/stack/%d", pointer, index)
|
|
if reason := singleLineTextProblem(tag, maxQuestionnaireStackTagRunes); reason != "" {
|
|
return invalidQuestionnaireField(location, tagPointer, reason)
|
|
}
|
|
key := strings.ToLower(tag)
|
|
if _, exists := seen[key]; exists {
|
|
return invalidQuestionnaireField(location, tagPointer, "must not repeat an earlier item")
|
|
}
|
|
seen[key] = struct{}{}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateQuestionnaireWorkFormats(formats []QuestionnaireWorkFormat, location string) error {
|
|
seen := make(map[QuestionnaireWorkFormat]struct{}, len(formats))
|
|
for index, format := range formats {
|
|
pointer := fmt.Sprintf("/work_context/work_formats/%d", index)
|
|
if !format.IsKnown() {
|
|
return invalidQuestionnaireField(location, pointer, "must be remote, office, or hybrid")
|
|
}
|
|
if _, exists := seen[format]; exists {
|
|
return invalidQuestionnaireField(location, pointer, "must not repeat an earlier item")
|
|
}
|
|
seen[format] = struct{}{}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateQuestionnaireTaskLanguages(
|
|
answers []QuestionnaireSpecialization,
|
|
availability []SpecializationAvailability,
|
|
location string,
|
|
) error {
|
|
allowed := make(map[SpecializationCode]map[TaskLanguageCode]struct{}, len(availability))
|
|
for _, item := range availability {
|
|
if !item.Specialization.IsKnown() {
|
|
return fmt.Errorf("%s - availability contains an unknown specialization: %w", location, ErrInvalidCandidateQuestionnaire)
|
|
}
|
|
languages := make(map[TaskLanguageCode]struct{}, len(item.TaskLanguages))
|
|
for _, language := range item.TaskLanguages {
|
|
if !language.IsKnown() {
|
|
return fmt.Errorf("%s - availability contains an unknown task language: %w", location, ErrInvalidCandidateQuestionnaire)
|
|
}
|
|
languages[language] = struct{}{}
|
|
}
|
|
allowed[item.Specialization] = languages
|
|
}
|
|
for specializationIndex, answer := range answers {
|
|
for languageIndex, language := range answer.TaskLanguages {
|
|
if _, exists := allowed[answer.Specialization][language]; !exists {
|
|
pointer := fmt.Sprintf("/specializations/%d/task_languages/%d", specializationIndex, languageIndex)
|
|
return invalidQuestionnaireField(location, pointer, "must be offered by the current published bank for this specialization")
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func equalQuestionnaireContent(
|
|
leftSpecializations []QuestionnaireSpecialization,
|
|
leftFormats []QuestionnaireWorkFormat,
|
|
right questionnaireContent,
|
|
) bool {
|
|
if !slices.Equal(leftFormats, right.workFormats) || len(leftSpecializations) != len(right.specializations) {
|
|
return false
|
|
}
|
|
for index, left := range leftSpecializations {
|
|
right := right.specializations[index]
|
|
if left.Specialization != right.Specialization || left.SelfAssessedGrade != right.SelfAssessedGrade ||
|
|
!slices.Equal(left.TaskLanguages, right.TaskLanguages) || !slices.Equal(left.Stack, right.Stack) ||
|
|
!equalQuestionnaireExperience(left.Experience, right.Experience) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func equalQuestionnaireExperience(left, right *QuestionnaireExperience) bool {
|
|
if left == nil || right == nil {
|
|
return left == right
|
|
}
|
|
return *left == *right
|
|
}
|
|
|
|
func cloneQuestionnaireSpecializations(items []QuestionnaireSpecialization) []QuestionnaireSpecialization {
|
|
if items == nil {
|
|
return nil
|
|
}
|
|
cloned := make([]QuestionnaireSpecialization, len(items))
|
|
for index, item := range items {
|
|
cloned[index] = item
|
|
cloned[index].TaskLanguages = slices.Clone(item.TaskLanguages)
|
|
cloned[index].Stack = slices.Clone(item.Stack)
|
|
if item.Experience != nil {
|
|
experience := *item.Experience
|
|
cloned[index].Experience = &experience
|
|
}
|
|
}
|
|
return cloned
|
|
}
|