feat: persist versioned organization needs
This commit is contained in:
1 parent
f81cd0ae09
commit
ee3738ee73
14 files changed
+2388
No files matched your search
@@ -0,0 +1,276 @@
|
||||
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{}
|
||||
|
||||
func (unit *UnitOfWork) Needs() outbound.NeedRepository {
|
||||
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) 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.MaxNeedSnapshotBytes {
|
||||
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 == 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})
|
||||
}
|
||||
Reference in new issue
Block a user