415 lines
17 KiB
Go
415 lines
17 KiB
Go
package postgres
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
|
|
"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.NeedRepository = needRepository{}
|
|
_ outbound.NeedListRepository = needRepository{}
|
|
_ outbound.NeedCreationResultRepository = needRepository{}
|
|
)
|
|
|
|
func (unit *UnitOfWork) Needs() outbound.NeedRepository {
|
|
return needRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (unit *UnitOfWork) NeedLists() outbound.NeedListRepository {
|
|
return needRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (unit *UnitOfWork) NeedCreationResults() outbound.NeedCreationResultRepository {
|
|
return needRepository{queries: unit.queries}
|
|
}
|
|
|
|
type needRepository struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func (repository needRepository) Create(ctx context.Context, need domain.Need) error {
|
|
const location = "needRepository.Create"
|
|
snapshot, encoded, err := encodeNeedSnapshot(need)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - validate and encode need: %w", location, err)
|
|
}
|
|
if snapshot.Version != 1 || snapshot.RequirementsVersion != 1 {
|
|
return fmt.Errorf("%s - creation must start at version 1: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
if err := repository.queries.InsertOrganizationNeed(ctx, sqlc.InsertOrganizationNeedParams{
|
|
ID: pgUUID(snapshot.ID),
|
|
OrganizationID: pgUUID(snapshot.OrganizationID),
|
|
CurrentVersion: snapshot.Version,
|
|
RequirementsVersion: snapshot.RequirementsVersion,
|
|
CreatedAt: pgTime(snapshot.CreatedAt),
|
|
UpdatedAt: pgTime(snapshot.UpdatedAt),
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - insert need: %w", location, mapNeedError(err))
|
|
}
|
|
if err := repository.queries.InsertOrganizationNeedVersion(ctx, sqlc.InsertOrganizationNeedVersionParams{
|
|
OrganizationID: pgUUID(snapshot.OrganizationID),
|
|
NeedID: pgUUID(snapshot.ID),
|
|
Version: snapshot.Version,
|
|
Snapshot: encoded,
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - append initial need snapshot: %w", location, mapNeedError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository needRepository) Get(ctx context.Context, organizationID, needID uuid.UUID) (domain.Need, error) {
|
|
const location = "needRepository.Get"
|
|
if err := validateNeedScope(location, organizationID, needID); err != nil {
|
|
return domain.Need{}, err
|
|
}
|
|
row, err := repository.queries.ReadCurrentOrganizationNeed(ctx, sqlc.ReadCurrentOrganizationNeedParams{
|
|
OrganizationID: pgUUID(organizationID),
|
|
NeedID: pgUUID(needID),
|
|
})
|
|
if err != nil {
|
|
return domain.Need{}, fmt.Errorf("%s - read current need: %w", location, mapNeedNoRows(err))
|
|
}
|
|
if !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
|
|
return domain.Need{}, fmt.Errorf("%s - stored need timestamps are invalid", location)
|
|
}
|
|
return restoreNeedSnapshot(location, row.Snapshot, organizationID, needID, row.CurrentVersion, row.RequirementsVersion, &row.CreatedAt.Time, &row.UpdatedAt.Time)
|
|
}
|
|
|
|
func (repository needRepository) GetVersion(
|
|
ctx context.Context,
|
|
organizationID, needID uuid.UUID,
|
|
version int64,
|
|
) (domain.Need, error) {
|
|
const location = "needRepository.GetVersion"
|
|
if err := validateNeedScope(location, organizationID, needID); err != nil {
|
|
return domain.Need{}, err
|
|
}
|
|
if version < 1 {
|
|
return domain.Need{}, fmt.Errorf("%s - version must be positive: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
encoded, err := repository.queries.ReadOrganizationNeedVersion(ctx, sqlc.ReadOrganizationNeedVersionParams{
|
|
OrganizationID: pgUUID(organizationID),
|
|
NeedID: pgUUID(needID),
|
|
Version: version,
|
|
})
|
|
if err != nil {
|
|
return domain.Need{}, fmt.Errorf("%s - read historical need: %w", location, mapNeedNoRows(err))
|
|
}
|
|
return restoreNeedSnapshot(location, encoded, organizationID, needID, version, 0, nil, nil)
|
|
}
|
|
|
|
func (repository needRepository) List(ctx context.Context, query outbound.NeedListQuery) (outbound.NeedPage, error) {
|
|
const location = "needRepository.List"
|
|
if query.OrganizationID == uuid.Nil {
|
|
return outbound.NeedPage{}, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
if query.Limit < 1 || query.Limit > outbound.MaxNeedPageSize {
|
|
return outbound.NeedPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxNeedPageSize, domain.ErrInvalidNeed)
|
|
}
|
|
params := sqlc.ListOrganizationNeedsParams{
|
|
OrganizationID: pgUUID(query.OrganizationID),
|
|
RowLimit: query.Limit + 1,
|
|
}
|
|
if query.After != nil {
|
|
if err := validateNeedListPosition(location, *query.After); err != nil {
|
|
return outbound.NeedPage{}, err
|
|
}
|
|
params.AfterCreatedAt = pgTime(query.After.CreatedAt)
|
|
params.AfterNeedID = pgUUID(query.After.NeedID)
|
|
}
|
|
rows, err := repository.queries.ListOrganizationNeeds(ctx, params)
|
|
if err != nil {
|
|
return outbound.NeedPage{}, fmt.Errorf("%s - select current needs: %w", location, mapNeedError(err))
|
|
}
|
|
page := outbound.NeedPage{HasMore: len(rows) > int(query.Limit)}
|
|
if page.HasMore {
|
|
rows = rows[:query.Limit]
|
|
}
|
|
page.Items = make([]domain.Need, 0, len(rows))
|
|
for _, row := range rows {
|
|
if !row.OrganizationID.Valid || !row.NeedID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || uuid.UUID(row.OrganizationID.Bytes) != query.OrganizationID {
|
|
return outbound.NeedPage{}, fmt.Errorf("%s - current need row has invalid scope or metadata", location)
|
|
}
|
|
need, err := restoreNeedSnapshot(
|
|
location, row.Snapshot, query.OrganizationID, uuid.UUID(row.NeedID.Bytes),
|
|
row.CurrentVersion, row.RequirementsVersion, &row.CreatedAt.Time, &row.UpdatedAt.Time,
|
|
)
|
|
if err != nil {
|
|
return outbound.NeedPage{}, err
|
|
}
|
|
page.Items = append(page.Items, need)
|
|
}
|
|
return page, nil
|
|
}
|
|
|
|
func validateNeedListPosition(location string, position outbound.NeedListPosition) error {
|
|
createdAt := position.CreatedAt
|
|
if position.NeedID == uuid.Nil || createdAt.IsZero() || createdAt.Year() < 1 || createdAt.Year() > 9999 ||
|
|
createdAt.Unix() < 0 || createdAt.Nanosecond()%int(time.Microsecond) != 0 {
|
|
return fmt.Errorf("%s - pagination position is outside the stored need timestamp range: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository needRepository) SaveCreationResult(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
snapshot domain.NeedResponseSnapshot,
|
|
) error {
|
|
const location = "needRepository.SaveCreationResult"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
_, encoded, err := encodeNeedCreationResult(snapshot)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - validate and encode response snapshot: %w", location, err)
|
|
}
|
|
if err := repository.queries.SaveOrganizationNeedCreationResult(ctx, sqlc.SaveOrganizationNeedCreationResultParams{
|
|
ScopeHash: scope[:], Snapshot: encoded,
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - store response snapshot: %w", location, mapNeedError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository needRepository) GetCreationResult(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
) (domain.NeedResponseSnapshot, error) {
|
|
const location = "needRepository.GetCreationResult"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
encoded, err := repository.queries.GetOrganizationNeedCreationResult(ctx, scope[:])
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.NeedResponseSnapshot{}, outbound.ErrNeedCreationResultNotFound
|
|
}
|
|
if err != nil {
|
|
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - read response snapshot: %w", location, mapNeedError(err))
|
|
}
|
|
if len(encoded) > domain.MaxNeedCreationResultStorageBytes {
|
|
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot exceeds its bound", location)
|
|
}
|
|
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
|
|
decoder.DisallowUnknownFields()
|
|
var snapshot domain.NeedResponseSnapshot
|
|
if err := decoder.Decode(&snapshot); err != nil {
|
|
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot is invalid", location)
|
|
}
|
|
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
|
|
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot has trailing data", location)
|
|
}
|
|
validated, _, err := encodeNeedCreationResult(snapshot)
|
|
if err != nil {
|
|
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - restore response snapshot: %w", location, err)
|
|
}
|
|
return validated, nil
|
|
}
|
|
|
|
func encodeNeedCreationResult(snapshot domain.NeedResponseSnapshot) (domain.NeedResponseSnapshot, []byte, error) {
|
|
validated, err := domain.RestoreNeedResponseSnapshot(snapshot)
|
|
if err != nil {
|
|
return domain.NeedResponseSnapshot{}, nil, err
|
|
}
|
|
encoded, err := json.Marshal(validated)
|
|
if err != nil {
|
|
return domain.NeedResponseSnapshot{}, nil, fmt.Errorf("encode need response snapshot: %w", err)
|
|
}
|
|
if len(encoded) > domain.MaxNeedCreationResultBytes {
|
|
return domain.NeedResponseSnapshot{}, nil, fmt.Errorf("need response snapshot exceeds its storage bound: %w", domain.ErrInvalidNeed)
|
|
}
|
|
return validated, encoded, nil
|
|
}
|
|
|
|
func (repository needRepository) Save(
|
|
ctx context.Context,
|
|
organizationID, needID uuid.UUID,
|
|
expectedVersion int64,
|
|
next domain.Need,
|
|
) error {
|
|
const location = "needRepository.Save"
|
|
if err := validateNeedScope(location, organizationID, needID); err != nil {
|
|
return err
|
|
}
|
|
if expectedVersion < 1 || next.IsZero() || next.ID() != needID || next.OrganizationID() != organizationID {
|
|
return fmt.Errorf("%s - need and expected version are invalid: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
|
|
current, err := repository.getCurrent(ctx, location, organizationID, needID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if current.Version() != expectedVersion {
|
|
return fmt.Errorf("%s - expected version is stale: %w", location, outbound.ErrNeedVersionConflict)
|
|
}
|
|
if !current.IsNextVersionOf(next, expectedVersion) {
|
|
return fmt.Errorf("%s - next snapshot does not follow the current need: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
snapshot, encoded, err := encodeNeedSnapshot(next)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - validate and encode next snapshot: %w", location, err)
|
|
}
|
|
stored, err := repository.queries.AdvanceOrganizationNeed(ctx, sqlc.AdvanceOrganizationNeedParams{
|
|
RequirementsVersion: snapshot.RequirementsVersion,
|
|
UpdatedAt: pgTime(snapshot.UpdatedAt),
|
|
OrganizationID: pgUUID(organizationID),
|
|
NeedID: pgUUID(needID),
|
|
ExpectedVersion: expectedVersion,
|
|
NextVersion: snapshot.Version,
|
|
Snapshot: encoded,
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return repository.classifyAdvanceMiss(ctx, location, organizationID, needID, expectedVersion)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s - append next snapshot and advance current version: %w", location, mapNeedError(err))
|
|
}
|
|
if _, err := restoreNeedSnapshot(location, stored, organizationID, needID, snapshot.Version, snapshot.RequirementsVersion, &snapshot.CreatedAt, &snapshot.UpdatedAt); err != nil {
|
|
return fmt.Errorf("%s - verify appended snapshot: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository needRepository) getCurrent(
|
|
ctx context.Context,
|
|
location string,
|
|
organizationID, needID uuid.UUID,
|
|
) (domain.Need, error) {
|
|
row, err := repository.queries.ReadCurrentOrganizationNeed(ctx, sqlc.ReadCurrentOrganizationNeedParams{
|
|
OrganizationID: pgUUID(organizationID),
|
|
NeedID: pgUUID(needID),
|
|
})
|
|
if err != nil {
|
|
return domain.Need{}, fmt.Errorf("%s - read current need: %w", location, mapNeedNoRows(err))
|
|
}
|
|
if !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
|
|
return domain.Need{}, fmt.Errorf("%s - stored need timestamps are invalid", location)
|
|
}
|
|
return restoreNeedSnapshot(location, row.Snapshot, organizationID, needID, row.CurrentVersion, row.RequirementsVersion, &row.CreatedAt.Time, &row.UpdatedAt.Time)
|
|
}
|
|
|
|
func (repository needRepository) classifyAdvanceMiss(
|
|
ctx context.Context,
|
|
location string,
|
|
organizationID, needID uuid.UUID,
|
|
expectedVersion int64,
|
|
) error {
|
|
current, err := repository.getCurrent(ctx, location, organizationID, needID)
|
|
if errors.Is(err, outbound.ErrNeedNotFound) {
|
|
return err
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s - classify compare-and-swap miss: %w", location, err)
|
|
}
|
|
if current.Version() != expectedVersion {
|
|
return fmt.Errorf("%s - another writer advanced the need: %w", location, outbound.ErrNeedVersionConflict)
|
|
}
|
|
return fmt.Errorf("%s - compare-and-swap missed without a version change: %w", location, outbound.ErrTransactionConflict)
|
|
}
|
|
|
|
func encodeNeedSnapshot(need domain.Need) (domain.NeedSnapshot, []byte, error) {
|
|
if need.IsZero() {
|
|
return domain.NeedSnapshot{}, nil, domain.ErrInvalidNeed
|
|
}
|
|
snapshot := need.Snapshot()
|
|
// PostgreSQL stores timestamptz with microsecond precision. Canonicalize
|
|
// the immutable payload to the same precision as the parent row.
|
|
snapshot.CreatedAt = snapshot.CreatedAt.UTC().Truncate(time.Microsecond)
|
|
snapshot.UpdatedAt = snapshot.UpdatedAt.UTC().Truncate(time.Microsecond)
|
|
validated, err := domain.RestoreNeed(snapshot)
|
|
if err != nil {
|
|
return domain.NeedSnapshot{}, nil, err
|
|
}
|
|
snapshot = validated.Snapshot()
|
|
encoded, err := json.Marshal(snapshot)
|
|
if err != nil {
|
|
return domain.NeedSnapshot{}, nil, fmt.Errorf("encode need snapshot: %w", err)
|
|
}
|
|
if len(encoded) > domain.MaxNeedSnapshotBytes {
|
|
return domain.NeedSnapshot{}, nil, fmt.Errorf("need snapshot exceeds its storage bound: %w", domain.ErrInvalidNeed)
|
|
}
|
|
return snapshot, encoded, nil
|
|
}
|
|
|
|
func restoreNeedSnapshot(
|
|
location string,
|
|
encoded string,
|
|
organizationID, needID uuid.UUID,
|
|
version, requirementsVersion int64,
|
|
createdAt, updatedAt *time.Time,
|
|
) (domain.Need, error) {
|
|
if len(encoded) > domain.MaxNeedSnapshotStorageBytes {
|
|
return domain.Need{}, fmt.Errorf("%s - stored snapshot exceeds its bound", location)
|
|
}
|
|
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
|
|
decoder.DisallowUnknownFields()
|
|
var snapshot domain.NeedSnapshot
|
|
if err := decoder.Decode(&snapshot); err != nil {
|
|
return domain.Need{}, fmt.Errorf("%s - stored snapshot is invalid", location)
|
|
}
|
|
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
|
|
return domain.Need{}, fmt.Errorf("%s - stored snapshot has trailing data", location)
|
|
}
|
|
if snapshot.ID != needID || snapshot.OrganizationID != organizationID || snapshot.Version != version {
|
|
return domain.Need{}, fmt.Errorf("%s - stored snapshot identity or version does not match its scope", location)
|
|
}
|
|
if requirementsVersion > 0 && snapshot.RequirementsVersion != requirementsVersion {
|
|
return domain.Need{}, fmt.Errorf("%s - stored requirements version does not match its parent", location)
|
|
}
|
|
if createdAt != nil && !snapshot.CreatedAt.UTC().Truncate(time.Microsecond).Equal(createdAt.UTC().Truncate(time.Microsecond)) {
|
|
return domain.Need{}, fmt.Errorf("%s - stored creation time does not match its parent", location)
|
|
}
|
|
if updatedAt != nil && !snapshot.UpdatedAt.UTC().Truncate(time.Microsecond).Equal(updatedAt.UTC().Truncate(time.Microsecond)) {
|
|
return domain.Need{}, fmt.Errorf("%s - stored update time does not match its parent", location)
|
|
}
|
|
need, err := domain.RestoreNeed(snapshot)
|
|
if err != nil {
|
|
return domain.Need{}, fmt.Errorf("%s - restore domain snapshot: %w", location, err)
|
|
}
|
|
return need, nil
|
|
}
|
|
|
|
func validateNeedScope(location string, organizationID, needID uuid.UUID) error {
|
|
if organizationID == uuid.Nil || needID == uuid.Nil {
|
|
return fmt.Errorf("%s - organization and need IDs must be set: %w", location, domain.ErrInvalidNeed)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func mapNeedNoRows(err error) error {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return outbound.ErrNeedNotFound
|
|
}
|
|
return mapNeedError(err)
|
|
}
|
|
|
|
func mapNeedError(err error) error {
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) {
|
|
return sanitizeConnectError(err)
|
|
}
|
|
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "organization_needs_organization_fkey" {
|
|
return fmt.Errorf("postgres.mapNeedError - organization no longer exists: %w", outbound.ErrOrganizationNotFound)
|
|
}
|
|
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "organization_need_creation_results_idempotency_fkey" {
|
|
return fmt.Errorf("postgres.mapNeedError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
|
}
|
|
if pgError.Code == uniqueViolationCode && pgError.ConstraintName == "organization_needs_pkey" {
|
|
return fmt.Errorf("postgres.mapNeedError - need ID already exists: %w", outbound.ErrNeedAlreadyExists)
|
|
}
|
|
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
|
}
|