255 lines
11 KiB
Go
255 lines
11 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"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.InvitationAcceptResultRepository = invitationRepository{}
|
|
_ outbound.ContactGrantRepository = contactGrantRepository{}
|
|
)
|
|
|
|
func (unit *UnitOfWork) InvitationAcceptResults() outbound.InvitationAcceptResultRepository {
|
|
return invitationRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (unit *UnitOfWork) ContactGrants() outbound.ContactGrantRepository {
|
|
return contactGrantRepository{queries: unit.queries}
|
|
}
|
|
|
|
type contactGrantRepository struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
// Accept stores the acceptance of an invitation. The compare-and-swap applies
|
|
// only to a delivered or viewed invitation at the expected version and terms
|
|
// version, before its deadline, so a stale writer loses without changing it.
|
|
func (repository invitationRepository) Accept(
|
|
ctx context.Context,
|
|
expectedVersion int64,
|
|
next domain.Invitation,
|
|
event domain.InvitationEvent,
|
|
) error {
|
|
const location = "invitationRepository.Accept"
|
|
stored := next.Stored()
|
|
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationAccepted) ||
|
|
stored.RespondedAt == nil || event.Kind != domain.InvitationEventAccepted {
|
|
return fmt.Errorf("%s - the next version must be the acceptance 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.AcceptInvitation(ctx, sqlc.AcceptInvitationParams{
|
|
NextVersion: stored.Version, AcceptedAt: pgTime(*stored.RespondedAt), OrganizationID: pgUUID(stored.OrganizationID),
|
|
InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, TermsVersion: stored.TermsVersion,
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return fmt.Errorf("%s - accept invitation: %w", location, outbound.ErrInvitationVersionConflict)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s - accept invitation: %w", location, mapInvitationError(err))
|
|
}
|
|
return repository.insertEvent(ctx, location, event)
|
|
}
|
|
|
|
func (repository invitationRepository) SaveAcceptResult(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
result outbound.InvitationAcceptResult,
|
|
) error {
|
|
const location = "invitationRepository.SaveAcceptResult"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
if err := validateInvitationAcceptResult(result); err != nil {
|
|
return fmt.Errorf("%s - validate outcome: %w", location, err)
|
|
}
|
|
if err := repository.queries.InsertInvitationAcceptResult(ctx, sqlc.InsertInvitationAcceptResultParams{
|
|
ScopeHash: scope[:], InvitationID: pgUUID(result.InvitationID), Outcome: string(result.Outcome),
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationAcceptResultError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository invitationRepository) GetAcceptResult(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
) (outbound.InvitationAcceptResult, error) {
|
|
const location = "invitationRepository.GetAcceptResult"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
row, err := repository.queries.GetInvitationAcceptResult(ctx, scope[:])
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound
|
|
}
|
|
if err != nil {
|
|
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
|
|
}
|
|
if !row.InvitationID.Valid {
|
|
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - stored outcome has no invitation: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
result := outbound.InvitationAcceptResult{
|
|
InvitationID: uuid.UUID(row.InvitationID.Bytes), Outcome: outbound.InvitationAcceptOutcome(row.Outcome),
|
|
}
|
|
if err := validateInvitationAcceptResult(result); err != nil {
|
|
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func validateInvitationAcceptResult(result outbound.InvitationAcceptResult) error {
|
|
const location = "postgres.validateInvitationAcceptResult"
|
|
switch result.Outcome {
|
|
case outbound.InvitationAcceptAccepted:
|
|
if result.InvitationID == uuid.Nil {
|
|
return fmt.Errorf("%s - an accepted outcome names the invitation: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
case outbound.InvitationAcceptNotFound, outbound.InvitationAcceptStateConflict:
|
|
// A refusal names the identifier of the path, which may name nothing.
|
|
default:
|
|
return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func mapInvitationAcceptResultError(err error) error {
|
|
var pgError *pgconn.PgError
|
|
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_accept_results_idempotency_fkey" {
|
|
return fmt.Errorf("postgres.mapInvitationAcceptResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
|
}
|
|
return mapInvitationError(err)
|
|
}
|
|
|
|
// Create stores a grant of an accepted invitation. The row can only be created
|
|
// active: a revoked grant is never stored by a new acceptance.
|
|
func (repository contactGrantRepository) Create(ctx context.Context, grant domain.ContactGrant) error {
|
|
const location = "contactGrantRepository.Create"
|
|
if grant.IsZero() || grant.Status() != domain.ContactGrantActive {
|
|
return fmt.Errorf("%s - the grant must be built by the domain and active: %w", location, domain.ErrInvalidContactGrant)
|
|
}
|
|
stored := grant.Stored()
|
|
if err := repository.queries.InsertContactGrant(ctx, sqlc.InsertContactGrantParams{
|
|
ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID),
|
|
SourceInvitationID: pgUUID(stored.InvitationID), ConsentRecordID: pgUUID(stored.ConsentRecordID),
|
|
TermsVersion: stored.TermsVersion, Fields: stored.Fields, ConsentTextVersion: stored.ConsentTextVersion,
|
|
GrantedAt: pgTime(stored.GrantedAt),
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - insert contact grant: %w", location, mapInvitationError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetByInvitation reads the grant of one invitation of one organization. The
|
|
// read rebuilds the grant through the domain, so a stored row that breaks a
|
|
// rule fails instead of being served.
|
|
func (repository contactGrantRepository) GetByInvitation(
|
|
ctx context.Context,
|
|
organizationID, invitationID uuid.UUID,
|
|
) (domain.ContactGrant, error) {
|
|
const location = "contactGrantRepository.GetByInvitation"
|
|
if organizationID == uuid.Nil || invitationID == uuid.Nil {
|
|
return domain.ContactGrant{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidContactGrant)
|
|
}
|
|
row, err := repository.queries.GetContactGrantByInvitation(ctx, sqlc.GetContactGrantByInvitationParams{
|
|
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, outbound.ErrContactGrantNotFound)
|
|
}
|
|
if err != nil {
|
|
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, mapInvitationError(err))
|
|
}
|
|
stored, err := storedContactGrantRow(row)
|
|
if err != nil {
|
|
return domain.ContactGrant{}, fmt.Errorf("%s - read stored grant: %w", location, err)
|
|
}
|
|
grant, err := domain.RestoreContactGrant(stored)
|
|
if err != nil {
|
|
return domain.ContactGrant{}, fmt.Errorf("%s - restore contact grant: %w", location, err)
|
|
}
|
|
if stored.OrganizationID != organizationID || stored.InvitationID != invitationID {
|
|
return domain.ContactGrant{}, fmt.Errorf("%s - stored grant has another scope: %w", location, domain.ErrInvalidContactGrant)
|
|
}
|
|
return grant, nil
|
|
}
|
|
|
|
// storedContactGrantRow maps a grant row to its stored form. A row without an
|
|
// identifier or a time is refused before the domain rebuilds the grant.
|
|
func storedContactGrantRow(row sqlc.ContactGrant) (domain.StoredContactGrant, error) {
|
|
if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.SourceInvitationID.Valid ||
|
|
!row.ConsentRecordID.Valid || !row.GrantedAt.Valid {
|
|
return domain.StoredContactGrant{}, fmt.Errorf("stored grant has missing identifiers: %w", domain.ErrInvalidContactGrant)
|
|
}
|
|
stored := domain.StoredContactGrant{
|
|
ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
|
|
CandidateID: uuid.UUID(row.CandidateID.Bytes), InvitationID: uuid.UUID(row.SourceInvitationID.Bytes),
|
|
ConsentRecordID: uuid.UUID(row.ConsentRecordID.Bytes), TermsVersion: row.TermsVersion, Fields: row.Fields,
|
|
ConsentTextVersion: row.ConsentTextVersion, GrantedAt: row.GrantedAt.Time.UTC(),
|
|
}
|
|
if row.RevokedAt.Valid {
|
|
revokedAt := row.RevokedAt.Time.UTC()
|
|
stored.RevokedAt = &revokedAt
|
|
}
|
|
if row.RevocationReason.Valid {
|
|
stored.RevocationReason = row.RevocationReason.String
|
|
}
|
|
return stored, nil
|
|
}
|
|
|
|
// LockForRead locks the C4 record before the grant, the order of the consent
|
|
// revocation, so a read and a revocation of the same consent cannot wait for
|
|
// each other in opposite orders. The locked grant is restored through the
|
|
// domain like GetByInvitation, and it must still name the grant that was read.
|
|
func (repository contactGrantRepository) LockForRead(
|
|
ctx context.Context,
|
|
grant domain.ContactGrant,
|
|
) (domain.ContactGrant, bool, error) {
|
|
const location = "contactGrantRepository.LockForRead"
|
|
if grant.IsZero() {
|
|
return domain.ContactGrant{}, false, fmt.Errorf("%s - grant must be built by the domain: %w", location, domain.ErrInvalidContactGrant)
|
|
}
|
|
consentCurrent := true
|
|
_, err := repository.queries.LockCurrentContactConsentRecord(ctx, sqlc.LockCurrentContactConsentRecordParams{
|
|
ConsentRecordID: pgUUID(grant.ConsentRecordID()), CandidateID: pgUUID(grant.CandidateID()),
|
|
OrganizationID: pgUUID(grant.OrganizationID()),
|
|
})
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
consentCurrent = false
|
|
case err != nil:
|
|
return domain.ContactGrant{}, false, fmt.Errorf("%s - lock consent C4 record: %w", location, mapInvitationError(err))
|
|
}
|
|
row, err := repository.queries.LockContactGrant(ctx, pgUUID(grant.ID()))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.ContactGrant{}, false, fmt.Errorf("%s - lock contact grant: %w", location, outbound.ErrContactGrantNotFound)
|
|
}
|
|
if err != nil {
|
|
return domain.ContactGrant{}, false, fmt.Errorf("%s - lock contact grant: %w", location, mapInvitationError(err))
|
|
}
|
|
stored, err := storedContactGrantRow(row)
|
|
if err != nil {
|
|
return domain.ContactGrant{}, false, fmt.Errorf("%s - read stored grant: %w", location, err)
|
|
}
|
|
current, err := domain.RestoreContactGrant(stored)
|
|
if err != nil {
|
|
return domain.ContactGrant{}, false, fmt.Errorf("%s - restore contact grant: %w", location, err)
|
|
}
|
|
if current.OrganizationID() != grant.OrganizationID() || current.CandidateID() != grant.CandidateID() ||
|
|
current.InvitationID() != grant.InvitationID() || current.ConsentRecordID() != grant.ConsentRecordID() {
|
|
return domain.ContactGrant{}, false, fmt.Errorf("%s - locked grant has another scope: %w", location, domain.ErrInvalidContactGrant)
|
|
}
|
|
return current, consentCurrent, nil
|
|
}
|