feat(invitations): accept invitations with C4 consent and contact grants; share the E0 quota across holdings
This commit is contained in:
1 parent
a5990d3fc6
commit
676b3c6e24
59 files changed
+4926
-194
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"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"
|
||||
@@ -26,6 +27,20 @@ type companyQuotaRepository struct {
|
||||
|
||||
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,
|
||||
@@ -38,7 +53,8 @@ func (repository companyQuotaRepository) ReserveInvitation(
|
||||
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 {
|
||||
scope, err := repository.lockAndCheckSnapshot(ctx, location, quota)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
|
||||
@@ -57,18 +73,15 @@ func (repository companyQuotaRepository) ReserveInvitation(
|
||||
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()),
|
||||
})
|
||||
count, earliestAt, err := repository.countInvitationUsage(ctx, location, scope, quota.InvitationWindowStart())
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
if usage.UsageCount < 0 {
|
||||
if count < 0 {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location)
|
||||
}
|
||||
if usage.UsageCount >= quota.InvitationLimit() {
|
||||
earliest, err := quotaWindowEarliest(usage.EarliestAt)
|
||||
if count >= quota.InvitationLimit() {
|
||||
earliest, err := quotaWindowEarliest(earliestAt)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err)
|
||||
}
|
||||
@@ -92,7 +105,8 @@ func (repository companyQuotaRepository) ReserveCardView(
|
||||
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 {
|
||||
scope, err := repository.lockAndCheckSnapshot(ctx, location, quota)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
|
||||
@@ -101,7 +115,7 @@ func (repository companyQuotaRepository) ReserveCardView(
|
||||
if err != nil || handled {
|
||||
return decision, err
|
||||
}
|
||||
return repository.reserveNewCardView(ctx, location, quota, candidateID, organizationID)
|
||||
return repository.reserveNewCardView(ctx, location, quota, candidateID, scope)
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) reserveExistingCardView(
|
||||
@@ -166,20 +180,17 @@ func (repository companyQuotaRepository) reserveNewCardView(
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
candidateID uuid.UUID,
|
||||
organizationID uuid.UUID,
|
||||
scope quotaScope,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
WindowStart: pgTime(quota.CardViewWindowStart()),
|
||||
})
|
||||
count, earliestAt, err := repository.countCardViewUsage(ctx, location, scope, quota.CardViewWindowStart())
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
if usage.UsageCount < 0 {
|
||||
if count < 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 count >= quota.CardViewLimit() {
|
||||
earliest, err := quotaWindowEarliest(earliestAt)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err)
|
||||
}
|
||||
@@ -194,30 +205,119 @@ func (repository companyQuotaRepository) reserveNewCardView(
|
||||
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"
|
||||
if _, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)); err != nil {
|
||||
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,
|
||||
) error {
|
||||
organizationID := pgUUID(quota.OrganizationID())
|
||||
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID)
|
||||
) (quotaScope, error) {
|
||||
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, pgUUID(quota.OrganizationID()))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
return quotaScope{}, 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))
|
||||
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()) ||
|
||||
@@ -225,7 +325,12 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot(
|
||||
!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()),
|
||||
@@ -242,6 +347,30 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot(
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
_ outbound.InvitationAcceptResultRepository = invitationRepository{}
|
||||
_ outbound.ContactGrantRepository = contactGrantRepository{}
|
||||
)
|
||||
|
||||
func (unit *UnitOfWork) InvitationAcceptResults() outbound.InvitationAcceptResultRepository {
|
||||
return invitationRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) ContactGrants() outbound.ContactGrantRepository {
|
||||
return contactGrantRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type contactGrantRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
// Accept stores the acceptance of an invitation. The compare-and-swap applies
|
||||
// only to a delivered or viewed invitation at the expected version and terms
|
||||
// version, before its deadline, so a stale writer loses without changing it.
|
||||
func (repository invitationRepository) Accept(
|
||||
ctx context.Context,
|
||||
expectedVersion int64,
|
||||
next domain.Invitation,
|
||||
event domain.InvitationEvent,
|
||||
) error {
|
||||
const location = "invitationRepository.Accept"
|
||||
stored := next.Stored()
|
||||
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationAccepted) ||
|
||||
stored.RespondedAt == nil || event.Kind != domain.InvitationEventAccepted {
|
||||
return fmt.Errorf("%s - the next version must be the acceptance that follows the expected one: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := repository.queries.AcceptInvitation(ctx, sqlc.AcceptInvitationParams{
|
||||
NextVersion: stored.Version, AcceptedAt: pgTime(*stored.RespondedAt), OrganizationID: pgUUID(stored.OrganizationID),
|
||||
InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, TermsVersion: stored.TermsVersion,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - accept invitation: %w", location, outbound.ErrInvitationVersionConflict)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - accept invitation: %w", location, mapInvitationError(err))
|
||||
}
|
||||
return repository.insertEvent(ctx, location, event)
|
||||
}
|
||||
|
||||
func (repository invitationRepository) SaveAcceptResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
result outbound.InvitationAcceptResult,
|
||||
) error {
|
||||
const location = "invitationRepository.SaveAcceptResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if err := validateInvitationAcceptResult(result); err != nil {
|
||||
return fmt.Errorf("%s - validate outcome: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertInvitationAcceptResult(ctx, sqlc.InsertInvitationAcceptResultParams{
|
||||
ScopeHash: scope[:], InvitationID: pgUUID(result.InvitationID), Outcome: string(result.Outcome),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationAcceptResultError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository invitationRepository) GetAcceptResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
) (outbound.InvitationAcceptResult, error) {
|
||||
const location = "invitationRepository.GetAcceptResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
row, err := repository.queries.GetInvitationAcceptResult(ctx, scope[:])
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
|
||||
}
|
||||
if !row.InvitationID.Valid {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - stored outcome has no invitation: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
result := outbound.InvitationAcceptResult{
|
||||
InvitationID: uuid.UUID(row.InvitationID.Bytes), Outcome: outbound.InvitationAcceptOutcome(row.Outcome),
|
||||
}
|
||||
if err := validateInvitationAcceptResult(result); err != nil {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func validateInvitationAcceptResult(result outbound.InvitationAcceptResult) error {
|
||||
const location = "postgres.validateInvitationAcceptResult"
|
||||
switch result.Outcome {
|
||||
case outbound.InvitationAcceptAccepted:
|
||||
if result.InvitationID == uuid.Nil {
|
||||
return fmt.Errorf("%s - an accepted outcome names the invitation: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
case outbound.InvitationAcceptNotFound, outbound.InvitationAcceptStateConflict:
|
||||
// A refusal names the identifier of the path, which may name nothing.
|
||||
default:
|
||||
return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapInvitationAcceptResultError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_accept_results_idempotency_fkey" {
|
||||
return fmt.Errorf("postgres.mapInvitationAcceptResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
||||
}
|
||||
return mapInvitationError(err)
|
||||
}
|
||||
|
||||
// Create stores a grant of an accepted invitation. The row can only be created
|
||||
// active: a revoked grant is never stored by a new acceptance.
|
||||
func (repository contactGrantRepository) Create(ctx context.Context, grant domain.ContactGrant) error {
|
||||
const location = "contactGrantRepository.Create"
|
||||
if grant.IsZero() || grant.Status() != domain.ContactGrantActive {
|
||||
return fmt.Errorf("%s - the grant must be built by the domain and active: %w", location, domain.ErrInvalidContactGrant)
|
||||
}
|
||||
stored := grant.Stored()
|
||||
if err := repository.queries.InsertContactGrant(ctx, sqlc.InsertContactGrantParams{
|
||||
ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID),
|
||||
SourceInvitationID: pgUUID(stored.InvitationID), ConsentRecordID: pgUUID(stored.ConsentRecordID),
|
||||
TermsVersion: stored.TermsVersion, Fields: stored.Fields, ConsentTextVersion: stored.ConsentTextVersion,
|
||||
GrantedAt: pgTime(stored.GrantedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert contact grant: %w", location, mapInvitationError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByInvitation reads the grant of one invitation of one organization. The
|
||||
// read rebuilds the grant through the domain, so a stored row that breaks a
|
||||
// rule fails instead of being served.
|
||||
func (repository contactGrantRepository) GetByInvitation(
|
||||
ctx context.Context,
|
||||
organizationID, invitationID uuid.UUID,
|
||||
) (domain.ContactGrant, error) {
|
||||
const location = "contactGrantRepository.GetByInvitation"
|
||||
if organizationID == uuid.Nil || invitationID == uuid.Nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidContactGrant)
|
||||
}
|
||||
row, err := repository.queries.GetContactGrantByInvitation(ctx, sqlc.GetContactGrantByInvitationParams{
|
||||
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, outbound.ErrContactGrantNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, mapInvitationError(err))
|
||||
}
|
||||
stored, err := storedContactGrantRow(row)
|
||||
if err != nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - read stored grant: %w", location, err)
|
||||
}
|
||||
grant, err := domain.RestoreContactGrant(stored)
|
||||
if err != nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - restore contact grant: %w", location, err)
|
||||
}
|
||||
if stored.OrganizationID != organizationID || stored.InvitationID != invitationID {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - stored grant has another scope: %w", location, domain.ErrInvalidContactGrant)
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
|
||||
// storedContactGrantRow maps a grant row to its stored form. A row without an
|
||||
// identifier or a time is refused before the domain rebuilds the grant.
|
||||
func storedContactGrantRow(row sqlc.ContactGrant) (domain.StoredContactGrant, error) {
|
||||
if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.SourceInvitationID.Valid ||
|
||||
!row.ConsentRecordID.Valid || !row.GrantedAt.Valid {
|
||||
return domain.StoredContactGrant{}, fmt.Errorf("stored grant has missing identifiers: %w", domain.ErrInvalidContactGrant)
|
||||
}
|
||||
stored := domain.StoredContactGrant{
|
||||
ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
|
||||
CandidateID: uuid.UUID(row.CandidateID.Bytes), InvitationID: uuid.UUID(row.SourceInvitationID.Bytes),
|
||||
ConsentRecordID: uuid.UUID(row.ConsentRecordID.Bytes), TermsVersion: row.TermsVersion, Fields: row.Fields,
|
||||
ConsentTextVersion: row.ConsentTextVersion, GrantedAt: row.GrantedAt.Time.UTC(),
|
||||
}
|
||||
if row.RevokedAt.Valid {
|
||||
revokedAt := row.RevokedAt.Time.UTC()
|
||||
stored.RevokedAt = &revokedAt
|
||||
}
|
||||
if row.RevocationReason.Valid {
|
||||
stored.RevocationReason = row.RevocationReason.String
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
@@ -24,6 +24,7 @@ var organizationConstraintErrors = map[constraintViolation]error{
|
||||
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
|
||||
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
|
||||
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "holdings_founder_account_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
|
||||
}
|
||||
|
||||
@@ -72,10 +73,14 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
|
||||
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
|
||||
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
|
||||
}
|
||||
holdingID, err := repository.ensureFounderHolding(ctx, owner.UserID(), organization.CreatedAt())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - join founder holding: %w", location, err)
|
||||
}
|
||||
profile := organization.Profile()
|
||||
contacts := profile.Contacts()
|
||||
verification := organization.Verification()
|
||||
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
|
||||
err = repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
|
||||
ID: pgUUID(organization.ID()),
|
||||
Name: profile.Name(),
|
||||
Description: pgOptionalText(profile.Description()),
|
||||
@@ -90,6 +95,7 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
|
||||
Version: organization.Version(),
|
||||
CreatedAt: pgTime(organization.CreatedAt()),
|
||||
UpdatedAt: pgTime(organization.UpdatedAt()),
|
||||
HoldingID: pgUUID(holdingID),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
|
||||
@@ -103,6 +109,37 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureFounderHolding returns the holding of the founder account and creates
|
||||
// it in the caller's transaction when the account has none. The insert ignores
|
||||
// an existing holding, so a concurrent creation of the same account waits for
|
||||
// the other transaction and then reads the holding that was stored.
|
||||
func (repository organizationRepository) ensureFounderHolding(
|
||||
ctx context.Context,
|
||||
founderID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
) (uuid.UUID, error) {
|
||||
const location = "organizationRepository.ensureFounderHolding"
|
||||
holding, err := domain.NewHolding(founderID, createdAt)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - build holding: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertHoldingIfAbsent(ctx, sqlc.InsertHoldingIfAbsentParams{
|
||||
ID: pgUUID(holding.ID()),
|
||||
FounderAccountID: pgUUID(holding.FounderAccountID()),
|
||||
CreatedAt: pgTime(holding.CreatedAt()),
|
||||
}); err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - insert holding: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
stored, err := repository.queries.GetHoldingIDByFounder(ctx, pgUUID(founderID))
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - read stored holding: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if !stored.Valid {
|
||||
return uuid.Nil, fmt.Errorf("%s - stored holding has no identifier", location)
|
||||
}
|
||||
return uuid.UUID(stored.Bytes), nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) SaveCreationResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
|
||||
@@ -11,6 +11,39 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const countCompanyCardViewQuotaHoldingWindow = `-- name: CountCompanyCardViewQuotaHoldingWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(usage.last_seen_at) AS earliest_at
|
||||
FROM company_card_view_quota_usage AS usage
|
||||
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
|
||||
WHERE
|
||||
organization.holding_id = $1
|
||||
AND organization.verification_level = 'e0'
|
||||
AND usage.last_seen_at > $2
|
||||
`
|
||||
|
||||
type CountCompanyCardViewQuotaHoldingWindowParams struct {
|
||||
HoldingID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CountCompanyCardViewQuotaHoldingWindowRow struct {
|
||||
UsageCount int64
|
||||
EarliestAt interface{}
|
||||
}
|
||||
|
||||
// Counts the distinct-card usage of the E0 pool of a holding, with the same
|
||||
// rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted
|
||||
// per organization: the same candidate seen by two organizations of one
|
||||
// holding is two charges.
|
||||
func (q *Queries) CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error) {
|
||||
row := q.db.QueryRow(ctx, countCompanyCardViewQuotaHoldingWindow, arg.HoldingID, arg.WindowStart)
|
||||
var i CountCompanyCardViewQuotaHoldingWindowRow
|
||||
err := row.Scan(&i.UsageCount, &i.EarliestAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
@@ -38,6 +71,38 @@ func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg Count
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCompanyInvitationQuotaHoldingWindow = `-- name: CountCompanyInvitationQuotaHoldingWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(usage.reserved_at) AS earliest_at
|
||||
FROM company_invitation_quota_usage AS usage
|
||||
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
|
||||
WHERE
|
||||
organization.holding_id = $1
|
||||
AND organization.verification_level = 'e0'
|
||||
AND usage.reserved_at > $2
|
||||
`
|
||||
|
||||
type CountCompanyInvitationQuotaHoldingWindowParams struct {
|
||||
HoldingID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CountCompanyInvitationQuotaHoldingWindowRow struct {
|
||||
UsageCount int64
|
||||
EarliestAt interface{}
|
||||
}
|
||||
|
||||
// Counts the invitation usage of the E0 pool of a holding: the usage of every
|
||||
// organization of the holding whose trust level is E0 when the count runs. Each
|
||||
// row stays attributed to the organization that consumed it.
|
||||
func (q *Queries) CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error) {
|
||||
row := q.db.QueryRow(ctx, countCompanyInvitationQuotaHoldingWindow, arg.HoldingID, arg.WindowStart)
|
||||
var i CountCompanyInvitationQuotaHoldingWindowRow
|
||||
err := row.Scan(&i.UsageCount, &i.EarliestAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
@@ -185,12 +250,33 @@ func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg Ins
|
||||
return err
|
||||
}
|
||||
|
||||
const lockCompanyQuotaHolding = `-- name: LockCompanyQuotaHolding :one
|
||||
SELECT id
|
||||
FROM holdings
|
||||
WHERE id = $1
|
||||
FOR NO KEY UPDATE
|
||||
`
|
||||
|
||||
// Takes the pool lock of an E0 holding. It follows the organization lock, so
|
||||
// every writer locks an organization first and its holding second. Two
|
||||
// reservations of one holding queue here, and the second one counts the
|
||||
// usage that the first one committed. The lock does not conflict with the
|
||||
// FOR KEY SHARE that organizations.holding_id takes when an organization joins
|
||||
// the holding.
|
||||
func (q *Queries) LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockCompanyQuotaHolding, holdingID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
|
||||
SELECT
|
||||
id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at
|
||||
verification_changed_at,
|
||||
holding_id
|
||||
FROM organizations
|
||||
WHERE id = $1
|
||||
FOR UPDATE
|
||||
@@ -201,6 +287,7 @@ type LockCompanyQuotaOrganizationRow struct {
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
|
||||
@@ -211,21 +298,33 @@ func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organization
|
||||
&i.VerificationLevel,
|
||||
&i.VerificationBasis,
|
||||
&i.VerificationChangedAt,
|
||||
&i.HoldingID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockCompanyQuotaOrganizationFirst = `-- name: LockCompanyQuotaOrganizationFirst :one
|
||||
|
||||
SELECT id
|
||||
SELECT
|
||||
id,
|
||||
verification_level,
|
||||
holding_id
|
||||
FROM organizations
|
||||
WHERE id = $1
|
||||
FOR NO KEY UPDATE
|
||||
`
|
||||
|
||||
// Writers lock the organization first, then invitation/card-view state, and
|
||||
// finally usage rows. The organization lock serializes quota decisions for
|
||||
// the tenant and makes the subsequent count and insert atomic.
|
||||
type LockCompanyQuotaOrganizationFirstRow struct {
|
||||
ID pgtype.UUID
|
||||
VerificationLevel string
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
// Writers lock the organization first, then, for an E0 organization, the holding
|
||||
// whose pool it shares, then invitation/card-view state, and finally usage rows.
|
||||
// The organization lock serializes quota decisions for the tenant, the holding
|
||||
// lock serializes the E0 pool across the organizations of one holding, and
|
||||
// together they make the subsequent count and insert atomic.
|
||||
// Takes the organization lock ahead of every share lock of a reader that will
|
||||
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
|
||||
// SHARE, so readers of one organization queue up instead of deadlocking on a
|
||||
@@ -233,12 +332,13 @@ FOR NO KEY UPDATE
|
||||
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
|
||||
// insert of a candidate, which holds the candidate's row and then needs this
|
||||
// one. The reservation itself still takes FOR UPDATE inside the same
|
||||
// transaction.
|
||||
func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error) {
|
||||
// transaction. The result carries the holding, whose pool an E0 organization
|
||||
// shares; the caller locks that holding right after this lock.
|
||||
func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganizationFirst, organizationID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
var i LockCompanyQuotaOrganizationFirstRow
|
||||
err := row.Scan(&i.ID, &i.VerificationLevel, &i.HoldingID)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: contact_grants.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getContactGrantByInvitation = `-- name: GetContactGrantByInvitation :one
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
candidate_id,
|
||||
source_invitation_id,
|
||||
consent_record_id,
|
||||
terms_version,
|
||||
fields,
|
||||
consent_text_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_reason
|
||||
FROM contact_grants
|
||||
WHERE
|
||||
organization_id = $1
|
||||
AND source_invitation_id = $2
|
||||
`
|
||||
|
||||
type GetContactGrantByInvitationParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
}
|
||||
|
||||
// Read the grant of one invitation of one organization. An invitation of
|
||||
// another organization finds nothing.
|
||||
func (q *Queries) GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error) {
|
||||
row := q.db.QueryRow(ctx, getContactGrantByInvitation, arg.OrganizationID, arg.InvitationID)
|
||||
var i ContactGrant
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrganizationID,
|
||||
&i.CandidateID,
|
||||
&i.SourceInvitationID,
|
||||
&i.ConsentRecordID,
|
||||
&i.TermsVersion,
|
||||
&i.Fields,
|
||||
&i.ConsentTextVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationReason,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertContactGrant = `-- name: InsertContactGrant :exec
|
||||
INSERT INTO contact_grants (
|
||||
id,
|
||||
organization_id,
|
||||
candidate_id,
|
||||
source_invitation_id,
|
||||
consent_record_id,
|
||||
terms_version,
|
||||
fields,
|
||||
consent_text_version,
|
||||
granted_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7::text [],
|
||||
$8,
|
||||
$9
|
||||
)
|
||||
`
|
||||
|
||||
type InsertContactGrantParams struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
SourceInvitationID pgtype.UUID
|
||||
ConsentRecordID pgtype.UUID
|
||||
TermsVersion int64
|
||||
Fields []string
|
||||
ConsentTextVersion string
|
||||
GrantedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Store the contact grant of an acceptance. The row is inserted in the same
|
||||
// transaction as its C4 consent record and the accepted state; the database
|
||||
// checks that the record, the invitation, and the candidate agree.
|
||||
func (q *Queries) InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error {
|
||||
_, err := q.db.Exec(ctx, insertContactGrant,
|
||||
arg.ID,
|
||||
arg.OrganizationID,
|
||||
arg.CandidateID,
|
||||
arg.SourceInvitationID,
|
||||
arg.ConsentRecordID,
|
||||
arg.TermsVersion,
|
||||
arg.Fields,
|
||||
arg.ConsentTextVersion,
|
||||
arg.GrantedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: holdings.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getHoldingIDByFounder = `-- name: GetHoldingIDByFounder :one
|
||||
SELECT id
|
||||
FROM holdings
|
||||
WHERE founder_account_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, getHoldingIDByFounder, founderAccountID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const insertHoldingIfAbsent = `-- name: InsertHoldingIfAbsent :exec
|
||||
INSERT INTO holdings (
|
||||
id,
|
||||
founder_account_id,
|
||||
created_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3
|
||||
)
|
||||
ON CONFLICT (founder_account_id) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertHoldingIfAbsentParams struct {
|
||||
ID pgtype.UUID
|
||||
FounderAccountID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Stores the holding of a founder account unless the account already has one.
|
||||
// A concurrent creation of the same account waits on the founder key until the
|
||||
// other transaction ends; then this insert does nothing, and the caller reads
|
||||
// the stored holding with GetHoldingIDByFounder.
|
||||
func (q *Queries) InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error {
|
||||
_, err := q.db.Exec(ctx, insertHoldingIfAbsent, arg.ID, arg.FounderAccountID, arg.CreatedAt)
|
||||
return err
|
||||
}
|
||||
@@ -11,6 +11,51 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const acceptInvitation = `-- name: AcceptInvitation :one
|
||||
UPDATE invitations
|
||||
SET
|
||||
state = 'accepted',
|
||||
version = $1,
|
||||
responded_at = $2,
|
||||
updated_at = $2
|
||||
WHERE
|
||||
organization_id = $3
|
||||
AND id = $4
|
||||
AND state IN ('delivered', 'viewed')
|
||||
AND version = $5
|
||||
AND terms_version = $6
|
||||
AND response_deadline_at > $2
|
||||
AND $1::bigint = $5::bigint + 1
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
type AcceptInvitationParams struct {
|
||||
NextVersion int64
|
||||
AcceptedAt pgtype.Timestamptz
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
ExpectedVersion int64
|
||||
TermsVersion int64
|
||||
}
|
||||
|
||||
// The compare-and-swap of an acceptance: it applies only to a delivered or
|
||||
// viewed invitation at the version and the terms version that the candidate
|
||||
// read, and before its deadline. The answer is the acceptance time, and the
|
||||
// deadline is kept.
|
||||
func (q *Queries) AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, acceptInvitation,
|
||||
arg.NextVersion,
|
||||
arg.AcceptedAt,
|
||||
arg.OrganizationID,
|
||||
arg.InvitationID,
|
||||
arg.ExpectedVersion,
|
||||
arg.TermsVersion,
|
||||
)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const declineInvitation = `-- name: DeclineInvitation :one
|
||||
UPDATE invitations
|
||||
SET
|
||||
@@ -51,6 +96,26 @@ func (q *Queries) DeclineInvitation(ctx context.Context, arg DeclineInvitationPa
|
||||
return id, err
|
||||
}
|
||||
|
||||
const getInvitationAcceptResult = `-- name: GetInvitationAcceptResult :one
|
||||
SELECT
|
||||
invitation_id,
|
||||
outcome
|
||||
FROM invitation_accept_results
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
type GetInvitationAcceptResultRow struct {
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
}
|
||||
|
||||
func (q *Queries) GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error) {
|
||||
row := q.db.QueryRow(ctx, getInvitationAcceptResult, scopeHash)
|
||||
var i GetInvitationAcceptResultRow
|
||||
err := row.Scan(&i.InvitationID, &i.Outcome)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getInvitationDeclineResult = `-- name: GetInvitationDeclineResult :one
|
||||
SELECT
|
||||
invitation_id,
|
||||
@@ -71,6 +136,29 @@ func (q *Queries) GetInvitationDeclineResult(ctx context.Context, scopeHash []by
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertInvitationAcceptResult = `-- name: InsertInvitationAcceptResult :exec
|
||||
INSERT INTO invitation_accept_results (
|
||||
scope_hash,
|
||||
invitation_id,
|
||||
outcome
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3
|
||||
)
|
||||
`
|
||||
|
||||
type InsertInvitationAcceptResultParams struct {
|
||||
ScopeHash []byte
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error {
|
||||
_, err := q.db.Exec(ctx, insertInvitationAcceptResult, arg.ScopeHash, arg.InvitationID, arg.Outcome)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertInvitationDecline = `-- name: InsertInvitationDecline :exec
|
||||
INSERT INTO invitation_declines (
|
||||
invitation_id,
|
||||
|
||||
@@ -476,6 +476,20 @@ type ConsumerProcessedEvent struct {
|
||||
ProcessedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ContactGrant struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
SourceInvitationID pgtype.UUID
|
||||
ConsentRecordID pgtype.UUID
|
||||
TermsVersion int64
|
||||
Fields []string
|
||||
ConsentTextVersion string
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationReason pgtype.Text
|
||||
}
|
||||
|
||||
type Delivery struct {
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
@@ -563,6 +577,12 @@ type EmailToken struct {
|
||||
PendingOnboardingStep pgtype.Text
|
||||
}
|
||||
|
||||
type Holding struct {
|
||||
ID pgtype.UUID
|
||||
FounderAccountID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type IdempotencyRecord struct {
|
||||
ScopeHash []byte
|
||||
Fingerprint []byte
|
||||
@@ -592,6 +612,12 @@ type Invitation struct {
|
||||
RespondedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type InvitationAcceptResult struct {
|
||||
ScopeHash []byte
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
}
|
||||
|
||||
type InvitationCreationResult struct {
|
||||
ScopeHash []byte
|
||||
Snapshot []byte
|
||||
@@ -715,6 +741,7 @@ type Organization struct {
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
type OrganizationCreationResult struct {
|
||||
|
||||
@@ -229,7 +229,8 @@ INSERT INTO organizations (
|
||||
verification_changed_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
updated_at,
|
||||
holding_id
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
@@ -244,7 +245,8 @@ INSERT INTO organizations (
|
||||
$11,
|
||||
$12,
|
||||
$13,
|
||||
$14
|
||||
$14,
|
||||
$15
|
||||
)
|
||||
`
|
||||
|
||||
@@ -263,12 +265,13 @@ type InsertOrganizationParams struct {
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
// it too.
|
||||
// gave it and the holding of its creator. The deferred constraint
|
||||
// organizations_owner_required fails the transaction at commit unless an
|
||||
// active owner membership was inserted in it too.
|
||||
func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error {
|
||||
_, err := q.db.Exec(ctx, insertOrganization,
|
||||
arg.ID,
|
||||
@@ -285,6 +288,7 @@ func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganization
|
||||
arg.Version,
|
||||
arg.CreatedAt,
|
||||
arg.UpdatedAt,
|
||||
arg.HoldingID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -549,6 +553,23 @@ type UpdateOrganizationProfileParams struct {
|
||||
ManagerRoles []string
|
||||
}
|
||||
|
||||
type UpdateOrganizationProfileRow struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
Description pgtype.Text
|
||||
Sphere pgtype.Text
|
||||
ContactWebsite pgtype.Text
|
||||
ContactEmail pgtype.Text
|
||||
ContactPhone pgtype.Text
|
||||
ContactTelegram pgtype.Text
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Changes the profile of an organization over the version the caller read
|
||||
// and advances the version in the same statement. It names no verification
|
||||
// column, so a profile update cannot move the trust level. The change
|
||||
@@ -562,7 +583,7 @@ type UpdateOrganizationProfileParams struct {
|
||||
// follow it). No row returns for a stale version, an account that is no
|
||||
// active manager, or an unknown organization; the adapter reads the
|
||||
// membership to tell them apart.
|
||||
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) {
|
||||
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error) {
|
||||
row := q.db.QueryRow(ctx, updateOrganizationProfile,
|
||||
arg.Name,
|
||||
arg.Description,
|
||||
@@ -577,7 +598,7 @@ func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrgan
|
||||
arg.ActorID,
|
||||
arg.ManagerRoles,
|
||||
)
|
||||
var i Organization
|
||||
var i UpdateOrganizationProfileRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
|
||||
@@ -11,6 +11,11 @@ import (
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
// The compare-and-swap of an acceptance: it applies only to a delivered or
|
||||
// viewed invitation at the version and the terms version that the candidate
|
||||
// read, and before its deadline. The answer is the acceptance time, and the
|
||||
// deadline is kept.
|
||||
AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error)
|
||||
// Adds recipients to the day and the month row. The caller holds their
|
||||
// locks from LockMailQuotaRows and has checked both limits.
|
||||
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
|
||||
@@ -131,7 +136,16 @@ type Querier interface {
|
||||
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)
|
||||
// Counts the distinct-card usage of the E0 pool of a holding, with the same
|
||||
// rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted
|
||||
// per organization: the same candidate seen by two organizations of one
|
||||
// holding is two charges.
|
||||
CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error)
|
||||
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
|
||||
// Counts the invitation usage of the E0 pool of a holding: the usage of every
|
||||
// organization of the holding whose trust level is E0 when the count runs. Each
|
||||
// row stays attributed to the organization that consumed it.
|
||||
CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error)
|
||||
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
|
||||
// Counts the families of a category that have at least one published
|
||||
// version, however many versions each has.
|
||||
@@ -275,6 +289,9 @@ type Querier interface {
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
|
||||
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
|
||||
// Read the grant of one invitation of one organization. An invitation of
|
||||
// another organization finds nothing.
|
||||
GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error)
|
||||
GetCurrentAssessmentCategoryOpening(ctx context.Context, category string) (AssessmentCategoryOpening, error)
|
||||
// The newest unrevoked record of a purpose other than C4.
|
||||
GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error)
|
||||
@@ -304,6 +321,8 @@ type Querier interface {
|
||||
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error)
|
||||
GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error)
|
||||
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
|
||||
GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error)
|
||||
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error)
|
||||
@@ -470,6 +489,10 @@ type Querier interface {
|
||||
// when no row returns; the insert then changes nothing and does not abort
|
||||
// the transaction.
|
||||
InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error)
|
||||
// Store the contact grant of an acceptance. The row is inserted in the same
|
||||
// transaction as its C4 consent record and the accepted state; the database
|
||||
// checks that the record, the invitation, and the candidate agree.
|
||||
InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error
|
||||
// Stores a new delivery. A delivery with the same ID already exists when the
|
||||
// same request is handled again; the statement then inserts nothing and
|
||||
// returns 0 rows, and the stored content stays as it was. While another
|
||||
@@ -477,10 +500,16 @@ type Querier interface {
|
||||
// for it.
|
||||
InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error)
|
||||
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
|
||||
// Stores the holding of a founder account unless the account already has one.
|
||||
// A concurrent creation of the same account waits on the founder key until the
|
||||
// other transaction ends; then this insert does nothing, and the caller reads
|
||||
// the stored holding with GetHoldingIDByFounder.
|
||||
InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error
|
||||
// The invitation row, its first terms version, and its first audit event are
|
||||
// inserted in one caller-owned transaction. The deferred reference to the
|
||||
// current terms version is checked when the transaction commits.
|
||||
InsertInvitation(ctx context.Context, arg InsertInvitationParams) error
|
||||
InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error
|
||||
InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error
|
||||
InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error
|
||||
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
|
||||
@@ -493,9 +522,9 @@ type Querier interface {
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error)
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
// it too.
|
||||
// gave it and the holding of its creator. The deferred constraint
|
||||
// organizations_owner_required fails the transaction at commit unless an
|
||||
// active owner membership was inserted in it too.
|
||||
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
|
||||
// The parent and first immutable snapshot are inserted in one caller-owned
|
||||
// transaction. Deferred version references are checked when it commits.
|
||||
@@ -741,10 +770,19 @@ type Querier interface {
|
||||
// canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
// other workers skip the row, so the handler never runs twice at once.
|
||||
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
|
||||
// Takes the pool lock of an E0 holding. It follows the organization lock, so
|
||||
// every writer locks an organization first and its holding second. Two
|
||||
// reservations of one holding queue here, and the second one counts the
|
||||
// usage that the first one committed. The lock does not conflict with the
|
||||
// FOR KEY SHARE that organizations.holding_id takes when an organization joins
|
||||
// the holding.
|
||||
LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, error)
|
||||
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
|
||||
// Writers lock the organization first, then invitation/card-view state, and
|
||||
// finally usage rows. The organization lock serializes quota decisions for
|
||||
// the tenant and makes the subsequent count and insert atomic.
|
||||
// Writers lock the organization first, then, for an E0 organization, the holding
|
||||
// whose pool it shares, then invitation/card-view state, and finally usage rows.
|
||||
// The organization lock serializes quota decisions for the tenant, the holding
|
||||
// lock serializes the E0 pool across the organizations of one holding, and
|
||||
// together they make the subsequent count and insert atomic.
|
||||
// Takes the organization lock ahead of every share lock of a reader that will
|
||||
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
|
||||
// SHARE, so readers of one organization queue up instead of deadlocking on a
|
||||
@@ -752,8 +790,9 @@ type Querier interface {
|
||||
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
|
||||
// insert of a candidate, which holds the candidate's row and then needs this
|
||||
// one. The reservation itself still takes FOR UPDATE inside the same
|
||||
// transaction.
|
||||
LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error)
|
||||
// transaction. The result carries the holding, whose pool an E0 organization
|
||||
// shares; the caller locks that holding right after this lock.
|
||||
LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, 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.
|
||||
@@ -1086,7 +1125,7 @@ type Querier interface {
|
||||
// follow it). No row returns for a stale version, an account that is no
|
||||
// active manager, or an unknown organization; the adapter reads the
|
||||
// membership to tell them apart.
|
||||
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error)
|
||||
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error)
|
||||
// Replaces the registration of an unverified account and advances the
|
||||
// registration version in the same statement, so no caller can choose it.
|
||||
// The version check rejects a writer that read an older row; a verified
|
||||
|
||||
Reference in new issue
Block a user