feat(invitations): send invitations into the candidate inbox atomically

This commit is contained in:
shira committed 2026-10-09 16:50:36 +03:00
1 parent fc35e27af5
commit 1a067221f7
46 files changed
+3276 -113

No files matched your search

@@ -14035,7 +14035,8 @@ func (s *Server) handleSearchOrganizationMatchesRequest(args [1]string, argsEsca
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
// Retry-After. Enforcement of the pending limit and the organization quota is planned.
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
// not checked yet.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a send of an invitation that was already sent answers 200 with the invitation in its current
@@ -20754,10 +20754,10 @@ func (s *NotificationContent) SetLinkPath(val NilString) {
// Which event put the notification into the inbox. The inbox stores a reference to the event, never
// its text.
//
// - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform
// delivery state of the invitation: it does not depend on any email, and a failed or missing email
// never blocks it. The invitation operations are planned; no invitation produces a notification
// yet.
// - invitation_delivered: an invitation reached the candidate's inbox. It does not depend on any
// email, and a failed or missing email never blocks it. The send of an invitation produces it
// through the outbox, so the notice appears shortly after the commit of the send, while the
// invitation itself is in ListMyInvitations from that commit.
// - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility
// check, the list, and the read state). It has no product meaning, needs no action, and is never
// produced by a user action.
@@ -1725,7 +1725,8 @@ type Handler interface {
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
// Retry-After. Enforcement of the pending limit and the organization quota is planned.
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
// not checked yet.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a send of an invitation that was already sent answers 200 with the invitation in its current
@@ -1916,7 +1916,8 @@ func (UnimplementedHandler) SearchOrganizationMatches(ctx context.Context, req M
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
// Retry-After. Enforcement of the pending limit and the organization quota is planned.
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
// not checked yet.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a send of an invitation that was already sent answers 200 with the invitation in its current
@@ -18,18 +18,22 @@ import (
const defaultInvitationLimit = 20
// InvitationOperations are the owner-scoped invitation draft reads and
// commands served by HTTP.
// InvitationOperations are the owner-scoped invitation reads and commands and
// the candidate's read of the own inbox served by HTTP.
type InvitationOperations interface {
Create(ctx context.Context, command invitationusecase.CreateCommand) (domain.OrganizationInvitationView, error)
Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error)
List(ctx context.Context, command invitationusecase.ListCommand) (invitationusecase.Page, error)
Update(ctx context.Context, command invitationusecase.UpdateCommand) (domain.OrganizationInvitationView, error)
Send(ctx context.Context, command invitationusecase.SendCommand) (domain.OrganizationInvitationView, error)
ListMine(ctx context.Context, command invitationusecase.CandidateListCommand) (invitationusecase.CandidatePage, error)
}
// InvitationHandler serves the organization side of invitation drafts. The
// organization comes from the path and the server-side membership, never from
// a body, and the candidate is only ever named by the opaque card handle.
// InvitationHandler serves the organization side of invitation drafts and
// their sending, and the candidate's inbox. The organization comes from the
// path and the server-side membership, never from a body, the candidate is
// only ever named by the opaque card handle, and the candidate's inbox is
// bound to the session.
type InvitationHandler struct {
operations InvitationOperations
}
@@ -69,6 +73,20 @@ func (handler *Handler) UpdateOrganizationInvitation(ctx context.Context, reques
return handler.invitation.UpdateOrganizationInvitation(ctx, request, params)
}
func (handler *Handler) SendOrganizationInvitation(ctx context.Context, request *api.InvitationCommand, params api.SendOrganizationInvitationParams) (api.SendOrganizationInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.SendOrganizationInvitation(ctx, request, params)
}
return handler.invitation.SendOrganizationInvitation(ctx, request, params)
}
func (handler *Handler) ListMyInvitations(ctx context.Context, params api.ListMyInvitationsParams) (api.ListMyInvitationsRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.ListMyInvitations(ctx, params)
}
return handler.invitation.ListMyInvitations(ctx, params)
}
func (handler *InvitationHandler) CreateOrganizationInvitation(
ctx context.Context,
request *api.OrganizationInvitationCreate,
@@ -203,6 +221,66 @@ func (handler *InvitationHandler) UpdateOrganizationInvitation(
return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil
}
func (handler *InvitationHandler) SendOrganizationInvitation(
ctx context.Context,
request *api.InvitationCommand,
params api.SendOrganizationInvitationParams,
) (api.SendOrganizationInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SendOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.SendOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
view, err := handler.operations.Send(ctx, invitationusecase.SendCommand{
ActorID: principal.UserID, OrganizationID: params.OrgID, InvitationID: params.InvitationID,
IdempotencyKey: params.IdempotencyKey, ExpectedVersion: int64(request.ExpectedVersion),
})
if err != nil {
return invitationSendFailure(ctx, err)
}
return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil
}
func (handler *InvitationHandler) ListMyInvitations(ctx context.Context, params api.ListMyInvitationsParams) (api.ListMyInvitationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyInvitationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, pointer := candidateInvitationListCommand(principal.UserID, params)
if pointer != "" {
return (*api.ListMyInvitationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
page, err := handler.operations.ListMine(ctx, command)
if err != nil {
if errors.Is(err, invitationusecase.ErrForbidden) {
return (*api.ListMyInvitationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
items := make([]api.CandidateInvitationSummary, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, candidateInvitationSummary(item))
}
next := api.NilString{}
next.SetToNull()
if page.HasMore && len(page.Items) > 0 {
last := page.Items[len(page.Items)-1]
cursor, err := encodeCandidateInvitationCursor(principal.UserID, outbound.CandidateInvitationPosition{
DeliveredAt: last.DeliveredAt, InvitationID: last.ID,
})
if err != nil {
return nil, fmt.Errorf("InvitationHandler.ListMyInvitations - encode cursor: %w", err)
}
next.SetTo(cursor)
}
return &api.CandidateInvitationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.CandidateInvitationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
// invitationFailure is the public classification of a usecase error. Every
// kind has one fixed problem, so a response never depends on which of two
// indistinguishable causes happened.
@@ -232,7 +310,7 @@ func classifyInvitationError(err error) invitationFailure {
return invitationFailureBadKey
case errors.Is(err, domain.ErrInvitationVersionConflict), errors.Is(err, outbound.ErrInvitationVersionConflict):
return invitationFailureVersionConflict
case errors.Is(err, domain.ErrInvitationNotDraft):
case errors.Is(err, domain.ErrInvitationNotDraft), errors.Is(err, invitationusecase.ErrSendBlocked):
return invitationFailureStateConflict
case errors.Is(err, domain.ErrInvalidInvitation), errors.Is(err, domain.ErrInvalidSalaryRange):
if _, ok := errors.AsType[*domain.InvitationFieldError](err); ok {
@@ -301,6 +379,52 @@ func invitationUpdateFailure(ctx context.Context, err error) (api.UpdateOrganiza
return nil, err
}
func invitationSendFailure(ctx context.Context, err error) (api.SendOrganizationInvitationRes, error) {
// The organization quota is a 429 with the time when it frees room; it is
// not stored under the key, so a later retry can succeed.
if limited, ok := errors.AsType[*invitationusecase.QuotaExceededError](err); ok {
return problem.RateLimited(ctx, wholeSeconds(time.Until(limited.RetryAt))), nil
}
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.SendOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.SendOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused:
return (*api.SendOrganizationInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case invitationFailureBadKey:
return (*api.SendOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case invitationFailureInvalid:
return (*api.SendOrganizationInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil
case invitationFailureVersionConflict:
return (*api.SendOrganizationInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case invitationFailureStateConflict:
return (*api.SendOrganizationInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case invitationFailureOther:
return nil, err
}
return nil, err
}
func candidateInvitationListCommand(actorID uuid.UUID, params api.ListMyInvitationsParams) (invitationusecase.CandidateListCommand, string) {
limit, ok := params.Limit.Get()
if !ok {
limit = defaultInvitationLimit
}
if limit < 1 || limit > outbound.MaxInvitationPageSize {
return invitationusecase.CandidateListCommand{}, "limit"
}
command := invitationusecase.CandidateListCommand{ActorID: actorID, Limit: limit}
if cursor, ok := params.Cursor.Get(); ok {
position, err := decodeCandidateInvitationCursor(cursor, actorID)
if err != nil {
return invitationusecase.CandidateListCommand{}, "cursor"
}
command.After = &position
}
return command, ""
}
func invitationListCommand(actorID uuid.UUID, params api.ListOrganizationInvitationsParams) (invitationusecase.ListCommand, string) {
limit, ok := params.Limit.Get()
if !ok {
@@ -493,3 +617,19 @@ func organizationInvitationSummary(view domain.OrganizationInvitationView) api.O
CreatedAt: api.Timestamp(view.CreatedAt), UpdatedAt: api.Timestamp(view.UpdatedAt),
}
}
func candidateInvitationSummary(summary domain.CandidateInvitationSummary) api.CandidateInvitationSummary {
formats := make([]api.WorkFormat, 0, len(summary.WorkFormats))
for _, format := range summary.WorkFormats {
formats = append(formats, api.WorkFormat(format))
}
return api.CandidateInvitationSummary{
ID: summary.ID,
Organization: api.InvitationOrganization{ID: summary.Organization.ID, Name: summary.Organization.Name},
State: api.InvitationState(summary.State), ExpiryReason: invitationExpiryResponse(summary.ExpiryReason),
Version: api.InvitationVersion(summary.Version), TermsVersion: api.InvitationTermsVersion(summary.TermsVersion),
RoleTitle: api.InvitationRoleTitle(summary.RoleTitle), Salary: salaryRangeResponse(summary.Salary), WorkFormats: formats,
ResponseDeadlineAt: api.Timestamp(summary.ResponseDeadlineAt), DeliveredAt: api.Timestamp(summary.DeliveredAt),
ViewedAt: nullableTimestamp(summary.ViewedAt), UpdatedAt: api.Timestamp(summary.UpdatedAt),
}
}
@@ -13,43 +13,79 @@ import (
)
const (
invitationCursorVersion = 1
invitationCursorBytes = 61
maxInvitationCursorTime = uint64(253402300799)
// invitationCursorVersion marks a page of one organization's invitations;
// candidateInvitationCursorVersion marks a page of one candidate's inbox.
// A cursor of one listing is refused by the other.
invitationCursorVersion = 1
candidateInvitationCursorVersion = 2
invitationCursorBytes = 61
maxInvitationCursorTime = uint64(253402300799)
)
// encodeInvitationCursor binds the position to the account and the
// organization that read the page, so a cursor of another reader or tenant is
// refused instead of continuing a foreign listing.
func encodeInvitationCursor(actorID, organizationID uuid.UUID, position outbound.InvitationListPosition) (string, error) {
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
if actorID == uuid.Nil || organizationID == uuid.Nil || position.InvitationID == uuid.Nil || position.CreatedAt.IsZero() ||
position.CreatedAt.Year() < 1 || position.CreatedAt.Year() > 9999 || seconds < 0 || uint64(seconds) > maxInvitationCursorTime ||
nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 {
return "", errors.New("invitation cursor requires an actor, organization, and valid page position")
if organizationID == uuid.Nil {
return "", errors.New("invitation cursor requires an organization")
}
var value [invitationCursorBytes]byte
value[0] = invitationCursorVersion
copy(value[1:17], actorID[:])
copy(value[17:33], organizationID[:])
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
copy(value[45:61], position.InvitationID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
return encodeInvitationPosition(invitationCursorVersion, actorID, organizationID, position.CreatedAt, position.InvitationID)
}
func decodeInvitationCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.InvitationListPosition, error) {
if organizationID == uuid.Nil {
return outbound.InvitationListPosition{}, errors.New("invitation cursor requires an organization")
}
at, invitationID, err := decodeInvitationPosition(cursor, invitationCursorVersion, actorID, organizationID)
if err != nil {
return outbound.InvitationListPosition{}, err
}
return outbound.InvitationListPosition{CreatedAt: at, InvitationID: invitationID}, nil
}
// encodeCandidateInvitationCursor binds the position of the candidate's inbox
// to the candidate who read the page.
func encodeCandidateInvitationCursor(actorID uuid.UUID, position outbound.CandidateInvitationPosition) (string, error) {
return encodeInvitationPosition(candidateInvitationCursorVersion, actorID, actorID, position.DeliveredAt, position.InvitationID)
}
func decodeCandidateInvitationCursor(cursor string, actorID uuid.UUID) (outbound.CandidateInvitationPosition, error) {
at, invitationID, err := decodeInvitationPosition(cursor, candidateInvitationCursorVersion, actorID, actorID)
if err != nil {
return outbound.CandidateInvitationPosition{}, err
}
return outbound.CandidateInvitationPosition{DeliveredAt: at, InvitationID: invitationID}, nil
}
func encodeInvitationPosition(version byte, actorID, scopeID uuid.UUID, at time.Time, invitationID uuid.UUID) (string, error) {
seconds, nanos := at.Unix(), at.Nanosecond()
if actorID == uuid.Nil || scopeID == uuid.Nil || invitationID == uuid.Nil || at.IsZero() ||
at.Year() < 1 || at.Year() > 9999 || seconds < 0 || uint64(seconds) > maxInvitationCursorTime ||
nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 {
return "", errors.New("invitation cursor requires an actor, a scope, and a valid page position")
}
var value [invitationCursorBytes]byte
value[0] = version
copy(value[1:17], actorID[:])
copy(value[17:33], scopeID[:])
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
copy(value[45:61], invitationID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeInvitationPosition(cursor string, version byte, actorID, scopeID uuid.UUID) (time.Time, uuid.UUID, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != invitationCursorBytes || actorID == uuid.Nil || organizationID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != invitationCursorVersion ||
uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != organizationID {
return outbound.InvitationListPosition{}, errors.New("invitation cursor is invalid")
if err != nil || len(value) != invitationCursorBytes || actorID == uuid.Nil || scopeID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != version ||
uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != scopeID {
return time.Time{}, uuid.Nil, errors.New("invitation cursor is invalid")
}
seconds := binary.BigEndian.Uint64(value[33:41])
nanos := binary.BigEndian.Uint32(value[41:45])
invitationID := uuid.UUID(value[45:61])
if seconds > uint64(math.MaxInt64) || seconds > maxInvitationCursorTime || nanos >= 1_000_000_000 || nanos%1_000 != 0 || invitationID == uuid.Nil {
return outbound.InvitationListPosition{}, errors.New("invitation cursor position is invalid")
return time.Time{}, uuid.Nil, errors.New("invitation cursor position is invalid")
}
return outbound.InvitationListPosition{CreatedAt: time.Unix(int64(seconds), int64(nanos)).UTC(), InvitationID: invitationID}, nil
return time.Unix(int64(seconds), int64(nanos)).UTC(), invitationID, nil
}
@@ -191,3 +191,73 @@ func TestInvitationCursorIsBoundToActorAndOrganization(t *testing.T) {
t.Error("a cursor with trailing data was accepted")
}
}
func TestInvitationSendFailuresMapToTheContractStatuses(t *testing.T) {
ctx := context.Background()
send := func(err error) any {
response, unexpected := invitationSendFailure(ctx, err)
if unexpected != nil {
return unexpected
}
return fmt.Sprintf("%T", response)
}
for name, test := range map[string]struct {
err error
want string
}{
"forbidden": {fmt.Errorf("wrapped: %w", outbound.ErrOrganizationManagerRequired), "*api.SendOrganizationInvitationForbidden"},
"unknown invitation": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.SendOrganizationInvitationNotFound"},
"reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.SendOrganizationInvitationUnprocessableEntity"},
"bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.SendOrganizationInvitationBadRequest"},
"stale version": {fmt.Errorf("wrapped: %w", domain.ErrInvitationVersionConflict), "*api.SendOrganizationInvitationPreconditionFailed"},
"blocked send": {fmt.Errorf("wrapped: %w", invitationusecase.ErrSendBlocked), "*api.SendOrganizationInvitationConflict"},
"quota": {&invitationusecase.QuotaExceededError{RetryAt: time.Now().Add(90 * time.Second)}, "*api.TooManyRequestsHeaders"},
} {
if got := send(test.err); got != test.want {
t.Errorf("%s: send failure = %v, want %s", name, got, test.want)
}
}
response, err := invitationSendFailure(ctx, fmt.Errorf("wrapped: %w", &invitationusecase.QuotaExceededError{RetryAt: time.Now().Add(90 * time.Second)}))
limited, ok := response.(*api.TooManyRequestsHeaders)
if err != nil || !ok || limited.Response.Code != api.ProblemCodeRateLimited {
t.Fatalf("quota failure = %T, %v; want 429 rate_limited", response, err)
}
if wait, set := limited.RetryAfter.Get(); !set || wait < 89 || wait > 90 {
t.Fatalf("Retry-After = %d, %v; want the seconds until the quota frees room", wait, set)
}
if _, passedOn := send(errors.New("storage failed")).(error); !passedOn {
t.Error("an unknown failure produced a public response instead of reaching the responder")
}
}
func TestCandidateInvitationCursorIsBoundToTheCandidateAndItsListing(t *testing.T) {
actorID := uuid.Must(uuid.NewV7())
position := outbound.CandidateInvitationPosition{
DeliveredAt: time.Date(2026, time.October, 9, 10, 0, 0, 123456000, time.UTC), InvitationID: uuid.Must(uuid.NewV7()),
}
cursor, err := encodeCandidateInvitationCursor(actorID, position)
if err != nil {
t.Fatalf("encodeCandidateInvitationCursor() error = %v", err)
}
decoded, err := decodeCandidateInvitationCursor(cursor, actorID)
if err != nil || !decoded.DeliveredAt.Equal(position.DeliveredAt) || decoded.InvitationID != position.InvitationID {
t.Fatalf("decodeCandidateInvitationCursor() = %+v, %v; want the same position", decoded, err)
}
if _, err := decodeCandidateInvitationCursor(cursor, uuid.Must(uuid.NewV7())); err == nil {
t.Error("a cursor of another candidate was accepted")
}
// An organization cursor of the same account does not continue the
// candidate's inbox, and the other way round.
organizationCursor, err := encodeInvitationCursor(actorID, actorID, outbound.InvitationListPosition{
CreatedAt: position.DeliveredAt, InvitationID: position.InvitationID,
})
if err != nil {
t.Fatalf("encodeInvitationCursor() error = %v", err)
}
if _, err := decodeCandidateInvitationCursor(organizationCursor, actorID); err == nil {
t.Error("an organization cursor continued the candidate's inbox")
}
if _, err := decodeInvitationCursor(cursor, actorID, actorID); err == nil {
t.Error("a candidate cursor continued an organization listing")
}
}
@@ -0,0 +1,253 @@
package postgres
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"unicode/utf8"
"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.InvitationSendResultRepository = invitationRepository{}
// maxInvitationOrganizationNameRunes is the bound of the organization name
// that the candidate's inbox shows, as in the public contract.
const maxInvitationOrganizationNameRunes = 200
func (unit *UnitOfWork) InvitationSendResults() outbound.InvitationSendResultRepository {
return invitationRepository{queries: unit.queries}
}
func (repository invitationRepository) Deliver(
ctx context.Context,
expectedVersion int64,
next domain.Invitation,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.Deliver"
stored := next.Stored()
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationDelivered) ||
stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil || event.Kind != domain.InvitationEventDelivered {
return fmt.Errorf("%s - the next version must be the delivery 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.DeliverInvitation(ctx, sqlc.DeliverInvitationParams{
NextVersion: stored.Version, DeliveredAt: pgTime(*stored.DeliveredAt), ResponseDeadlineAt: pgTime(*stored.ResponseDeadlineAt),
OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - deliver draft: %w", location, outbound.ErrInvitationVersionConflict)
}
if err != nil {
return fmt.Errorf("%s - deliver draft: %w", location, mapInvitationError(err))
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) ListForCandidate(
ctx context.Context,
query outbound.CandidateInvitationListQuery,
) (outbound.CandidateInvitationPage, error) {
const location = "invitationRepository.ListForCandidate"
if query.CandidateID == uuid.Nil {
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidInvitation)
}
if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize {
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation)
}
params := sqlc.ListCandidateInvitationsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
if query.After != nil {
after := *query.After
if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.DeliveredAt) {
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation)
}
params.AfterDeliveredAt = pgTime(after.DeliveredAt)
params.AfterInvitationID = pgUUID(after.InvitationID)
}
rows, err := repository.queries.ListCandidateInvitations(ctx, params)
if err != nil {
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err))
}
page := outbound.CandidateInvitationPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]outbound.CandidateInvitationEntry, 0, len(rows))
for _, row := range rows {
entry, err := restoreCandidateInvitationRow(location, row, query.CandidateID)
if err != nil {
return outbound.CandidateInvitationPage{}, err
}
page.Items = append(page.Items, entry)
}
return page, nil
}
func (repository invitationRepository) GetForCandidate(
ctx context.Context,
candidateID, invitationID uuid.UUID,
) (domain.Invitation, error) {
const location = "invitationRepository.GetForCandidate"
if candidateID == uuid.Nil || invitationID == uuid.Nil {
return domain.Invitation{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.ReadCandidateInvitation(ctx, sqlc.ReadCandidateInvitationParams{
CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID),
})
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err))
}
if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID {
return domain.Invitation{}, fmt.Errorf("%s - invitation row has an invalid scope: %w", location, domain.ErrInvalidInvitation)
}
return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), uuid.UUID(row.OrganizationID.Bytes))
}
func (repository invitationRepository) SaveSendResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result outbound.InvitationSendResult,
) error {
const location = "invitationRepository.SaveSendResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
if err := validateInvitationSendResult(result); err != nil {
return fmt.Errorf("%s - validate outcome: %w", location, err)
}
var snapshot []byte
if result.View != nil {
encoded, err := encodeInvitationCreationResult(*result.View)
if err != nil {
return fmt.Errorf("%s - encode response: %w", location, err)
}
snapshot = encoded
}
if err := repository.queries.InsertInvitationSendResult(ctx, sqlc.InsertInvitationSendResultParams{
ScopeHash: scope[:], OrganizationID: pgUUID(result.OrganizationID), InvitationID: pgUUID(result.InvitationID),
Outcome: string(result.Outcome), Snapshot: snapshot,
}); err != nil {
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationSendResultError(err))
}
return nil
}
func (repository invitationRepository) GetSendResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (outbound.InvitationSendResult, error) {
const location = "invitationRepository.GetSendResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return outbound.InvitationSendResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.GetInvitationSendResult(ctx, scope[:])
if errors.Is(err, pgx.ErrNoRows) {
return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound
}
if err != nil {
return outbound.InvitationSendResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
}
if !row.OrganizationID.Valid || !row.InvitationID.Valid {
return outbound.InvitationSendResult{}, fmt.Errorf("%s - stored outcome has no scope: %w", location, domain.ErrInvalidInvitation)
}
result := outbound.InvitationSendResult{
OrganizationID: uuid.UUID(row.OrganizationID.Bytes), InvitationID: uuid.UUID(row.InvitationID.Bytes),
Outcome: outbound.InvitationSendOutcome(row.Outcome),
}
if row.Snapshot != "" {
view, err := decodeInvitationSendView(location, []byte(row.Snapshot))
if err != nil {
return outbound.InvitationSendResult{}, err
}
result.View = &view
}
if err := validateInvitationSendResult(result); err != nil {
return outbound.InvitationSendResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
}
return result, nil
}
// decodeInvitationSendView restores the original response of a send. It
// shares the shape and the checks of a stored creation response.
func decodeInvitationSendView(location string, encoded []byte) (domain.OrganizationInvitationView, error) {
var view domain.OrganizationInvitationView
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&view); err != nil || decoder.More() {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation)
}
if err := validateInvitationCreationResult(view); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err)
}
return view, nil
}
func validateInvitationSendResult(result outbound.InvitationSendResult) error {
const location = "postgres.validateInvitationSendResult"
// The invitation of a refusal is the identifier of the path, which may
// name nothing, even the nil identifier; only a sent outcome names a real
// invitation.
if result.OrganizationID == uuid.Nil {
return fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation)
}
switch result.Outcome {
case outbound.InvitationSendSent:
if result.View == nil || result.View.ID != result.InvitationID || result.View.OrganizationID != result.OrganizationID ||
!result.View.State.IsKnown() || result.View.DeliveredAt == nil {
return fmt.Errorf("%s - a sent outcome must hold the delivered invitation: %w", location, domain.ErrInvalidInvitation)
}
case outbound.InvitationSendNotFound, outbound.InvitationSendStateConflict:
if result.View != nil {
return fmt.Errorf("%s - a refused outcome holds no response: %w", location, domain.ErrInvalidInvitation)
}
default:
return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation)
}
return nil
}
func restoreCandidateInvitationRow(
location string,
row sqlc.ListCandidateInvitationsRow,
candidateID uuid.UUID,
) (outbound.CandidateInvitationEntry, error) {
if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID ||
!utf8.ValidString(row.OrganizationName) || row.OrganizationName == "" ||
utf8.RuneCountInString(row.OrganizationName) > maxInvitationOrganizationNameRunes {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - invitation row has an invalid scope or sender: %w", location, domain.ErrInvalidInvitation)
}
invitation, err := restoreInvitationRow(location, sqlc.ListInvitationsRow{
ID: row.ID, OrganizationID: row.OrganizationID, CandidateID: row.CandidateID, NeedID: row.NeedID,
NeedRequirementsVersion: row.NeedRequirementsVersion, State: row.State, ExpiryReason: row.ExpiryReason,
Version: row.Version, TermsVersion: row.TermsVersion, ResponsePeriodDays: row.ResponsePeriodDays,
PolicyVersionID: row.PolicyVersionID, ResponseDeadlineAt: row.ResponseDeadlineAt, SalaryRaiseUsed: row.SalaryRaiseUsed,
CreatedBy: row.CreatedBy, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, DeliveredAt: row.DeliveredAt,
ViewedAt: row.ViewedAt, RespondedAt: row.RespondedAt, Terms: row.Terms,
}, uuid.UUID(row.OrganizationID.Bytes))
if err != nil {
return outbound.CandidateInvitationEntry{}, err
}
if !invitation.IsDelivered() {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - an undelivered invitation is not in the inbox: %w", location, domain.ErrInvalidInvitation)
}
return outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: row.OrganizationName}, nil
}
func mapInvitationSendResultError(err error) error {
var pgError *pgconn.PgError
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_send_results_idempotency_fkey" {
return fmt.Errorf("postgres.mapInvitationSendResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
}
return mapInvitationError(err)
}
@@ -0,0 +1,336 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: invitation_delivery.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const deliverInvitation = `-- name: DeliverInvitation :one
UPDATE invitations
SET
state = 'delivered',
version = $1,
delivered_at = $2,
response_deadline_at = $3,
updated_at = $2
WHERE
organization_id = $4
AND id = $5
AND state = 'draft'
AND version = $6
AND $1::bigint = $6::bigint + 1
RETURNING id
`
type DeliverInvitationParams struct {
NextVersion int64
DeliveredAt pgtype.Timestamptz
ResponseDeadlineAt pgtype.Timestamptz
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ExpectedVersion int64
}
// The conditional update is the compare-and-swap of a send: it applies only to
// a draft whose version is still the one the caller read, records the first
// delivery with its deadline, and advances the version by one. No row is
// returned when it lost a race or the invitation is no longer a draft.
func (q *Queries) DeliverInvitation(ctx context.Context, arg DeliverInvitationParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, deliverInvitation,
arg.NextVersion,
arg.DeliveredAt,
arg.ResponseDeadlineAt,
arg.OrganizationID,
arg.InvitationID,
arg.ExpectedVersion,
)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const getInvitationSendResult = `-- name: GetInvitationSendResult :one
SELECT
organization_id,
invitation_id,
outcome,
-- A refusal has no snapshot; the empty text stands for it.
coalesce(snapshot::text, '')::text AS snapshot
FROM invitation_send_results
WHERE scope_hash = $1
`
type GetInvitationSendResultRow struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
Outcome string
Snapshot string
}
func (q *Queries) GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error) {
row := q.db.QueryRow(ctx, getInvitationSendResult, scopeHash)
var i GetInvitationSendResultRow
err := row.Scan(
&i.OrganizationID,
&i.InvitationID,
&i.Outcome,
&i.Snapshot,
)
return i, err
}
const insertInvitationSendResult = `-- name: InsertInvitationSendResult :exec
INSERT INTO invitation_send_results (
scope_hash,
organization_id,
invitation_id,
outcome,
snapshot
) VALUES (
$1,
$2,
$3,
$4,
$5::jsonb
)
`
type InsertInvitationSendResultParams struct {
ScopeHash []byte
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
Outcome string
Snapshot []byte
}
func (q *Queries) InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error {
_, err := q.db.Exec(ctx, insertInvitationSendResult,
arg.ScopeHash,
arg.OrganizationID,
arg.InvitationID,
arg.Outcome,
arg.Snapshot,
)
return err
}
const listCandidateInvitations = `-- name: ListCandidateInvitations :many
SELECT
invitation.id,
invitation.organization_id,
invitation.candidate_id,
invitation.need_id,
invitation.need_requirements_version,
invitation.state,
invitation.expiry_reason,
invitation.version,
invitation.terms_version,
invitation.response_period_days,
invitation.policy_version_id,
invitation.response_deadline_at,
invitation.salary_raise_used,
invitation.created_by,
invitation.created_at,
invitation.updated_at,
invitation.delivered_at,
invitation.viewed_at,
invitation.responded_at,
terms.terms::text AS terms,
organization.name AS organization_name
FROM invitations AS invitation
INNER JOIN invitation_terms_versions AS terms
ON terms.invitation_id = invitation.id
AND terms.version = invitation.terms_version
INNER JOIN organizations AS organization
ON organization.id = invitation.organization_id
WHERE
invitation.candidate_id = $1
AND invitation.delivered_at IS NOT NULL
AND (
$2::timestamptz IS NULL
OR (invitation.delivered_at, invitation.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY invitation.delivered_at DESC, invitation.id DESC
LIMIT $4
`
type ListCandidateInvitationsParams struct {
CandidateID pgtype.UUID
AfterDeliveredAt pgtype.Timestamptz
AfterInvitationID pgtype.UUID
RowLimit int32
}
type ListCandidateInvitationsRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
Terms string
OrganizationName string
}
// One bounded page of the candidate's inbox: every invitation delivered to
// the candidate, in any later state, newest first by delivery time. Drafts
// have no delivery and are never listed. The candidate scopes the rows, so
// no identifier of another candidate can appear.
func (q *Queries) ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error) {
rows, err := q.db.Query(ctx, listCandidateInvitations,
arg.CandidateID,
arg.AfterDeliveredAt,
arg.AfterInvitationID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateInvitationsRow
for rows.Next() {
var i ListCandidateInvitationsRow
if err := rows.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.NeedID,
&i.NeedRequirementsVersion,
&i.State,
&i.ExpiryReason,
&i.Version,
&i.TermsVersion,
&i.ResponsePeriodDays,
&i.PolicyVersionID,
&i.ResponseDeadlineAt,
&i.SalaryRaiseUsed,
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeliveredAt,
&i.ViewedAt,
&i.RespondedAt,
&i.Terms,
&i.OrganizationName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const readCandidateInvitation = `-- name: ReadCandidateInvitation :one
SELECT
invitation.id,
invitation.organization_id,
invitation.candidate_id,
invitation.need_id,
invitation.need_requirements_version,
invitation.state,
invitation.expiry_reason,
invitation.version,
invitation.terms_version,
invitation.response_period_days,
invitation.policy_version_id,
invitation.response_deadline_at,
invitation.salary_raise_used,
invitation.created_by,
invitation.created_at,
invitation.updated_at,
invitation.delivered_at,
invitation.viewed_at,
invitation.responded_at,
terms.terms::text AS terms
FROM invitations AS invitation
INNER JOIN invitation_terms_versions AS terms
ON terms.invitation_id = invitation.id
AND terms.version = invitation.terms_version
WHERE
invitation.candidate_id = $1
AND invitation.id = $2
AND invitation.delivered_at IS NOT NULL
`
type ReadCandidateInvitationParams struct {
CandidateID pgtype.UUID
InvitationID pgtype.UUID
}
type ReadCandidateInvitationRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
Terms string
}
// Read one delivered invitation addressed to the candidate. A draft and an
// invitation of another candidate find nothing.
func (q *Queries) ReadCandidateInvitation(ctx context.Context, arg ReadCandidateInvitationParams) (ReadCandidateInvitationRow, error) {
row := q.db.QueryRow(ctx, readCandidateInvitation, arg.CandidateID, arg.InvitationID)
var i ReadCandidateInvitationRow
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.NeedID,
&i.NeedRequirementsVersion,
&i.State,
&i.ExpiryReason,
&i.Version,
&i.TermsVersion,
&i.ResponsePeriodDays,
&i.PolicyVersionID,
&i.ResponseDeadlineAt,
&i.SalaryRaiseUsed,
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeliveredAt,
&i.ViewedAt,
&i.RespondedAt,
&i.Terms,
)
return i, err
}
@@ -609,6 +609,14 @@ type InvitationEvent struct {
OccurredAt pgtype.Timestamptz
}
type InvitationSendResult struct {
ScopeHash []byte
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
Outcome string
Snapshot []byte
}
type InvitationTermsVersion struct {
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
@@ -201,6 +201,11 @@ type Querier interface {
// The restricting foreign key is checked at the end of the statement, after
// these rows are gone.
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
// The conditional update is the compare-and-swap of a send: it applies only to
// a draft whose version is still the one the caller read, records the first
// delivery with its deadline, and advances the version by one. No row is
// returned when it lost a race or the invitation is no longer a draft.
DeliverInvitation(ctx context.Context, arg DeliverInvitationParams) (pgtype.UUID, error)
// Lock order. Every transaction that writes mail_quota_usage first creates
// and locks all the usage rows it will touch with EnsureMailQuotaRows and
// LockMailQuotaRows, which both work in (period_kind, period_start) order,
@@ -297,6 +302,7 @@ type Querier interface {
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
@@ -472,6 +478,7 @@ type Querier interface {
// current terms version is checked when the transaction commits.
InsertInvitation(ctx context.Context, arg InsertInvitationParams) error
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error
InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
@@ -592,6 +599,11 @@ type Querier interface {
// (hidden_at, organization_id) position of the last record of the previous
// page.
ListCandidateHiddenOrganizations(ctx context.Context, arg ListCandidateHiddenOrganizationsParams) ([]ListCandidateHiddenOrganizationsRow, error)
// One bounded page of the candidate's inbox: every invitation delivered to
// the candidate, in any later state, newest first by delivery time. Drafts
// have no delivery and are never listed. The candidate scopes the rows, so
// no identifier of another candidate can appear.
ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error)
// The same selection for the candidate's own card preview, so the candidate
// sees what an organization would read. It is scoped by the owner and runs
// after the caller locked the effective C2 and publication; it does not apply
@@ -831,6 +843,9 @@ type Querier interface {
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
// Read one delivered invitation addressed to the candidate. A draft and an
// invitation of another candidate find nothing.
ReadCandidateInvitation(ctx context.Context, arg ReadCandidateInvitationParams) (ReadCandidateInvitationRow, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and