254 lines
11 KiB
Go
254 lines
11 KiB
Go
package postgres
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
var _ outbound.InvitationSendResultRepository = invitationRepository{}
|
|
|
|
// maxInvitationOrganizationNameRunes is the bound of the organization name
|
|
// that the candidate's inbox shows, as in the public contract.
|
|
const maxInvitationOrganizationNameRunes = 200
|
|
|
|
func (unit *UnitOfWork) InvitationSendResults() outbound.InvitationSendResultRepository {
|
|
return invitationRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (repository invitationRepository) Deliver(
|
|
ctx context.Context,
|
|
expectedVersion int64,
|
|
next domain.Invitation,
|
|
event domain.InvitationEvent,
|
|
) error {
|
|
const location = "invitationRepository.Deliver"
|
|
stored := next.Stored()
|
|
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationDelivered) ||
|
|
stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil || event.Kind != domain.InvitationEventDelivered {
|
|
return fmt.Errorf("%s - the next version must be the delivery that follows the expected one: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
|
|
return err
|
|
}
|
|
_, err := repository.queries.DeliverInvitation(ctx, sqlc.DeliverInvitationParams{
|
|
NextVersion: stored.Version, DeliveredAt: pgTime(*stored.DeliveredAt), ResponseDeadlineAt: pgTime(*stored.ResponseDeadlineAt),
|
|
OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return fmt.Errorf("%s - deliver draft: %w", location, outbound.ErrInvitationVersionConflict)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s - deliver draft: %w", location, mapInvitationError(err))
|
|
}
|
|
return repository.insertEvent(ctx, location, event)
|
|
}
|
|
|
|
func (repository invitationRepository) ListForCandidate(
|
|
ctx context.Context,
|
|
query outbound.CandidateInvitationListQuery,
|
|
) (outbound.CandidateInvitationPage, error) {
|
|
const location = "invitationRepository.ListForCandidate"
|
|
if query.CandidateID == uuid.Nil {
|
|
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize {
|
|
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation)
|
|
}
|
|
params := sqlc.ListCandidateInvitationsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
|
|
if query.After != nil {
|
|
after := *query.After
|
|
if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.DeliveredAt) {
|
|
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
params.AfterDeliveredAt = pgTime(after.DeliveredAt)
|
|
params.AfterInvitationID = pgUUID(after.InvitationID)
|
|
}
|
|
rows, err := repository.queries.ListCandidateInvitations(ctx, params)
|
|
if err != nil {
|
|
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err))
|
|
}
|
|
page := outbound.CandidateInvitationPage{HasMore: len(rows) > int(query.Limit)}
|
|
if page.HasMore {
|
|
rows = rows[:query.Limit]
|
|
}
|
|
page.Items = make([]outbound.CandidateInvitationEntry, 0, len(rows))
|
|
for _, row := range rows {
|
|
entry, err := restoreCandidateInvitationRow(location, row, query.CandidateID)
|
|
if err != nil {
|
|
return outbound.CandidateInvitationPage{}, err
|
|
}
|
|
page.Items = append(page.Items, entry)
|
|
}
|
|
return page, nil
|
|
}
|
|
|
|
func (repository invitationRepository) GetForCandidate(
|
|
ctx context.Context,
|
|
candidateID, invitationID uuid.UUID,
|
|
) (domain.Invitation, error) {
|
|
const location = "invitationRepository.GetForCandidate"
|
|
if candidateID == uuid.Nil || invitationID == uuid.Nil {
|
|
return domain.Invitation{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
row, err := repository.queries.ReadCandidateInvitation(ctx, sqlc.ReadCandidateInvitationParams{
|
|
CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID),
|
|
})
|
|
if err != nil {
|
|
return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err))
|
|
}
|
|
if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID {
|
|
return domain.Invitation{}, fmt.Errorf("%s - invitation row has an invalid scope: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), uuid.UUID(row.OrganizationID.Bytes))
|
|
}
|
|
|
|
func (repository invitationRepository) SaveSendResult(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
result outbound.InvitationSendResult,
|
|
) error {
|
|
const location = "invitationRepository.SaveSendResult"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
if err := validateInvitationSendResult(result); err != nil {
|
|
return fmt.Errorf("%s - validate outcome: %w", location, err)
|
|
}
|
|
var snapshot []byte
|
|
if result.View != nil {
|
|
encoded, err := encodeInvitationCreationResult(*result.View)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - encode response: %w", location, err)
|
|
}
|
|
snapshot = encoded
|
|
}
|
|
if err := repository.queries.InsertInvitationSendResult(ctx, sqlc.InsertInvitationSendResultParams{
|
|
ScopeHash: scope[:], OrganizationID: pgUUID(result.OrganizationID), InvitationID: pgUUID(result.InvitationID),
|
|
Outcome: string(result.Outcome), Snapshot: snapshot,
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationSendResultError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository invitationRepository) GetSendResult(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
) (outbound.InvitationSendResult, error) {
|
|
const location = "invitationRepository.GetSendResult"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return outbound.InvitationSendResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
row, err := repository.queries.GetInvitationSendResult(ctx, scope[:])
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound
|
|
}
|
|
if err != nil {
|
|
return outbound.InvitationSendResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
|
|
}
|
|
if !row.OrganizationID.Valid || !row.InvitationID.Valid {
|
|
return outbound.InvitationSendResult{}, fmt.Errorf("%s - stored outcome has no scope: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
result := outbound.InvitationSendResult{
|
|
OrganizationID: uuid.UUID(row.OrganizationID.Bytes), InvitationID: uuid.UUID(row.InvitationID.Bytes),
|
|
Outcome: outbound.InvitationSendOutcome(row.Outcome),
|
|
}
|
|
if row.Snapshot != "" {
|
|
view, err := decodeInvitationSendView(location, []byte(row.Snapshot))
|
|
if err != nil {
|
|
return outbound.InvitationSendResult{}, err
|
|
}
|
|
result.View = &view
|
|
}
|
|
if err := validateInvitationSendResult(result); err != nil {
|
|
return outbound.InvitationSendResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// decodeInvitationSendView restores the original response of a send. It
|
|
// shares the shape and the checks of a stored creation response.
|
|
func decodeInvitationSendView(location string, encoded []byte) (domain.OrganizationInvitationView, error) {
|
|
var view domain.OrganizationInvitationView
|
|
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(&view); err != nil || decoder.More() {
|
|
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
if err := validateInvitationCreationResult(view); err != nil {
|
|
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err)
|
|
}
|
|
return view, nil
|
|
}
|
|
|
|
func validateInvitationSendResult(result outbound.InvitationSendResult) error {
|
|
const location = "postgres.validateInvitationSendResult"
|
|
// The invitation of a refusal is the identifier of the path, which may
|
|
// name nothing, even the nil identifier; only a sent outcome names a real
|
|
// invitation.
|
|
if result.OrganizationID == uuid.Nil {
|
|
return fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
switch result.Outcome {
|
|
case outbound.InvitationSendSent:
|
|
if result.View == nil || result.View.ID != result.InvitationID || result.View.OrganizationID != result.OrganizationID ||
|
|
!result.View.State.IsKnown() || result.View.DeliveredAt == nil {
|
|
return fmt.Errorf("%s - a sent outcome must hold the delivered invitation: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
case outbound.InvitationSendNotFound, outbound.InvitationSendStateConflict:
|
|
if result.View != nil {
|
|
return fmt.Errorf("%s - a refused outcome holds no response: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
default:
|
|
return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func restoreCandidateInvitationRow(
|
|
location string,
|
|
row sqlc.ListCandidateInvitationsRow,
|
|
candidateID uuid.UUID,
|
|
) (outbound.CandidateInvitationEntry, error) {
|
|
if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID ||
|
|
!utf8.ValidString(row.OrganizationName) || row.OrganizationName == "" ||
|
|
utf8.RuneCountInString(row.OrganizationName) > maxInvitationOrganizationNameRunes {
|
|
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - invitation row has an invalid scope or sender: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
invitation, err := restoreInvitationRow(location, sqlc.ListInvitationsRow{
|
|
ID: row.ID, OrganizationID: row.OrganizationID, CandidateID: row.CandidateID, NeedID: row.NeedID,
|
|
NeedRequirementsVersion: row.NeedRequirementsVersion, State: row.State, ExpiryReason: row.ExpiryReason,
|
|
Version: row.Version, TermsVersion: row.TermsVersion, ResponsePeriodDays: row.ResponsePeriodDays,
|
|
PolicyVersionID: row.PolicyVersionID, ResponseDeadlineAt: row.ResponseDeadlineAt, SalaryRaiseUsed: row.SalaryRaiseUsed,
|
|
CreatedBy: row.CreatedBy, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, DeliveredAt: row.DeliveredAt,
|
|
ViewedAt: row.ViewedAt, RespondedAt: row.RespondedAt, Terms: row.Terms,
|
|
}, uuid.UUID(row.OrganizationID.Bytes))
|
|
if err != nil {
|
|
return outbound.CandidateInvitationEntry{}, err
|
|
}
|
|
if !invitation.IsDelivered() {
|
|
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - an undelivered invitation is not in the inbox: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
return outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: row.OrganizationName}, nil
|
|
}
|
|
|
|
func mapInvitationSendResultError(err error) error {
|
|
var pgError *pgconn.PgError
|
|
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_send_results_idempotency_fkey" {
|
|
return fmt.Errorf("postgres.mapInvitationSendResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
|
}
|
|
return mapInvitationError(err)
|
|
}
|