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" ) const companyQuotaViewCleanupBatchSize int32 = 100 func (unit *UnitOfWork) CompanyQuotas() outbound.CompanyQuotaRepository { return companyQuotaRepository{queries: unit.queries} } type companyQuotaRepository struct { queries *sqlc.Queries } var _ outbound.CompanyQuotaRepository = companyQuotaRepository{} // quotaScope names the usage rows that one reservation counts. An organization // at a tier that shares its holding pool counts the usage of every E0 // organization of the holding; any other tier counts its own usage only. type quotaScope struct { organizationID uuid.UUID // holdingID is the holding of the shared pool, and uuid.Nil when the // organization keeps its own pool. holdingID uuid.UUID } func (scope quotaScope) sharesHoldingPool() bool { return scope.holdingID != uuid.Nil } func (repository companyQuotaRepository) ReserveInvitation( ctx context.Context, quota domain.CompanyQuota, invitationID uuid.UUID, ) (outbound.CompanyQuotaDecision, error) { const location = "companyQuotaRepository.ReserveInvitation" if err := validateCompanyQuota(location, quota); err != nil { return outbound.CompanyQuotaDecision{}, err } if invitationID == uuid.Nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota) } scope, err := repository.lockAndCheckSnapshot(ctx, location, quota) if err != nil { return outbound.CompanyQuotaDecision{}, err } organizationID := pgUUID(quota.OrganizationID()) invitation, err := repository.queries.FindCompanyInvitationQuotaUsage(ctx, sqlc.FindCompanyInvitationQuotaUsageParams{ OrganizationID: organizationID, InvitationID: pgUUID(invitationID), }) if err == nil { if !invitation.Valid || invitation.Bytes != invitationID { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - existing invitation usage did not match its key", location) } return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil } if !errors.Is(err, pgx.ErrNoRows) { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read invitation usage: %w", location, mapOrganizationError(err)) } count, earliestAt, err := repository.countInvitationUsage(ctx, location, scope, quota.InvitationWindowStart()) if err != nil { return outbound.CompanyQuotaDecision{}, err } if count < 0 { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location) } if count >= quota.InvitationLimit() { earliest, err := quotaWindowEarliest(earliestAt) if err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err) } return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.InvitationWindow()).UTC()}, nil } if err := repository.queries.InsertCompanyInvitationQuotaUsage(ctx, companyInvitationUsageParams(quota, invitationID)); err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - insert invitation usage: %w", location, mapOrganizationError(err)) } return outbound.CompanyQuotaDecision{Allowed: true}, nil } func (repository companyQuotaRepository) ReserveCardView( ctx context.Context, quota domain.CompanyQuota, candidateID uuid.UUID, ) (outbound.CompanyQuotaDecision, error) { const location = "companyQuotaRepository.ReserveCardView" if err := validateCompanyQuota(location, quota); err != nil { return outbound.CompanyQuotaDecision{}, err } if candidateID == uuid.Nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota) } scope, err := repository.lockAndCheckSnapshot(ctx, location, quota) if err != nil { return outbound.CompanyQuotaDecision{}, err } organizationID := quota.OrganizationID() decision, handled, err := repository.reserveExistingCardView(ctx, location, quota, organizationID, candidateID) if err != nil || handled { return decision, err } return repository.reserveNewCardView(ctx, location, quota, candidateID, scope) } func (repository companyQuotaRepository) reserveExistingCardView( ctx context.Context, location string, quota domain.CompanyQuota, organizationID uuid.UUID, candidateID uuid.UUID, ) (outbound.CompanyQuotaDecision, bool, error) { existing, findErr := repository.queries.FindCompanyCardViewQuotaUsage(ctx, sqlc.FindCompanyCardViewQuotaUsageParams{ OrganizationID: pgUUID(organizationID), CandidateID: pgUUID(candidateID), }) if errors.Is(findErr, pgx.ErrNoRows) { return outbound.CompanyQuotaDecision{}, false, nil } if findErr != nil { return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - read card-view usage: %w", location, mapOrganizationError(findErr)) } if !existing.Valid { return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - existing card-view timestamp is invalid", location) } if !existing.Time.After(quota.CardViewWindowStart()) { return outbound.CompanyQuotaDecision{}, false, nil } decision, err := repository.refreshActiveCardView(ctx, location, quota, organizationID, candidateID) return decision, true, err } func (repository companyQuotaRepository) refreshActiveCardView( ctx context.Context, location string, quota domain.CompanyQuota, organizationID uuid.UUID, candidateID uuid.UUID, ) (outbound.CompanyQuotaDecision, error) { updated, err := repository.queries.RefreshCompanyCardViewQuotaUsage(ctx, sqlc.RefreshCompanyCardViewQuotaUsageParams{ LastSeenAt: pgTime(quota.At()), PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()), VerificationLevel: string(quota.VerificationLevel()), VerificationBasis: string(quota.VerificationBasis()), VerificationChangedAt: pgTime(quota.VerificationChangedAt()), QuotaTier: string(quota.Tier()), OrganizationID: pgUUID(organizationID), CandidateID: pgUUID(candidateID), WindowStart: pgTime(quota.CardViewWindowStart()), }) if err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - refresh card-view usage: %w", location, mapOrganizationError(err)) } if updated != 1 { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - active card-view usage changed while organization was locked", location) } if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil { return outbound.CompanyQuotaDecision{}, err } return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil } func (repository companyQuotaRepository) reserveNewCardView( ctx context.Context, location string, quota domain.CompanyQuota, candidateID uuid.UUID, scope quotaScope, ) (outbound.CompanyQuotaDecision, error) { count, earliestAt, err := repository.countCardViewUsage(ctx, location, scope, quota.CardViewWindowStart()) if err != nil { return outbound.CompanyQuotaDecision{}, err } if count < 0 { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location) } if count >= quota.CardViewLimit() { earliest, err := quotaWindowEarliest(earliestAt) if err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err) } return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.CardViewWindow()).UTC()}, nil } if err := repository.queries.SaveCompanyCardViewQuotaUsage(ctx, companyCardViewUsageParams(quota, candidateID)); err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - save card-view usage: %w", location, mapOrganizationError(err)) } if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil { return outbound.CompanyQuotaDecision{}, err } return outbound.CompanyQuotaDecision{Allowed: true}, nil } // countInvitationUsage returns the invitation usage in the window of scope and // the earliest counted reservation, which sets the retry time of a denial. func (repository companyQuotaRepository) countInvitationUsage( ctx context.Context, location string, scope quotaScope, windowStart time.Time, ) (int64, any, error) { if scope.sharesHoldingPool() { usage, err := repository.queries.CountCompanyInvitationQuotaHoldingWindow(ctx, sqlc.CountCompanyInvitationQuotaHoldingWindowParams{ HoldingID: pgUUID(scope.holdingID), WindowStart: pgTime(windowStart), }) if err != nil { return 0, nil, fmt.Errorf("%s - count invitation usage of the holding pool: %w", location, mapOrganizationError(err)) } return usage.UsageCount, usage.EarliestAt, nil } usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{ OrganizationID: pgUUID(scope.organizationID), WindowStart: pgTime(windowStart), }) if err != nil { return 0, nil, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err)) } return usage.UsageCount, usage.EarliestAt, nil } // countCardViewUsage is countInvitationUsage for distinct card views. func (repository companyQuotaRepository) countCardViewUsage( ctx context.Context, location string, scope quotaScope, windowStart time.Time, ) (int64, any, error) { if scope.sharesHoldingPool() { usage, err := repository.queries.CountCompanyCardViewQuotaHoldingWindow(ctx, sqlc.CountCompanyCardViewQuotaHoldingWindowParams{ HoldingID: pgUUID(scope.holdingID), WindowStart: pgTime(windowStart), }) if err != nil { return 0, nil, fmt.Errorf("%s - count card-view usage of the holding pool: %w", location, mapOrganizationError(err)) } return usage.UsageCount, usage.EarliestAt, nil } usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{ OrganizationID: pgUUID(scope.organizationID), WindowStart: pgTime(windowStart), }) if err != nil { return 0, nil, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err)) } return usage.UsageCount, usage.EarliestAt, nil } // LockOrganization takes the organization lock and, for an E0 organization, // the lock of its holding, in that order. Every caller that reserves usage // later takes it first, so the pool is serialized before any other lock. func (repository companyQuotaRepository) LockOrganization(ctx context.Context, organizationID uuid.UUID) error { const location = "companyQuotaRepository.LockOrganization" organization, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return fmt.Errorf("%s - organization was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err)) } // The level is read under the organization lock, which a trust change // must also take, so the tier cannot change before the holding is locked. if tier, ok := domain.OrganizationVerificationLevel(organization.VerificationLevel).QuotaTier(); ok && tier.SharesHoldingPool() { if _, err := lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID); err != nil { return err } } return nil } // lockAndCheckSnapshot takes the organization lock for the reservation, checks // the stored trust and effective policy against the snapshot, and returns the // usage scope. The holding of an E0 organization is locked after the // organization and before the usage is counted. func (repository companyQuotaRepository) lockAndCheckSnapshot( ctx context.Context, location string, quota domain.CompanyQuota, ) (quotaScope, error) { organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, pgUUID(quota.OrganizationID())) if errors.Is(err, pgx.ErrNoRows) { return quotaScope{}, fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } if err != nil { return quotaScope{}, fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err)) } if err := checkStoredTrust(location, quota, organization); err != nil { return quotaScope{}, err } scope := quotaScope{organizationID: quota.OrganizationID()} if quota.Tier().SharesHoldingPool() { scope.holdingID, err = lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID) if err != nil { return quotaScope{}, err } } if err := repository.checkEffectivePolicy(ctx, location, quota); err != nil { return quotaScope{}, err } return scope, nil } // checkStoredTrust refuses a reservation whose snapshot no longer matches the // verification of the locked organization. func checkStoredTrust(location string, quota domain.CompanyQuota, organization sqlc.LockCompanyQuotaOrganizationRow) error { if !organization.ID.Valid || organization.ID.Bytes != quota.OrganizationID() || !organization.VerificationChangedAt.Valid || organization.VerificationLevel != string(quota.VerificationLevel()) || organization.VerificationBasis != string(quota.VerificationBasis()) || !organization.VerificationChangedAt.Time.Equal(quota.VerificationChangedAt()) { return fmt.Errorf("%s - stored organization trust changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } return nil } // checkEffectivePolicy refuses a reservation whose policy version is no longer // the effective product policy at the application clock snapshot. func (repository companyQuotaRepository) checkEffectivePolicy(ctx context.Context, location string, quota domain.CompanyQuota) error { policy, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{ PolicyKey: string(domain.ProductPolicyKey), At: pgTime(quota.At()), }) if errors.Is(err, pgx.ErrNoRows) { return fmt.Errorf("%s - no effective product policy remains: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } if err != nil { return fmt.Errorf("%s - recheck effective product policy: %w", location, mapPolicyError(err)) } if !policy.ID.Valid || policy.ID.Bytes != quota.PolicyVersionID().UUID() || policy.PolicyKey != string(domain.ProductPolicyKey) { return fmt.Errorf("%s - effective product policy changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } return nil } // lockQuotaHolding takes the pool lock of an E0 holding. The caller must hold // the lock of the organization that names the holding. func lockQuotaHolding( ctx context.Context, queries *sqlc.Queries, location string, holdingID pgtype.UUID, ) (uuid.UUID, error) { if !holdingID.Valid { return uuid.Nil, fmt.Errorf("%s - organization has no holding", location) } locked, err := queries.LockCompanyQuotaHolding(ctx, holdingID) if errors.Is(err, pgx.ErrNoRows) { return uuid.Nil, fmt.Errorf("%s - holding was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } if err != nil { return uuid.Nil, fmt.Errorf("%s - lock holding: %w", location, mapOrganizationError(err)) } if !locked.Valid { return uuid.Nil, fmt.Errorf("%s - locked holding has no identifier", location) } return uuid.UUID(locked.Bytes), nil } func (repository companyQuotaRepository) cleanupExpiredCardViews( ctx context.Context, location string, quota domain.CompanyQuota, ) error { _, err := repository.queries.DeleteExpiredCompanyCardViewQuotaUsage(ctx, sqlc.DeleteExpiredCompanyCardViewQuotaUsageParams{ OrganizationID: pgUUID(quota.OrganizationID()), WindowStart: pgTime(quota.CardViewWindowStart()), RowLimit: companyQuotaViewCleanupBatchSize, }) if err != nil { return fmt.Errorf("%s - clean expired card-view usage: %w", location, mapOrganizationError(err)) } return nil } func validateCompanyQuota(location string, quota domain.CompanyQuota) error { if quota.IsZero() || quota.OrganizationID() == uuid.Nil || quota.PolicyVersionID().UUID() == uuid.Nil || quota.At().IsZero() || quota.At().Unix() < 0 || quota.InvitationWindow() <= 0 || quota.InvitationLimit() <= 0 || quota.CardViewWindow() <= 0 || quota.CardViewLimit() <= 0 || quota.InvitationWindowStart().IsZero() || quota.CardViewWindowStart().IsZero() { return fmt.Errorf("%s - quota snapshot was not built from an active policy and stored organization: %w", location, domain.ErrInvalidCompanyQuota) } return nil } func quotaWindowEarliest(value interface{}) (time.Time, error) { switch timestamp := value.(type) { case time.Time: if timestamp.IsZero() { return time.Time{}, errors.New("window timestamp is zero") } return timestamp.UTC(), nil case *time.Time: if timestamp == nil || timestamp.IsZero() { return time.Time{}, errors.New("window timestamp is missing") } return timestamp.UTC(), nil default: return time.Time{}, errors.New("window timestamp has an unexpected database value") } } func companyInvitationUsageParams(quota domain.CompanyQuota, invitationID uuid.UUID) sqlc.InsertCompanyInvitationQuotaUsageParams { return sqlc.InsertCompanyInvitationQuotaUsageParams{ OrganizationID: pgUUID(quota.OrganizationID()), InvitationID: pgUUID(invitationID), ReservedAt: pgTime(quota.At()), PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()), VerificationLevel: string(quota.VerificationLevel()), VerificationBasis: string(quota.VerificationBasis()), VerificationChangedAt: pgTime(quota.VerificationChangedAt()), QuotaTier: string(quota.Tier()), } } func companyCardViewUsageParams(quota domain.CompanyQuota, candidateID uuid.UUID) sqlc.SaveCompanyCardViewQuotaUsageParams { return sqlc.SaveCompanyCardViewQuotaUsageParams{ OrganizationID: pgUUID(quota.OrganizationID()), CandidateID: pgUUID(candidateID), LastSeenAt: pgTime(quota.At()), PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()), VerificationLevel: string(quota.VerificationLevel()), VerificationBasis: string(quota.VerificationBasis()), VerificationChangedAt: pgTime(quota.VerificationChangedAt()), QuotaTier: string(quota.Tier()), } }