package postgres import ( "bytes" "context" "encoding/json" "errors" "fmt" "math" "slices" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) var ( _ outbound.InvitationRepository = invitationRepository{} _ outbound.InvitationCreationResultRepository = invitationRepository{} ) // maxInvitationCreationResultBytes bounds the stored original response of a // create: the terms plus the alias and the fixed fields. const maxInvitationCreationResultBytes = 163840 func (unit *UnitOfWork) Invitations() outbound.InvitationRepository { return invitationRepository{queries: unit.queries} } func (unit *UnitOfWork) InvitationCreationResults() outbound.InvitationCreationResultRepository { return invitationRepository{queries: unit.queries} } type invitationRepository struct { queries *sqlc.Queries } func (repository invitationRepository) Create( ctx context.Context, invitation domain.Invitation, event domain.InvitationEvent, ) error { const location = "invitationRepository.Create" stored := invitation.Stored() if stored.State != string(domain.InvitationDraft) || stored.Version != 1 || stored.TermsVersion != 1 { return fmt.Errorf("%s - creation must store a draft at version 1: %w", location, domain.ErrInvalidInvitation) } if err := repository.insertEventPrerequisites(location, invitation, event, 1); err != nil { return err } period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays) if err != nil { return err } if err := repository.queries.InsertInvitation(ctx, sqlc.InsertInvitationParams{ ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID), NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need), State: stored.State, Version: stored.Version, TermsVersion: stored.TermsVersion, ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()), CreatedBy: pgUUID(stored.CreatedBy), CreatedAt: pgTime(stored.CreatedAt), UpdatedAt: pgTime(stored.UpdatedAt), }); err != nil { return fmt.Errorf("%s - insert invitation: %w", location, mapInvitationError(err)) } if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil { return err } return repository.insertEvent(ctx, location, event) } func (repository invitationRepository) Get( ctx context.Context, organizationID, invitationID uuid.UUID, ) (domain.Invitation, error) { const location = "invitationRepository.Get" if organizationID == uuid.Nil || invitationID == uuid.Nil { return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) } row, err := repository.queries.ReadInvitation(ctx, sqlc.ReadInvitationParams{ OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), }) if err != nil { return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err)) } return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), organizationID) } func (repository invitationRepository) GetForUpdate( ctx context.Context, organizationID, invitationID uuid.UUID, ) (domain.Invitation, error) { const location = "invitationRepository.GetForUpdate" if organizationID == uuid.Nil || invitationID == uuid.Nil { return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) } if _, err := repository.queries.LockInvitation(ctx, sqlc.LockInvitationParams{ OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), }); err != nil { return domain.Invitation{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err)) } invitation, err := repository.Get(ctx, organizationID, invitationID) if err != nil { return domain.Invitation{}, fmt.Errorf("%s - read locked invitation: %w", location, err) } return invitation, nil } func (repository invitationRepository) GetTermsVersion( ctx context.Context, organizationID, invitationID uuid.UUID, version int64, ) (domain.InvitationTerms, error) { const location = "invitationRepository.GetTermsVersion" if organizationID == uuid.Nil || invitationID == uuid.Nil || version < 1 { return domain.InvitationTerms{}, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation) } encoded, err := repository.queries.ReadInvitationTermsVersion(ctx, sqlc.ReadInvitationTermsVersionParams{ OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), Version: version, }) if err != nil { return domain.InvitationTerms{}, fmt.Errorf("%s - read terms version: %w", location, mapInvitationNoRows(err)) } terms, err := domain.DecodeInvitationTerms([]byte(encoded)) if err != nil { return domain.InvitationTerms{}, fmt.Errorf("%s - restore terms: %w", location, err) } return terms, nil } func (repository invitationRepository) List( ctx context.Context, query outbound.InvitationListQuery, ) (outbound.InvitationPage, error) { const location = "invitationRepository.List" if query.OrganizationID == uuid.Nil { return outbound.InvitationPage{}, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation) } if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize { return outbound.InvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation) } params := sqlc.ListInvitationsParams{OrganizationID: pgUUID(query.OrganizationID), RowLimit: query.Limit + 1} if query.After != nil { after := *query.After if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.CreatedAt) { return outbound.InvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation) } params.AfterCreatedAt = pgTime(after.CreatedAt) params.AfterInvitationID = pgUUID(after.InvitationID) } rows, err := repository.queries.ListInvitations(ctx, params) if err != nil { return outbound.InvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err)) } page := outbound.InvitationPage{HasMore: len(rows) > int(query.Limit)} if page.HasMore { rows = rows[:query.Limit] } page.Items = make([]domain.Invitation, 0, len(rows)) for _, row := range rows { invitation, err := restoreInvitationRow(location, row, query.OrganizationID) if err != nil { return outbound.InvitationPage{}, err } page.Items = append(page.Items, invitation) } return page, nil } func (repository invitationRepository) SaveDraft( ctx context.Context, expectedVersion int64, next domain.Invitation, termsChanged bool, event domain.InvitationEvent, ) error { const location = "invitationRepository.SaveDraft" stored := next.Stored() if expectedVersion < 1 || stored.Version != expectedVersion+1 { return fmt.Errorf("%s - the next version must follow the expected one: %w", location, domain.ErrInvalidInvitation) } if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil { return err } period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays) if err != nil { return err } _, err = repository.queries.AdvanceInvitationDraft(ctx, sqlc.AdvanceInvitationDraftParams{ NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need), ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()), TermsVersion: stored.TermsVersion, NextVersion: stored.Version, UpdatedAt: pgTime(stored.UpdatedAt), OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, }) if errors.Is(err, pgx.ErrNoRows) { return fmt.Errorf("%s - advance draft: %w", location, outbound.ErrInvitationVersionConflict) } if err != nil { return fmt.Errorf("%s - advance draft: %w", location, mapInvitationError(err)) } if termsChanged { if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil { return err } } return repository.insertEvent(ctx, location, event) } func (repository invitationRepository) NeedVersionExists( ctx context.Context, organizationID, needID uuid.UUID, requirementsVersion int64, ) (bool, error) { const location = "invitationRepository.NeedVersionExists" if organizationID == uuid.Nil || needID == uuid.Nil || requirementsVersion < 1 { return false, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation) } found, err := repository.queries.InvitationNeedVersionExists(ctx, sqlc.InvitationNeedVersionExistsParams{ OrganizationID: pgUUID(organizationID), NeedID: pgUUID(needID), RequirementsVersion: requirementsVersion, }) if err != nil { return false, fmt.Errorf("%s - look up need version: %w", location, mapInvitationError(err)) } return found, nil } func (repository invitationRepository) SaveCreationResult( ctx context.Context, scope [outbound.IdempotencyDigestSize]byte, result domain.OrganizationInvitationView, ) error { const location = "invitationRepository.SaveCreationResult" if scope == ([outbound.IdempotencyDigestSize]byte{}) { return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) } encoded, err := encodeInvitationCreationResult(result) if err != nil { return fmt.Errorf("%s - encode response: %w", location, err) } if err := repository.queries.SaveInvitationCreationResult(ctx, sqlc.SaveInvitationCreationResultParams{ ScopeHash: scope[:], Snapshot: encoded, }); err != nil { return fmt.Errorf("%s - store response: %w", location, mapInvitationError(err)) } return nil } func (repository invitationRepository) GetCreationResult( ctx context.Context, scope [outbound.IdempotencyDigestSize]byte, ) (domain.OrganizationInvitationView, error) { const location = "invitationRepository.GetCreationResult" if scope == ([outbound.IdempotencyDigestSize]byte{}) { return domain.OrganizationInvitationView{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) } encoded, err := repository.queries.GetInvitationCreationResult(ctx, scope[:]) if errors.Is(err, pgx.ErrNoRows) { return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound } if err != nil { return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read response: %w", location, mapInvitationError(err)) } return decodeInvitationCreationResult(location, []byte(encoded)) } // insertEventPrerequisites checks that the audit event describes the version // that the caller is about to store. Only the server's expiry has no actor. func (repository invitationRepository) insertEventPrerequisites( location string, invitation domain.Invitation, event domain.InvitationEvent, version int64, ) error { actorMissing := event.ActorID == uuid.Nil if event.ID == uuid.Nil || event.InvitationID != invitation.ID() || event.OrganizationID != invitation.OrganizationID() || event.Version != version || event.TermsVersion != invitation.TermsVersion() || actorMissing != (event.Kind == domain.InvitationEventExpired) || !validStoredInvitationTime(event.OccurredAt) { return fmt.Errorf("%s - the audit event does not describe the stored version: %w", location, domain.ErrInvalidInvitation) } return nil } func (repository invitationRepository) insertTermsVersion( ctx context.Context, location string, stored domain.StoredInvitation, version int64, at time.Time, ) error { encoded, err := domain.EncodeInvitationTerms(stored.Terms) if err != nil { return fmt.Errorf("%s - encode terms: %w", location, err) } if err := repository.queries.InsertInvitationTermsVersion(ctx, sqlc.InsertInvitationTermsVersionParams{ InvitationID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), Version: version, Terms: encoded, SalaryFrom: stored.Terms.Salary.SalaryFrom, SalaryTo: stored.Terms.Salary.SalaryTo, SalaryCurrency: stored.Terms.Salary.Currency, SalaryPeriod: stored.Terms.Salary.Period, SalaryTaxBasis: stored.Terms.Salary.TaxBasis, CreatedAt: pgTime(at), }); err != nil { return fmt.Errorf("%s - append terms version: %w", location, mapInvitationError(err)) } return nil } func (repository invitationRepository) insertEvent(ctx context.Context, location string, event domain.InvitationEvent) error { fields := make([]string, 0, len(event.ChangedFields)) for _, field := range event.ChangedFields { fields = append(fields, string(field)) } slices.Sort(fields) // The expiry is the server's own change, so its event has no actor. actor := pgtype.UUID{} if event.ActorID != uuid.Nil { actor = pgUUID(event.ActorID) } if err := repository.queries.InsertInvitationEvent(ctx, sqlc.InsertInvitationEventParams{ ID: pgUUID(event.ID), InvitationID: pgUUID(event.InvitationID), OrganizationID: pgUUID(event.OrganizationID), Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: actor, ChangedFields: fields, OccurredAt: pgTime(event.OccurredAt), }); err != nil { return fmt.Errorf("%s - record audit event: %w", location, mapInvitationError(err)) } return nil } func restoreInvitationRow(location string, row sqlc.ListInvitationsRow, organizationID uuid.UUID) (domain.Invitation, error) { if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.CreatedBy.Valid || !row.PolicyVersionID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || uuid.UUID(row.OrganizationID.Bytes) != organizationID { return domain.Invitation{}, fmt.Errorf("%s - invitation row has invalid scope or metadata: %w", location, domain.ErrInvalidInvitation) } terms, err := domain.DecodeInvitationTerms([]byte(row.Terms)) if err != nil { return domain.Invitation{}, fmt.Errorf("%s - restore terms: %w", location, err) } stored := domain.StoredInvitation{ ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes), CandidateID: uuid.UUID(row.CandidateID.Bytes), State: row.State, Version: row.Version, TermsVersion: row.TermsVersion, Terms: terms, ResponsePeriodDays: int32(row.ResponsePeriodDays), PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), SalaryRaiseUsed: row.SalaryRaiseUsed, CreatedBy: uuid.UUID(row.CreatedBy.Bytes), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time, ResponseDeadlineAt: optionalTime(row.ResponseDeadlineAt), DeliveredAt: optionalTime(row.DeliveredAt), ViewedAt: optionalTime(row.ViewedAt), RespondedAt: optionalTime(row.RespondedAt), } if row.ExpiryReason.Valid { reason := row.ExpiryReason.String stored.ExpiryReason = &reason } if row.NeedID.Valid != row.NeedRequirementsVersion.Valid { return domain.Invitation{}, fmt.Errorf("%s - need link is incomplete: %w", location, domain.ErrInvalidInvitation) } if row.NeedID.Valid { stored.Need = &domain.InvitationNeedRef{NeedID: uuid.UUID(row.NeedID.Bytes), RequirementsVersion: row.NeedRequirementsVersion.Int64} } invitation, err := domain.RestoreInvitation(stored) if err != nil { return domain.Invitation{}, fmt.Errorf("%s - restore invitation: %w", location, err) } return invitation, nil } func encodeInvitationCreationResult(result domain.OrganizationInvitationView) ([]byte, error) { if err := validateInvitationCreationResult(result); err != nil { return nil, err } encoded, err := json.Marshal(result) if err != nil { return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - marshal: %w", err) } if len(encoded) > maxInvitationCreationResultBytes { return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - response exceeds %d bytes: %w", maxInvitationCreationResultBytes, domain.ErrInvalidInvitation) } return encoded, nil } func decodeInvitationCreationResult(location string, encoded []byte) (domain.OrganizationInvitationView, error) { var result domain.OrganizationInvitationView decoder := json.NewDecoder(bytes.NewReader(encoded)) decoder.DisallowUnknownFields() if err := decoder.Decode(&result); err != nil || decoder.More() { return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation) } if err := validateInvitationCreationResult(result); err != nil { return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err) } return result, nil } func validateInvitationCreationResult(result domain.OrganizationInvitationView) error { if result.ID == uuid.Nil || result.OrganizationID == uuid.Nil || !domain.IsCandidateViewPseudonym(result.CandidateHandle) { return fmt.Errorf("postgres.validateInvitationCreationResult - identity is incomplete: %w", domain.ErrInvalidInvitation) } if err := result.Terms.Validate(); err != nil { return fmt.Errorf("postgres.validateInvitationCreationResult - validate terms: %w", err) } return nil } func invitationNeedID(need *domain.InvitationNeedRef) pgtype.UUID { if need == nil { return pgtype.UUID{} } return pgUUID(need.NeedID) } func invitationNeedVersion(need *domain.InvitationNeedRef) pgtype.Int8 { if need == nil { return pgtype.Int8{} } return pgtype.Int8{Int64: need.RequirementsVersion, Valid: true} } func validStoredInvitationTime(value time.Time) bool { return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0 } func mapInvitationNoRows(err error) error { if errors.Is(err, pgx.ErrNoRows) { return outbound.ErrInvitationNotFound } return mapInvitationError(err) } func mapInvitationError(err error) error { var pgError *pgconn.PgError if !errors.As(err, &pgError) { return sanitizeConnectError(err) } if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitations_organization_fkey" { return fmt.Errorf("postgres.mapInvitationError - organization no longer exists: %w", outbound.ErrOrganizationNotFound) } if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_creation_results_idempotency_fkey" { return fmt.Errorf("postgres.mapInvitationError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound) } return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) } // invitationResponsePeriodParam converts the period to its smallint column. // The domain allows only the periods of the product policy, so a value out of // range is an invalid invitation, never a silently truncated one. func invitationResponsePeriodParam(location string, days int32) (int16, error) { if days < 1 || days > math.MaxInt16 { return 0, fmt.Errorf("%s - response period is out of range: %w", location, domain.ErrInvalidInvitation) } return int16(days), nil }