feat: persist versioned organization needs

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 16:25:17 +03:00
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})
}
@@ -396,6 +396,22 @@ type OrganizationCreationResult struct {
Snapshot []byte
}
type OrganizationNeed struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type OrganizationNeedVersion struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
Version int64
Snapshot []byte
}
type OrganizationRepresentative struct {
OrganizationID pgtype.UUID
Ordinal int16
@@ -0,0 +1,226 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: needs.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceOrganizationNeed = `-- name: AdvanceOrganizationNeed :one
WITH advanced AS (
UPDATE organization_needs
SET
current_version = organization_needs.current_version + 1,
requirements_version = $1,
updated_at = $2
WHERE
organization_needs.organization_id = $3
AND organization_needs.id = $4
AND organization_needs.current_version = $5
AND $6::bigint = organization_needs.current_version + 1
AND (
$1::bigint = organization_needs.requirements_version
OR $1::bigint = organization_needs.current_version + 1
)
RETURNING organization_needs.organization_id, organization_needs.id, organization_needs.current_version
), appended AS (
INSERT INTO organization_need_versions (
organization_id,
need_id,
version,
snapshot
)
SELECT
advanced.organization_id,
advanced.id,
advanced.current_version,
$7::jsonb
FROM advanced
RETURNING
organization_need_versions.organization_id,
organization_need_versions.need_id,
organization_need_versions.version,
organization_need_versions.snapshot::text AS snapshot
)
SELECT appended.snapshot
FROM appended
`
type AdvanceOrganizationNeedParams struct {
RequirementsVersion int64
UpdatedAt pgtype.Timestamptz
OrganizationID pgtype.UUID
NeedID pgtype.UUID
ExpectedVersion int64
NextVersion int64
Snapshot []byte
}
// The conditional parent update is the compare-and-swap. Appending the
// snapshot is part of the same SQL statement, so a failed insert leaves the
// parent pointer unchanged even before the surrounding transaction rolls
// back. No row is returned when the expected version lost a race.
func (q *Queries) AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrganizationNeedParams) (string, error) {
row := q.db.QueryRow(ctx, advanceOrganizationNeed,
arg.RequirementsVersion,
arg.UpdatedAt,
arg.OrganizationID,
arg.NeedID,
arg.ExpectedVersion,
arg.NextVersion,
arg.Snapshot,
)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
const insertOrganizationNeed = `-- name: InsertOrganizationNeed :exec
INSERT INTO organization_needs (
id,
organization_id,
current_version,
requirements_version,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6
)
`
type InsertOrganizationNeedParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// The parent and first immutable snapshot are inserted in one caller-owned
// transaction. Deferred version references are checked when it commits.
func (q *Queries) InsertOrganizationNeed(ctx context.Context, arg InsertOrganizationNeedParams) error {
_, err := q.db.Exec(ctx, insertOrganizationNeed,
arg.ID,
arg.OrganizationID,
arg.CurrentVersion,
arg.RequirementsVersion,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganizationNeedVersion = `-- name: InsertOrganizationNeedVersion :exec
INSERT INTO organization_need_versions (
organization_id,
need_id,
version,
snapshot
) VALUES (
$1,
$2,
$3,
$4::jsonb
)
`
type InsertOrganizationNeedVersionParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
Version int64
Snapshot []byte
}
func (q *Queries) InsertOrganizationNeedVersion(ctx context.Context, arg InsertOrganizationNeedVersionParams) error {
_, err := q.db.Exec(ctx, insertOrganizationNeedVersion,
arg.OrganizationID,
arg.NeedID,
arg.Version,
arg.Snapshot,
)
return err
}
const readCurrentOrganizationNeed = `-- name: ReadCurrentOrganizationNeed :one
SELECT
need.organization_id,
need.id AS need_id,
need.current_version,
need.requirements_version,
need.created_at,
need.updated_at,
version.snapshot::text AS snapshot
FROM organization_needs AS need
INNER JOIN organization_need_versions AS version
ON version.organization_id = need.organization_id
AND version.need_id = need.id
AND version.version = need.current_version
WHERE
need.organization_id = $1
AND need.id = $2
`
type ReadCurrentOrganizationNeedParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
}
type ReadCurrentOrganizationNeedRow struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Snapshot string
}
// Read one current version with its organization-scoped parent metadata.
func (q *Queries) ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error) {
row := q.db.QueryRow(ctx, readCurrentOrganizationNeed, arg.OrganizationID, arg.NeedID)
var i ReadCurrentOrganizationNeedRow
err := row.Scan(
&i.OrganizationID,
&i.NeedID,
&i.CurrentVersion,
&i.RequirementsVersion,
&i.CreatedAt,
&i.UpdatedAt,
&i.Snapshot,
)
return i, err
}
const readOrganizationNeedVersion = `-- name: ReadOrganizationNeedVersion :one
SELECT snapshot::text AS snapshot
FROM organization_need_versions
WHERE
organization_id = $1
AND need_id = $2
AND version = $3
`
type ReadOrganizationNeedVersionParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
Version int64
}
// Read one historical version without exposing another organization's record.
func (q *Queries) ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error) {
row := q.db.QueryRow(ctx, readOrganizationNeedVersion, arg.OrganizationID, arg.NeedID, arg.Version)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
@@ -30,6 +30,11 @@ type Querier interface {
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error)
// The conditional parent update is the compare-and-swap. Appending the
// snapshot is part of the same SQL statement, so a failed insert leaves the
// parent pointer unchanged even before the surrounding transaction rolls
// back. No row is returned when the expected version lost a race.
AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrganizationNeedParams) (string, error)
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
@@ -353,6 +358,10 @@ type Querier interface {
// transaction at commit unless an active owner membership was inserted in
// it too.
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
// The parent and first immutable snapshot are inserted in one caller-owned
// transaction. Deferred version references are checked when it commits.
InsertOrganizationNeed(ctx context.Context, arg InsertOrganizationNeedParams) error
InsertOrganizationNeedVersion(ctx context.Context, arg InsertOrganizationNeedVersionParams) error
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
@@ -533,6 +542,10 @@ type Querier interface {
// lapse is computed by the caller from lapses_at and its clock and is never
// written.
ReadCandidateSearchStatus(ctx context.Context, userID pgtype.UUID) (CandidateSearchStatus, error)
// Read one current version with its organization-scoped parent metadata.
ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error)
// Read one historical version without exposing another organization's record.
ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error)
// The organization-facing read of a candidate's publication: the effective
// view (published and backed by an unrevoked C2) and no hiding of the reading
// organization. No row means the organization reads nothing, whichever of