314 lines
13 KiB
Go
314 lines
13 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"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{}
|
|
|
|
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)
|
|
}
|
|
if err := repository.lockAndCheckSnapshot(ctx, location, quota); 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))
|
|
}
|
|
|
|
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
|
|
OrganizationID: organizationID,
|
|
WindowStart: pgTime(quota.InvitationWindowStart()),
|
|
})
|
|
if err != nil {
|
|
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
|
|
}
|
|
if usage.UsageCount < 0 {
|
|
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location)
|
|
}
|
|
if usage.UsageCount >= quota.InvitationLimit() {
|
|
earliest, err := quotaWindowEarliest(usage.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)
|
|
}
|
|
if err := repository.lockAndCheckSnapshot(ctx, location, quota); 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, organizationID)
|
|
}
|
|
|
|
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,
|
|
organizationID uuid.UUID,
|
|
) (outbound.CompanyQuotaDecision, error) {
|
|
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
|
|
OrganizationID: pgUUID(organizationID),
|
|
WindowStart: pgTime(quota.CardViewWindowStart()),
|
|
})
|
|
if err != nil {
|
|
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
|
|
}
|
|
if usage.UsageCount < 0 {
|
|
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location)
|
|
}
|
|
if usage.UsageCount >= quota.CardViewLimit() {
|
|
earliest, err := quotaWindowEarliest(usage.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
|
|
}
|
|
|
|
func (repository companyQuotaRepository) LockOrganization(ctx context.Context, organizationID uuid.UUID) error {
|
|
const location = "companyQuotaRepository.LockOrganization"
|
|
if _, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)); 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))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository companyQuotaRepository) lockAndCheckSnapshot(
|
|
ctx context.Context,
|
|
location string,
|
|
quota domain.CompanyQuota,
|
|
) error {
|
|
organizationID := pgUUID(quota.OrganizationID())
|
|
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
|
|
}
|
|
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)
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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()),
|
|
}
|
|
}
|