302 lines
13 KiB
Go
302 lines
13 KiB
Go
package postgres
|
|
|
|
import (
|
|
"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"
|
|
)
|
|
|
|
const maxCandidateProfileHistorySnapshotBytes = 262144
|
|
|
|
var _ outbound.CandidateProfileRepositories = (*UnitOfWork)(nil)
|
|
|
|
func (unit *UnitOfWork) CandidateProfiles() outbound.CandidateProfileRepository {
|
|
return candidateProfileRepository{queries: unit.queries}
|
|
}
|
|
|
|
type candidateProfileRepository struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
type candidateProfileHistoryClaim struct {
|
|
Kind string `json:"kind"`
|
|
Ordinal int `json:"ordinal"`
|
|
Value json.RawMessage `json:"value"`
|
|
Status string `json:"status"`
|
|
Origin string `json:"origin"`
|
|
TrustLevel int `json:"trust_level"`
|
|
Quote *string `json:"quote,omitempty"`
|
|
ExtractionVersion *string `json:"extraction_version,omitempty"`
|
|
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
|
|
}
|
|
|
|
type candidateProfileHistorySnapshot struct {
|
|
Version int64 `json:"version"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
Claims []candidateProfileHistoryClaim `json:"claims"`
|
|
ParallelPeriodAcknowledgements []domain.ProfileParallelPeriodAcknowledgement `json:"parallel_period_acknowledgements"`
|
|
}
|
|
|
|
func (repository candidateProfileRepository) Get(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
|
|
const location = "candidateProfileRepository.Get"
|
|
if userID == uuid.Nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
|
|
}
|
|
rows, err := repository.queries.ReadCandidateProfile(ctx, pgUUID(userID))
|
|
if err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - select profile: %w", location, mapCandidateProfileError(err))
|
|
}
|
|
if len(rows) == 0 {
|
|
profile, err := domain.EmptyCandidateProfile(userID)
|
|
if err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - create empty profile: %w", location, err)
|
|
}
|
|
return profile, nil
|
|
}
|
|
stored := domain.StoredCandidateProfile{
|
|
UserID: userID, Version: rows[0].Version,
|
|
CreatedAt: rows[0].CreatedAt.Time, UpdatedAt: rows[0].UpdatedAt.Time,
|
|
}
|
|
if err := json.Unmarshal([]byte(rows[0].ParallelPeriodAcknowledgements), &stored.ParallelPeriodAcknowledgements); err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - decode stored period confirmations: %w", location, domain.ErrInvalidCandidateProfile)
|
|
}
|
|
for _, row := range rows {
|
|
if !row.Kind.Valid {
|
|
continue
|
|
}
|
|
stored.Claims = append(stored.Claims, domain.StoredProfileClaim{
|
|
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: row.Value,
|
|
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
|
|
Quote: row.Quote.String, ExtractionVersion: row.ExtractionVersion.String,
|
|
ConfirmedAt: row.ConfirmedAt.Time,
|
|
})
|
|
}
|
|
profile, err := domain.RestoreCandidateProfile(stored)
|
|
if err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - restore profile: %w", location, err)
|
|
}
|
|
return profile, nil
|
|
}
|
|
|
|
func (repository candidateProfileRepository) Save(
|
|
ctx context.Context,
|
|
expectedVersion int64,
|
|
profile domain.CandidateProfile,
|
|
) (domain.CandidateProfile, error) {
|
|
const location = "candidateProfileRepository.Save"
|
|
if profile.IsZero() || expectedVersion < 0 || profile.Version() != expectedVersion || profile.UpdatedAt().IsZero() {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - profile and expected version are inconsistent: %w", location, domain.ErrInvalidCandidateProfile)
|
|
}
|
|
claims, err := profile.Content().StoredClaims()
|
|
if err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - encode profile claims: %w", location, err)
|
|
}
|
|
snapshot, err := candidateProfileSnapshot(profile, claims)
|
|
if err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - encode profile history: %w", location, err)
|
|
}
|
|
if len(snapshot) > maxCandidateProfileHistorySnapshotBytes {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - history snapshot exceeds its storage bound: %w", location, outbound.ErrCandidateProfileHistoryTooLarge)
|
|
}
|
|
|
|
userID := pgUUID(profile.UserID())
|
|
stored, err := repository.advanceProfileVersion(ctx, userID, expectedVersion, profile.UpdatedAt())
|
|
if err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - advance profile version: %w", location, mapCandidateProfileError(err))
|
|
}
|
|
if err := repository.replaceProfileClaims(ctx, userID, claims); err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - replace claims: %w", location, err)
|
|
}
|
|
if err := repository.replaceProfilePeriodConfirmations(ctx, userID, profile.Content().ParallelPeriodAcknowledgements()); err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - replace period confirmations: %w", location, err)
|
|
}
|
|
if err := repository.queries.AppendCandidateProfileHistory(ctx, sqlc.AppendCandidateProfileHistoryParams{
|
|
UserID: userID, Version: stored.Version, ChangedAt: stored.UpdatedAt, Snapshot: snapshot,
|
|
}); err != nil {
|
|
return domain.CandidateProfile{}, fmt.Errorf("%s - append profile history: %w", location, mapCandidateProfileError(err))
|
|
}
|
|
return domain.RestoreCandidateProfile(domain.StoredCandidateProfile{
|
|
UserID: profile.UserID(), Version: stored.Version, CreatedAt: stored.CreatedAt.Time, UpdatedAt: stored.UpdatedAt.Time,
|
|
Claims: claims, ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
|
|
})
|
|
}
|
|
|
|
func (repository candidateProfileRepository) advanceProfileVersion(
|
|
ctx context.Context,
|
|
userID pgtype.UUID,
|
|
expectedVersion int64,
|
|
at time.Time,
|
|
) (sqlc.CandidateProfile, error) {
|
|
var stored sqlc.CandidateProfile
|
|
var err error
|
|
if expectedVersion == 0 {
|
|
stored, err = repository.queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{
|
|
UserID: userID, At: pgTime(at),
|
|
})
|
|
} else {
|
|
stored, err = repository.queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
|
|
UserID: userID, ExpectedVersion: expectedVersion, At: pgTime(at),
|
|
})
|
|
}
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return sqlc.CandidateProfile{}, outbound.ErrCandidateProfileVersionConflict
|
|
}
|
|
if err != nil {
|
|
return sqlc.CandidateProfile{}, mapCandidateProfileError(err)
|
|
}
|
|
return stored, nil
|
|
}
|
|
|
|
func (repository candidateProfileRepository) replaceProfileClaims(
|
|
ctx context.Context,
|
|
userID pgtype.UUID,
|
|
claims []domain.StoredProfileClaim,
|
|
) error {
|
|
if err := repository.queries.DeleteCandidateProfileClaims(ctx, userID); err != nil {
|
|
return mapCandidateProfileError(err)
|
|
}
|
|
for _, claim := range claims {
|
|
ordinal, err := candidateProfileOrdinal(claim.Ordinal)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var confirmedAt *time.Time
|
|
if !claim.ConfirmedAt.IsZero() {
|
|
confirmedAt = &claim.ConfirmedAt
|
|
}
|
|
if err := repository.queries.InsertCandidateProfileClaim(ctx, sqlc.InsertCandidateProfileClaimParams{
|
|
UserID: userID, Kind: claim.Kind, Ordinal: ordinal, Value: claim.Value,
|
|
Status: claim.Status, Origin: claim.Origin, Quote: pgOptionalText(claim.Quote),
|
|
ExtractionVersion: pgOptionalText(claim.ExtractionVersion), ConfirmedAt: pgOptionalTime(confirmedAt),
|
|
}); err != nil {
|
|
return mapCandidateProfileError(err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository candidateProfileRepository) replaceProfilePeriodConfirmations(
|
|
ctx context.Context,
|
|
userID pgtype.UUID,
|
|
confirmations []domain.ProfileParallelPeriodAcknowledgement,
|
|
) error {
|
|
if err := repository.queries.DeleteCandidateProfileOverlapConfirmations(ctx, userID); err != nil {
|
|
return mapCandidateProfileError(err)
|
|
}
|
|
for _, confirmation := range confirmations {
|
|
if confirmation.FirstIndex >= confirmation.SecondIndex {
|
|
return fmt.Errorf("postgres.replaceProfilePeriodConfirmations - pair indices are invalid: %w", domain.ErrInvalidCandidateProfile)
|
|
}
|
|
firstIndex, err := candidateProfilePeriodIndex(confirmation.FirstIndex)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
secondIndex, err := candidateProfilePeriodIndex(confirmation.SecondIndex)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := repository.queries.InsertCandidateProfileOverlapConfirmation(ctx, sqlc.InsertCandidateProfileOverlapConfirmationParams{
|
|
UserID: userID, FirstIndex: firstIndex, SecondIndex: secondIndex,
|
|
FirstStartedOn: confirmation.FirstPeriod.StartedOn, FirstEndedOn: pgOptionalText(confirmation.FirstPeriod.EndedOn),
|
|
SecondStartedOn: confirmation.SecondPeriod.StartedOn, SecondEndedOn: pgOptionalText(confirmation.SecondPeriod.EndedOn),
|
|
}); err != nil {
|
|
return mapCandidateProfileError(err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func candidateProfileOrdinal(value int) (int16, error) {
|
|
if value < 0 || value > math.MaxInt16 {
|
|
return 0, fmt.Errorf("postgres.candidateProfileOrdinal - ordinal is outside the storage range: %w", domain.ErrInvalidCandidateProfile)
|
|
}
|
|
return int16(value), nil
|
|
}
|
|
|
|
func candidateProfilePeriodIndex(value int) (int16, error) {
|
|
if value < 0 || value > 19 || value > math.MaxInt16 {
|
|
return 0, fmt.Errorf("postgres.candidateProfilePeriodIndex - index is outside the storage range: %w", domain.ErrInvalidCandidateProfile)
|
|
}
|
|
return int16(value), nil
|
|
}
|
|
|
|
func candidateProfileSnapshot(profile domain.CandidateProfile, claims []domain.StoredProfileClaim) ([]byte, error) {
|
|
encodedClaims := make([]candidateProfileHistoryClaim, 0, len(claims))
|
|
for _, claim := range claims {
|
|
item := candidateProfileHistoryClaim{
|
|
Kind: claim.Kind, Ordinal: claim.Ordinal, Value: json.RawMessage(claim.Value),
|
|
Status: claim.Status, Origin: claim.Origin, TrustLevel: claim.TrustLevel,
|
|
}
|
|
if claim.Quote != "" {
|
|
item.Quote = &claim.Quote
|
|
}
|
|
if claim.ExtractionVersion != "" {
|
|
item.ExtractionVersion = &claim.ExtractionVersion
|
|
}
|
|
if !claim.ConfirmedAt.IsZero() {
|
|
confirmedAt := claim.ConfirmedAt
|
|
item.ConfirmedAt = &confirmedAt
|
|
}
|
|
encodedClaims = append(encodedClaims, item)
|
|
}
|
|
return json.Marshal(candidateProfileHistorySnapshot{
|
|
Version: profile.Version() + 1, CreatedAt: profile.CreatedAt().UTC().Truncate(time.Microsecond),
|
|
UpdatedAt: profile.UpdatedAt().UTC().Truncate(time.Microsecond),
|
|
Claims: encodedClaims, ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
|
|
})
|
|
}
|
|
|
|
func (repository candidateProfileRepository) AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error {
|
|
const location = "candidateProfileRepository.AdvanceOnboarding"
|
|
if userID == uuid.Nil || at.IsZero() {
|
|
return fmt.Errorf("%s - user ID and time must be set: %w", location, domain.ErrInvalidCandidateProfile)
|
|
}
|
|
if err := repository.queries.AdvanceCandidateOnboardingAfterProfile(ctx, sqlc.AdvanceCandidateOnboardingAfterProfileParams{
|
|
UserID: pgUUID(userID), At: pgTime(at),
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - advance candidate step: %w", location, mapCandidateProfileError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func mapCandidateProfileError(err error) error {
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) {
|
|
return sanitizeConnectError(err)
|
|
}
|
|
switch {
|
|
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
|
|
"candidate_profiles_user_id_fkey", "candidate_profile_claims_user_id_fkey",
|
|
"candidate_profile_overlap_confirmations_profile_fkey", "candidate_profile_history_profile_fkey",
|
|
}, pgError.ConstraintName):
|
|
return fmt.Errorf("postgres.mapCandidateProfileError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrUserNotFound)
|
|
case pgError.Code == checkViolationCode && pgError.ConstraintName == "candidate_profile_history_snapshot_bounded":
|
|
return outbound.ErrCandidateProfileHistoryTooLarge
|
|
case pgError.Code == checkViolationCode && slices.Contains([]string{
|
|
"candidate_profiles_version_positive", "candidate_profile_claims_kind_ordinal",
|
|
"candidate_profile_claims_status_known", "candidate_profile_claims_origin_known",
|
|
"candidate_profile_claims_trust_level_zero", "candidate_profile_claims_confirmation",
|
|
"candidate_profile_claims_origin_provenance", "candidate_profile_claims_quote_format",
|
|
"candidate_profile_claims_extraction_version_format", "candidate_profile_overlap_confirmations_indices",
|
|
"candidate_profile_overlap_confirmations_months",
|
|
}, pgError.ConstraintName):
|
|
return fmt.Errorf("postgres.mapCandidateProfileError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateProfile)
|
|
default:
|
|
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
|
}
|
|
}
|