feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,183 @@
package postgres
import (
"context"
"errors"
"fmt"
"math"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func (repository assessmentAttemptRepository) GetAvailabilityActiveAttempt(
ctx context.Context,
userID uuid.UUID,
specialization domain.SpecializationCode,
) (outbound.AssessmentActiveAttemptSummary, bool, error) {
const location = "assessmentAttemptRepository.GetAvailabilityActiveAttempt"
if userID == uuid.Nil || !specialization.IsKnown() {
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - candidate track is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
}
row, err := repository.queries.GetAssessmentAvailabilityActiveAttempt(ctx, sqlc.GetAssessmentAvailabilityActiveAttemptParams{
UserID: pgUUID(userID), Specialization: pgText(string(specialization)),
})
if errors.Is(err, pgx.ErrNoRows) {
return outbound.AssessmentActiveAttemptSummary{}, false, nil
}
if err != nil {
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - read active attempt: %w", location, mapAssessmentAttemptError(err))
}
if !row.ID.Valid || row.ID.Bytes == uuid.Nil || !row.ExpiresAt.Valid {
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - active attempt summary is invalid", location)
}
return outbound.AssessmentActiveAttemptSummary{
ID: domain.AssessmentAttemptID(row.ID.Bytes), ExpiresAt: row.ExpiresAt.Time,
}, true, nil
}
func (repository assessmentAttemptRepository) ListAvailabilityRootSummaries(
ctx context.Context,
userID uuid.UUID,
specialization domain.SpecializationCode,
since time.Time,
) ([]outbound.AssessmentRootAvailabilitySummary, error) {
const location = "assessmentAttemptRepository.ListAvailabilityRootSummaries"
if userID == uuid.Nil || !specialization.IsKnown() || since.IsZero() {
return nil, fmt.Errorf("%s - candidate track and horizon are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
}
rows, err := repository.queries.ListAssessmentAvailabilityRootSummaries(ctx, sqlc.ListAssessmentAvailabilityRootSummariesParams{
UserID: pgUUID(userID), Specialization: pgText(string(specialization)), Since: pgTime(since),
})
if err != nil {
return nil, fmt.Errorf("%s - read root summaries: %w", location, mapAssessmentAttemptError(err))
}
summaries := make([]outbound.AssessmentRootAvailabilitySummary, 0, len(rows))
for _, row := range rows {
summary, err := restoreAvailabilityRootSummary(row)
if err != nil {
return nil, fmt.Errorf("%s - restore root summary: %w", location, err)
}
summaries = append(summaries, summary)
}
return summaries, nil
}
func restoreAvailabilityRootSummary(
row sqlc.ListAssessmentAvailabilityRootSummariesRow,
) (outbound.AssessmentRootAvailabilitySummary, error) {
if !validAvailabilityRootSummary(row) {
return outbound.AssessmentRootAvailabilitySummary{}, errors.New("stored assessment root summary is invalid")
}
rootGrade := domain.GradeCode(row.RootTargetGrade.String)
latestGrade := domain.GradeCode(row.LatestTargetGrade.String)
return outbound.AssessmentRootAvailabilitySummary{
RootTargetGrade: rootGrade, RootCreatedAt: row.RootCreatedAt.Time,
RootUpdatedAt: row.RootUpdatedAt.Time, RootExpiresAt: row.RootExpiresAt.Time,
RootState: domain.AssessmentAttemptState(row.RootState), RootOutcome: domain.AssessmentAttemptOutcome(row.RootOutcome.String),
RootChainDeadline: row.RootChainDeadline.Time, LatestTargetGrade: latestGrade,
LatestUpdatedAt: row.LatestUpdatedAt.Time, LatestExpiresAt: row.LatestExpiresAt.Time,
LatestState: domain.AssessmentAttemptState(row.LatestState), LatestOutcome: domain.AssessmentAttemptOutcome(row.LatestOutcome.String),
LatestChainDeadline: row.LatestChainDeadline.Time, LatestPlatformError: row.LatestPlatformError,
}, nil
}
func validAvailabilityRootSummary(row sqlc.ListAssessmentAvailabilityRootSummariesRow) bool {
rootGrade, latestGrade := domain.GradeCode(row.RootTargetGrade.String), domain.GradeCode(row.LatestTargetGrade.String)
return row.RootTargetGrade.Valid && rootGrade.IsKnown() && row.LatestTargetGrade.Valid && latestGrade.IsKnown() &&
row.RootCreatedAt.Valid && row.RootUpdatedAt.Valid && row.RootExpiresAt.Valid && row.RootChainDeadline.Valid &&
row.LatestUpdatedAt.Valid && row.LatestExpiresAt.Valid && row.LatestChainDeadline.Valid &&
validAvailabilityAttemptState(row.RootState) && validAvailabilityAttemptState(row.LatestState) &&
validAvailabilityOutcome(row.RootOutcome) && validAvailabilityOutcome(row.LatestOutcome)
}
func (repository assessmentAttemptRepository) GetRootQuotaSnapshot(
ctx context.Context,
userID uuid.UUID,
since, asOf time.Time,
window time.Duration,
maxAttempts int32,
) (outbound.AssessmentRootQuotaSnapshot, error) {
const location = "assessmentAttemptRepository.GetRootQuotaSnapshot"
if userID == uuid.Nil || since.IsZero() || asOf.IsZero() || !asOf.After(since) || window <= 0 ||
maxAttempts < 1 || window%time.Second != 0 {
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - candidate and quota window are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
}
seconds := window.Seconds()
if math.IsInf(seconds, 0) || math.IsNaN(seconds) {
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - quota window exceeds supported precision: %w", location, domain.ErrInvalidAssessmentAttempt)
}
row, err := repository.queries.GetAssessmentRootQuotaAvailability(ctx, sqlc.GetAssessmentRootQuotaAvailabilityParams{
MaxAttempts: int64(maxAttempts), WindowSeconds: seconds, UserID: pgUUID(userID),
Since: pgTime(since), AsOf: pgTime(asOf),
})
if err != nil {
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - read root quota: %w", location, mapAssessmentAttemptError(err))
}
if row.AttemptCount < 0 || row.AttemptCount > math.MaxInt32 {
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - root quota count is outside the supported range", location)
}
snapshot := outbound.AssessmentRootQuotaSnapshot{Count: int32(row.AttemptCount)}
if row.AvailableAt.Valid {
availableAt := row.AvailableAt.Time
snapshot.AvailableAt = &availableAt
}
return snapshot, nil
}
func (repository assessmentAttemptRepository) ListDisclosedFamilyKeys(
ctx context.Context,
userID uuid.UUID,
since time.Time,
) ([]domain.AssessmentFamilyKey, error) {
const location = "assessmentAttemptRepository.ListDisclosedFamilyKeys"
if userID == uuid.Nil || since.IsZero() {
return nil, fmt.Errorf("%s - candidate and disclosure horizon are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
}
rows, err := repository.queries.ListAssessmentDisclosedFamilyKeys(ctx, sqlc.ListAssessmentDisclosedFamilyKeysParams{
UserID: pgUUID(userID), Since: pgTime(since),
})
if err != nil {
return nil, fmt.Errorf("%s - read disclosed family keys: %w", location, mapAssessmentAttemptError(err))
}
keys := make([]domain.AssessmentFamilyKey, 0, len(rows))
for _, storedKey := range rows {
key, err := domain.ParseAssessmentFamilyKey(storedKey)
if err != nil {
return nil, fmt.Errorf("%s - stored family key is invalid: %w", location, err)
}
keys = append(keys, key)
}
return keys, nil
}
func validAvailabilityAttemptState(state string) bool {
switch domain.AssessmentAttemptState(state) {
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize,
domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
domain.AssessmentAttemptStateInsufficientBank:
return true
default:
return false
}
}
func validAvailabilityOutcome(outcome pgtype.Text) bool {
if !outcome.Valid {
return true
}
switch domain.AssessmentAttemptOutcome(outcome.String) {
case domain.AssessmentAttemptOutcomeConfirmed, domain.AssessmentAttemptOutcomeNotConfirmed,
domain.AssessmentAttemptOutcomeNotDetermined, domain.AssessmentAttemptOutcomeDemonstration:
return domain.AssessmentAttemptOutcome(outcome.String) != domain.AssessmentAttemptOutcomeDemonstration
default:
return false
}
}
@@ -0,0 +1,241 @@
package postgres
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
type assessmentAttemptResultDocument struct {
SchemaVersion int32 `json:"schema_version"`
Attempt assessmentAttemptPublicResultDocument `json:"attempt"`
Pins assessmentAttemptResultPinsDocument `json:"pins"`
Outcome domain.AssessmentAttemptOutcome `json:"outcome"`
NotDeterminedReason string `json:"not_determined_reason,omitempty"`
BasicScore *domain.AssessmentBasicScore `json:"basic_score,omitempty"`
Rationale domain.AssessmentAttemptDecisionRationale `json:"rationale"`
Limitations []string `json:"limitations"`
Summary string `json:"summary,omitempty"`
DecidedAt time.Time `json:"decided_at"`
}
type assessmentAttemptPublicResultDocument struct {
ID uuid.UUID `json:"id"`
Version int64 `json:"version"`
Kind domain.AssessmentAttemptKind `json:"kind"`
Mode domain.AssessmentAttemptMode `json:"mode"`
State domain.AssessmentAttemptState `json:"state"`
Specialization *domain.SpecializationCode `json:"specialization"`
TargetGrade *domain.GradeCode `json:"target_grade"`
TaskLanguage *domain.TaskLanguageCode `json:"task_language"`
RootAttemptID *uuid.UUID `json:"root_attempt_id,omitempty"`
ChainDeadline *time.Time `json:"chain_deadline,omitempty"`
PolicyVersion int32 `json:"policy_version"`
BankVersion string `json:"bank_version"`
AlgorithmVersion string `json:"algorithm_version"`
StartedAt time.Time `json:"started_at"`
ExpiresAt time.Time `json:"expires_at"`
FinishedAt *time.Time `json:"finished_at"`
MaxItems int32 `json:"max_items"`
AnsweredItems int32 `json:"answered_items"`
SessionsUsed int32 `json:"sessions_used"`
MaxSessions int32 `json:"max_sessions"`
IdleTimeout int32 `json:"idle_timeout_seconds"`
CurrentItem *domain.AssessmentAttemptPublicItem `json:"current_item"`
Practices []domain.AssessmentAttemptPublicPractice `json:"practices"`
}
type assessmentAttemptResultPinsDocument struct {
ProductPolicyVersionID uuid.UUID `json:"product_policy_version_id"`
ProductPolicyVersion int32 `json:"product_policy_version"`
GradingPolicyVersionID *uuid.UUID `json:"grading_policy_version_id,omitempty"`
OpeningID *uuid.UUID `json:"opening_id,omitempty"`
OpeningManifestHash *string `json:"opening_manifest_sha256,omitempty"`
TrainingBindingID *uuid.UUID `json:"training_binding_id,omitempty"`
TrainingManifestHash *string `json:"training_manifest_sha256,omitempty"`
BankVersion string `json:"bank_version"`
AlgorithmVersion string `json:"algorithm_version"`
}
func marshalAssessmentAttemptResultDocument(result domain.AssessmentAttemptResultSnapshot) ([]byte, error) {
const location = "postgres.marshalAssessmentAttemptResultDocument"
validated, err := domain.RestoreAssessmentAttemptResultSnapshot(result)
if err != nil {
return nil, fmt.Errorf("%s - validate result: %w", location, err)
}
document := assessmentAttemptResultDocumentFromSnapshot(validated)
encoded, err := json.Marshal(document)
if err != nil || len(encoded) > 65536 {
return nil, fmt.Errorf("%s - encode bounded result: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return encoded, nil
}
func decodeAssessmentAttemptResultDocument(encoded []byte) (domain.AssessmentAttemptResultSnapshot, error) {
const location = "postgres.decodeAssessmentAttemptResultDocument"
if len(encoded) == 0 || len(encoded) > 65536 || !json.Valid(encoded) {
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - stored document is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
}
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.DisallowUnknownFields()
var document assessmentAttemptResultDocument
if err := decoder.Decode(&document); err != nil {
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - decode stored document: %w", location, domain.ErrInvalidAssessmentAttempt)
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - stored document has trailing data: %w", location, domain.ErrInvalidAssessmentAttempt)
}
result, err := assessmentAttemptResultSnapshotFromDocument(document)
if err != nil {
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - restore version pins: %w", location, err)
}
validated, err := domain.RestoreAssessmentAttemptResultSnapshot(result)
if err != nil {
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - validate stored result: %w", location, err)
}
return validated, nil
}
func assessmentAttemptResultDocumentFromSnapshot(
result domain.AssessmentAttemptResultSnapshot,
) assessmentAttemptResultDocument {
attempt := result.Attempt
documentAttempt := assessmentAttemptPublicResultDocument{
ID: attempt.ID.UUID(), Version: attempt.Version, Kind: attempt.Kind, Mode: attempt.Mode,
State: attempt.State, Specialization: attempt.Specialization, TargetGrade: attempt.TargetGrade,
TaskLanguage: attempt.TaskLanguage, ChainDeadline: attempt.ChainDeadline,
PolicyVersion: attempt.PolicyVersion, BankVersion: attempt.BankVersion,
AlgorithmVersion: attempt.AlgorithmVersion, StartedAt: attempt.StartedAt,
ExpiresAt: attempt.ExpiresAt, FinishedAt: attempt.FinishedAt,
MaxItems: attempt.MaxItems, AnsweredItems: attempt.AnsweredItems,
SessionsUsed: attempt.SessionsUsed, MaxSessions: attempt.MaxSessions,
IdleTimeout: attempt.IdleTimeout, CurrentItem: attempt.CurrentItem, Practices: attempt.Practices,
}
if attempt.RootAttemptID != nil {
rootID := attempt.RootAttemptID.UUID()
documentAttempt.RootAttemptID = &rootID
}
pins := result.Pins
gradingPolicyVersionID := optionalAssessmentPolicyVersionUUID(pins.GradingPolicyVersionID)
openingID := optionalAssessmentUUID(pins.OpeningID)
openingManifestHash := optionalAssessmentDigest(pins.OpeningManifestHash)
trainingBindingID := optionalAssessmentUUID(pins.TrainingBindingID)
trainingManifestHash := optionalAssessmentDigest(pins.TrainingManifestHash)
return assessmentAttemptResultDocument{
SchemaVersion: result.SchemaVersion, Attempt: documentAttempt,
Pins: assessmentAttemptResultPinsDocument{
ProductPolicyVersionID: uuid.UUID(pins.ProductPolicyVersionID), ProductPolicyVersion: pins.ProductPolicyVersion,
GradingPolicyVersionID: gradingPolicyVersionID, OpeningID: openingID,
OpeningManifestHash: openingManifestHash, TrainingBindingID: trainingBindingID,
TrainingManifestHash: trainingManifestHash, BankVersion: pins.BankVersion,
AlgorithmVersion: pins.AlgorithmVersion,
},
Outcome: result.Outcome, NotDeterminedReason: result.NotDeterminedReason,
BasicScore: result.BasicScore, Rationale: result.Rationale,
Limitations: result.Limitations, Summary: result.Summary, DecidedAt: result.DecidedAt,
}
}
func assessmentAttemptResultSnapshotFromDocument(
document assessmentAttemptResultDocument,
) (domain.AssessmentAttemptResultSnapshot, error) {
attempt := document.Attempt
snapshotAttempt := domain.AssessmentAttemptPublicSnapshot{
ID: domain.AssessmentAttemptID(attempt.ID), Version: attempt.Version, Kind: attempt.Kind,
Mode: attempt.Mode, State: attempt.State, Specialization: attempt.Specialization,
TargetGrade: attempt.TargetGrade, TaskLanguage: attempt.TaskLanguage,
ChainDeadline: attempt.ChainDeadline, PolicyVersion: attempt.PolicyVersion,
BankVersion: attempt.BankVersion, AlgorithmVersion: attempt.AlgorithmVersion,
StartedAt: attempt.StartedAt, ExpiresAt: attempt.ExpiresAt, FinishedAt: attempt.FinishedAt,
MaxItems: attempt.MaxItems, AnsweredItems: attempt.AnsweredItems,
SessionsUsed: attempt.SessionsUsed, MaxSessions: attempt.MaxSessions,
IdleTimeout: attempt.IdleTimeout, CurrentItem: attempt.CurrentItem, Practices: attempt.Practices,
}
if attempt.RootAttemptID != nil {
rootID := domain.AssessmentAttemptID(*attempt.RootAttemptID)
snapshotAttempt.RootAttemptID = &rootID
}
pins := document.Pins
openingManifestHash, err := restoreOptionalAssessmentDigest(pins.OpeningManifestHash)
if err != nil {
return domain.AssessmentAttemptResultSnapshot{}, err
}
trainingManifestHash, err := restoreOptionalAssessmentDigest(pins.TrainingManifestHash)
if err != nil {
return domain.AssessmentAttemptResultSnapshot{}, err
}
return domain.AssessmentAttemptResultSnapshot{
SchemaVersion: document.SchemaVersion, Attempt: snapshotAttempt,
Pins: domain.AssessmentAttemptResultPins{
ProductPolicyVersionID: domain.PolicyVersionID(pins.ProductPolicyVersionID),
ProductPolicyVersion: pins.ProductPolicyVersion,
GradingPolicyVersionID: assessmentPolicyVersionIDFromOptionalUUID(pins.GradingPolicyVersionID),
OpeningID: assessmentUUIDFromOptional(pins.OpeningID), OpeningManifestHash: openingManifestHash,
TrainingBindingID: assessmentUUIDFromOptional(pins.TrainingBindingID), TrainingManifestHash: trainingManifestHash,
BankVersion: pins.BankVersion, AlgorithmVersion: pins.AlgorithmVersion,
},
Outcome: document.Outcome, NotDeterminedReason: document.NotDeterminedReason,
BasicScore: document.BasicScore, Rationale: document.Rationale,
Limitations: document.Limitations, Summary: document.Summary, DecidedAt: document.DecidedAt,
}, nil
}
func optionalAssessmentPolicyVersionUUID(value domain.PolicyVersionID) *uuid.UUID {
if value == domain.PolicyVersionID(uuid.Nil) {
return nil
}
id := uuid.UUID(value)
return &id
}
func optionalAssessmentUUID(value uuid.UUID) *uuid.UUID {
if value == uuid.Nil {
return nil
}
return &value
}
func optionalAssessmentDigest(value [sha256.Size]byte) *string {
if value == [sha256.Size]byte{} {
return nil
}
digest := hex.EncodeToString(value[:])
return &digest
}
func assessmentPolicyVersionIDFromOptionalUUID(value *uuid.UUID) domain.PolicyVersionID {
if value == nil {
return domain.PolicyVersionID(uuid.Nil)
}
return domain.PolicyVersionID(*value)
}
func assessmentUUIDFromOptional(value *uuid.UUID) uuid.UUID {
if value == nil {
return uuid.Nil
}
return *value
}
func restoreOptionalAssessmentDigest(value *string) ([sha256.Size]byte, error) {
if value == nil {
return [sha256.Size]byte{}, nil
}
digest, err := hex.DecodeString(*value)
if err != nil || len(digest) != sha256.Size || hex.EncodeToString(digest) != *value {
return [sha256.Size]byte{}, domain.ErrInvalidAssessmentAttempt
}
var restored [sha256.Size]byte
copy(restored[:], digest)
return restored, nil
}
@@ -0,0 +1,99 @@
package postgres
import (
"encoding/hex"
"encoding/json"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func TestAssessmentAttemptResultDocumentUsesNullableUUIDPins(t *testing.T) {
attemptID := uuid.New()
productPolicyID := uuid.New()
gradingPolicyID := uuid.New()
openingID := uuid.New()
trainingBindingID := uuid.New()
openingHash := [32]byte{1, 2, 3}
trainingHash := [32]byte{4, 5, 6}
tests := []struct {
name string
pins domain.AssessmentAttemptResultPins
presentPinFields []string
absentPinFields []string
}{
{
name: "real assessment",
pins: domain.AssessmentAttemptResultPins{
ProductPolicyVersionID: domain.PolicyVersionID(productPolicyID), ProductPolicyVersion: 2,
GradingPolicyVersionID: domain.PolicyVersionID(gradingPolicyID), OpeningID: openingID,
OpeningManifestHash: openingHash, BankVersion: "bank.v1", AlgorithmVersion: "demo_basic.v1",
},
presentPinFields: []string{productPolicyID.String(), gradingPolicyID.String(), openingID.String(), hex.EncodeToString(openingHash[:])},
absentPinFields: []string{trainingBindingID.String(), "00000000-0000-0000-0000-000000000000"},
},
{
name: "express training",
pins: domain.AssessmentAttemptResultPins{
ProductPolicyVersionID: domain.PolicyVersionID(productPolicyID), ProductPolicyVersion: 2,
TrainingBindingID: trainingBindingID, TrainingManifestHash: trainingHash,
BankVersion: "bank.v1", AlgorithmVersion: "demo_express.v1",
},
presentPinFields: []string{productPolicyID.String(), trainingBindingID.String(), hex.EncodeToString(trainingHash[:])},
absentPinFields: []string{gradingPolicyID.String(), openingID.String(), "00000000-0000-0000-0000-000000000000"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
document := assessmentAttemptResultDocumentFromSnapshot(domain.AssessmentAttemptResultSnapshot{
Attempt: domain.AssessmentAttemptPublicSnapshot{ID: domain.AssessmentAttemptID(attemptID)},
Pins: test.pins,
})
encoded, err := json.Marshal(document)
if err != nil {
t.Fatalf("marshal result document: %v", err)
}
var decoded map[string]any
if err := json.Unmarshal(encoded, &decoded); err != nil {
t.Fatalf("decode result document: %v", err)
}
pins, ok := decoded["pins"].(map[string]any)
if !ok || pins["product_policy_version_id"] != productPolicyID.String() {
t.Fatalf("result pins = %#v, want UUID string for product policy", decoded["pins"])
}
for _, value := range test.presentPinFields {
if !strings.Contains(string(encoded), `"`+value+`"`) {
t.Errorf("encoded result does not contain string pin %q: %s", value, encoded)
}
}
for _, value := range test.absentPinFields {
if strings.Contains(string(encoded), value) {
t.Errorf("encoded result contains unrelated or zero pin %q: %s", value, encoded)
}
}
restored, err := assessmentAttemptResultSnapshotFromDocument(document)
if err != nil || restored.Pins != test.pins {
t.Fatalf("restore result pins = %+v, error %v, want %+v", restored.Pins, err, test.pins)
}
})
}
}
func TestRestoreAssessmentAttemptResultDocumentRejectsNoncanonicalPinHash(t *testing.T) {
productPolicyID := uuid.New()
openingID := uuid.New()
wrongHash := "01"
document := assessmentAttemptResultDocument{
Pins: assessmentAttemptResultPinsDocument{
ProductPolicyVersionID: productPolicyID,
OpeningID: &openingID,
OpeningManifestHash: &wrongHash,
},
}
if _, err := assessmentAttemptResultSnapshotFromDocument(document); err == nil {
t.Fatal("assessmentAttemptResultSnapshotFromDocument() accepted an invalid pin hash")
}
}
@@ -0,0 +1,62 @@
package postgres
import (
"context"
"fmt"
"time"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func (repository assessmentBankRepository) ListCurrentAssessmentAvailabilitySelections(
ctx context.Context,
asOf time.Time,
) ([]outbound.AssessmentAvailabilitySelection, error) {
const location = "assessmentBankRepository.ListCurrentAssessmentAvailabilitySelections"
if asOf.IsZero() {
return nil, fmt.Errorf("%s - database time is required: %w", location, domain.ErrInvalidAssessmentFamily)
}
rows, err := repository.queries.ListCurrentAssessmentAvailabilitySelections(ctx, pgTime(asOf))
if err != nil {
return nil, fmt.Errorf("%s - select current bindings: %w", location, mapAssessmentError(err))
}
selections := make([]outbound.AssessmentAvailabilitySelection, 0, len(rows))
for _, row := range rows {
metadataRow := sqlc.ListCurrentSpecializationAvailabilityRow{
OpeningID: row.OpeningID, Category: row.Category, PolicyVersionID: row.PolicyVersionID,
RequiredFamilies: row.RequiredFamilies, PublishedCount: row.PublishedCount,
EffectivePolicyID: row.EffectivePolicyID, Specialization: row.Specialization,
Grade: row.Grade, TaskLanguages: row.TaskLanguages,
PublishedManifestSha256: row.PublishedManifestSha256, PublishedManifest: row.PublishedManifest,
}
metadata, current, err := currentAssessmentCatalogMetadata(metadataRow)
if err != nil {
return nil, fmt.Errorf("%s - validate reviewed binding: %w", location, err)
}
if !current {
continue
}
if !row.OpeningID.Valid || row.OpeningID.Bytes == [16]byte{} ||
!row.EffectivePolicyVersion.Valid || row.EffectivePolicyVersion.Int32 < 1 {
return nil, fmt.Errorf("%s - current binding identity is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
}
manifest, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
if err != nil {
return nil, fmt.Errorf("%s - decode verified family manifest: %w", location, err)
}
familyKeys := make([]domain.AssessmentFamilyKey, 0, len(manifest))
for _, entry := range manifest {
familyKeys = append(familyKeys, entry.FamilyKey)
}
selections = append(selections, outbound.AssessmentAvailabilitySelection{
OpeningID: row.OpeningID.Bytes, Category: domain.AssessmentCategory(row.Category),
ProductPolicyVersionID: domain.PolicyVersionID(row.EffectivePolicyID.Bytes),
ProductPolicyVersion: row.EffectivePolicyVersion.Int32,
Specialization: metadata.Specialization(), Grade: metadata.Grade(),
TaskLanguages: metadata.TaskLanguages(), FamilyKeys: familyKeys,
})
}
return selections, nil
}
@@ -43,6 +43,19 @@ func TestMapAssessmentErrorRecognizesBankConstraints(t *testing.T) {
}
}
func TestPinnedFamilyLookupMapsOnlyMissingFamiliesToUnavailable(t *testing.T) {
missing := mapPinnedFamilyLookupError(errors.Join(errors.New("select pinned family"), outbound.ErrAssessmentFamilyNotFound))
if !errors.Is(missing, outbound.ErrAssessmentSelectionUnavailable) {
t.Fatalf("map missing pinned family error = %v, want ErrAssessmentSelectionUnavailable", missing)
}
transient := errors.New("database connection reset")
got := mapPinnedFamilyLookupError(transient)
if !errors.Is(got, transient) || errors.Is(got, outbound.ErrAssessmentSelectionUnavailable) {
t.Fatalf("map transient pinned family error = %v, want original infrastructure error", got)
}
}
func TestLockCategoryWorksOnlyInsideATransaction(t *testing.T) {
// A repository without queries proves that no statement runs.
standalone := assessmentBankRepository{transactional: false}
@@ -13,6 +13,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
@@ -94,6 +95,419 @@ func (repository assessmentBankRepository) ListCurrentSpecializationAvailability
return buildAssessmentCatalogAvailability(aggregates), nil
}
func (repository assessmentBankRepository) ResolveCurrentSelection(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
language *domain.TaskLanguageCode,
) (outbound.AssessmentBankSelection, error) {
const location = "assessmentBankRepository.ResolveCurrentSelection"
if !repository.transactional {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - current selection needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
}
initial, err := repository.currentSelectionRows(ctx, specialization, grade, language)
if err != nil {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - read candidate selection: %w", location, err)
}
if len(initial) == 0 {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - no current reviewed selection: %w", location, outbound.ErrAssessmentSelectionUnavailable)
}
if len(initial) > 1 {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - multiple current reviewed selections: %w", location, outbound.ErrAssessmentSelectionAmbiguous)
}
category := domain.AssessmentCategory(initial[0].Category)
if err := repository.LockCategory(ctx, category); err != nil {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - lock selected category: %w", location, err)
}
current, err := repository.currentSelectionRows(ctx, specialization, grade, language)
if err != nil {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - recheck candidate selection: %w", location, err)
}
if len(current) == 0 || len(current) > 1 || current[0].Category != string(category) ||
current[0].OpeningID.Bytes != initial[0].OpeningID.Bytes {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - selection changed while locking: %w", location, outbound.ErrAssessmentSelectionUnavailable)
}
return repository.currentSelectionFromRow(ctx, current[0])
}
func (repository assessmentBankRepository) currentSelectionRows(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
language *domain.TaskLanguageCode,
) ([]sqlc.ResolveCurrentAssessmentSelectionRow, error) {
var selectedLanguage pgtype.Text
if language != nil {
selectedLanguage = pgText(string(*language))
}
rows, err := repository.queries.ResolveCurrentAssessmentSelection(ctx, sqlc.ResolveCurrentAssessmentSelectionParams{
Specialization: string(specialization), Grade: string(grade), TaskLanguage: selectedLanguage,
})
if err != nil {
return nil, mapAssessmentError(err)
}
current := make([]sqlc.ResolveCurrentAssessmentSelectionRow, 0, len(rows))
for _, row := range rows {
metadata, available, err := currentAssessmentSelectionMetadata(row)
if err != nil {
return nil, fmt.Errorf("validate current catalog binding: %w", err)
}
if !available || metadata.Specialization() != specialization || metadata.Grade() != grade ||
!assessmentCatalogLanguageMatches(metadata.TaskLanguages(), language) {
continue
}
current = append(current, row)
}
return current, nil
}
func currentAssessmentSelectionMetadata(
row sqlc.ResolveCurrentAssessmentSelectionRow,
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
return currentAssessmentCatalogMetadata(sqlc.ListCurrentSpecializationAvailabilityRow{
OpeningID: row.OpeningID, Category: row.Category, PolicyVersionID: row.PolicyVersionID,
RequiredFamilies: row.RequiredFamilies, PublishedCount: row.PublishedCount,
EffectivePolicyID: row.EffectivePolicyID, Specialization: row.Specialization,
Grade: row.Grade, TaskLanguages: row.TaskLanguages,
PublishedManifestSha256: row.PublishedManifestSha256, PublishedManifest: row.PublishedManifest,
})
}
func assessmentCatalogLanguageMatches(
available []domain.TaskLanguageCode,
requested *domain.TaskLanguageCode,
) bool {
if requested == nil {
return len(available) == 0
}
return slices.Contains(available, *requested)
}
func (repository assessmentBankRepository) currentSelectionFromRow(
ctx context.Context,
row sqlc.ResolveCurrentAssessmentSelectionRow,
) (outbound.AssessmentBankSelection, error) {
const location = "assessmentBankRepository.currentSelectionFromRow"
if !row.EffectivePolicyID.Valid || !row.EffectivePolicyVersion.Valid || row.EffectivePolicyVersion.Int32 < 1 {
return outbound.AssessmentBankSelection{}, outbound.ErrAssessmentSelectionUnavailable
}
opening, err := repository.selectionOpening(ctx, row)
if err != nil {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - validate current opening: %w", location, err)
}
entries, manifestSHA, err := currentSelectionManifest(row)
if err != nil {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - validate current manifest: %w", location, err)
}
families, err := repository.resolveCurrentSelectionFamilies(ctx, opening.Category, entries)
if err != nil {
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - resolve pinned families: %w", location, err)
}
return outbound.AssessmentBankSelection{
Opening: opening, ProductPolicyVersionID: domain.PolicyVersionID(row.EffectivePolicyID.Bytes),
ProductPolicyVersion: row.EffectivePolicyVersion.Int32, ManifestSHA: manifestSHA, Families: families,
}, nil
}
func (repository assessmentBankRepository) selectionOpening(
ctx context.Context,
row sqlc.ResolveCurrentAssessmentSelectionRow,
) (domain.AssessmentCategoryOpening, error) {
opening, err := repository.GetCurrentCategoryOpening(ctx, domain.AssessmentCategory(row.Category))
if err != nil {
return domain.AssessmentCategoryOpening{}, err
}
if opening.ID != row.OpeningID.Bytes || opening.PolicyVersionID != domain.PolicyVersionID(row.PolicyVersionID.Bytes) ||
opening.RequiredFamilies != row.RequiredFamilies || row.PublishedCount < row.RequiredFamilies {
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentSelectionUnavailable
}
return opening, nil
}
func currentSelectionManifest(
row sqlc.ResolveCurrentAssessmentSelectionRow,
) ([]domain.AssessmentCategoryManifestEntry, [sha256.Size]byte, error) {
entries, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
if err != nil {
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
}
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
if err != nil || len(entries) != int(row.PublishedCount) || !slices.Equal(fingerprint[:], row.PublishedManifestSha256) {
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
}
return entries, fingerprint, nil
}
func (repository assessmentBankRepository) resolveCurrentSelectionFamilies(
ctx context.Context,
category domain.AssessmentCategory,
entries []domain.AssessmentCategoryManifestEntry,
) ([]domain.AssessmentFamily, error) {
families := make([]domain.AssessmentFamily, 0, len(entries))
for _, entry := range entries {
family, err := repository.GetFamilyVersion(ctx, entry.FamilyKey, entry.Version)
if err != nil {
return nil, mapPinnedFamilyLookupError(err)
}
hash := family.ContentHash()
if family.Category() != category || family.Lifecycle() != domain.AssessmentLifecyclePublished ||
family.ReviewStatus() != domain.AssessmentReviewApproved || !slices.Equal(hash[:], entry.ContentSHA256) {
return nil, outbound.ErrAssessmentSelectionUnavailable
}
families = append(families, family)
}
return families, nil
}
func mapPinnedFamilyLookupError(err error) error {
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
return outbound.ErrAssessmentSelectionUnavailable
}
return err
}
func (repository assessmentBankRepository) ResolveCurrentTrainingSelection(
ctx context.Context,
productPolicyID domain.PolicyVersionID,
productPolicyVersion int32,
) (outbound.AssessmentTrainingBankSelection, error) {
const location = "assessmentBankRepository.ResolveCurrentTrainingSelection"
if !repository.transactional {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - training selection needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
}
initial, err := repository.queries.ListCurrentAssessmentTrainingBindings(ctx)
if err != nil {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - read current bindings: %w", location, mapAssessmentError(err))
}
locked, err := repository.lockCurrentTrainingCategories(ctx, initial, productPolicyID, productPolicyVersion)
if err != nil {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - lock training categories: %w", location, err)
}
current, err := repository.queries.ListCurrentAssessmentTrainingBindings(ctx)
if err != nil {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - recheck current bindings: %w", location, mapAssessmentError(err))
}
selections, err := repository.currentTrainingSelections(ctx, current, locked, productPolicyID, productPolicyVersion)
if err != nil {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - validate current bindings: %w", location, err)
}
if len(selections) == 0 {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - no current reviewed training binding: %w", location, outbound.ErrAssessmentSelectionUnavailable)
}
if len(selections) > 1 {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - multiple current reviewed training bindings: %w", location, outbound.ErrAssessmentSelectionAmbiguous)
}
return selections[0], nil
}
func (repository assessmentBankRepository) lockCurrentTrainingCategories(
ctx context.Context,
rows []sqlc.ListCurrentAssessmentTrainingBindingsRow,
productPolicyID domain.PolicyVersionID,
productPolicyVersion int32,
) (map[domain.AssessmentCategory]struct{}, error) {
locked := make(map[domain.AssessmentCategory]struct{})
for _, row := range rows {
if !matchesProductPolicy(row.ProductPolicyVersionID, row.ProductPolicyVersion, productPolicyID, productPolicyVersion) {
continue
}
category := domain.AssessmentCategory(row.Category)
if _, exists := locked[category]; exists {
continue
}
if err := repository.LockCategory(ctx, category); err != nil {
return nil, err
}
locked[category] = struct{}{}
}
return locked, nil
}
func (repository assessmentBankRepository) currentTrainingSelections(
ctx context.Context,
rows []sqlc.ListCurrentAssessmentTrainingBindingsRow,
locked map[domain.AssessmentCategory]struct{},
productPolicyID domain.PolicyVersionID,
productPolicyVersion int32,
) ([]outbound.AssessmentTrainingBankSelection, error) {
selections := make([]outbound.AssessmentTrainingBankSelection, 0, len(rows))
for _, row := range rows {
if !matchesProductPolicy(row.ProductPolicyVersionID, row.ProductPolicyVersion, productPolicyID, productPolicyVersion) {
continue
}
category := domain.AssessmentCategory(row.Category)
if _, ok := locked[category]; !ok {
return nil, outbound.ErrAssessmentSelectionUnavailable
}
selection, err := repository.currentTrainingSelectionFromRow(ctx, row)
if errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) {
continue
}
if err != nil {
return nil, err
}
selections = append(selections, selection)
}
return selections, nil
}
func matchesProductPolicy(
rowID pgtype.UUID,
rowVersion int32,
policyID domain.PolicyVersionID,
policyVersion int32,
) bool {
return rowID.Bytes == uuid.UUID(policyID) && rowVersion == policyVersion
}
func (repository assessmentBankRepository) currentTrainingSelectionFromRow(
ctx context.Context,
row sqlc.ListCurrentAssessmentTrainingBindingsRow,
) (outbound.AssessmentTrainingBankSelection, error) {
const location = "assessmentBankRepository.currentTrainingSelectionFromRow"
category := domain.AssessmentCategory(row.Category)
entries, manifestSHA, err := repository.validateCurrentTrainingManifest(ctx, category, row)
if err != nil {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - validate current manifest: %w", location, err)
}
members, err := repository.queries.ListAssessmentTrainingBindingFamilies(ctx, pgUUID(row.ID.Bytes))
if err != nil {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - read pinned training families: %w", location, mapAssessmentError(err))
}
families, err := repository.resolveCurrentTrainingFamilies(ctx, category, entries, members)
if err != nil {
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - resolve pinned families: %w", location, err)
}
return outbound.AssessmentTrainingBankSelection{
BindingID: row.ID.Bytes, Category: category,
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
ProductPolicyVersion: row.ProductPolicyVersion, ManifestSHA: manifestSHA, Families: families,
}, nil
}
func (repository assessmentBankRepository) validateCurrentTrainingManifest(
ctx context.Context,
category domain.AssessmentCategory,
row sqlc.ListCurrentAssessmentTrainingBindingsRow,
) ([]domain.AssessmentCategoryManifestEntry, [sha256.Size]byte, error) {
entries, err := decodeAssessmentCategoryManifest(string(row.FamilyManifest))
if err != nil || len(entries) != int(row.ItemCount) {
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
}
manifestSHA, err := assessmentCategoryManifestFingerprint(entries)
if err != nil || !slices.Equal(manifestSHA[:], row.ManifestSha256) {
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
}
liveEntries, err := repository.currentPublishedManifestEntries(ctx, category)
if err != nil {
return nil, [sha256.Size]byte{}, err
}
liveHash, err := assessmentCategoryManifestFingerprint(liveEntries)
if err != nil || !assessmentManifestEntriesEqual(entries, liveEntries) || !slices.Equal(liveHash[:], row.ManifestSha256) {
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
}
return entries, manifestSHA, nil
}
func (repository assessmentBankRepository) currentPublishedManifestEntries(
ctx context.Context,
category domain.AssessmentCategory,
) ([]domain.AssessmentCategoryManifestEntry, error) {
rows, err := repository.queries.ReadPublishedAssessmentCategoryManifest(ctx, string(category))
if err != nil {
return nil, mapAssessmentError(err)
}
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
for _, row := range rows {
key, parseErr := domain.ParseAssessmentFamilyKey(row.FamilyKey)
if parseErr != nil || row.Version < 1 || len(row.ContentSha256) != sha256.Size {
return nil, domain.ErrInvalidAssessmentFamily
}
entries = append(entries, domain.AssessmentCategoryManifestEntry{
FamilyKey: key, Version: row.Version, ContentSHA256: slices.Clone(row.ContentSha256),
})
}
return entries, nil
}
func (repository assessmentBankRepository) resolveCurrentTrainingFamilies(
ctx context.Context,
category domain.AssessmentCategory,
entries []domain.AssessmentCategoryManifestEntry,
members []sqlc.ListAssessmentTrainingBindingFamiliesRow,
) ([]domain.AssessmentFamily, error) {
if len(members) != len(entries) {
return nil, outbound.ErrAssessmentSelectionUnavailable
}
sort.Slice(entries, func(i, j int) bool {
if entries[i].FamilyKey == entries[j].FamilyKey {
return entries[i].Version < entries[j].Version
}
return entries[i].FamilyKey < entries[j].FamilyKey
})
families := make([]domain.AssessmentFamily, 0, len(entries))
for index, entry := range entries {
family, err := repository.resolveTrainingFamily(ctx, category, entry, members[index], index)
if err != nil {
return nil, err
}
families = append(families, family)
}
return families, nil
}
func (repository assessmentBankRepository) resolveTrainingFamily(
ctx context.Context,
category domain.AssessmentCategory,
entry domain.AssessmentCategoryManifestEntry,
member sqlc.ListAssessmentTrainingBindingFamiliesRow,
index int,
) (domain.AssessmentFamily, error) {
if member.Ordinal < 1 || int64(member.Ordinal) != int64(index)+1 || member.FamilyKey != string(entry.FamilyKey) ||
member.FamilyVersion != entry.Version || !slices.Equal(member.ContentSha256, entry.ContentSHA256) {
return domain.AssessmentFamily{}, outbound.ErrAssessmentSelectionUnavailable
}
family, err := repository.GetFamilyVersion(ctx, entry.FamilyKey, entry.Version)
if err != nil {
return domain.AssessmentFamily{}, mapPinnedFamilyLookupError(err)
}
hash := family.ContentHash()
if family.ID().UUID() != member.FamilyID.Bytes || family.Category() != category ||
family.Lifecycle() != domain.AssessmentLifecyclePublished || family.ReviewStatus() != domain.AssessmentReviewApproved ||
!slices.Equal(hash[:], entry.ContentSHA256) {
return domain.AssessmentFamily{}, outbound.ErrAssessmentSelectionUnavailable
}
return family, nil
}
func assessmentManifestEntriesEqual(
left []domain.AssessmentCategoryManifestEntry,
right []domain.AssessmentCategoryManifestEntry,
) bool {
if len(left) != len(right) {
return false
}
canonical := func(entries []domain.AssessmentCategoryManifestEntry) []domain.AssessmentCategoryManifestEntry {
result := slices.Clone(entries)
sort.Slice(result, func(i, j int) bool {
if result[i].FamilyKey == result[j].FamilyKey {
return result[i].Version < result[j].Version
}
return result[i].FamilyKey < result[j].FamilyKey
})
return result
}
orderedLeft, orderedRight := canonical(left), canonical(right)
for index := range orderedLeft {
if orderedLeft[index].FamilyKey != orderedRight[index].FamilyKey ||
orderedLeft[index].Version != orderedRight[index].Version ||
!slices.Equal(orderedLeft[index].ContentSHA256, orderedRight[index].ContentSHA256) {
return false
}
}
return true
}
func currentAssessmentCatalogMetadata(
row sqlc.ListCurrentSpecializationAvailabilityRow,
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
@@ -0,0 +1,190 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const assessmentSignalBatchEventLimit = 50
var (
_ outbound.AssessmentSignalRepositories = (*UnitOfWork)(nil)
_ outbound.AssessmentSignalRepository = assessmentSignalRepository{}
)
func (unit *UnitOfWork) AssessmentSignals() outbound.AssessmentSignalRepository {
return assessmentSignalRepository{queries: unit.queries}
}
type assessmentSignalRepository struct {
queries *sqlc.Queries
}
func (repository assessmentSignalRepository) CountRecentOutcomes(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
since time.Time,
) (int64, time.Time, error) {
const location = "assessmentSignalRepository.CountRecentOutcomes"
if attemptID.IsZero() || since.IsZero() {
return 0, time.Time{}, fmt.Errorf("%s - attempt and window start are required: %w", location, domain.ErrInvalidAssessmentSignal)
}
row, err := repository.queries.CountRecentAssessmentSignalOutcomes(ctx, sqlc.CountRecentAssessmentSignalOutcomesParams{
AttemptID: pgUUID(attemptID.UUID()), Since: pgTime(since),
})
if err != nil {
return 0, time.Time{}, fmt.Errorf("%s - count recent receipts: %w", location, mapAssessmentError(err))
}
if row.OutcomeCount < 0 {
return 0, time.Time{}, fmt.Errorf("%s - stored receipt count is negative", location)
}
oldest, err := quotaWindowEarliest(row.OldestAt)
if err != nil {
return 0, time.Time{}, fmt.Errorf("%s - read oldest receipt: %w", location, err)
}
return row.OutcomeCount, oldest, nil
}
func (repository assessmentSignalRepository) CountAttemptEvents(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
) (int64, error) {
const location = "assessmentSignalRepository.CountAttemptEvents"
if attemptID.IsZero() {
return 0, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentSignal)
}
count, err := repository.queries.CountAssessmentSignalEvents(ctx, pgUUID(attemptID.UUID()))
if err != nil {
return 0, fmt.Errorf("%s - count stored events: %w", location, mapAssessmentError(err))
}
if count < 0 {
return 0, fmt.Errorf("%s - stored event count is negative", location)
}
return count, nil
}
func (repository assessmentSignalRepository) SaveBatch(ctx context.Context, batch domain.AssessmentSignalBatch) error {
const location = "assessmentSignalRepository.SaveBatch"
if _, err := domain.NewAssessmentSignalBatch(batch.ID(), batch.AttemptID(), batch.ReceivedAt(), batch.Events()); err != nil {
return fmt.Errorf("%s - batch is invalid: %w", location, err)
}
events := batch.Events()
eventCount, err := assessmentSignalBatchEventCount(events)
if err != nil {
return fmt.Errorf("%s - event count is outside the database bound: %w", location, err)
}
if err := repository.queries.InsertAssessmentSignalBatch(ctx, sqlc.InsertAssessmentSignalBatchParams{
ID: pgUUID(batch.ID()), AttemptID: pgUUID(batch.AttemptID().UUID()), ReceivedAt: pgTime(batch.ReceivedAt()),
EventCount: eventCount,
}); err != nil {
return fmt.Errorf("%s - insert batch receipt: %w", location, mapAssessmentError(err))
}
for index, event := range events {
duration, hasDuration := event.DurationMS()
size, hasSize := event.SizeBytes()
if err := repository.queries.InsertAssessmentSignalEvent(ctx, sqlc.InsertAssessmentSignalEventParams{
BatchID: pgUUID(batch.ID()), AttemptID: pgUUID(batch.AttemptID().UUID()), Ordinal: int32(index + 1),
ItemInstanceID: pgUUID(event.ItemInstanceID()), Kind: string(event.Kind()), OccurredAt: pgTime(event.OccurredAt()),
DurationMs: nullableSignalMeasurement(duration, hasDuration), SizeBytes: nullableSignalMeasurement(size, hasSize),
}); err != nil {
return fmt.Errorf("%s - insert event metadata: %w", location, mapAssessmentError(err))
}
}
return nil
}
func assessmentSignalBatchEventCount(events []domain.AssessmentSignalEvent) (int32, error) {
if len(events) < 1 || len(events) > assessmentSignalBatchEventLimit {
return 0, domain.ErrInvalidAssessmentSignal
}
var count int32
for range events {
count++
}
return count, nil
}
func (repository assessmentSignalRepository) SaveOutcome(
ctx context.Context,
scope outbound.AssessmentAttemptIdempotencyScope,
attemptID domain.AssessmentAttemptID,
receipt domain.AssessmentSignalReceipt,
) error {
const location = "assessmentSignalRepository.SaveOutcome"
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) || attemptID.IsZero() {
return fmt.Errorf("%s - scope and attempt ID are required: %w", location, domain.ErrInvalidAssessmentSignal)
}
if _, err := domain.NewAssessmentSignalReceipt(receipt.Status(), receipt.AcceptedEvents(), receipt.ReceivedAt()); err != nil {
return fmt.Errorf("%s - receipt is invalid: %w", location, err)
}
if err := repository.queries.InsertAssessmentSignalOutcome(ctx, sqlc.InsertAssessmentSignalOutcomeParams{
ScopeHash: scope[:], AttemptID: pgUUID(attemptID.UUID()), Status: string(receipt.Status()),
AcceptedEvents: receipt.AcceptedEvents(), ReceivedAt: pgTime(receipt.ReceivedAt()),
}); err != nil {
return fmt.Errorf("%s - insert immutable receipt: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentSignalRepository) DeleteExpiredOutcome(
ctx context.Context,
scope outbound.AssessmentAttemptIdempotencyScope,
) error {
const location = "assessmentSignalRepository.DeleteExpiredOutcome"
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) {
return fmt.Errorf("%s - scope is required: %w", location, domain.ErrInvalidAssessmentSignal)
}
if err := repository.queries.DeleteExpiredAssessmentSignalOutcome(ctx, scope[:]); err != nil {
return fmt.Errorf("%s - remove expired receipt: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentSignalRepository) GetOutcome(
ctx context.Context,
scope outbound.AssessmentAttemptIdempotencyScope,
) (domain.AssessmentSignalReceipt, error) {
const location = "assessmentSignalRepository.GetOutcome"
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - scope is required: %w", location, domain.ErrInvalidAssessmentSignal)
}
row, err := repository.queries.GetAssessmentSignalOutcome(ctx, scope[:])
if errors.Is(err, pgx.ErrNoRows) {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - receipt does not exist: %w", location, outbound.ErrAssessmentSignalOutcomeNotFound)
}
if err != nil {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - read immutable receipt: %w", location, mapAssessmentError(err))
}
receivedAt, err := requiredSignalReceiptTime(row.ReceivedAt)
if err != nil {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - restore receipt time: %w", location, err)
}
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptStatus(row.Status), row.AcceptedEvents, receivedAt)
if err != nil {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - restore receipt: %w", location, err)
}
return receipt, nil
}
func nullableSignalMeasurement(value int32, valid bool) pgtype.Int4 {
if !valid {
return pgtype.Int4{}
}
return pgtype.Int4{Int32: value, Valid: true}
}
func requiredSignalReceiptTime(value pgtype.Timestamptz) (time.Time, error) {
if !value.Valid || value.Time.IsZero() {
return time.Time{}, domain.ErrInvalidAssessmentSignal
}
return value.Time.UTC(), nil
}
@@ -256,6 +256,22 @@ func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, pu
return consentRecordFromRow(consentRecordRow(row))
}
func (ledger consentLedger) LockCurrentForUse(
ctx context.Context,
subjectID uuid.UUID,
purpose domain.ConsentPurpose,
) (domain.ConsentRecord, error) {
const location = "consentLedger.LockCurrentForUse"
if subjectID == uuid.Nil || purpose != domain.ConsentPurposeAutoCategorization {
return domain.ConsentRecord{}, fmt.Errorf("%s - only a valid subject and C3 can authorize automated use: %w", location, domain.ErrInvalidConsent)
}
row, err := ledger.queries.LockCurrentConsentForUse(ctx, pgUUID(subjectID))
if err != nil {
return domain.ConsentRecord{}, fmt.Errorf("%s - lock current C3 record: %w", location, mapConsentNoRows(err, outbound.ErrConsentNotFound))
}
return consentRecordFromRow(consentRecordRow(row))
}
func (ledger consentLedger) LockRegistration(
ctx context.Context,
subjectID uuid.UUID,
@@ -18,12 +18,24 @@ import (
"lincodex/backend/internal/port/outbound"
)
var _ outbound.NeedRepository = needRepository{}
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
}
@@ -99,6 +111,129 @@ func (repository needRepository) GetVersion(
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,
@@ -216,7 +351,7 @@ func restoreNeedSnapshot(
version, requirementsVersion int64,
createdAt, updatedAt *time.Time,
) (domain.Need, error) {
if len(encoded) > domain.MaxNeedSnapshotBytes {
if len(encoded) > domain.MaxNeedSnapshotStorageBytes {
return domain.Need{}, fmt.Errorf("%s - stored snapshot exceeds its bound", location)
}
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
@@ -269,6 +404,9 @@ func mapNeedError(err error) error {
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)
}
@@ -316,6 +316,33 @@ func (repository organizationRepository) GetForMember(
return organization, membership, nil
}
func (repository organizationRepository) LockActiveMembership(
ctx context.Context,
organizationID, userID uuid.UUID,
) (domain.Membership, error) {
const location = "organizationRepository.LockActiveMembership"
row, err := repository.queries.LockActiveMembership(ctx, sqlc.LockActiveMembershipParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - lock active membership: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
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
}
// 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.
@@ -0,0 +1,207 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
"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"
)
var _ outbound.PrivacyCohortRepository = privacyCohortRepository{}
// PrivacyCohortStore reads the current visible candidate cohort outside a
// transaction. The single query provides one consistent publication and
// hidden-organization snapshot.
type PrivacyCohortStore struct {
queries *sqlc.Queries
}
func NewPrivacyCohortStore(pool *pgxpool.Pool) *PrivacyCohortStore {
return &PrivacyCohortStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
func (unit *UnitOfWork) PrivacyCohort() outbound.PrivacyCohortRepository {
return privacyCohortRepository{queries: unit.queries}
}
func (unit *UnitOfWork) PrivacyView() outbound.PrivacyViewRepository {
return privacyCohortRepository{queries: unit.queries}
}
func (store *PrivacyCohortStore) ListVisibleCandidateViewSources(
ctx context.Context,
organizationID uuid.UUID,
) ([]domain.CandidateViewSource, error) {
return (privacyCohortRepository{queries: store.queries}).ListVisibleCandidateViewSources(ctx, organizationID)
}
type privacyCohortRepository struct {
queries *sqlc.Queries
}
type privacyCohortCandidate struct {
id uuid.UUID
fields domain.CardFieldSet
claims []domain.StoredProfileClaim
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
workFormats []domain.QuestionnaireWorkFormat
}
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
ctx context.Context,
organizationID uuid.UUID,
) ([]domain.CandidateViewSource, error) {
const location = "privacyCohortRepository.ListVisibleCandidateViewSources"
if organizationID == uuid.Nil {
return nil, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
rows, err := repository.queries.ListVisibleCandidateViewSources(ctx, pgUUID(organizationID))
if err != nil {
return nil, fmt.Errorf("%s - select visible sources: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
if len(rows) == 0 {
return []domain.CandidateViewSource{}, nil
}
result := make([]domain.CandidateViewSource, 0, len(rows))
current := privacyCohortCandidate{}
for _, row := range rows {
candidateID, err := privacyCohortUUID(row.UserID)
if err != nil {
return nil, fmt.Errorf("%s - source identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
}
if current.id != uuid.Nil && current.id != candidateID {
source, err := buildPrivacyCohortSource(current)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
}
result = append(result, source)
current = privacyCohortCandidate{}
}
if current.id == uuid.Nil {
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
}
}
if row.Kind.Valid {
claim, err := privacyCohortStoredClaim(row)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate claims: %w", location, err)
}
current.claims = append(current.claims, claim)
}
}
source, err := buildPrivacyCohortSource(current)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
}
result = append(result, source)
return result, nil
}
func newPrivacyCohortCandidate(
candidateID uuid.UUID,
fieldCodes []string,
workFormatCodes []string,
acknowledgementsValue any,
) (privacyCohortCandidate, error) {
fields := make([]domain.CardField, 0, len(fieldCodes))
for _, code := range fieldCodes {
fields = append(fields, domain.CardField(code))
}
fieldSet, err := domain.NewCardFieldSet(fields)
if err != nil {
return privacyCohortCandidate{}, fmt.Errorf("invalid publication fields: %w", domain.ErrInvalidCandidateViewSource)
}
workFormats := make([]domain.QuestionnaireWorkFormat, 0, len(workFormatCodes))
for _, code := range workFormatCodes {
workFormats = append(workFormats, domain.QuestionnaireWorkFormat(code))
}
acknowledgementsJSON, err := privacyCohortEncodedJSONBytes(acknowledgementsValue)
if err != nil {
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
}
var acknowledgements []domain.ProfileParallelPeriodAcknowledgement
if err := json.Unmarshal(acknowledgementsJSON, &acknowledgements); err != nil {
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
}
return privacyCohortCandidate{
id: candidateID, fields: fieldSet, workFormats: workFormats,
acknowledgements: acknowledgements,
}, nil
}
func privacyCohortStoredClaim(row sqlc.ListVisibleCandidateViewSourcesRow) (domain.StoredProfileClaim, error) {
value, err := privacyCohortJSONBytes(row.SafeValue)
if err != nil {
return domain.StoredProfileClaim{}, fmt.Errorf("safe JSON type %T is invalid: %w", row.SafeValue, domain.ErrInvalidCandidateProfile)
}
if !row.Ordinal.Valid || !row.Status.Valid || !row.Origin.Valid || !row.TrustLevel.Valid {
return domain.StoredProfileClaim{}, fmt.Errorf("claim metadata is incomplete: %w", domain.ErrInvalidCandidateProfile)
}
confirmedAt := time.Time{}
if row.ConfirmedAt.Valid {
confirmedAt = row.ConfirmedAt.Time.UTC()
}
return domain.StoredProfileClaim{
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: value,
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
ExtractionVersion: row.ExtractionVersion.String, ConfirmedAt: confirmedAt,
}, nil
}
func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.CandidateViewSource, error) {
content, err := domain.RestoreCandidateProfileContentWithParallelPeriods(candidate.claims, candidate.acknowledgements)
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
}
return domain.NewCandidateViewSource(
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), nil,
candidate.workFormats, nil,
)
}
func privacyCohortJSONBytes(value any) ([]byte, error) {
switch typed := value.(type) {
case []byte:
return slices.Clone(typed), nil
case json.RawMessage:
return slices.Clone(typed), nil
default:
encoded, err := json.Marshal(typed)
if err != nil {
return nil, errors.New("JSON projection has an unexpected type")
}
return encoded, nil
}
}
func privacyCohortEncodedJSONBytes(value any) ([]byte, error) {
switch typed := value.(type) {
case string:
return []byte(typed), nil
case []byte:
return slices.Clone(typed), nil
case json.RawMessage:
return slices.Clone(typed), nil
default:
return nil, errors.New("encoded JSON projection has an unexpected type")
}
}
func privacyCohortUUID(value pgtype.UUID) (uuid.UUID, error) {
if !value.Valid || value.Bytes == uuid.Nil {
return uuid.Nil, domain.ErrInvalidCandidateViewSource
}
return uuid.UUID(value.Bytes), nil
}
@@ -0,0 +1,441 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"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"
)
var _ outbound.PrivacySettingsRepository = privacySettingsRepository{}
var privacySettingsConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "candidate_publications_consent_fkey"}: outbound.ErrConsentNotFound,
{foreignKeyViolationCode, "candidate_hidden_organizations_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "candidate_hidden_organizations_organization_id_fkey"}: outbound.ErrCandidatePrivacyOrganizationNotVisible,
{foreignKeyViolationCode, "candidate_privacy_events_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "candidate_privacy_events_consent_fkey"}: outbound.ErrConsentNotFound,
{foreignKeyViolationCode, "candidate_privacy_events_organization_id_fkey"}: outbound.ErrCandidatePrivacyOrganizationNotVisible,
{checkViolationCode, "candidate_hidden_organizations_limit"}: outbound.ErrCandidateHiddenOrganizationLimit,
}
func (unit *UnitOfWork) PrivacySettings() outbound.PrivacySettingsRepository {
return privacySettingsRepository{queries: unit.queries}
}
type privacySettingsRepository struct {
queries *sqlc.Queries
}
func (repository privacySettingsRepository) ReadSettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
const location = "privacySettingsRepository.ReadSettings"
if userID == uuid.Nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - user ID is empty: %w", location, domain.ErrInvalidVisibility)
}
row, err := repository.queries.ReadCandidatePrivacySettings(ctx, pgUUID(userID))
if err != nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - select settings: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrUserNotFound))
}
if got, err := privacySettingsUUID(row.UserID); err != nil || got != userID {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - result identity is invalid: %w", location, domain.ErrInvalidVisibility)
}
publication, err := publicationFromSettingsRow(userID, row)
if err != nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - restore publication: %w", location, err)
}
searchStatus, err := searchStatusFromSettingsRow(userID, row)
if err != nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - restore search status: %w", location, err)
}
return outbound.CandidatePrivacySettings{
Publication: publication, SearchStatus: searchStatus, HiddenCount: row.HiddenCount,
}, nil
}
func publicationFromSettingsRow(userID uuid.UUID, row sqlc.ReadCandidatePrivacySettingsRow) (domain.Publication, error) {
if !row.PublicationState.Valid {
return domain.NewPublication(userID)
}
consentID, err := privacySettingsUUID(row.PublicationConsentRecordID)
if err != nil {
return domain.Publication{}, fmt.Errorf("publication consent ID is invalid: %w", domain.ErrInvalidVisibility)
}
if !row.PublicationVersion.Valid || !row.PublicationPublishedAt.Valid {
return domain.Publication{}, fmt.Errorf("publication snapshot is incomplete: %w", domain.ErrInvalidVisibility)
}
stored := domain.StoredPublication{
UserID: userID, State: row.PublicationState.String, Fields: row.PublicationFields,
ConsentRecordID: consentID, PublishedAt: row.PublicationPublishedAt.Time.UTC(),
ClosedAt: privacySettingsTime(row.PublicationClosedAt), Version: row.PublicationVersion.Int64,
ConsentRevoked: row.PublicationConsentRevokedAt.Valid,
}
return domain.RestorePublication(stored)
}
func searchStatusFromSettingsRow(userID uuid.UUID, row sqlc.ReadCandidatePrivacySettingsRow) (domain.SearchStatus, error) {
if !row.SearchStatus.Valid {
return domain.NewSearchStatus(userID)
}
if !row.SearchVersion.Valid {
return domain.SearchStatus{}, fmt.Errorf("search status snapshot is incomplete: %w", domain.ErrInvalidVisibility)
}
var policyVersionID domain.PolicyVersionID
if row.SearchPolicyVersionID.Valid {
policyVersionID = domain.PolicyVersionID(row.SearchPolicyVersionID.Bytes)
}
return domain.RestoreSearchStatus(domain.StoredSearchStatus{
UserID: userID, Status: row.SearchStatus.String,
ConfirmedAt: privacySettingsTime(row.SearchConfirmedAt), LapsesAt: privacySettingsTime(row.SearchLapsesAt),
PolicyVersionID: policyVersionID, Version: row.SearchVersion.Int64,
})
}
func (repository privacySettingsRepository) LockCurrentC2ForPublication(ctx context.Context, userID uuid.UUID) (uuid.UUID, error) {
const location = "privacySettingsRepository.LockCurrentC2ForPublication"
if userID == uuid.Nil {
return uuid.Nil, fmt.Errorf("%s - user ID is empty: %w", location, domain.ErrInvalidVisibility)
}
id, err := repository.queries.LockCurrentC2Record(ctx, pgUUID(userID))
if err != nil {
return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrConsentNotFound))
}
return privacySettingsUUID(id)
}
func (repository privacySettingsRepository) SavePublication(ctx context.Context, publication domain.Publication, expectedVersion int64) error {
const location = "privacySettingsRepository.SavePublication"
if publication.UserID() == uuid.Nil || publication.Version() != expectedVersion+1 || expectedVersion < 0 {
return fmt.Errorf("%s - publication version is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.InsertCandidatePublicationParams{
UserID: pgUUID(publication.UserID()), State: string(publication.StoredState()), Fields: publication.StoredFields(),
ConsentRecordID: privacySettingsOptionalUUID(publication.ConsentRecordID()),
PublishedAt: pgTime(publication.PublishedAt()), ClosedAt: privacySettingsOptionalTime(publication.ClosedAt()),
At: pgTime(privacySettingsPublicationUpdatedAt(publication)),
}
var err error
if expectedVersion == 0 {
_, err = repository.queries.InsertCandidatePublication(ctx, params)
} else {
_, err = repository.queries.UpdateCandidatePublication(ctx, sqlc.UpdateCandidatePublicationParams{
State: params.State, Fields: params.Fields, ConsentRecordID: params.ConsentRecordID,
PublishedAt: params.PublishedAt, ClosedAt: params.ClosedAt, At: params.At,
UserID: params.UserID, ExpectedVersion: expectedVersion,
})
}
if err != nil {
return fmt.Errorf("%s - persist publication: %w", location, mapPrivacySettingsWriteError(err, domain.ErrVisibilityVersionConflict))
}
return nil
}
func privacySettingsPublicationUpdatedAt(publication domain.Publication) time.Time {
if publication.StoredState() == domain.PublicationClosed {
return publication.ClosedAt()
}
return publication.PublishedAt()
}
func (repository privacySettingsRepository) SaveSearchStatus(ctx context.Context, status domain.SearchStatus, expectedVersion int64, at time.Time) error {
const location = "privacySettingsRepository.SaveSearchStatus"
if status.UserID() == uuid.Nil || status.Version() != expectedVersion+1 || expectedVersion < 0 {
return fmt.Errorf("%s - status version is invalid: %w", location, domain.ErrInvalidVisibility)
}
policyID := status.PolicyVersionID().UUID()
params := sqlc.InsertCandidateSearchStatusParams{
UserID: pgUUID(status.UserID()), Status: string(status.StoredValue()),
ConfirmedAt: privacySettingsOptionalTime(status.ConfirmedAt()),
LapsesAt: privacySettingsOptionalTime(status.LapsesAt()), PolicyVersionID: privacySettingsOptionalUUID(policyID),
At: pgTime(at.UTC().Truncate(time.Microsecond)),
}
var err error
if expectedVersion == 0 {
_, err = repository.queries.InsertCandidateSearchStatus(ctx, params)
} else {
_, err = repository.queries.UpdateCandidateSearchStatus(ctx, sqlc.UpdateCandidateSearchStatusParams{
UserID: params.UserID, Status: params.Status, ConfirmedAt: params.ConfirmedAt, LapsesAt: params.LapsesAt,
PolicyVersionID: params.PolicyVersionID, At: params.At, ExpectedVersion: expectedVersion,
})
}
if err != nil {
return fmt.Errorf("%s - persist status: %w", location, mapPrivacySettingsWriteError(err, domain.ErrVisibilityVersionConflict))
}
return nil
}
func (repository privacySettingsRepository) CountHiddenOrganizations(ctx context.Context, userID uuid.UUID) (int64, error) {
if userID == uuid.Nil {
return 0, domain.ErrInvalidVisibility
}
count, err := repository.queries.CountCandidateHiddenOrganizations(ctx, pgUUID(userID))
if err != nil {
return 0, fmt.Errorf("privacySettingsRepository.CountHiddenOrganizations - count records: %w", mapPrivacySettingsError(err))
}
return count, nil
}
func (repository privacySettingsRepository) GetHiddenOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
const location = "privacySettingsRepository.GetHiddenOrganization"
if userID == uuid.Nil || organizationID == uuid.Nil {
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
}
row, err := repository.queries.GetCandidateHiddenOrganization(ctx, sqlc.GetCandidateHiddenOrganizationParams{
UserID: pgUUID(userID), OrganizationID: pgUUID(organizationID),
})
if err != nil {
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - select record: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrCandidatePrivacySettingsNotFound))
}
return hiddenOrganizationFromRow(row.OrganizationID, row.OrganizationName, row.HiddenAt)
}
func (repository privacySettingsRepository) CandidateCanSeeOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.CandidateVisibleOrganization, error) {
const location = "privacySettingsRepository.CandidateCanSeeOrganization"
if userID == uuid.Nil || organizationID == uuid.Nil {
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
}
row, err := repository.queries.CandidateCanSeeOrganization(ctx, sqlc.CandidateCanSeeOrganizationParams{
OrganizationID: pgUUID(organizationID), UserID: pgUUID(userID),
})
if err != nil {
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - select visible organization: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrCandidatePrivacyOrganizationNotVisible))
}
id, err := privacySettingsUUID(row.ID)
if err != nil || id != organizationID || row.Name == "" {
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - organization snapshot is invalid: %w", location, domain.ErrInvalidVisibility)
}
return outbound.CandidateVisibleOrganization{ID: id, Name: row.Name}, nil
}
func (repository privacySettingsRepository) HideOrganization(ctx context.Context, hidden domain.HiddenOrganization) (bool, error) {
const location = "privacySettingsRepository.HideOrganization"
if hidden.UserID() == uuid.Nil || hidden.OrganizationID() == uuid.Nil || hidden.HiddenAt().IsZero() {
return false, fmt.Errorf("%s - hiding is invalid: %w", location, domain.ErrInvalidVisibility)
}
_, err := repository.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{
UserID: pgUUID(hidden.UserID()), OrganizationID: pgUUID(hidden.OrganizationID()), At: pgTime(hidden.HiddenAt()),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - insert record: %w", location, mapPrivacySettingsError(err))
}
return true, nil
}
func (repository privacySettingsRepository) UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (bool, error) {
const location = "privacySettingsRepository.UnhideOrganization"
if userID == uuid.Nil || organizationID == uuid.Nil {
return false, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
}
_, err := repository.queries.DeleteCandidateHiddenOrganization(ctx, sqlc.DeleteCandidateHiddenOrganizationParams{
UserID: pgUUID(userID), OrganizationID: pgUUID(organizationID),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - delete record: %w", location, mapPrivacySettingsError(err))
}
return true, nil
}
func (repository privacySettingsRepository) ListHiddenOrganizations(ctx context.Context, query outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error) {
const location = "privacySettingsRepository.ListHiddenOrganizations"
if query.UserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxPrivacyPageSize {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.ListCandidateHiddenOrganizationsParams{UserID: pgUUID(query.UserID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.HiddenAt.IsZero() || query.After.OrganizationID == uuid.Nil {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - cursor is invalid: %w", location, domain.ErrInvalidVisibility)
}
params.AfterHiddenAt = pgTime(query.After.HiddenAt)
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
}
rows, err := repository.queries.ListCandidateHiddenOrganizations(ctx, params)
if err != nil {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - select records: %w", location, mapPrivacySettingsError(err))
}
page := outbound.HiddenOrganizationPage{Items: make([]outbound.HiddenOrganizationRecord, 0, min(len(rows), int(query.Limit)))}
for index, row := range rows {
if index == int(query.Limit) {
page.HasMore = true
break
}
record, err := hiddenOrganizationFromRow(row.OrganizationID, row.OrganizationName, row.HiddenAt)
if err != nil {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - restore record: %w", location, err)
}
page.Items = append(page.Items, record)
}
return page, nil
}
func (repository privacySettingsRepository) RecordPrivacyEvent(ctx context.Context, event domain.PrivacyEvent) error {
const location = "privacySettingsRepository.RecordPrivacyEvent"
if event.ID() == uuid.Nil || event.UserID() == uuid.Nil || !event.Kind().Valid() || event.OccurredAt().IsZero() {
return fmt.Errorf("%s - event is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.InsertCandidatePrivacyEventParams{
ID: pgUUID(event.ID()), UserID: pgUUID(event.UserID()), Kind: string(event.Kind()), OccurredAt: pgTime(event.OccurredAt()),
}
if event.HasFieldSet() {
params.Fields = event.Fields().Codes()
}
if event.ConsentRecordID() != uuid.Nil {
params.ConsentRecordID = pgUUID(event.ConsentRecordID())
}
if event.OrganizationID() != uuid.Nil {
params.OrganizationID = pgUUID(event.OrganizationID())
}
if err := repository.queries.InsertCandidatePrivacyEvent(ctx, params); err != nil {
return fmt.Errorf("%s - insert event: %w", location, mapPrivacySettingsError(err))
}
return nil
}
func (repository privacySettingsRepository) ListPrivacyEvents(ctx context.Context, query outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error) {
const location = "privacySettingsRepository.ListPrivacyEvents"
if query.UserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxPrivacyPageSize {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.ListCandidatePrivacyEventsParams{UserID: pgUUID(query.UserID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.OccurredAt.IsZero() || query.After.ID == uuid.Nil {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - cursor is invalid: %w", location, domain.ErrInvalidVisibility)
}
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
params.AfterID = pgUUID(query.After.ID)
}
rows, err := repository.queries.ListCandidatePrivacyEvents(ctx, params)
if err != nil {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - select events: %w", location, mapPrivacySettingsError(err))
}
page := outbound.CandidatePrivacyEventPage{Items: make([]outbound.CandidatePrivacyEventRecord, 0, min(len(rows), int(query.Limit)))}
for index, row := range rows {
if index == int(query.Limit) {
page.HasMore = true
break
}
record, err := privacyEventFromRow(row)
if err != nil {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - restore event: %w", location, err)
}
page.Items = append(page.Items, record)
}
return page, nil
}
func privacyEventFromRow(row sqlc.ListCandidatePrivacyEventsRow) (outbound.CandidatePrivacyEventRecord, error) {
id, err := privacySettingsUUID(row.ID)
if err != nil || !row.OccurredAt.Valid {
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
}
record := outbound.CandidatePrivacyEventRecord{ID: id, Kind: domain.PrivacyEventKind(row.Kind), OccurredAt: row.OccurredAt.Time.UTC()}
if !record.Kind.Valid() {
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
}
if row.Fields != nil {
fields, err := domain.NewCardFieldSet(stringsToCardFields(row.Fields))
if err != nil {
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
}
record.Fields = &fields
}
if row.ConsentRecordID.Valid {
record.ConsentRecordID, err = privacySettingsUUID(row.ConsentRecordID)
if err != nil {
return outbound.CandidatePrivacyEventRecord{}, err
}
}
if row.OrganizationID.Valid {
record.OrganizationID, err = privacySettingsUUID(row.OrganizationID)
if err != nil {
return outbound.CandidatePrivacyEventRecord{}, err
}
}
if row.OrganizationName.Valid {
record.OrganizationName = row.OrganizationName.String
}
return record, nil
}
func hiddenOrganizationFromRow(id pgtype.UUID, name string, hiddenAt pgtype.Timestamptz) (outbound.HiddenOrganizationRecord, error) {
organizationID, err := privacySettingsUUID(id)
if err != nil || name == "" || !hiddenAt.Valid {
return outbound.HiddenOrganizationRecord{}, domain.ErrInvalidVisibility
}
return outbound.HiddenOrganizationRecord{OrganizationID: organizationID, OrganizationName: name, HiddenAt: hiddenAt.Time.UTC()}, nil
}
func privacySettingsOptionalTime(value time.Time) pgtype.Timestamptz {
if value.IsZero() {
return pgtype.Timestamptz{}
}
return pgTime(value)
}
func privacySettingsOptionalUUID(value uuid.UUID) pgtype.UUID {
if value == uuid.Nil {
return pgtype.UUID{}
}
return pgUUID(value)
}
func privacySettingsTime(value pgtype.Timestamptz) time.Time {
if !value.Valid {
return time.Time{}
}
return value.Time.UTC()
}
func privacySettingsUUID(value pgtype.UUID) (uuid.UUID, error) {
if !value.Valid || uuid.UUID(value.Bytes) == uuid.Nil {
return uuid.Nil, domain.ErrInvalidVisibility
}
return uuid.UUID(value.Bytes), nil
}
func stringsToCardFields(codes []string) []domain.CardField {
fields := make([]domain.CardField, 0, len(codes))
for _, code := range codes {
fields = append(fields, domain.CardField(code))
}
return fields
}
func mapPrivacySettingsNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapPrivacySettingsError(err)
}
func mapPrivacySettingsWriteError(err, noRows error) error {
if errors.Is(err, pgx.ErrNoRows) {
return noRows
}
return mapPrivacySettingsError(err)
}
func mapPrivacySettingsError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
violation := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}
if sentinel, ok := privacySettingsConstraintErrors[violation]; ok {
return fmt.Errorf("postgres.mapPrivacySettingsError - constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
@@ -0,0 +1,267 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.PrivacyViewRepository = privacyCohortRepository{}
// CurrentFields stays closed until invitation grants have transaction-bound
// persistence. The C4 ledger alone does not identify a live invitation grant.
func (privacyCohortRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) {
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
}
func (privacyCohortRepository) CloseForVisibility(context.Context, uuid.UUID, uuid.UUID, time.Time) error {
// No C4 contact-grant persistence exists in this release. Contact reads are
// closed by default, so there is no persisted grant to reactivate later.
return nil
}
func (repository privacyCohortRepository) LockCandidateAccountForView(ctx context.Context, candidateID uuid.UUID) error {
const location = "privacyCohortRepository.LockCandidateAccountForView"
if candidateID == uuid.Nil {
return fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
_, err := repository.queries.LockCandidateAccountForView(ctx, pgUUID(candidateID))
if err != nil {
return fmt.Errorf("%s - lock candidate account: %w", location,
mapNoRows(sanitizeConnectError(err), outbound.ErrUserNotFound))
}
return nil
}
func (repository privacyCohortRepository) LockCurrentC2ForView(ctx context.Context, candidateID uuid.UUID) (uuid.UUID, error) {
const location = "privacyCohortRepository.LockCurrentC2ForView"
if candidateID == uuid.Nil {
return uuid.Nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
consentID, err := repository.queries.LockCurrentC2ForView(ctx, pgUUID(candidateID))
if err != nil {
return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location,
mapNoRows(sanitizeConnectError(err), outbound.ErrCandidateC2Unavailable))
}
return privacyCohortUUID(consentID)
}
func (repository privacyCohortRepository) LockVisiblePublicationForView(
ctx context.Context,
organizationID, candidateID, consentRecordID uuid.UUID,
) (bool, error) {
const location = "privacyCohortRepository.LockVisiblePublicationForView"
if organizationID == uuid.Nil || candidateID == uuid.Nil || consentRecordID == uuid.Nil {
return false, fmt.Errorf("%s - identifiers must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
_, err := repository.queries.LockVisiblePublicationForView(ctx, sqlc.LockVisiblePublicationForViewParams{
OrganizationID: pgUUID(organizationID), CandidateID: pgUUID(candidateID), ConsentRecordID: pgUUID(consentRecordID),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - lock visible publication: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return true, nil
}
func (repository privacyCohortRepository) LockPublicationForPreview(ctx context.Context, candidateID uuid.UUID) (bool, error) {
const location = "privacyCohortRepository.LockPublicationForPreview"
if candidateID == uuid.Nil {
return false, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
_, err := repository.queries.LockPublicationForCandidatePreview(ctx, pgUUID(candidateID))
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - lock current publication: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return true, nil
}
func (repository privacyCohortRepository) ReadCandidateViewSourceForPreview(
ctx context.Context,
candidateID uuid.UUID,
) (domain.CandidateViewSource, error) {
const location = "privacyCohortRepository.ReadCandidateViewSourceForPreview"
if candidateID == uuid.Nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
rows, err := repository.queries.ReadCandidateViewSourceForPreview(ctx, pgUUID(candidateID))
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - read candidate projection: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
if len(rows) == 0 {
return domain.CandidateViewSource{}, fmt.Errorf("%s - current publication has no projection row: %w", location, outbound.ErrPrivacyCohortUnavailable)
}
return buildPreviewCandidateViewSource(candidateID, rows)
}
func buildPreviewCandidateViewSource(
candidateID uuid.UUID,
rows []sqlc.ReadCandidateViewSourceForPreviewRow,
) (domain.CandidateViewSource, error) {
const location = "buildPreviewCandidateViewSource"
first := rows[0]
if got, err := privacyCohortUUID(first.UserID); err != nil || got != candidateID {
return domain.CandidateViewSource{}, fmt.Errorf("%s - projection identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
}
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements)
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
}
for _, row := range rows {
if row.Kind.Valid {
claim, err := previewStoredClaim(row)
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate claim: %w", location, err)
}
candidate.claims = append(candidate.claims, claim)
}
}
return buildPrivacyCohortSource(candidate)
}
func previewStoredClaim(row sqlc.ReadCandidateViewSourceForPreviewRow) (domain.StoredProfileClaim, error) {
value, err := privacyCohortJSONBytes(row.SafeValue)
if err != nil {
return domain.StoredProfileClaim{}, fmt.Errorf("safe JSON type %T is invalid: %w", row.SafeValue, domain.ErrInvalidCandidateProfile)
}
if !row.Ordinal.Valid || !row.Status.Valid || !row.Origin.Valid || !row.TrustLevel.Valid {
return domain.StoredProfileClaim{}, fmt.Errorf("claim metadata is incomplete: %w", domain.ErrInvalidCandidateProfile)
}
confirmedAt := timeValueOrZero(row.ConfirmedAt)
return domain.StoredProfileClaim{
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: value,
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
ExtractionVersion: row.ExtractionVersion.String, ConfirmedAt: confirmedAt,
}, nil
}
func timeValueOrZero(value pgtype.Timestamptz) time.Time {
if !value.Valid {
return time.Time{}
}
return value.Time.UTC()
}
func (repository privacyCohortRepository) RecordCandidateCardAccess(ctx context.Context, access domain.CandidateCardAccess) error {
const location = "privacyCohortRepository.RecordCandidateCardAccess"
if access.IsZero() || access.ActorID() == uuid.Nil {
return fmt.Errorf("%s - access event is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
err := repository.queries.InsertCandidateCardAccessEvent(ctx, sqlc.InsertCandidateCardAccessEventParams{
ID: pgUUID(access.ID()), CandidateID: pgUUID(access.CandidateID()),
OrganizationID: pgUUID(access.OrganizationID()), ActorID: pgUUID(access.ActorID()),
Kind: string(access.Kind()), FieldCodes: access.FieldCodes(), OccurredAt: pgTime(access.OccurredAt()),
})
if err != nil {
return fmt.Errorf("%s - insert access audit: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
func (repository privacyCohortRepository) ListCandidateCardAccess(
ctx context.Context,
query outbound.CandidateCardAccessListQuery,
) (outbound.CandidateCardAccessListPage, error) {
const location = "privacyCohortRepository.ListCandidateCardAccess"
if query.CandidateID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxCandidateCardAccessPageSize {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
params := sqlc.ListCandidateCardAccessEventsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.ID == uuid.Nil || query.After.OccurredAt.IsZero() {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - continuation position is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
params.AfterID = pgUUID(query.After.ID)
}
rows, err := repository.queries.ListCandidateCardAccessEvents(ctx, params)
if err != nil {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - list access audit: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return buildCandidateCardAccessPage(query.CandidateID, query.Limit, rows)
}
func buildCandidateCardAccessPage(
candidateID uuid.UUID,
limit int32,
rows []sqlc.ListCandidateCardAccessEventsRow,
) (outbound.CandidateCardAccessListPage, error) {
const location = "buildCandidateCardAccessPage"
page := outbound.CandidateCardAccessListPage{
Items: make([]domain.CandidateCardAccess, 0, min(len(rows), int(limit))),
OrganizationNames: make(map[uuid.UUID]string),
}
if len(rows) > int(limit) {
page.HasMore = true
rows = rows[:limit]
}
for _, row := range rows {
access, organizationID, err := restoreCandidateCardAccessEvent(row, candidateID)
if err != nil {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - restore access event: %w", location, err)
}
page.Items = append(page.Items, access)
page.OrganizationNames[organizationID] = row.OrganizationName
}
return page, nil
}
func restoreCandidateCardAccessEvent(
row sqlc.ListCandidateCardAccessEventsRow,
expectedCandidateID uuid.UUID,
) (domain.CandidateCardAccess, uuid.UUID, error) {
const location = "restoreCandidateCardAccessEvent"
id, err := privacyCohortUUID(row.ID)
if err != nil {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access identifier is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
candidateID, err := privacyCohortUUID(row.CandidateID)
if err != nil || candidateID != expectedCandidateID {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access candidate is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
organizationID, err := privacyCohortUUID(row.OrganizationID)
if err != nil {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access organization is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
access, err := domain.RestoreCandidateCardAccess(id, restoreCandidateCardAccessInput(row, candidateID, organizationID))
if err != nil {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access event values are invalid: %w", location, err)
}
return access, organizationID, nil
}
func restoreCandidateCardAccessInput(
row sqlc.ListCandidateCardAccessEventsRow,
candidateID, organizationID uuid.UUID,
) domain.CandidateCardAccessInput {
var projectionFields []domain.CardField
var contactFields []domain.ContactField
for _, code := range row.FieldCodes {
if field := domain.CardField(code); field.Valid() {
projectionFields = append(projectionFields, field)
continue
}
contactFields = append(contactFields, domain.ContactField(code))
}
input := domain.CandidateCardAccessInput{
CandidateID: candidateID, OrganizationID: organizationID,
ActorID: optionalUUID(row.ActorID), Kind: domain.CandidateCardAccessKind(row.Kind),
ProjectionFields: projectionFields, ContactFields: contactFields,
OccurredAt: timeValueOrZero(row.OccurredAt),
}
return input
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,365 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_availability.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentAvailabilityActiveAttempt = `-- name: GetAssessmentAvailabilityActiveAttempt :one
SELECT id, expires_at
FROM assessment_attempts
WHERE user_id = $1
AND specialization = $2
AND kind IN ('root', 'corrective')
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
ORDER BY created_at DESC, id DESC
LIMIT 1
`
type GetAssessmentAvailabilityActiveAttemptParams struct {
UserID pgtype.UUID
Specialization pgtype.Text
}
type GetAssessmentAvailabilityActiveAttemptRow struct {
ID pgtype.UUID
ExpiresAt pgtype.Timestamptz
}
// Reads an active real attempt without taking the write lock used by create.
// The availability GET never expires or otherwise mutates this row.
func (q *Queries) GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error) {
row := q.db.QueryRow(ctx, getAssessmentAvailabilityActiveAttempt, arg.UserID, arg.Specialization)
var i GetAssessmentAvailabilityActiveAttemptRow
err := row.Scan(&i.ID, &i.ExpiresAt)
return i, err
}
const getAssessmentRootQuotaAvailability = `-- name: GetAssessmentRootQuotaAvailability :one
WITH eligible AS (
SELECT attempt.id, attempt.created_at
FROM assessment_attempts AS attempt
LEFT JOIN assessment_attempt_results AS result
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
WHERE attempt.user_id = $3
AND attempt.kind = 'root'
AND attempt.state <> 'insufficient_bank'
AND attempt.created_at >= $4::timestamptz
AND attempt.created_at <= $5::timestamptz
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
NOT IN ('insufficient_bank', 'sandbox_unavailable')
), total AS (
SELECT count(*)::bigint AS attempt_count FROM eligible
)
SELECT
total.attempt_count,
CASE WHEN total.attempt_count >= $1::bigint THEN (
SELECT eligible.created_at
+ make_interval(secs => $2::double precision)
+ interval '1 microsecond'
FROM eligible
ORDER BY eligible.created_at, eligible.id
LIMIT 1
OFFSET (total.attempt_count - $1::bigint)
) ELSE NULL::timestamptz END AS available_at
FROM total
`
type GetAssessmentRootQuotaAvailabilityParams struct {
MaxAttempts int64
WindowSeconds float64
UserID pgtype.UUID
Since pgtype.Timestamptz
AsOf pgtype.Timestamptz
}
type GetAssessmentRootQuotaAvailabilityRow struct {
AttemptCount int64
AvailableAt pgtype.Timestamptz
}
// Counts eligible root attempts in a policy window and computes the instant
// at which one additional root slot opens. The microsecond adjustment matches
// the creation predicate created_at >= since at PostgreSQL timestamp precision.
func (q *Queries) GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error) {
row := q.db.QueryRow(ctx, getAssessmentRootQuotaAvailability,
arg.MaxAttempts,
arg.WindowSeconds,
arg.UserID,
arg.Since,
arg.AsOf,
)
var i GetAssessmentRootQuotaAvailabilityRow
err := row.Scan(&i.AttemptCount, &i.AvailableAt)
return i, err
}
const listAssessmentAvailabilityRootSummaries = `-- name: ListAssessmentAvailabilityRootSummaries :many
SELECT
root.target_grade AS root_target_grade,
root.created_at AS root_created_at,
root.updated_at AS root_updated_at,
root.expires_at AS root_expires_at,
root.state AS root_state,
root.outcome AS root_outcome,
root.chain_deadline AS root_chain_deadline,
latest.target_grade AS latest_target_grade,
latest.updated_at AS latest_updated_at,
latest.expires_at AS latest_expires_at,
latest.state AS latest_state,
latest.outcome AS latest_outcome,
latest.chain_deadline AS latest_chain_deadline,
COALESCE(latest_result.result_snapshot->>'not_determined_reason', '')::text AS latest_platform_error
FROM assessment_attempts AS root
JOIN LATERAL (
SELECT attempt.id, attempt.user_id, attempt.kind, attempt.mode, attempt.state, attempt.outcome, attempt.bank_category, attempt.specialization, attempt.target_grade, attempt.task_language, attempt.root_attempt_id, attempt.product_policy_version_id, attempt.product_policy_version, attempt.grading_policy_version_id, attempt.opening_id, attempt.opening_manifest_sha256, attempt.training_binding_id, attempt.training_manifest_sha256, attempt.bank_version, attempt.algorithm_version, attempt.created_at, attempt.updated_at, attempt.expires_at, attempt.chain_deadline, attempt.idle_timeout_seconds, attempt.max_sessions, attempt.sessions_used, attempt.session_started_at, attempt.last_activity_at, attempt.version, attempt.ended_at
FROM assessment_attempts AS attempt
WHERE attempt.user_id = root.user_id
AND attempt.root_attempt_id = root.id
AND attempt.kind IN ('root', 'corrective')
ORDER BY attempt.created_at DESC, attempt.id DESC
LIMIT 1
) AS latest ON true
LEFT JOIN assessment_attempt_results AS root_result
ON root_result.attempt_id = root.id AND root_result.user_id = root.user_id
LEFT JOIN assessment_attempt_results AS latest_result
ON latest_result.attempt_id = latest.id AND latest_result.user_id = latest.user_id
WHERE root.user_id = $1
AND root.specialization = $2
AND root.kind = 'root'
AND root.created_at >= $3::timestamptz
AND root.state <> 'insufficient_bank'
AND COALESCE(root_result.result_snapshot->>'not_determined_reason', '')
NOT IN ('insufficient_bank', 'sandbox_unavailable')
ORDER BY root.created_at DESC, root.id DESC
`
type ListAssessmentAvailabilityRootSummariesParams struct {
UserID pgtype.UUID
Specialization pgtype.Text
Since pgtype.Timestamptz
}
type ListAssessmentAvailabilityRootSummariesRow struct {
RootTargetGrade pgtype.Text
RootCreatedAt pgtype.Timestamptz
RootUpdatedAt pgtype.Timestamptz
RootExpiresAt pgtype.Timestamptz
RootState string
RootOutcome pgtype.Text
RootChainDeadline pgtype.Timestamptz
LatestTargetGrade pgtype.Text
LatestUpdatedAt pgtype.Timestamptz
LatestExpiresAt pgtype.Timestamptz
LatestState string
LatestOutcome pgtype.Text
LatestChainDeadline pgtype.Timestamptz
LatestPlatformError string
}
// Reads roots within the policy horizon and the last header in each correction
// chain. It deliberately omits frozen items, answers, and row locks.
func (q *Queries) ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error) {
rows, err := q.db.Query(ctx, listAssessmentAvailabilityRootSummaries, arg.UserID, arg.Specialization, arg.Since)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAssessmentAvailabilityRootSummariesRow
for rows.Next() {
var i ListAssessmentAvailabilityRootSummariesRow
if err := rows.Scan(
&i.RootTargetGrade,
&i.RootCreatedAt,
&i.RootUpdatedAt,
&i.RootExpiresAt,
&i.RootState,
&i.RootOutcome,
&i.RootChainDeadline,
&i.LatestTargetGrade,
&i.LatestUpdatedAt,
&i.LatestExpiresAt,
&i.LatestState,
&i.LatestOutcome,
&i.LatestChainDeadline,
&i.LatestPlatformError,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAssessmentDisclosedFamilyKeys = `-- name: ListAssessmentDisclosedFamilyKeys :many
WITH progress AS (
SELECT
attempt.id AS attempt_id,
attempt.created_at,
COALESCE(max(item.ordinal) FILTER (WHERE item.answered_at IS NOT NULL), 0) + 1 AS last_disclosed_ordinal
FROM assessment_attempts AS attempt
JOIN assessment_attempt_items AS item ON item.attempt_id = attempt.id
WHERE attempt.user_id = $2
AND attempt.kind IN ('root', 'corrective')
AND attempt.expires_at > $1::timestamptz
GROUP BY attempt.id
), disclosed AS (
SELECT
item.family_key,
CASE
WHEN item.ordinal = 1 THEN progress.created_at
ELSE previous.answered_at
END AS disclosed_at
FROM progress
JOIN assessment_attempt_items AS item ON item.attempt_id = progress.attempt_id
LEFT JOIN assessment_attempt_items AS previous
ON previous.attempt_id = item.attempt_id AND previous.ordinal = item.ordinal - 1
WHERE item.ordinal <= progress.last_disclosed_ordinal
)
SELECT DISTINCT disclosed.family_key
FROM disclosed
WHERE disclosed.disclosed_at > $1::timestamptz
ORDER BY disclosed.family_key
`
type ListAssessmentDisclosedFamilyKeysParams struct {
Since pgtype.Timestamptz
UserID pgtype.UUID
}
// Counts family instances disclosed after the non-repeat boundary. The first
// item is disclosed when the attempt is created; each later item is disclosed
// when the preceding answer is accepted. This per-item timestamp prevents a
// long-running attempt from making later items appear older than they are.
// Counting the first unanswered item after expiry is conservative when the
// final response was lost, while frozen future items remain excluded.
func (q *Queries) ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error) {
rows, err := q.db.Query(ctx, listAssessmentDisclosedFamilyKeys, arg.Since, arg.UserID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []string
for rows.Next() {
var family_key string
if err := rows.Scan(&family_key); err != nil {
return nil, err
}
items = append(items, family_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCurrentAssessmentAvailabilitySelections = `-- name: ListCurrentAssessmentAvailabilitySelections :many
WITH current_policy AS (
SELECT id, version
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= $1::timestamptz
ORDER BY version DESC
LIMIT 1
), current_openings AS (
SELECT DISTINCT ON (category)
id,
category,
policy_version_id,
required_families,
opened_at
FROM assessment_category_openings
ORDER BY category, opened_at DESC, id DESC
)
SELECT
opening.id AS opening_id,
opening.category,
opening.policy_version_id,
opening.required_families,
COALESCE((
SELECT count(DISTINCT family.family_key)::integer
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), 0)::integer AS published_count,
policy.id AS effective_policy_id,
policy.version AS effective_policy_version,
binding.specialization,
binding.grade,
binding.task_languages,
binding.published_manifest_sha256,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'family_key', family.family_key,
'version', family.version,
'content_sha256', encode(family.content_sha256, 'hex')
) ORDER BY family.family_key, family.version
)
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), '[]'::jsonb)::text AS published_manifest
FROM current_openings AS opening
JOIN assessment_category_catalog_bindings AS binding
ON binding.opening_id = opening.id
LEFT JOIN current_policy AS policy ON true
ORDER BY binding.specialization, binding.grade, binding.task_languages, opening.category
`
type ListCurrentAssessmentAvailabilitySelectionsRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
EffectivePolicyVersion pgtype.Int4
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// Returns current reviewed grade/language bindings and the live published
// family manifest at one caller-supplied database time. The adapter verifies
// the pinned manifest hash before exposing only family keys.
func (q *Queries) ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error) {
rows, err := q.db.Query(ctx, listCurrentAssessmentAvailabilitySelections, asOf)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCurrentAssessmentAvailabilitySelectionsRow
for rows.Next() {
var i ListCurrentAssessmentAvailabilitySelectionsRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.EffectivePolicyVersion,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,201 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_signals.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countAssessmentSignalEvents = `-- name: CountAssessmentSignalEvents :one
SELECT count(*)::bigint AS event_count
FROM assessment_signal_events
WHERE attempt_id = $1
`
// Count events only for the already owner-locked attempt.
func (q *Queries) CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error) {
row := q.db.QueryRow(ctx, countAssessmentSignalEvents, attemptID)
var event_count int64
err := row.Scan(&event_count)
return event_count, err
}
const countRecentAssessmentSignalOutcomes = `-- name: CountRecentAssessmentSignalOutcomes :one
SELECT
count(*)::bigint AS outcome_count,
COALESCE(min(received_at), $1::timestamptz) AS oldest_at
FROM assessment_signal_idempotency_outcomes
WHERE
attempt_id = $2
AND received_at > $1
`
type CountRecentAssessmentSignalOutcomesParams struct {
Since pgtype.Timestamptz
AttemptID pgtype.UUID
}
type CountRecentAssessmentSignalOutcomesRow struct {
OutcomeCount int64
OldestAt interface{}
}
// New outcomes share the generic idempotency row and are counted for the
// attempt's rolling receipt window. Replays bypass this query in the usecase.
func (q *Queries) CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error) {
row := q.db.QueryRow(ctx, countRecentAssessmentSignalOutcomes, arg.Since, arg.AttemptID)
var i CountRecentAssessmentSignalOutcomesRow
err := row.Scan(&i.OutcomeCount, &i.OldestAt)
return i, err
}
const deleteExpiredAssessmentSignalOutcome = `-- name: DeleteExpiredAssessmentSignalOutcome :exec
DELETE FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = $1
`
// The generic reservation has already established that a previous outcome is
// expired before this child is removed and replaced in the same transaction.
func (q *Queries) DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error {
_, err := q.db.Exec(ctx, deleteExpiredAssessmentSignalOutcome, scopeHash)
return err
}
const getAssessmentSignalOutcome = `-- name: GetAssessmentSignalOutcome :one
SELECT status, accepted_events, received_at
FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = $1
`
type GetAssessmentSignalOutcomeRow struct {
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
// Read only the receipt associated with the reserved idempotency scope.
func (q *Queries) GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error) {
row := q.db.QueryRow(ctx, getAssessmentSignalOutcome, scopeHash)
var i GetAssessmentSignalOutcomeRow
err := row.Scan(&i.Status, &i.AcceptedEvents, &i.ReceivedAt)
return i, err
}
const insertAssessmentSignalBatch = `-- name: InsertAssessmentSignalBatch :exec
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
VALUES (
$1,
$2,
$3,
$4
)
`
type InsertAssessmentSignalBatchParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
ReceivedAt pgtype.Timestamptz
EventCount int32
}
// The attempt row is already locked by the caller. Store a parent before its
// bounded child events, in the same transaction as the immutable receipt.
func (q *Queries) InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalBatch,
arg.ID,
arg.AttemptID,
arg.ReceivedAt,
arg.EventCount,
)
return err
}
const insertAssessmentSignalEvent = `-- name: InsertAssessmentSignalEvent :exec
INSERT INTO assessment_signal_events (
batch_id,
attempt_id,
ordinal,
item_instance_id,
kind,
occurred_at,
duration_ms,
size_bytes
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7::integer,
$8::integer
)
`
type InsertAssessmentSignalEventParams struct {
BatchID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
ItemInstanceID pgtype.UUID
Kind string
OccurredAt pgtype.Timestamptz
DurationMs pgtype.Int4
SizeBytes pgtype.Int4
}
// Each inserted event is checked by the database guard against attempt state
// and the aggregate capacity as a second line of defense.
func (q *Queries) InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalEvent,
arg.BatchID,
arg.AttemptID,
arg.Ordinal,
arg.ItemInstanceID,
arg.Kind,
arg.OccurredAt,
arg.DurationMs,
arg.SizeBytes,
)
return err
}
const insertAssessmentSignalOutcome = `-- name: InsertAssessmentSignalOutcome :exec
INSERT INTO assessment_signal_idempotency_outcomes (
scope_hash,
attempt_id,
status,
accepted_events,
received_at
) VALUES (
$1,
$2,
$3,
$4,
$5
)
`
type InsertAssessmentSignalOutcomeParams struct {
ScopeHash []byte
AttemptID pgtype.UUID
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
// Save exactly one immutable response receipt for each live idempotency scope.
func (q *Queries) InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalOutcome,
arg.ScopeHash,
arg.AttemptID,
arg.Status,
arg.AcceptedEvents,
arg.ReceivedAt,
)
return err
}
@@ -871,6 +871,79 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
return items, nil
}
const lockCurrentConsentForUse = `-- name: LockCurrentConsentForUse :one
SELECT
id,
subject_id,
purpose,
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
'active'::text AS state
FROM consent_records
WHERE
subject_id = $1
AND purpose = 'c3'
AND revoked_at IS NULL
ORDER BY granted_at DESC, id DESC
LIMIT 1
FOR SHARE
`
type LockCurrentConsentForUseRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
func (q *Queries) LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error) {
row := q.db.QueryRow(ctx, lockCurrentConsentForUse, subjectID)
var i LockCurrentConsentForUseRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const lockRegistrationConsentRecord = `-- name: LockRegistrationConsentRecord :one
SELECT
id,
@@ -16,6 +16,89 @@ type AccountDeletionRequest struct {
CompletedAt pgtype.Timestamptz
}
type AssessmentAttempt struct {
ID pgtype.UUID
UserID pgtype.UUID
Kind string
Mode string
State string
Outcome pgtype.Text
BankCategory string
Specialization pgtype.Text
TargetGrade pgtype.Text
TaskLanguage pgtype.Text
RootAttemptID pgtype.UUID
ProductPolicyVersionID pgtype.UUID
ProductPolicyVersion int32
GradingPolicyVersionID pgtype.UUID
OpeningID pgtype.UUID
OpeningManifestSha256 []byte
TrainingBindingID pgtype.UUID
TrainingManifestSha256 []byte
BankVersion string
AlgorithmVersion string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ChainDeadline pgtype.Timestamptz
IdleTimeoutSeconds int32
MaxSessions int32
SessionsUsed int32
SessionStartedAt pgtype.Timestamptz
LastActivityAt pgtype.Timestamptz
Version int64
EndedAt pgtype.Timestamptz
}
type AssessmentAttemptIdempotencyOutcome struct {
ScopeHash []byte
Operation string
StatusCode int16
ProblemCode pgtype.Text
ResponseSnapshot []byte
ResponseSchemaVersion int16
CreatedAt pgtype.Timestamptz
PendingItemIds []pgtype.UUID
}
type AssessmentAttemptItem struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
FamilyID pgtype.UUID
FamilyKey string
FamilyVersion int32
FamilyContentSha256 []byte
Variant []byte
Answer []byte
AnsweredAt pgtype.Timestamptz
}
type AssessmentAttemptResult struct {
AttemptID pgtype.UUID
UserID pgtype.UUID
ResultSnapshot []byte
SchemaVersion int16
Kind string
Mode string
Outcome string
ProductPolicyVersionID pgtype.UUID
ProductPolicyVersion int32
GradingPolicyVersionID pgtype.UUID
OpeningID pgtype.UUID
OpeningManifestSha256 []byte
TrainingBindingID pgtype.UUID
TrainingManifestSha256 []byte
BankVersion string
AlgorithmVersion string
RationaleRule string
PassMarkBasisPoints pgtype.Int4
ScoredItems pgtype.Int2
RawScore pgtype.Int2
PassPoints pgtype.Int2
DecidedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
OpeningID pgtype.UUID
Specialization string
@@ -60,6 +143,62 @@ type AssessmentFamily struct {
RetiredBy pgtype.Text
}
type AssessmentSignalBatch struct {
ID pgtype.UUID
AttemptID pgtype.UUID
ReceivedAt pgtype.Timestamptz
EventCount int32
}
type AssessmentSignalEvent struct {
BatchID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
ItemInstanceID pgtype.UUID
Kind string
OccurredAt pgtype.Timestamptz
DurationMs pgtype.Int4
SizeBytes pgtype.Int4
}
type AssessmentSignalIdempotencyOutcome struct {
ScopeHash []byte
AttemptID pgtype.UUID
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
type AssessmentTrainingBankBinding struct {
ID pgtype.UUID
Category string
ProductPolicyVersionID pgtype.UUID
ItemCount int32
ManifestSha256 []byte
FamilyManifest []byte
ReviewedBy string
CreatedAt pgtype.Timestamptz
}
type AssessmentTrainingBankBindingFamily struct {
BindingID pgtype.UUID
Ordinal int32
FamilyID pgtype.UUID
FamilyKey string
FamilyVersion int32
ContentSha256 []byte
}
type CandidateCardAccessEvent struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
}
type CandidateEffectivePublication struct {
UserID pgtype.UUID
Fields []string
@@ -405,6 +544,11 @@ type OrganizationNeed struct {
UpdatedAt pgtype.Timestamptz
}
type OrganizationNeedCreationResult struct {
ScopeHash []byte
Snapshot []byte
}
type OrganizationNeedVersion struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
@@ -472,6 +616,57 @@ type Session struct {
RevokedAt pgtype.Timestamptz
}
type SupportCase struct {
ID pgtype.UUID
CaseNumber string
OwnerID pgtype.UUID
CaseType string
Status string
Description string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
ComplaintReason pgtype.Text
RubricVersion pgtype.Int4
RubricOpeningID pgtype.UUID
RubricPolicyVersionID pgtype.UUID
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
DecisionReason pgtype.Text
DecisionAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type SupportCaseCreateOutcome struct {
ScopeHash []byte
OutcomeKind string
CaseSnapshot []byte
TargetWasLate pgtype.Bool
CreatedAt pgtype.Timestamptz
}
type SupportCaseEvent struct {
CaseID pgtype.UUID
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
type SupportCaseRequestEvent struct {
ID int64
OwnerID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
type User struct {
ID pgtype.UUID
Email string
@@ -80,6 +80,21 @@ func (q *Queries) AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrgani
return snapshot, err
}
const getOrganizationNeedCreationResult = `-- name: GetOrganizationNeedCreationResult :one
SELECT snapshot::text AS snapshot
FROM organization_need_creation_results
WHERE scope_hash = $1
`
// Read only the immutable original response. The current need may have moved
// to a later version since this result was created.
func (q *Queries) GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error) {
row := q.db.QueryRow(ctx, getOrganizationNeedCreationResult, scopeHash)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
const insertOrganizationNeed = `-- name: InsertOrganizationNeed :exec
INSERT INTO organization_needs (
id,
@@ -152,6 +167,85 @@ func (q *Queries) InsertOrganizationNeedVersion(ctx context.Context, arg InsertO
return err
}
const listOrganizationNeeds = `-- name: ListOrganizationNeeds :many
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 (
$2::timestamptz IS NULL
OR (need.created_at, need.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY need.created_at DESC, need.id DESC
LIMIT $4
`
type ListOrganizationNeedsParams struct {
OrganizationID pgtype.UUID
AfterCreatedAt pgtype.Timestamptz
AfterNeedID pgtype.UUID
RowLimit int32
}
type ListOrganizationNeedsRow struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Snapshot string
}
// Read one bounded newest-first page of current needs. Both the organization
// scope and the tuple cursor are applied before the limit.
func (q *Queries) ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error) {
rows, err := q.db.Query(ctx, listOrganizationNeeds,
arg.OrganizationID,
arg.AfterCreatedAt,
arg.AfterNeedID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationNeedsRow
for rows.Next() {
var i ListOrganizationNeedsRow
if err := rows.Scan(
&i.OrganizationID,
&i.NeedID,
&i.CurrentVersion,
&i.RequirementsVersion,
&i.CreatedAt,
&i.UpdatedAt,
&i.Snapshot,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const readCurrentOrganizationNeed = `-- name: ReadCurrentOrganizationNeed :one
SELECT
need.organization_id,
@@ -224,3 +318,23 @@ func (q *Queries) ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrgan
err := row.Scan(&snapshot)
return snapshot, err
}
const saveOrganizationNeedCreationResult = `-- name: SaveOrganizationNeedCreationResult :exec
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
VALUES ($1, $2::jsonb)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot
`
type SaveOrganizationNeedCreationResultParams struct {
ScopeHash []byte
Snapshot []byte
}
// The generic idempotency scope serializes retries. Replacing the child row
// is safe only in the transaction that reserves an expired scope for a new
// create; live retries read and return the stored response without writing.
func (q *Queries) SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error {
_, err := q.db.Exec(ctx, saveOrganizationNeedCreationResult, arg.ScopeHash, arg.Snapshot)
return err
}
@@ -405,6 +405,63 @@ func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganiza
return items, nil
}
const lockActiveMembership = `-- name: LockActiveMembership :one
WITH locked_organization AS MATERIALIZED (
SELECT organizations.id
FROM organizations
WHERE organizations.id = $2
FOR SHARE
)
SELECT
membership.id AS membership_id,
membership.organization_id,
membership.user_id,
membership.role,
membership.state,
membership.created_at,
membership.updated_at
FROM memberships AS membership
INNER JOIN locked_organization ON locked_organization.id = membership.organization_id
WHERE
membership.user_id = $1
AND membership.state = 'active'
FOR SHARE OF membership
`
type LockActiveMembershipParams struct {
UserID pgtype.UUID
OrganizationID pgtype.UUID
}
type LockActiveMembershipRow struct {
MembershipID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Locks the organization first and then the active membership, using the
// same order as organization profile writes. A company operation keeps both
// share locks until its transaction commits, so a concurrent revocation
// cannot authorize a write after it has committed.
func (q *Queries) LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error) {
row := q.db.QueryRow(ctx, lockActiveMembership, arg.UserID, arg.OrganizationID)
var i LockActiveMembershipRow
err := row.Scan(
&i.MembershipID,
&i.OrganizationID,
&i.UserID,
&i.Role,
&i.State,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const saveOrganizationCreationResult = `-- name: SaveOrganizationCreationResult :exec
INSERT INTO organization_creation_results (scope_hash, snapshot)
VALUES ($1, $2)
@@ -11,6 +11,44 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const candidateCanSeeOrganization = `-- name: CandidateCanSeeOrganization :one
SELECT organizations.id, organizations.name
FROM organizations
WHERE organizations.id = $1
AND (
EXISTS (
SELECT 1 FROM candidate_card_access_events
WHERE candidate_card_access_events.candidate_id = $2
AND candidate_card_access_events.organization_id = organizations.id
)
OR EXISTS (
SELECT 1 FROM candidate_hidden_organizations
WHERE candidate_hidden_organizations.user_id = $2
AND candidate_hidden_organizations.organization_id = organizations.id
)
)
`
type CandidateCanSeeOrganizationParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
type CandidateCanSeeOrganizationRow struct {
ID pgtype.UUID
Name string
}
// The candidate may name an organization in privacy settings only if that
// organization already appears in their own access history or is already
// hidden. Unknown and unseen organizations produce the same no-row result.
func (q *Queries) CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error) {
row := q.db.QueryRow(ctx, candidateCanSeeOrganization, arg.OrganizationID, arg.UserID)
var i CandidateCanSeeOrganizationRow
err := row.Scan(&i.ID, &i.Name)
return i, err
}
const countCandidateHiddenOrganizations = `-- name: CountCandidateHiddenOrganizations :one
SELECT count(*) AS total
FROM candidate_hidden_organizations
@@ -79,6 +117,52 @@ func (q *Queries) GetCandidateHiddenOrganization(ctx context.Context, arg GetCan
return i, err
}
const insertCandidateCardAccessEvent = `-- name: InsertCandidateCardAccessEvent :exec
INSERT INTO candidate_card_access_events (
id,
candidate_id,
organization_id,
actor_id,
kind,
field_codes,
occurred_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertCandidateCardAccessEventParams struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
}
// Records a successfully authorized view after visibility and quota checks.
// The audit contains only identities, the access kind, published field codes,
// and time; it never receives the projection content, ranking, or filters.
func (q *Queries) InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error {
_, err := q.db.Exec(ctx, insertCandidateCardAccessEvent,
arg.ID,
arg.CandidateID,
arg.OrganizationID,
arg.ActorID,
arg.Kind,
arg.FieldCodes,
arg.OccurredAt,
)
return err
}
const insertCandidateHiddenOrganization = `-- name: InsertCandidateHiddenOrganization :one
INSERT INTO candidate_hidden_organizations (
user_id,
@@ -272,6 +356,88 @@ func (q *Queries) InsertCandidateSearchStatus(ctx context.Context, arg InsertCan
return i, err
}
const listCandidateCardAccessEvents = `-- name: ListCandidateCardAccessEvents :many
SELECT
candidate_card_access_events.id,
candidate_card_access_events.candidate_id,
candidate_card_access_events.organization_id,
candidate_card_access_events.actor_id,
candidate_card_access_events.kind,
candidate_card_access_events.field_codes,
candidate_card_access_events.occurred_at,
organizations.name AS organization_name
FROM candidate_card_access_events
INNER JOIN organizations
ON organizations.id = candidate_card_access_events.organization_id
WHERE
candidate_card_access_events.candidate_id = $1
AND (
$2::timestamptz IS NULL
OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC
LIMIT $4
`
type ListCandidateCardAccessEventsParams struct {
CandidateID pgtype.UUID
AfterOccurredAt pgtype.Timestamptz
AfterID pgtype.UUID
RowLimit int32
}
type ListCandidateCardAccessEventsRow struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
OrganizationName string
}
// Lists only the current candidate's own access history. It deliberately
// omits the employee, requested card fields, and search context. The privacy
// read adapter resolves an organization name only through this recorded
// access relation, which is already visible to the candidate.
func (q *Queries) ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error) {
rows, err := q.db.Query(ctx, listCandidateCardAccessEvents,
arg.CandidateID,
arg.AfterOccurredAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateCardAccessEventsRow
for rows.Next() {
var i ListCandidateCardAccessEventsRow
if err := rows.Scan(
&i.ID,
&i.CandidateID,
&i.OrganizationID,
&i.ActorID,
&i.Kind,
&i.FieldCodes,
&i.OccurredAt,
&i.OrganizationName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCandidateHiddenOrganizations = `-- name: ListCandidateHiddenOrganizations :many
SELECT
candidate_hidden_organizations.organization_id,
@@ -480,8 +646,88 @@ func (q *Queries) LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID
return id, err
}
const readCandidatePublication = `-- name: ReadCandidatePublication :one
const readCandidatePrivacySettings = `-- name: ReadCandidatePrivacySettings :one
SELECT
users.id AS user_id,
candidate_publications.state AS publication_state,
candidate_publications.fields AS publication_fields,
candidate_publications.consent_record_id AS publication_consent_record_id,
candidate_publications.published_at AS publication_published_at,
candidate_publications.closed_at AS publication_closed_at,
candidate_publications.version AS publication_version,
consent_records.revoked_at AS publication_consent_revoked_at,
candidate_search_statuses.status AS search_status,
candidate_search_statuses.confirmed_at AS search_confirmed_at,
candidate_search_statuses.lapses_at AS search_lapses_at,
candidate_search_statuses.policy_version_id AS search_policy_version_id,
candidate_search_statuses.version AS search_version,
(
SELECT count(*)
FROM candidate_hidden_organizations
WHERE candidate_hidden_organizations.user_id = users.id
) AS hidden_count
FROM users
LEFT JOIN candidate_publications
ON candidate_publications.user_id = users.id
LEFT JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
LEFT JOIN candidate_search_statuses
ON candidate_search_statuses.user_id = users.id
WHERE users.id = $1
`
type ReadCandidatePrivacySettingsRow struct {
UserID pgtype.UUID
PublicationState pgtype.Text
PublicationFields []string
PublicationConsentRecordID pgtype.UUID
PublicationPublishedAt pgtype.Timestamptz
PublicationClosedAt pgtype.Timestamptz
PublicationVersion pgtype.Int8
PublicationConsentRevokedAt pgtype.Timestamptz
SearchStatus pgtype.Text
SearchConfirmedAt pgtype.Timestamptz
SearchLapsesAt pgtype.Timestamptz
SearchPolicyVersionID pgtype.UUID
SearchVersion pgtype.Int8
HiddenCount int64
}
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the candidate-owned settings and hidden count from one statement
// snapshot. Missing setting rows are restored as the closed/not-looking
// defaults in the adapter. The account row scopes the result but does not
// expose private profile values.
func (q *Queries) ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error) {
row := q.db.QueryRow(ctx, readCandidatePrivacySettings, userID)
var i ReadCandidatePrivacySettingsRow
err := row.Scan(
&i.UserID,
&i.PublicationState,
&i.PublicationFields,
&i.PublicationConsentRecordID,
&i.PublicationPublishedAt,
&i.PublicationClosedAt,
&i.PublicationVersion,
&i.PublicationConsentRevokedAt,
&i.SearchStatus,
&i.SearchConfirmedAt,
&i.SearchLapsesAt,
&i.SearchPolicyVersionID,
&i.SearchVersion,
&i.HiddenCount,
)
return i, err
}
const readCandidatePublication = `-- name: ReadCandidatePublication :one
SELECT
candidate_publications.user_id,
candidate_publications.state,
@@ -512,13 +758,6 @@ type ReadCandidatePublicationRow struct {
ConsentRevokedAt pgtype.Timestamptz
}
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the publication with the revocation state of the C2 record behind it
// in one statement, so the stored setting and the ledger come from one
// snapshot. The effective state is computed from them: published only while
@@ -0,0 +1,330 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: privacy_cohort.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const listVisibleCandidateViewSources = `-- name: ListVisibleCandidateViewSources :many
SELECT
effective.user_id,
effective.fields,
claim.kind,
claim.ordinal,
CASE
WHEN claim.kind = 'experience' THEN jsonb_build_object(
'employer_name', NULL::text,
'specialization', claim.value ->> 'specialization',
'started_on', claim.value ->> 'started_on',
'ended_on', claim.value -> 'ended_on',
'summary', NULL::text
)
ELSE claim.value
END AS safe_value,
claim.status,
claim.origin,
claim.trust_level,
claim.extraction_version,
claim.confirmed_at,
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'first_index', overlap.first_index,
'second_index', overlap.second_index,
'first_period', jsonb_build_object(
'started_on', overlap.first_started_on,
'ended_on', overlap.first_ended_on
),
'second_period', jsonb_build_object(
'started_on', overlap.second_started_on,
'ended_on', overlap.second_ended_on
)
) ORDER BY overlap.first_index, overlap.second_index
)::text
FROM candidate_profile_overlap_confirmations AS overlap
WHERE overlap.user_id = effective.user_id
),
'[]'::text
) AS parallel_period_acknowledgements
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE hidden.user_id = effective.user_id
AND hidden.organization_id = $1
)
ORDER BY effective.user_id, claim.kind, claim.ordinal
`
type ListVisibleCandidateViewSourcesRow struct {
UserID pgtype.UUID
Fields []string
Kind pgtype.Text
Ordinal pgtype.Int2
SafeValue interface{}
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
}
// Organization-facing anonymous candidate projection inputs. The calling
// usecase has already authorized the active organization membership. This
// single statement snapshot filters both revoked/unpublished C2 states and
// candidates hidden from this organization before any profile value is read.
// The projection reads only stack, declared role, and experience dates. It
// deliberately excludes names, contacts, salary, location, soft skills,
// employer names, summaries, and imported excerpts.
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
rows, err := q.db.Query(ctx, listVisibleCandidateViewSources, organizationID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListVisibleCandidateViewSourcesRow
for rows.Next() {
var i ListVisibleCandidateViewSourcesRow
if err := rows.Scan(
&i.UserID,
&i.Fields,
&i.Kind,
&i.Ordinal,
&i.SafeValue,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockCandidateAccountForView = `-- name: LockCandidateAccountForView :one
SELECT users.id
FROM users
WHERE users.id = $1
FOR SHARE
`
// Lock the account before an organization checks candidate visibility. The
// hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
// a hide either commits before the later visibility recheck or waits for the
// read transaction to finish.
func (q *Queries) LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCandidateAccountForView, candidateID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockCurrentC2ForView = `-- name: LockCurrentC2ForView :one
SELECT consent_records.id
FROM consent_records
WHERE
consent_records.subject_id = $1
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NULL
ORDER BY consent_records.granted_at DESC, consent_records.id DESC
LIMIT 1
FOR SHARE
`
// Lock the current C2 before locking the publication. C2 revocation updates
// this row before it locks the publication, so preserving this order avoids
// a lock inversion and makes the current consent stable through the read.
func (q *Queries) LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCurrentC2ForView, candidateID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockPublicationForCandidatePreview = `-- name: LockPublicationForCandidatePreview :one
SELECT candidate_publications.user_id
FROM candidate_publications
INNER JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
WHERE
candidate_publications.user_id = $1
AND candidate_publications.state = 'published'
AND consent_records.subject_id = candidate_publications.user_id
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NULL
FOR SHARE OF candidate_publications, consent_records
`
// Lock a candidate's current publication for the private preview. This has
// no organization context and never enters the employer read quota or audit.
func (q *Queries) LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockPublicationForCandidatePreview, candidateID)
var user_id pgtype.UUID
err := row.Scan(&user_id)
return user_id, err
}
const lockVisiblePublicationForView = `-- name: LockVisiblePublicationForView :one
SELECT candidate_publications.user_id
FROM candidate_publications
INNER JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
WHERE
candidate_publications.user_id = $1
AND candidate_publications.state = 'published'
AND candidate_publications.consent_record_id = $2
AND consent_records.subject_id = candidate_publications.user_id
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = candidate_publications.user_id
AND hidden.organization_id = $3
)
FOR SHARE OF candidate_publications, consent_records
`
type LockVisiblePublicationForViewParams struct {
CandidateID pgtype.UUID
ConsentRecordID pgtype.UUID
OrganizationID pgtype.UUID
}
// Lock and recheck one candidate's exact current publication only after the
// active C2 row is share-locked. No row includes unpublished, revoked, stale
// publication, and organization-hidden states.
func (q *Queries) LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockVisiblePublicationForView, arg.CandidateID, arg.ConsentRecordID, arg.OrganizationID)
var user_id pgtype.UUID
err := row.Scan(&user_id)
return user_id, err
}
const readCandidateViewSourceForPreview = `-- name: ReadCandidateViewSourceForPreview :many
SELECT
effective.user_id,
effective.fields,
claim.kind,
claim.ordinal,
CASE
WHEN claim.kind = 'experience' THEN jsonb_build_object(
'employer_name', NULL::text,
'specialization', claim.value ->> 'specialization',
'started_on', claim.value ->> 'started_on',
'ended_on', claim.value -> 'ended_on',
'summary', NULL::text
)
ELSE claim.value
END AS safe_value,
claim.status,
claim.origin,
claim.trust_level,
claim.extraction_version,
claim.confirmed_at,
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'first_index', overlap.first_index,
'second_index', overlap.second_index,
'first_period', jsonb_build_object(
'started_on', overlap.first_started_on,
'ended_on', overlap.first_ended_on
),
'second_period', jsonb_build_object(
'started_on', overlap.second_started_on,
'ended_on', overlap.second_ended_on
)
) ORDER BY overlap.first_index, overlap.second_index
)::text
FROM candidate_profile_overlap_confirmations AS overlap
WHERE overlap.user_id = effective.user_id
),
'[]'::text
) AS parallel_period_acknowledgements
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE effective.user_id = $1
ORDER BY effective.user_id, claim.kind, claim.ordinal
`
type ReadCandidateViewSourceForPreviewRow struct {
UserID pgtype.UUID
Fields []string
Kind pgtype.Text
Ordinal pgtype.Int2
SafeValue interface{}
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
}
// Read the candidate's current private projection inputs after the caller
// locks its active C2 and publication. It selects only fields allowed in the
// anonymous-card projection and is never used for employer visibility.
func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error) {
rows, err := q.db.Query(ctx, readCandidateViewSourceForPreview, candidateID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadCandidateViewSourceForPreviewRow
for rows.Next() {
var i ReadCandidateViewSourceForPreviewRow
if err := rows.Scan(
&i.UserID,
&i.Fields,
&i.Kind,
&i.Ordinal,
&i.SafeValue,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -60,6 +60,10 @@ type Querier interface {
// redacts the bodies of a token mail like any other cancellation. now is the
// application clock.
CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error)
// The candidate may name an organization in privacy settings only if that
// organization already appears in their own access history or is already
// hidden. Unknown and unseen organizations produce the same no-row result.
CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error)
// Claims the most overdue delivery that the sending worker may send, in one
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
// (the literals match the predicate of deliveries_due_idx, so an idle poll
@@ -118,6 +122,8 @@ type Querier interface {
// returned registration version in the same transaction, rolled back when it
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
// Count events only for the already owner-locked attempt.
CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error)
// Counts the hiding records of one candidate for the settings read.
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
@@ -125,10 +131,22 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// New outcomes share the generic idempotency row and are counted for the
// attempt's rolling receipt window. Replays bypass this query in the usecase.
CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error)
// Counts root attempts only; the caller applies the effective policy's
// configured window and the product's approved accounting scope.
CountRootAssessmentAttemptsSince(ctx context.Context, arg CountRootAssessmentAttemptsSinceParams) (int64, error)
// The strict lower boundary means an event exactly one window old no longer
// counts. The use case derives Retry-After from first_in_window.
CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error)
// Creates one durable deletion request per subject until a worker completes it.
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error)
// A newly reserved generic idempotency window can replace an expired typed
// outcome before the new immutable response is inserted.
DeleteAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) error
// Lifts one hiding. No row returns when the organization was not hidden, so
// the caller writes the history event only for a real deletion and answers
// 204 either way.
@@ -142,9 +160,15 @@ type Querier interface {
// Replaces all specialization answers after the version row advanced in the
// same transaction.
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error
// The generic reservation has already established that a previous outcome is
// expired before this child is removed and replaced in the same transaction.
DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// No raw Idempotency-Key or request body reaches these statements. Failure
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
@@ -190,9 +214,30 @@ type Querier interface {
// Reads the durable active deletion request when an earlier request already
// exists. A completed request does not suppress a later explicit request.
GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error)
// Locks the active real attempt after LockAssessmentAttemptScope.
GetActiveAssessmentAttemptForSpecialization(ctx context.Context, arg GetActiveAssessmentAttemptForSpecializationParams) (AssessmentAttempt, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
// Locks the one active express attempt after LockAssessmentAttemptScope.
GetActiveTrainingAssessmentAttempt(ctx context.Context, userID pgtype.UUID) (AssessmentAttempt, error)
// Returns a full private attempt only to its candidate.
GetAssessmentAttemptForCandidate(ctx context.Context, arg GetAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
GetAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentAttemptIdempotencyOutcomeRow, error)
// Reads the immutable attempt kind without locking the row. Session commands
// use this only to decide whether C3 applies before acquiring the row lock.
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
// Reads a result only for the owning candidate.
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
// Reads an active real attempt without taking the write lock used by create.
// The availability GET never expires or otherwise mutates this row.
GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error)
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
// Counts eligible root attempts in a policy window and computes the instant
// at which one additional root slot opens. The microsecond adjustment matches
// the creation predicate created_at >= since at PostgreSQL timestamp precision.
GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error)
// Read only the receipt associated with the reserved idempotency scope.
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
// Reads one hiding of the candidate with the current name of the
// organization.
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
@@ -236,6 +281,8 @@ type Querier interface {
// resend, which issues its token with the same credentials.
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the latest root in a specialization, optionally restricted to grade.
GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error)
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
@@ -250,6 +297,9 @@ type Querier interface {
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
// Read only the immutable original response. The current need may have moved
// to a later version since this result was created.
GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
@@ -278,6 +328,15 @@ type Querier interface {
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Inserts the attempt header. The database guard rechecks the current policy,
// opening or disjoint training binding, and immutable pins.
InsertAssessmentAttempt(ctx context.Context, arg InsertAssessmentAttemptParams) error
InsertAssessmentAttemptIdempotencyOutcome(ctx context.Context, arg InsertAssessmentAttemptIdempotencyOutcomeParams) error
// Stores the immutable generated variant and empty answer slot.
InsertAssessmentAttemptItem(ctx context.Context, arg InsertAssessmentAttemptItemParams) error
// Stores one immutable candidate-visible result with the decision rationale
// and source versions used by its finalized attempt.
InsertAssessmentAttemptResult(ctx context.Context, arg InsertAssessmentAttemptResultParams) error
// Stores an explicit mapping against a newly-created immutable opening. The
// insert trigger checks the opening, declared reviewer, current policy, and
// live coverage; the adapter supplies the fingerprint of the published set.
@@ -292,6 +351,18 @@ type Querier interface {
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction.
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
// The attempt row is already locked by the caller. Store a parent before its
// bounded child events, in the same transaction as the immutable receipt.
InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error
// Each inserted event is checked by the database guard against attempt state
// and the aggregate capacity as a second line of defense.
InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error
// Save exactly one immutable response receipt for each live idempotency scope.
InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error
// Records a successfully authorized view after visibility and quota checks.
// The audit contains only identities, the access kind, published field codes,
// and time; it never receives the projection content, ranking, or filters.
InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error
// Hides one organization. No row returns when the pair already exists, and
// the caller reads the existing record with its original time. The foreign key
// refuses an unknown organization (SQLSTATE 23503); the caller answers it
@@ -390,12 +461,44 @@ type Querier interface {
// transaction and then inserts nothing, or inserts after its rollback.
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
InsertSession(ctx context.Context, arg InsertSessionParams) error
// The initial public history is inserted in the caller's case transaction.
// Any unique business conflict leaves the transaction usable so the caller can
// store the immutable 409 outcome under the request's idempotency key.
InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error)
InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error
InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error
InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
// Reads chain headers in creation order. The use case verifies root eligibility
// and descending target grades in the domain before it creates a correction.
ListAssessmentAttemptChain(ctx context.Context, arg ListAssessmentAttemptChainParams) ([]AssessmentAttempt, error)
// Reads private frozen variants and candidate answer bytes in stable order.
ListAssessmentAttemptItems(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAttemptItemsRow, error)
// Reads roots within the policy horizon and the last header in each correction
// chain. It deliberately omits frozen items, answers, and row locks.
ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error)
// Counts family instances disclosed after the non-repeat boundary. The first
// item is disclosed when the attempt is created; each later item is disclosed
// when the preceding answer is accepted. This per-item timestamp prevents a
// long-running attempt from making later items appear older than they are.
// Counting the first unanswered item after expiry is conservative when the
// final response was lost, while frozen future items remain excluded.
ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error)
// One page of the versions of a category in key and version order, after the
// given position; an empty key and version 0 start at the beginning. The
// (family_key, version) unique index serves the scan.
ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error)
// Reads the exact family membership pinned by a training binding.
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
// Lists only the current candidate's own access history. It deliberately
// omits the employee, requested card fields, and search context. The privacy
// read adapter resolves an organization name only through this recorded
// access relation, which is already visible to the candidate.
ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error)
// One page of the candidate's hidden organizations, newest first with the
// organization identifier as the tie-breaker. The page continues after the
// (hidden_at, organization_id) position of the last record of the previous
@@ -414,12 +517,22 @@ type Querier interface {
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
// the last record of the previous page.
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
// Returns current reviewed grade/language bindings and the live published
// family manifest at one caller-supplied database time. The adapter verifies
// the pinned manifest hash before exposing only family keys.
ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error)
// Lists explicit immutable training bindings for the effective product
// policy. Callers reject more than one matching active binding as ambiguous.
ListCurrentAssessmentTrainingBindings(ctx context.Context) ([]ListCurrentAssessmentTrainingBindingsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
// Produces current catalog availability in one PostgreSQL statement snapshot.
// The adapter compares the ordered live family manifest with the pinned
// fingerprint; stale bindings are omitted fail-closed.
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// Read one bounded newest-first page of current needs. Both the organization
// scope and the tuple cursor are applied before the limit.
ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
@@ -428,10 +541,36 @@ type Querier interface {
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
// and event history. The tuple cursor matches the composite sort key.
ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error)
// Organization-facing anonymous candidate projection inputs. The calling
// usecase has already authorized the active organization membership. This
// single statement snapshot filters both revoked/unpublished C2 states and
// candidates hidden from this organization before any profile value is read.
// The projection reads only stack, declared role, and experience dates. It
// deliberately excludes names, contacts, salary, location, soft skills,
// employer names, summaries, and imported excerpts.
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
// Locks the organization first and then the active membership, using the
// same order as organization profile writes. A company operation keeps both
// share locks until its transaction commits, so a concurrent revocation
// cannot authorize a write after it has committed.
LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error)
// Locks one owner-scoped attempt while a session command performs its CAS.
LockAssessmentAttemptForCandidate(ctx context.Context, arg LockAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
// Serializes root quota checks for one candidate before taking its optional
// specialization or training lock. All callers acquire these locks in order.
LockAssessmentAttemptScope(ctx context.Context, arg LockAssessmentAttemptScopeParams) error
// Serializes the operations that change which versions of a category are
// published or open the category, until the transaction ends. The key is
// namespaced, so it cannot collide with another use of advisory locks.
LockAssessmentCategory(ctx context.Context, category string) error
// Lock the account before an organization checks candidate visibility. The
// hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
// a hide either commits before the later visibility recheck or waits for the
// read transaction to finish.
LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Locks the candidate's published row only when it refers to a C2 record
// revoked by this transaction. The setting remains linked to that immutable
// record; ReadCandidatePublication computes the effective closed state and
@@ -452,6 +591,10 @@ type Querier interface {
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// Lock the current C2 before locking the publication. C2 revocation updates
// this row before it locks the publication, so preserving this order avoids
// a lock inversion and makes the current consent stable through the read.
LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Takes the candidate's current unrevoked C2 record for a publication and
// keeps it locked until the transaction ends. The share lock conflicts with
// the revocation stamp (an UPDATE of the row), so a revocation either commits
@@ -461,6 +604,9 @@ type Querier interface {
// publication and must re-read the effective state (ReadCandidatePublication)
// in that transaction to build its response.
LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID) (pgtype.UUID, error)
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error)
// Locks the listed window rows until the transaction ends, in
// (period_kind, period_start) order, the same order for every caller, and
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
@@ -482,8 +628,17 @@ type Querier interface {
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
// Lock a candidate's current publication for the private preview. This has
// no organization context and never enters the employer read quota or audit.
LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Locks the active registration C1 while its pending registration is applied.
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
// Serialize per-owner budget checks even before the first event exists.
LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error
// Lock and recheck one candidate's exact current publication only after the
// active C2 row is share-locked. No row includes unpublished, revoked, stale
// publication, and organization-hidden states.
LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error)
// Notes that a request is about to start, by the database clock, and clears
// the count of worker failures. For an operator-authorized send, this sets
// its single-use marker without overwriting the original first-send time. The
@@ -504,10 +659,16 @@ type Querier interface {
// Verifies the email only for the registration version the consumed token
// was issued for.
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
// request are expected and do not expose request contents.
NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error)
Ping(ctx context.Context) (int32, error)
// Reports whether a family has any version without reading a document, so a
// caller that only needs presence never depends on decoding.
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
// Keep up to the maximum supported window, regardless of the current policy.
// The bounded delete prevents one create from doing unbounded cleanup work.
PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error)
// Moves a draft to published by the named operator and returns the row with
// the publication time set by the guard trigger. No row means the version
// was not a draft any more.
@@ -515,6 +676,18 @@ type Querier interface {
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the candidate-owned settings and hidden count from one statement
// snapshot. Missing setting rows are restored as the closed/not-looking
// defaults in the adapter. The account row scopes the result but does not
// expose private profile values.
ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error)
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
@@ -523,13 +696,6 @@ type Querier interface {
// 0). Claims come in a stable order: single fields by kind, list items by
// position. Never replace this with two statements.
ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the publication with the revocation state of the C2 record behind it
// in one statement, so the stored setting and the ledger come from one
// snapshot. The effective state is computed from them: published only while
@@ -542,10 +708,16 @@ 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 the candidate's current private projection inputs after the caller
// locks its active C2 and publication. It selects only fields allowed in the
// anonymous-card projection and is never used for employer visibility.
ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, 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)
// Reads a full owner-scoped record. Object values are identifiers only.
ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, 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
@@ -557,6 +729,9 @@ type Querier interface {
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error)
ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error)
// Reads the immutable public history only after the case owner has matched.
ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
@@ -609,6 +784,14 @@ type Querier interface {
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error)
// Finds candidate-requested selections across currently opened categories.
// The adapter validates policy and manifest freshness, locks the category,
// then runs this query again before it returns any pinned families.
ResolveCurrentAssessmentSelection(ctx context.Context, arg ResolveCurrentAssessmentSelectionParams) ([]ResolveCurrentAssessmentSelectionRow, error)
// Lists every current reviewed category binding for one exact public target.
// Manual support cases have no task-language selector, so the use case must
// accept a rubric only when one distinct current opening matches.
ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error)
RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error)
// Revokes every unrevoked record of a purpose other than C4, superseded ones
// included, and returns them. A revocation time before the grant time, from
@@ -625,6 +808,10 @@ type Querier interface {
// and owner membership. A reused expired scope replaces the snapshot in the
// same transaction as the new organization.
SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error
// The generic idempotency scope serializes retries. Replacing the child row
// is safe only in the transaction that reserves an expired scope for a new
// create; live retries read and return the stored response without writing.
SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error
// Bounds a consumer transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a process that froze or lost the network inside the
@@ -661,6 +848,14 @@ type Querier interface {
// revoked, expired, or idle session is not revived; the update re-checks
// those conditions against a concurrent change.
TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error)
// Stores one final answer before advancing the enclosing attempt version.
// The caller holds the owner-scoped attempt row lock for the surrounding unit.
UpdateAssessmentAttemptItemAnswer(ctx context.Context, arg UpdateAssessmentAttemptItemAnswerParams) (pgtype.UUID, error)
// Applies a versioned session transition after the attempt row is locked.
UpdateAssessmentAttemptSession(ctx context.Context, arg UpdateAssessmentAttemptSessionParams) (AssessmentAttempt, error)
// Applies an answer, expiry, or finalization transition after the attempt row
// is locked. Session limits and all immutable pins remain unchanged.
UpdateAssessmentAttemptTransition(ctx context.Context, arg UpdateAssessmentAttemptTransitionParams) (AssessmentAttempt, error)
// Replaces the publication over the version the caller read and advances the
// version in the same statement. No row returns for a stale version, which
// the caller answers as a version conflict. The update time never moves back,
@@ -0,0 +1,502 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: support_cases.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countSupportCaseRequestEvents = `-- name: CountSupportCaseRequestEvents :one
SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window
FROM support_case_request_events
WHERE owner_id = $1
AND requested_at > $2::timestamptz
AND requested_at <= $3::timestamptz
`
type CountSupportCaseRequestEventsParams struct {
OwnerID pgtype.UUID
WindowStart pgtype.Timestamptz
At pgtype.Timestamptz
}
type CountSupportCaseRequestEventsRow struct {
EventCount int64
FirstInWindow interface{}
}
// The strict lower boundary means an event exactly one window old no longer
// counts. The use case derives Retry-After from first_in_window.
func (q *Queries) CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error) {
row := q.db.QueryRow(ctx, countSupportCaseRequestEvents, arg.OwnerID, arg.WindowStart, arg.At)
var i CountSupportCaseRequestEventsRow
err := row.Scan(&i.EventCount, &i.FirstInWindow)
return i, err
}
const deleteSupportCaseCreateOutcome = `-- name: DeleteSupportCaseCreateOutcome :exec
DELETE FROM support_case_create_outcomes
WHERE scope_hash = $1
`
// No raw Idempotency-Key or request body reaches these statements. Failure
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
func (q *Queries) DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error {
_, err := q.db.Exec(ctx, deleteSupportCaseCreateOutcome, scopeHash)
return err
}
const insertSupportCase = `-- name: InsertSupportCase :execrows
INSERT INTO support_cases (
id, case_number, owner_id, case_type, status, description,
object_type, object_id, assessment_specialization, assessment_grade,
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
target_business_days, target_due_at,
target_answered_at, target_policy_version, target_calendar_version,
decision_outcome, decision_reason, decision_at, created_at, updated_at
) VALUES (
$1, $2, $3, $4,
$5, $6, $7, $8,
$9, $10,
$11, $12, $13,
$14, $15,
$16, $17, $18,
$19, $20, $21,
$22, $23, $24
)
ON CONFLICT DO NOTHING
`
type InsertSupportCaseParams struct {
ID pgtype.UUID
CaseNumber string
OwnerID pgtype.UUID
CaseType string
Status string
Description string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
ComplaintReason pgtype.Text
RubricVersion pgtype.Int4
RubricOpeningID pgtype.UUID
RubricPolicyVersionID pgtype.UUID
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
DecisionReason pgtype.Text
DecisionAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// The initial public history is inserted in the caller's case transaction.
// Any unique business conflict leaves the transaction usable so the caller can
// store the immutable 409 outcome under the request's idempotency key.
func (q *Queries) InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error) {
result, err := q.db.Exec(ctx, insertSupportCase,
arg.ID,
arg.CaseNumber,
arg.OwnerID,
arg.CaseType,
arg.Status,
arg.Description,
arg.ObjectType,
arg.ObjectID,
arg.AssessmentSpecialization,
arg.AssessmentGrade,
arg.ComplaintReason,
arg.RubricVersion,
arg.RubricOpeningID,
arg.RubricPolicyVersionID,
arg.TargetBusinessDays,
arg.TargetDueAt,
arg.TargetAnsweredAt,
arg.TargetPolicyVersion,
arg.TargetCalendarVersion,
arg.DecisionOutcome,
arg.DecisionReason,
arg.DecisionAt,
arg.CreatedAt,
arg.UpdatedAt,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const insertSupportCaseCreateOutcome = `-- name: InsertSupportCaseCreateOutcome :exec
INSERT INTO support_case_create_outcomes (
scope_hash, outcome_kind, case_snapshot, target_was_late, created_at
) VALUES (
$1, $2,
CASE WHEN $2::text = 'created' THEN $3::jsonb END,
CASE WHEN $2::text = 'created' THEN $4::boolean END,
$5
)
`
type InsertSupportCaseCreateOutcomeParams struct {
ScopeHash []byte
OutcomeKind string
CaseSnapshot []byte
TargetWasLate bool
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseCreateOutcome,
arg.ScopeHash,
arg.OutcomeKind,
arg.CaseSnapshot,
arg.TargetWasLate,
arg.CreatedAt,
)
return err
}
const insertSupportCaseEvent = `-- name: InsertSupportCaseEvent :exec
INSERT INTO support_case_events (
case_id, sequence, event_kind, actor_kind, occurred_at, status, message
) VALUES (
$1, $2, $3, $4,
$5, $6, $7
)
`
type InsertSupportCaseEventParams struct {
CaseID pgtype.UUID
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
func (q *Queries) InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseEvent,
arg.CaseID,
arg.Sequence,
arg.EventKind,
arg.ActorKind,
arg.OccurredAt,
arg.Status,
arg.Message,
)
return err
}
const insertSupportCaseRequestEvent = `-- name: InsertSupportCaseRequestEvent :exec
INSERT INTO support_case_request_events (owner_id, requested_at)
VALUES ($1, $2)
`
type InsertSupportCaseRequestEventParams struct {
OwnerID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
func (q *Queries) InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseRequestEvent, arg.OwnerID, arg.RequestedAt)
return err
}
const latestSupportCaseRequestEvent = `-- name: LatestSupportCaseRequestEvent :one
SELECT requested_at
FROM support_case_request_events
WHERE owner_id = $1
ORDER BY requested_at DESC, id DESC
LIMIT 1
`
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
func (q *Queries) LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, latestSupportCaseRequestEvent, ownerID)
var requested_at pgtype.Timestamptz
err := row.Scan(&requested_at)
return requested_at, err
}
const listOwnedSupportCases = `-- name: ListOwnedSupportCases :many
WITH cursor_input AS MATERIALIZED (
SELECT
$3::timestamptz AS after_created_at,
$4::uuid AS after_id
)
SELECT
id, case_number, case_type, status, object_type, object_id,
assessment_specialization, assessment_grade, target_business_days,
target_due_at, target_answered_at, target_policy_version,
target_calendar_version, decision_outcome, created_at, updated_at
FROM support_cases
CROSS JOIN cursor_input
WHERE owner_id = $1
AND (
cursor_input.after_created_at IS NULL
OR (created_at, id) < (
cursor_input.after_created_at,
cursor_input.after_id
)
)
ORDER BY created_at DESC, id DESC
LIMIT $2
`
type ListOwnedSupportCasesParams struct {
OwnerID pgtype.UUID
RowLimit int32
AfterCreatedAt pgtype.Timestamptz
AfterID pgtype.UUID
}
type ListOwnedSupportCasesRow struct {
ID pgtype.UUID
CaseNumber string
CaseType string
Status string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
// and event history. The tuple cursor matches the composite sort key.
func (q *Queries) ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error) {
rows, err := q.db.Query(ctx, listOwnedSupportCases,
arg.OwnerID,
arg.RowLimit,
arg.AfterCreatedAt,
arg.AfterID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOwnedSupportCasesRow
for rows.Next() {
var i ListOwnedSupportCasesRow
if err := rows.Scan(
&i.ID,
&i.CaseNumber,
&i.CaseType,
&i.Status,
&i.ObjectType,
&i.ObjectID,
&i.AssessmentSpecialization,
&i.AssessmentGrade,
&i.TargetBusinessDays,
&i.TargetDueAt,
&i.TargetAnsweredAt,
&i.TargetPolicyVersion,
&i.TargetCalendarVersion,
&i.DecisionOutcome,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockSupportCaseRequestBudget = `-- name: LockSupportCaseRequestBudget :exec
SELECT pg_advisory_xact_lock(
hashtextextended('lincodex.support.case.requests:' || $1::uuid::text, 0)
)
`
// Serialize per-owner budget checks even before the first event exists.
func (q *Queries) LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error {
_, err := q.db.Exec(ctx, lockSupportCaseRequestBudget, ownerID)
return err
}
const nextSupportCaseNumber = `-- name: NextSupportCaseNumber :one
WITH next_value AS MATERIALIZED (
SELECT nextval('support_case_number_seq') AS value
)
SELECT
'SC-' || $1::text || '-' ||
CASE
WHEN next_value.value < 1000000 THEN lpad(next_value.value::text, 6, '0')
ELSE next_value.value::text
END::text AS case_number
FROM next_value
`
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
// request are expected and do not expose request contents.
func (q *Queries) NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error) {
row := q.db.QueryRow(ctx, nextSupportCaseNumber, utcYear)
var case_number interface{}
err := row.Scan(&case_number)
return case_number, err
}
const pruneSupportCaseRequestEvents = `-- name: PruneSupportCaseRequestEvents :execrows
WITH expired AS MATERIALIZED (
SELECT source.id
FROM support_case_request_events AS source
WHERE source.owner_id = $1
AND source.requested_at <= $2::timestamptz - interval '24 hours'
ORDER BY source.requested_at, source.id
LIMIT 100
FOR UPDATE SKIP LOCKED
)
DELETE FROM support_case_request_events AS event
USING expired
WHERE event.id = expired.id
`
type PruneSupportCaseRequestEventsParams struct {
OwnerID pgtype.UUID
At pgtype.Timestamptz
}
// Keep up to the maximum supported window, regardless of the current policy.
// The bounded delete prevents one create from doing unbounded cleanup work.
func (q *Queries) PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error) {
result, err := q.db.Exec(ctx, pruneSupportCaseRequestEvents, arg.OwnerID, arg.At)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const readOwnedSupportCase = `-- name: ReadOwnedSupportCase :one
SELECT
id, case_number, owner_id, case_type, status, description,
object_type, object_id, assessment_specialization, assessment_grade,
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
target_business_days, target_due_at,
target_answered_at, target_policy_version, target_calendar_version,
decision_outcome, decision_reason, decision_at, created_at, updated_at
FROM support_cases
WHERE id = $1 AND owner_id = $2
`
type ReadOwnedSupportCaseParams struct {
CaseID pgtype.UUID
OwnerID pgtype.UUID
}
// Reads a full owner-scoped record. Object values are identifiers only.
func (q *Queries) ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, error) {
row := q.db.QueryRow(ctx, readOwnedSupportCase, arg.CaseID, arg.OwnerID)
var i SupportCase
err := row.Scan(
&i.ID,
&i.CaseNumber,
&i.OwnerID,
&i.CaseType,
&i.Status,
&i.Description,
&i.ObjectType,
&i.ObjectID,
&i.AssessmentSpecialization,
&i.AssessmentGrade,
&i.ComplaintReason,
&i.RubricVersion,
&i.RubricOpeningID,
&i.RubricPolicyVersionID,
&i.TargetBusinessDays,
&i.TargetDueAt,
&i.TargetAnsweredAt,
&i.TargetPolicyVersion,
&i.TargetCalendarVersion,
&i.DecisionOutcome,
&i.DecisionReason,
&i.DecisionAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const readSupportCaseCreateOutcome = `-- name: ReadSupportCaseCreateOutcome :one
SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late
FROM support_case_create_outcomes
WHERE scope_hash = $1
`
type ReadSupportCaseCreateOutcomeRow struct {
OutcomeKind string
CaseSnapshot interface{}
TargetWasLate pgtype.Bool
}
func (q *Queries) ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error) {
row := q.db.QueryRow(ctx, readSupportCaseCreateOutcome, scopeHash)
var i ReadSupportCaseCreateOutcomeRow
err := row.Scan(&i.OutcomeKind, &i.CaseSnapshot, &i.TargetWasLate)
return i, err
}
const readSupportCaseEvents = `-- name: ReadSupportCaseEvents :many
SELECT sequence, event_kind, actor_kind, occurred_at, status, message
FROM support_case_events
WHERE case_id = $1
ORDER BY sequence
`
type ReadSupportCaseEventsRow struct {
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
// Reads the immutable public history only after the case owner has matched.
func (q *Queries) ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error) {
rows, err := q.db.Query(ctx, readSupportCaseEvents, caseID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadSupportCaseEventsRow
for rows.Next() {
var i ReadSupportCaseEventsRow
if err := rows.Scan(
&i.Sequence,
&i.EventKind,
&i.ActorKind,
&i.OccurredAt,
&i.Status,
&i.Message,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,120 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: support_rubrics.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const resolveCurrentSupportCaseRubrics = `-- name: ResolveCurrentSupportCaseRubrics :many
WITH current_openings AS (
SELECT DISTINCT ON (category)
id,
category,
policy_version_id,
required_families
FROM assessment_category_openings
ORDER BY category, opened_at DESC, id DESC
), current_policy AS (
SELECT id, version
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
ORDER BY version DESC
LIMIT 1
)
SELECT
opening.id AS opening_id,
opening.category,
opening.policy_version_id,
opening.required_families,
COALESCE((
SELECT count(DISTINCT family.family_key)::integer
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), 0)::integer AS published_count,
policy.id AS effective_policy_id,
policy.version AS effective_policy_version,
binding.specialization,
binding.grade,
binding.task_languages,
binding.published_manifest_sha256,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'family_key', family.family_key,
'version', family.version,
'content_sha256', encode(family.content_sha256, 'hex')
) ORDER BY family.family_key, family.version
)
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), '[]'::jsonb)::text AS published_manifest
FROM current_openings AS opening
JOIN assessment_category_catalog_bindings AS binding
ON binding.opening_id = opening.id
LEFT JOIN current_policy AS policy ON true
WHERE binding.specialization = $1
AND binding.grade = $2
ORDER BY opening.category
`
type ResolveCurrentSupportCaseRubricsParams struct {
Specialization string
Grade string
}
type ResolveCurrentSupportCaseRubricsRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
EffectivePolicyVersion pgtype.Int4
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// Lists every current reviewed category binding for one exact public target.
// Manual support cases have no task-language selector, so the use case must
// accept a rubric only when one distinct current opening matches.
func (q *Queries) ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error) {
rows, err := q.db.Query(ctx, resolveCurrentSupportCaseRubrics, arg.Specialization, arg.Grade)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ResolveCurrentSupportCaseRubricsRow
for rows.Next() {
var i ResolveCurrentSupportCaseRubricsRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.EffectivePolicyVersion,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,618 @@
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"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const maxSupportCaseSnapshotBytes = 1 << 20
var supportCaseConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "support_cases_owner_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "support_case_create_outcomes_scope_hash_fkey"}: outbound.ErrIdempotencyRecordNotFound,
}
var (
_ outbound.SupportCaseRepository = supportCaseRepository{}
_ outbound.SupportCaseCreateOutcomeRepository = supportCaseRepository{}
_ outbound.SupportCaseRequestLimitRepository = supportCaseRepository{}
_ outbound.SupportCaseRepositories = (*UnitOfWork)(nil)
)
func (unit *UnitOfWork) SupportCases() outbound.SupportCaseRepository {
return supportCaseRepository{queries: unit.queries}
}
func (unit *UnitOfWork) SupportCaseCreateOutcomes() outbound.SupportCaseCreateOutcomeRepository {
return supportCaseRepository{queries: unit.queries}
}
func (unit *UnitOfWork) SupportCaseRequestLimits() outbound.SupportCaseRequestLimitRepository {
return supportCaseRepository{queries: unit.queries}
}
type supportCaseRepository struct {
queries *sqlc.Queries
}
func (repository supportCaseRepository) NextNumber(ctx context.Context, createdAt time.Time) (domain.SupportCaseNumber, error) {
const location = "supportCaseRepository.NextNumber"
if createdAt.IsZero() || createdAt.Year() < 1 || createdAt.Year() > 9999 {
return "", fmt.Errorf("%s - creation time is invalid: %w", location, domain.ErrInvalidSupportCase)
}
value, err := repository.queries.NextSupportCaseNumber(ctx, fmt.Sprintf("%04d", createdAt.UTC().Year()))
if err != nil {
return "", fmt.Errorf("%s - allocate number: %w", location, mapSupportCaseError(err))
}
var number string
switch stored := value.(type) {
case string:
number = stored
case []byte:
number = string(stored)
default:
return "", fmt.Errorf("%s - database returned an invalid number type", location)
}
parsed, err := domain.ParseSupportCaseNumber(number)
if err != nil {
return "", fmt.Errorf("%s - database returned an invalid number", location)
}
return parsed, nil
}
func (repository supportCaseRepository) Create(ctx context.Context, supportCase domain.SupportCase) error {
const location = "supportCaseRepository.Create"
if supportCase.IsZero() {
return fmt.Errorf("%s - case is not initialized: %w", location, domain.ErrInvalidSupportCase)
}
snapshot := supportCase.Snapshot()
validated, err := domain.RestoreSupportCase(snapshot)
if err != nil {
return fmt.Errorf("%s - validate case: %w", location, err)
}
snapshot = validated.Snapshot()
row := supportCaseInsertParams(snapshot)
inserted, err := repository.queries.InsertSupportCase(ctx, row)
if err != nil {
return fmt.Errorf("%s - insert case: %w", location, mapSupportCaseError(err))
}
if inserted != 1 {
return fmt.Errorf("%s - unique business rule rejected the case: %w", location, outbound.ErrSupportCaseConflict)
}
for _, event := range snapshot.History {
if err := repository.queries.InsertSupportCaseEvent(ctx, supportCaseEventParams(snapshot.ID.UUID(), event)); err != nil {
return fmt.Errorf("%s - insert public event: %w", location, mapSupportCaseError(err))
}
}
return nil
}
func (repository supportCaseRepository) GetOwned(ctx context.Context, ownerID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) {
const location = "supportCaseRepository.GetOwned"
if ownerID == uuid.Nil || caseID.IsZero() {
return domain.SupportCase{}, fmt.Errorf("%s - scope identifiers are invalid: %w", location, domain.ErrInvalidSupportCase)
}
row, err := repository.queries.ReadOwnedSupportCase(ctx, sqlc.ReadOwnedSupportCaseParams{
CaseID: pgUUID(caseID.UUID()), OwnerID: pgUUID(ownerID),
})
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - read owner-scoped case: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseNotFound))
}
events, err := repository.queries.ReadSupportCaseEvents(ctx, pgUUID(caseID.UUID()))
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - read public history: %w", location, mapSupportCaseError(err))
}
snapshot, err := supportCaseSnapshotFromRow(row, events)
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - restore stored case: %w", location, err)
}
if snapshot.OwnerID != ownerID || snapshot.ID != caseID {
return domain.SupportCase{}, fmt.Errorf("%s - stored case scope does not match query", location)
}
supportCase, err := domain.RestoreSupportCase(snapshot)
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - validate stored case: %w", location, err)
}
return supportCase, nil
}
func (repository supportCaseRepository) ListOwned(ctx context.Context, query outbound.SupportCaseListQuery) (outbound.SupportCaseListPage, error) {
const location = "supportCaseRepository.ListOwned"
if query.OwnerID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxSupportCasePageSize {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - owner and page limit are invalid: %w", location, domain.ErrInvalidSupportCase)
}
params := sqlc.ListOwnedSupportCasesParams{OwnerID: pgUUID(query.OwnerID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.ID.IsZero() || !validSupportCasePositionTime(query.After.CreatedAt) {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - cursor position is invalid: %w", location, domain.ErrInvalidSupportCase)
}
params.AfterCreatedAt = pgTime(query.After.CreatedAt.UTC())
params.AfterID = pgUUID(query.After.ID.UUID())
}
rows, err := repository.queries.ListOwnedSupportCases(ctx, params)
if err != nil {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - select owner-scoped summaries: %w", location, mapSupportCaseError(err))
}
page := outbound.SupportCaseListPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]domain.SupportCaseSummary, 0, len(rows))
for _, row := range rows {
summary, err := supportCaseSummaryFromRow(row)
if err != nil {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - restore stored summary: %w", location, err)
}
page.Items = append(page.Items, summary)
}
return page, nil
}
func (repository supportCaseRepository) DeleteCreateOutcome(ctx context.Context, scope [outbound.IdempotencyDigestSize]byte) error {
const location = "supportCaseRepository.DeleteCreateOutcome"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return fmt.Errorf("%s - idempotency scope must be set", location)
}
if err := repository.queries.DeleteSupportCaseCreateOutcome(ctx, scope[:]); err != nil {
return fmt.Errorf("%s - delete expired outcome: %w", location, mapSupportCaseError(err))
}
return nil
}
func (repository supportCaseRepository) SaveCreateOutcome(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
outcome domain.SupportCaseCreateOutcome,
createdAt time.Time,
) error {
const location = "supportCaseRepository.SaveCreateOutcome"
if scope == ([outbound.IdempotencyDigestSize]byte{}) || !validSupportCasePositionTime(createdAt) {
return fmt.Errorf("%s - scope and creation time must be valid", location)
}
validated, err := domain.RestoreSupportCaseCreateOutcome(outcome.Snapshot())
if err != nil {
return fmt.Errorf("%s - validate outcome: %w", location, err)
}
snapshot := validated.Snapshot()
encoded := []byte(`{}`)
var targetWasLate bool
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
encoded, err = json.Marshal(snapshot.Case)
if err != nil {
return fmt.Errorf("%s - encode outcome snapshot", location)
}
if len(encoded) > maxSupportCaseSnapshotBytes {
return fmt.Errorf("%s - outcome snapshot exceeds its storage bound: %w", location, domain.ErrInvalidSupportCase)
}
targetWasLate = snapshot.TargetWasLate
}
if err := repository.queries.InsertSupportCaseCreateOutcome(ctx, sqlc.InsertSupportCaseCreateOutcomeParams{
ScopeHash: scope[:], OutcomeKind: string(snapshot.Kind), CaseSnapshot: encoded,
TargetWasLate: targetWasLate, CreatedAt: pgTime(createdAt.UTC().Truncate(time.Microsecond)),
}); err != nil {
return fmt.Errorf("%s - insert immutable outcome: %w", location, mapSupportCaseError(err))
}
return nil
}
func (repository supportCaseRepository) GetCreateOutcome(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (domain.SupportCaseCreateOutcome, error) {
const location = "supportCaseRepository.GetCreateOutcome"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - idempotency scope must be set", location)
}
row, err := repository.queries.ReadSupportCaseCreateOutcome(ctx, scope[:])
if err != nil {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - read immutable outcome: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseCreateOutcomeNotFound))
}
snapshot := domain.SupportCaseCreateOutcomeSnapshot{Kind: domain.SupportCaseCreateOutcomeKind(row.OutcomeKind)}
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
encoded, ok := supportCaseJSONBytes(row.CaseSnapshot)
if !ok || len(encoded) == 0 || len(encoded) > maxSupportCaseSnapshotBytes || !row.TargetWasLate.Valid {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored created outcome is invalid", location)
}
var stored domain.SupportCaseSnapshot
if err := decodeSupportCaseJSON(encoded, &stored); err != nil {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored case snapshot is invalid", location)
}
snapshot.Case = &stored
snapshot.TargetWasLate = row.TargetWasLate.Bool
} else if row.TargetWasLate.Valid {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored failure outcome has a late flag", location)
}
outcome, err := domain.RestoreSupportCaseCreateOutcome(snapshot)
if err != nil {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
}
return outcome, nil
}
func (repository supportCaseRepository) Consume(
ctx context.Context,
ownerID uuid.UUID,
at time.Time,
maxRequests int32,
window time.Duration,
) (outbound.SupportCaseRequestLimitResult, error) {
const location = "supportCaseRepository.Consume"
if ownerID == uuid.Nil || !validSupportCasePositionTime(at) || maxRequests < 1 || window < time.Second ||
window > domain.MaxSupportRequestWindow || window%time.Second != 0 {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - request budget parameters are invalid: %w", location, domain.ErrInvalidSupportCase)
}
at = at.UTC().Truncate(time.Microsecond)
if _, err := repository.queries.PruneSupportCaseRequestEvents(ctx, sqlc.PruneSupportCaseRequestEventsParams{
OwnerID: pgUUID(ownerID), At: pgTime(at),
}); err != nil {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - prune request history: %w", location, mapSupportCaseError(err))
}
windowStart := at.Add(-window)
count, err := repository.queries.CountSupportCaseRequestEvents(ctx, sqlc.CountSupportCaseRequestEventsParams{
OwnerID: pgUUID(ownerID), WindowStart: pgTime(windowStart), At: pgTime(at),
})
if err != nil {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - count request history: %w", location, mapSupportCaseError(err))
}
if count.EventCount >= int64(maxRequests) {
first, ok := supportCaseFirstEventTime(count.FirstInWindow)
if !ok {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - oldest qualifying event is missing", location)
}
retryAfter := first.Add(window).Sub(at)
if retryAfter <= 0 {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - retry interval is invalid", location)
}
return outbound.SupportCaseRequestLimitResult{Allowed: false, RetryAfter: retryAfter}, nil
}
if err := repository.queries.InsertSupportCaseRequestEvent(ctx, sqlc.InsertSupportCaseRequestEventParams{
OwnerID: pgUUID(ownerID), RequestedAt: pgTime(at),
}); err != nil {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - record request: %w", location, mapSupportCaseError(err))
}
return outbound.SupportCaseRequestLimitResult{Allowed: true}, nil
}
func (repository supportCaseRepository) LockOwner(ctx context.Context, ownerID uuid.UUID) (time.Time, error) {
const location = "supportCaseRepository.LockOwner"
if ownerID == uuid.Nil {
return time.Time{}, fmt.Errorf("%s - owner ID must be set", location)
}
if err := repository.queries.LockSupportCaseRequestBudget(ctx, pgUUID(ownerID)); err != nil {
return time.Time{}, fmt.Errorf("%s - take transaction lock: %w", location, mapSupportCaseError(err))
}
latest, err := repository.queries.LatestSupportCaseRequestEvent(ctx, pgUUID(ownerID))
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, nil
}
if err != nil {
return time.Time{}, fmt.Errorf("%s - read latest request timestamp: %w", location, mapSupportCaseError(err))
}
if !validSupportCasePositionTime(latest.Time) {
return time.Time{}, fmt.Errorf("%s - stored request timestamp is invalid", location)
}
return latest.Time.UTC().Truncate(time.Microsecond), nil
}
func supportCaseInsertParams(snapshot domain.SupportCaseSnapshot) sqlc.InsertSupportCaseParams {
return sqlc.InsertSupportCaseParams{
ID: pgUUID(snapshot.ID.UUID()), CaseNumber: snapshot.Number.String(), OwnerID: pgUUID(snapshot.OwnerID),
CaseType: string(snapshot.Type), Status: string(snapshot.Status), Description: snapshot.Description,
ObjectType: optionalSupportText(snapshot.Object, func(value *domain.SupportCaseReference) string { return string(value.Type) }),
ObjectID: optionalSupportUUID(snapshot.Object),
AssessmentSpecialization: optionalSupportAssessment(snapshot.AssessmentTarget, true),
AssessmentGrade: optionalSupportAssessment(snapshot.AssessmentTarget, false),
ComplaintReason: optionalSupportComplaint(snapshot.ComplaintReason), RubricVersion: optionalSupportInt32(snapshot.RubricVersion),
RubricOpeningID: optionalSupportUUIDPointer(snapshot.RubricOpeningID),
RubricPolicyVersionID: optionalSupportPolicyID(snapshot.RubricPolicyID),
TargetBusinessDays: int32(snapshot.ResponseTarget.BusinessDays), TargetDueAt: pgTime(snapshot.ResponseTarget.DueAt),
TargetAnsweredAt: pgOptionalTime(snapshot.ResponseTarget.AnsweredAt), TargetPolicyVersion: snapshot.ResponseTarget.PolicyVersion,
TargetCalendarVersion: snapshot.ResponseTarget.CalendarVersion,
DecisionOutcome: optionalSupportDecision(snapshot.Decision, true), DecisionReason: optionalSupportDecision(snapshot.Decision, false),
DecisionAt: optionalSupportDecisionTime(snapshot.Decision), CreatedAt: pgTime(snapshot.CreatedAt), UpdatedAt: pgTime(snapshot.UpdatedAt),
}
}
func supportCaseEventParams(caseID uuid.UUID, event domain.SupportCaseEventSnapshot) sqlc.InsertSupportCaseEventParams {
return sqlc.InsertSupportCaseEventParams{
CaseID: pgUUID(caseID), Sequence: event.Sequence, EventKind: string(event.Kind), ActorKind: string(event.Actor),
OccurredAt: pgTime(event.OccurredAt), Status: optionalSupportEventStatus(event.Status), Message: optionalSupportEventMessage(event.Message),
}
}
func supportCaseSnapshotFromRow(row sqlc.SupportCase, events []sqlc.ReadSupportCaseEventsRow) (domain.SupportCaseSnapshot, error) {
const location = "supportCaseSnapshotFromRow"
if !row.ID.Valid || !row.OwnerID.Valid || !row.TargetDueAt.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - required stored fields are missing", location)
}
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
if err != nil {
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - case number is invalid", location)
}
snapshot := domain.SupportCaseSnapshot{
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, OwnerID: uuid.UUID(row.OwnerID.Bytes),
Type: domain.SupportCaseType(row.CaseType), Status: domain.SupportCaseStatus(row.Status), Description: row.Description,
Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
ComplaintReason: optionalSupportCaseComplaint(row.ComplaintReason), RubricVersion: optionalSupportCaseInt4(row.RubricVersion),
RubricOpeningID: optionalSupportCaseUUID(row.RubricOpeningID),
RubricPolicyID: optionalSupportCasePolicyID(row.RubricPolicyVersionID),
ResponseTarget: domain.SupportResponseTargetSnapshot{
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
CalendarVersion: row.TargetCalendarVersion,
},
Decision: supportCaseDecisionFromColumns(row.DecisionOutcome, row.DecisionReason, row.DecisionAt),
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
History: make([]domain.SupportCaseEventSnapshot, 0, len(events)),
}
for _, stored := range events {
if !stored.OccurredAt.Valid {
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - stored event timestamp is missing", location)
}
snapshot.History = append(snapshot.History, domain.SupportCaseEventSnapshot{
Sequence: stored.Sequence, Kind: domain.SupportCaseEventKind(stored.EventKind), Actor: domain.SupportCaseActorKind(stored.ActorKind),
OccurredAt: stored.OccurredAt.Time, Status: optionalSupportCaseStatus(stored.Status), Message: optionalSupportCaseText(stored.Message),
})
}
return snapshot, nil
}
func supportCaseSummaryFromRow(row sqlc.ListOwnedSupportCasesRow) (domain.SupportCaseSummary, error) {
const location = "supportCaseSummaryFromRow"
if !row.ID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || !row.TargetDueAt.Valid {
return domain.SupportCaseSummary{}, fmt.Errorf("%s - required stored fields are missing", location)
}
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
if err != nil {
return domain.SupportCaseSummary{}, fmt.Errorf("%s - case number is invalid", location)
}
summary := domain.SupportCaseSummary{
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, Type: domain.SupportCaseType(row.CaseType),
Status: domain.SupportCaseStatus(row.Status), Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
ResponseTarget: domain.SupportResponseTargetSnapshot{
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
CalendarVersion: row.TargetCalendarVersion,
},
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
}
if row.DecisionOutcome.Valid {
outcome := domain.SupportCaseDecisionOutcome(row.DecisionOutcome.String)
summary.DecisionOutcome = &outcome
}
return domain.RestoreSupportCaseSummary(summary)
}
func supportCaseReferenceFromColumns(objectType pgtype.Text, objectID pgtype.UUID) *domain.SupportCaseReference {
if !objectType.Valid && !objectID.Valid {
return nil
}
return &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(objectType.String), ID: uuid.UUID(objectID.Bytes)}
}
func supportCaseAssessmentFromColumns(specialization, grade pgtype.Text) *domain.SupportCaseAssessmentTarget {
if !specialization.Valid && !grade.Valid {
return nil
}
return &domain.SupportCaseAssessmentTarget{
Specialization: domain.SpecializationCode(specialization.String), Grade: domain.GradeCode(grade.String),
}
}
func supportCaseDecisionFromColumns(outcome, reason pgtype.Text, at pgtype.Timestamptz) *domain.SupportCaseDecisionSnapshot {
if !outcome.Valid && !reason.Valid && !at.Valid {
return nil
}
return &domain.SupportCaseDecisionSnapshot{
Outcome: domain.SupportCaseDecisionOutcome(outcome.String), Reason: reason.String, DecidedAt: at.Time,
}
}
func optionalSupportText[T any](value *T, selectValue func(*T) string) pgtype.Text {
if value == nil {
return pgtype.Text{}
}
return pgText(selectValue(value))
}
func optionalSupportUUID(reference *domain.SupportCaseReference) pgtype.UUID {
if reference == nil {
return pgtype.UUID{}
}
return pgUUID(reference.ID)
}
func optionalSupportUUIDPointer(value *uuid.UUID) pgtype.UUID {
if value == nil {
return pgtype.UUID{}
}
return pgUUID(*value)
}
func optionalSupportPolicyID(value *domain.PolicyVersionID) pgtype.UUID {
if value == nil {
return pgtype.UUID{}
}
return pgUUID(value.UUID())
}
func optionalSupportAssessment(target *domain.SupportCaseAssessmentTarget, specialization bool) pgtype.Text {
if target == nil {
return pgtype.Text{}
}
if specialization {
return pgText(string(target.Specialization))
}
return pgText(string(target.Grade))
}
func optionalSupportComplaint(reason *domain.SupportCaseComplaintReason) pgtype.Text {
if reason == nil {
return pgtype.Text{}
}
return pgText(string(*reason))
}
func optionalSupportInt32(value *int32) pgtype.Int4 {
if value == nil {
return pgtype.Int4{}
}
return pgtype.Int4{Int32: *value, Valid: true}
}
func optionalSupportDecision(decision *domain.SupportCaseDecisionSnapshot, outcome bool) pgtype.Text {
if decision == nil {
return pgtype.Text{}
}
if outcome {
return pgText(string(decision.Outcome))
}
return pgText(decision.Reason)
}
func optionalSupportDecisionTime(decision *domain.SupportCaseDecisionSnapshot) pgtype.Timestamptz {
if decision == nil {
return pgtype.Timestamptz{}
}
return pgTime(decision.DecidedAt)
}
func optionalSupportEventStatus(status *domain.SupportCaseStatus) pgtype.Text {
if status == nil {
return pgtype.Text{}
}
return pgText(string(*status))
}
func optionalSupportEventMessage(message *string) pgtype.Text {
if message == nil {
return pgtype.Text{}
}
return pgText(*message)
}
func optionalSupportCaseComplaint(value pgtype.Text) *domain.SupportCaseComplaintReason {
if !value.Valid {
return nil
}
result := domain.SupportCaseComplaintReason(value.String)
return &result
}
func optionalSupportCaseInt4(value pgtype.Int4) *int32 {
if !value.Valid {
return nil
}
return &value.Int32
}
func optionalSupportCaseUUID(value pgtype.UUID) *uuid.UUID {
if !value.Valid {
return nil
}
result := uuid.UUID(value.Bytes)
return &result
}
func optionalSupportCasePolicyID(value pgtype.UUID) *domain.PolicyVersionID {
if !value.Valid {
return nil
}
result := domain.PolicyVersionID(value.Bytes)
return &result
}
func optionalSupportCaseStatus(value pgtype.Text) *domain.SupportCaseStatus {
if !value.Valid {
return nil
}
result := domain.SupportCaseStatus(value.String)
return &result
}
func optionalSupportCaseText(value pgtype.Text) *string {
if !value.Valid {
return nil
}
result := value.String
return &result
}
func supportCaseFirstEventTime(value any) (time.Time, bool) {
switch typed := value.(type) {
case time.Time:
return typed, !typed.IsZero()
case pgtype.Timestamptz:
return typed.Time, typed.Valid && !typed.Time.IsZero()
case *time.Time:
if typed != nil {
return *typed, !typed.IsZero()
}
case nil:
return time.Time{}, false
}
return time.Time{}, false
}
func supportCaseJSONBytes(value any) ([]byte, bool) {
switch typed := value.(type) {
case string:
return []byte(typed), true
case []byte:
return typed, true
default:
return nil, false
}
}
func decodeSupportCaseJSON(encoded []byte, destination any) error {
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return err
}
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
return errors.New("stored support case snapshot contains trailing data")
}
return nil
}
func validSupportCasePositionTime(value time.Time) bool {
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0 &&
value.Nanosecond()%int(time.Microsecond) == 0
}
func mapSupportCaseNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapSupportCaseError(err)
}
func mapSupportCaseError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
key := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}
if sentinel, ok := supportCaseConstraintErrors[key]; ok {
return fmt.Errorf("postgres.mapSupportCaseError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
@@ -0,0 +1,152 @@
package postgres
import (
"context"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.SupportCaseRubricRepository = supportCaseRubricRepository{}
type supportCaseRubricRepository struct {
queries *sqlc.Queries
bank assessmentBankRepository
}
func (unit *UnitOfWork) SupportCaseRubrics() outbound.SupportCaseRubricRepository {
return supportCaseRubricRepository{
queries: unit.queries,
bank: assessmentBankRepository{queries: unit.queries, transactional: true},
}
}
func (repository supportCaseRubricRepository) ResolveCurrent(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) (*outbound.SupportCaseRubric, error) {
const location = "supportCaseRubricRepository.ResolveCurrent"
if !repository.bank.transactional {
return nil, fmt.Errorf("%s - rubric resolution needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
}
if !specialization.IsKnown() || !grade.IsKnown() {
return nil, fmt.Errorf("%s - target is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
}
row, available, err := repository.currentUniqueOpening(ctx, specialization, grade)
if err != nil {
return nil, fmt.Errorf("%s - resolve current target opening: %w", location, err)
}
if !available {
return nil, nil
}
selectionRow := supportRubricSelectionRow(row)
selection, err := repository.bank.currentSelectionFromRow(ctx, selectionRow)
if err != nil {
return nil, fmt.Errorf("%s - validate reviewed rubric manifest: %w", location, err)
}
if !supportRubricSelectionMatches(selection, row) {
return nil, fmt.Errorf("%s - current rubric pin changed during resolution: %w", location, outbound.ErrAssessmentSelectionUnavailable)
}
return &outbound.SupportCaseRubric{
Version: selection.ProductPolicyVersion,
OpeningID: selection.Opening.ID,
PolicyVersionID: selection.Opening.PolicyVersionID,
}, nil
}
func (repository supportCaseRubricRepository) currentUniqueOpening(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) (sqlc.ResolveCurrentSupportCaseRubricsRow, bool, error) {
initial, err := repository.currentRows(ctx, specialization, grade)
if err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("read current target bindings: %w", err)
}
initialRow, unique := uniqueSupportRubricOpening(initial)
if !unique {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, nil
}
category, err := domain.ParseAssessmentCategory(initialRow.Category)
if err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("parse current category: %w", domain.ErrInvalidAssessmentFamily)
}
if err := repository.bank.LockCategory(ctx, category); err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("lock current category: %w", err)
}
current, err := repository.currentRows(ctx, specialization, grade)
if err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("recheck current target bindings: %w", err)
}
currentRow, unique := uniqueSupportRubricOpening(current)
if !unique || currentRow.OpeningID.Bytes != initialRow.OpeningID.Bytes {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, nil
}
return currentRow, true, nil
}
func supportRubricSelectionMatches(
selection outbound.AssessmentBankSelection,
row sqlc.ResolveCurrentSupportCaseRubricsRow,
) bool {
return selection.ProductPolicyVersion > 0 && !selection.Opening.PolicyVersionID.IsZero() &&
selection.Opening.ID == row.OpeningID.Bytes &&
selection.Opening.PolicyVersionID == domain.PolicyVersionID(row.PolicyVersionID.Bytes) &&
selection.ProductPolicyVersion == row.EffectivePolicyVersion.Int32
}
func (repository supportCaseRubricRepository) currentRows(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) ([]sqlc.ResolveCurrentSupportCaseRubricsRow, error) {
rows, err := repository.queries.ResolveCurrentSupportCaseRubrics(ctx, sqlc.ResolveCurrentSupportCaseRubricsParams{
Specialization: string(specialization), Grade: string(grade),
})
if err != nil {
return nil, mapAssessmentError(err)
}
current := make([]sqlc.ResolveCurrentSupportCaseRubricsRow, 0, len(rows))
for _, row := range rows {
metadata, available, err := currentAssessmentSelectionMetadata(supportRubricSelectionRow(row))
if err != nil {
return nil, fmt.Errorf("validate current catalog binding: %w", err)
}
if !available || metadata.Specialization() != specialization || metadata.Grade() != grade {
continue
}
current = append(current, row)
}
return current, nil
}
func supportRubricSelectionRow(row sqlc.ResolveCurrentSupportCaseRubricsRow) sqlc.ResolveCurrentAssessmentSelectionRow {
return sqlc.ResolveCurrentAssessmentSelectionRow(row)
}
func uniqueSupportRubricOpening(
rows []sqlc.ResolveCurrentSupportCaseRubricsRow,
) (sqlc.ResolveCurrentSupportCaseRubricsRow, bool) {
var selected sqlc.ResolveCurrentSupportCaseRubricsRow
seen := make(map[uuid.UUID]struct{}, len(rows))
for _, row := range rows {
if !row.OpeningID.Valid || row.OpeningID.Bytes == uuid.Nil {
continue
}
if _, exists := seen[row.OpeningID.Bytes]; exists {
continue
}
seen[row.OpeningID.Bytes] = struct{}{}
if len(seen) > 1 {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false
}
selected = row
}
return selected, len(seen) == 1
}
@@ -37,6 +37,7 @@ func NewTransactor(pool *pgxpool.Pool) *Transactor {
}
var _ outbound.Transactor = (*Transactor)(nil)
var _ outbound.ReadOnlySnapshotTransactor = (*Transactor)(nil)
// transactionContextKey marks a context passed to a transaction callback so a
// nested WithinTransaction call fails instead of opening a second connection.
@@ -81,6 +82,42 @@ func (transactor *Transactor) WithinTransaction(
return nil
}
// WithinReadOnlySnapshot runs a callback against one repeatable-read snapshot.
// PostgreSQL rejects writes made through the supplied UnitOfWork.
func (transactor *Transactor) WithinReadOnlySnapshot(
ctx context.Context,
fn func(ctx context.Context, unit outbound.UnitOfWork) error,
) error {
if ctx.Value(transactionContextKey{}) != nil {
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - begin transaction: %w", outbound.ErrNestedTransaction)
}
options := pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}
tx, err := transactor.pool.BeginTx(ctx, options)
if err != nil {
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - begin transaction: %w", sanitizeConnectError(err))
}
finished := false
defer func() {
if !finished {
_ = rollback(ctx, tx)
}
}()
fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)})
finished = true
if fnErr != nil {
fnErr = markTransactionConflict(fnErr)
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
return errors.Join(fnErr, fmt.Errorf("Transactor.WithinReadOnlySnapshot - roll back transaction: %w", rollbackErr))
}
return fnErr
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - commit transaction: %w", markTransactionConflict(err))
}
return nil
}
func rollback(ctx context.Context, tx pgx.Tx) error {
rollbackContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout)
defer cancel()