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

188 lines
7.2 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
// integrityConstraintViolationCode is the SQLSTATE that the
// policy_versions_refuse_change trigger raises.
integrityConstraintViolationCode = "23000"
checkViolationCode = "23514"
// policyVersionsImmutableConstraint is the constraint name the trigger
// reports. It is not a table constraint; the trigger sets it so the error
// can be matched like one.
policyVersionsImmutableConstraint = "policy_versions_immutable"
)
// policyConstraintErrors maps policy errors whose cause is a caller-visible
// outcome to port sentinels by SQLSTATE and constraint name, never by text.
// Unique violations do not occur: the insert uses ON CONFLICT DO NOTHING.
var policyConstraintErrors = map[constraintViolation]error{
{integrityConstraintViolationCode, policyVersionsImmutableConstraint}: outbound.ErrPolicyVersionImmutable,
{checkViolationCode, "policy_versions_effective_after_creation"}: outbound.ErrPolicyVersionBackdated,
}
// mapPolicyError turns a known policy constraint or trigger error into its
// port sentinel and keeps the constraint name. Any other PostgreSQL error is
// replaced by its SQLSTATE and constraint name, as the identity repositories
// do, so authors and document values never reach error text. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database;
// other errors that do not come from PostgreSQL pass through.
func mapPolicyError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := policyConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapPolicyError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// PolicyStore provides the policy repository outside a transaction. Every
// call runs as its own statement on a pool connection. Called with a context
// that belongs to a Transactor callback, it fails with
// outbound.ErrNestedTransaction; use UnitOfWork.Policies there.
type PolicyStore struct {
queries *sqlc.Queries
}
func NewPolicyStore(pool *pgxpool.Pool) *PolicyStore {
return &PolicyStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
func (store *PolicyStore) Policies() outbound.PolicyRepository {
return policyRepository{queries: store.queries}
}
func (unit *UnitOfWork) Policies() outbound.PolicyRepository {
return policyRepository{queries: unit.queries}
}
type policyRepository struct {
queries *sqlc.Queries
}
var _ outbound.PolicyRepository = policyRepository{}
func (repository policyRepository) Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) {
if draft.IsZero() || draft.Version() <= 0 {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - draft was not built and numbered by domain.NewPolicyVersionDraft: %w", domain.ErrInvalidPolicyVersion)
}
effectiveAt := pgtype.Timestamptz{}
if scheduled, ok := draft.EffectiveAt(); ok {
effectiveAt = pgTime(scheduled)
}
hash := draft.DocumentHash()
row, err := repository.queries.InsertPolicyVersion(ctx, sqlc.InsertPolicyVersionParams{
ID: pgUUID(draft.ID().UUID()),
PolicyKey: string(draft.Key()),
Version: draft.Version(),
Kind: string(draft.Kind()),
EffectiveAt: effectiveAt,
Author: string(draft.Author()),
Document: draft.Document(),
DocumentSha256: hash[:],
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - insert %s version %d: %w", draft.Key(), draft.Version(), outbound.ErrPolicyVersionConflict)
}
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - insert policy version: %w", mapPolicyError(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) GetByID(ctx context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
row, err := repository.queries.GetPolicyVersionByID(ctx, pgUUID(id.UUID()))
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetByID - select policy version: %w", mapPolicyNoRows(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) GetEffective(ctx context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error) {
if err := requireTime("policyRepository.GetEffective", at, domain.ErrInvalidPolicyVersion); err != nil {
return domain.PolicyVersion{}, err
}
if err := requireKnownFamily("policyRepository.GetEffective", key); err != nil {
return domain.PolicyVersion{}, err
}
row, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{
PolicyKey: string(key),
At: pgTime(at),
})
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetEffective - select policy version: %w", mapPolicyNoRows(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) GetLatest(ctx context.Context, key domain.PolicyKey) (domain.PolicyVersion, error) {
if err := requireKnownFamily("policyRepository.GetLatest", key); err != nil {
return domain.PolicyVersion{}, err
}
row, err := repository.queries.GetLatestPolicyVersion(ctx, string(key))
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetLatest - select policy version: %w", mapPolicyNoRows(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) HasVersions(ctx context.Context, key domain.PolicyKey) (bool, error) {
if err := requireKnownFamily("policyRepository.HasVersions", key); err != nil {
return false, err
}
present, err := repository.queries.PolicyVersionExists(ctx, string(key))
if err != nil {
return false, fmt.Errorf("policyRepository.HasVersions - check policy versions: %w", mapPolicyError(err))
}
return present, nil
}
func requireKnownFamily(location string, key domain.PolicyKey) error {
if _, err := domain.ParsePolicyKey(string(key)); err != nil {
return fmt.Errorf("%s - validate family: %w", location, err)
}
return nil
}
func mapPolicyNoRows(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ErrPolicyVersionNotFound
}
return mapPolicyError(err)
}
func policyVersionFromRow(row sqlc.PolicyVersion) (domain.PolicyVersion, error) {
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
ID: domain.PolicyVersionID(row.ID.Bytes),
Key: row.PolicyKey,
Version: row.Version,
Kind: row.Kind,
Author: row.Author,
EffectiveAt: row.EffectiveAt.Time,
CreatedAt: row.CreatedAt.Time,
Document: row.Document,
DocumentHash: row.DocumentSha256,
})
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("postgres.policyVersionFromRow - restore policy version: %w", err)
}
return version, nil
}