Files
lincodex/backend/internal/adapter/secondary/postgres/organizations.go
T

431 lines
18 KiB
Go

package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"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"
)
// organizationConstraintErrors maps the organization constraints whose
// violation is a caller-visible outcome to port sentinels by SQLSTATE and
// constraint name, never by text.
var organizationConstraintErrors = map[constraintViolation]error{
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
}
// mapOrganizationError turns a known organization constraint violation into
// its port sentinel and keeps the constraint name. Any other PostgreSQL error
// is replaced by its SQLSTATE and constraint name, because its detail quotes
// the failing row, which holds names of representatives. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database.
func mapOrganizationError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := organizationConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapOrganizationError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
var _ outbound.OrganizationRepositories = (*UnitOfWork)(nil)
func (unit *UnitOfWork) Organizations() outbound.OrganizationRepository {
return organizationRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Memberships() outbound.MembershipRepository {
return membershipRepository{queries: unit.queries}
}
type organizationRepository struct {
queries *sqlc.Queries
}
var _ outbound.OrganizationRepository = organizationRepository{}
func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error {
const location = "organizationRepository.CreateWithOwner"
switch {
case organization.IsZero():
return fmt.Errorf("%s - organization was not built by domain.NewOrganization: %w", location, domain.ErrInvalidOrganization)
case owner.IsZero():
return fmt.Errorf("%s - owner was not built by domain.NewOwnerMembership: %w", location, domain.ErrInvalidMembership)
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
}
profile := organization.Profile()
contacts := profile.Contacts()
verification := organization.Verification()
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
ID: pgUUID(organization.ID()),
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
VerificationLevel: string(verification.Level()),
VerificationBasis: string(verification.Basis()),
VerificationChangedAt: pgTime(verification.ChangedAt()),
Version: organization.Version(),
CreatedAt: pgTime(organization.CreatedAt()),
UpdatedAt: pgTime(organization.UpdatedAt()),
})
if err != nil {
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return fmt.Errorf("%s - insert representatives: %w", location, err)
}
if err := insertMembership(ctx, repository.queries, owner); err != nil {
return fmt.Errorf("%s - insert owner membership: %w", location, err)
}
return nil
}
func (repository organizationRepository) insertRepresentatives(
ctx context.Context,
organizationID uuid.UUID,
representatives []domain.OrganizationRepresentative,
) error {
for index, representative := range representatives {
err := repository.queries.InsertOrganizationRepresentative(ctx, sqlc.InsertOrganizationRepresentativeParams{
OrganizationID: pgUUID(organizationID),
Ordinal: int16(index),
Name: representative.Name(),
JobTitle: representative.JobTitle(),
})
if err != nil {
return mapOrganizationError(err)
}
}
return nil
}
func (repository organizationRepository) GetForMember(
ctx context.Context,
organizationID, userID uuid.UUID,
) (domain.Organization, domain.Membership, error) {
const location = "organizationRepository.GetForMember"
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - select organization: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
}
representatives, err := decodeRepresentatives(row.Representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - decode representatives: %w", location, err)
}
organization, err := organizationFromColumns(organizationColumns{
ID: row.ID, Name: row.Name, Description: row.Description, Sphere: row.Sphere,
ContactWebsite: row.ContactWebsite, ContactEmail: row.ContactEmail,
ContactPhone: row.ContactPhone, ContactTelegram: row.ContactTelegram,
VerificationLevel: row.VerificationLevel, VerificationBasis: row.VerificationBasis,
VerificationChangedAt: row.VerificationChangedAt, Version: row.Version,
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
}, representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, err
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: organizationID,
UserID: userID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return organization, membership, nil
}
// representativeJSON is one element of the representatives column that
// GetOrganizationForMember aggregates in the same statement as the
// organization, so the profile and the list come from one snapshot.
type representativeJSON struct {
Name string `json:"name"`
JobTitle string `json:"job_title"`
}
func decodeRepresentatives(column string) ([]domain.StoredRepresentative, error) {
var decoded []representativeJSON
if err := json.Unmarshal([]byte(column), &decoded); err != nil {
// The error of the decoder can quote the document, which holds names.
return nil, errors.New("postgres.decodeRepresentatives - the representatives column is not a list of name and job title")
}
representatives := make([]domain.StoredRepresentative, 0, len(decoded))
for _, representative := range decoded {
representatives = append(representatives, domain.StoredRepresentative(representative))
}
return representatives, nil
}
func (repository organizationRepository) ListForUser(ctx context.Context, query outbound.OrganizationListQuery) (outbound.OrganizationPage, error) {
const location = "organizationRepository.ListForUser"
if query.UserID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - user ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
if query.Limit < 1 || query.Limit > outbound.MaxOrganizationPageSize {
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
}
params := sqlc.ListOrganizationsForUserParams{
UserID: pgUUID(query.UserID),
// One extra row tells whether another page follows.
RowLimit: query.Limit + 1,
}
if query.After != nil {
if err := requireTime(location, query.After.JoinedAt, domain.ErrInvalidMembership); err != nil {
return outbound.OrganizationPage{}, err
}
if query.After.OrganizationID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - position organization ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
params.AfterJoinedAt = pgTime(query.After.JoinedAt)
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
}
rows, err := repository.queries.ListOrganizationsForUser(ctx, params)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - select organizations: %w", location, mapOrganizationError(err))
}
page := outbound.OrganizationPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]outbound.MemberOrganization, 0, len(rows))
for _, row := range rows {
summary, err := domain.RestoreOrganizationSummary(optionalUUID(row.ID), row.Name, row.VerificationLevel)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore organization: %w", location, err)
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: summary.ID(),
UserID: query.UserID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
page.Items = append(page.Items, outbound.MemberOrganization{Organization: summary, Membership: membership})
}
return page, nil
}
func (repository organizationRepository) UpdateProfile(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) (domain.Organization, error) {
const location = "organizationRepository.UpdateProfile"
if organization.IsZero() || actorID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - organization and actor must be set: %w", location, domain.ErrInvalidOrganization)
}
// The generated parameter structs of this repository hold representative
// names and contacts: never log them.
profile := organization.Profile()
contacts := profile.Contacts()
row, err := repository.queries.UpdateOrganizationProfile(ctx, sqlc.UpdateOrganizationProfileParams{
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
UpdatedAt: pgTime(organization.UpdatedAt()),
ID: pgUUID(organization.ID()),
ExpectedVersion: organization.Version(),
ActorID: pgUUID(actorID),
ManagerRoles: managerRoleNames(),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, repository.explainRejectedUpdate(ctx, actorID, organization))
}
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, mapOrganizationError(err))
}
// The row lock of the update holds until the transaction ends, so no
// other writer replaces the list between these statements.
if err := repository.queries.DeleteOrganizationRepresentatives(ctx, row.ID); err != nil {
return domain.Organization{}, fmt.Errorf("%s - delete representatives: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return domain.Organization{}, fmt.Errorf("%s - insert representatives: %w", location, err)
}
stored := make([]domain.StoredRepresentative, 0, len(profile.Representatives()))
for _, representative := range profile.Representatives() {
stored = append(stored, domain.StoredRepresentative{Name: representative.Name(), JobTitle: representative.JobTitle()})
}
return organizationFromColumns(organizationColumns(row), stored)
}
// explainRejectedUpdate tells why the update matched no row: an unknown
// organization or an actor without an active membership, a membership whose
// role cannot manage, or a stale version, in that order.
func (repository organizationRepository) explainRejectedUpdate(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) error {
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organization.ID()),
UserID: pgUUID(actorID),
})
switch {
case errors.Is(err, pgx.ErrNoRows):
return outbound.ErrOrganizationNotFound
case err != nil:
return mapOrganizationError(err)
}
role, err := domain.ParseOrganizationRole(row.MembershipRole)
switch {
case err != nil:
return fmt.Errorf("postgres.explainRejectedUpdate - validate role: %w", err)
case !role.CanManageOrganization():
return outbound.ErrOrganizationManagerRequired
default:
return outbound.ErrOrganizationVersionConflict
}
}
func managerRoleNames() []string {
roles := domain.ManagerRoles()
names := make([]string, 0, len(roles))
for _, role := range roles {
names = append(names, string(role))
}
return names
}
// organizationColumns has the columns of an organization row that every
// organization query returns. The generated row of UpdateOrganizationProfile
// converts to it.
type organizationColumns struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func organizationFromColumns(columns organizationColumns, representatives []domain.StoredRepresentative) (domain.Organization, error) {
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
ID: optionalUUID(columns.ID),
Name: columns.Name,
Description: columns.Description.String,
Sphere: columns.Sphere.String,
Website: columns.ContactWebsite.String,
Email: columns.ContactEmail.String,
Phone: columns.ContactPhone.String,
Telegram: columns.ContactTelegram.String,
Representatives: representatives,
VerificationLevel: columns.VerificationLevel,
VerificationBasis: columns.VerificationBasis,
VerificationChangedAt: columns.VerificationChangedAt.Time,
Version: columns.Version,
CreatedAt: columns.CreatedAt.Time,
UpdatedAt: columns.UpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, fmt.Errorf("postgres.organizationFromColumns - restore organization: %w", err)
}
return organization, nil
}
type membershipRepository struct {
queries *sqlc.Queries
}
var _ outbound.MembershipRepository = membershipRepository{}
func (repository membershipRepository) Insert(ctx context.Context, membership domain.Membership) error {
if membership.IsZero() {
return fmt.Errorf("membershipRepository.Insert - membership was not built by domain.NewMembership: %w", domain.ErrInvalidMembership)
}
if err := insertMembership(ctx, repository.queries, membership); err != nil {
return fmt.Errorf("membershipRepository.Insert - insert membership: %w", err)
}
return nil
}
func insertMembership(ctx context.Context, queries *sqlc.Queries, membership domain.Membership) error {
err := queries.InsertMembership(ctx, sqlc.InsertMembershipParams{
ID: pgUUID(membership.ID()),
OrganizationID: pgUUID(membership.OrganizationID()),
UserID: pgUUID(membership.UserID()),
Role: string(membership.Role()),
State: string(membership.State()),
CreatedAt: pgTime(membership.CreatedAt()),
UpdatedAt: pgTime(membership.UpdatedAt()),
})
if err != nil {
return mapOrganizationError(err)
}
return nil
}
func (repository membershipRepository) Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
const location = "membershipRepository.Get"
row, err := repository.queries.GetMembership(ctx, sqlc.GetMembershipParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - select membership: %w", location, mapOrganizationNoRows(err, outbound.ErrMembershipNotFound))
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.ID),
OrganizationID: optionalUUID(row.OrganizationID),
UserID: optionalUUID(row.UserID),
Role: row.Role,
State: row.State,
CreatedAt: row.CreatedAt.Time,
UpdatedAt: row.UpdatedAt.Time,
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return membership, nil
}
func mapOrganizationNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapOrganizationError(err)
}