Files

167 lines
6.3 KiB
Go

package invitation
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
// ResponseDeadlineJobKind names the scheduled job that expires an invitation
// at its response deadline. The delivery schedules it in its own transaction.
const ResponseDeadlineJobKind = "invitation.response_deadline"
const (
responseDeadlineLocation = "invitation.ResponseDeadlineJob.Handle"
scheduleDeadlineLocation = "invitation.scheduleResponseDeadline"
)
// ResponseDeadlineJob expires a delivered or viewed invitation whose response
// deadline has passed. The job is keyed by its invitation, so a delivery has one
// job, and the job is idempotent: a run that finds the invitation answered or
// expired changes nothing. The expiry creates no consent, no contact grant, and
// no quota change.
type ResponseDeadlineJob struct {
clock func() time.Time
}
// NewResponseDeadlineJob returns the handler of ResponseDeadlineJobKind. A nil
// clock is the process clock.
func NewResponseDeadlineJob(clock func() time.Time) *ResponseDeadlineJob {
if clock == nil {
clock = time.Now
}
return &ResponseDeadlineJob{clock: clock}
}
// JobKind is the stable kind name.
func (*ResponseDeadlineJob) JobKind() string { return ResponseDeadlineJobKind }
// Handle expires the invitation of the job when it still waits for an answer.
// The row is locked before the answer is read, so a candidate command that
// answers at the same moment either wins first, and the job then changes
// nothing, or waits and finds the expiry. The job runs at its due time, which is
// the deadline the invitation stores; a clock that has not reached that deadline
// returns an error, so the job is retried instead of completing unexpired.
func (job *ResponseDeadlineJob) Handle(ctx context.Context, unit outbound.UnitOfWork, scheduled outbound.ClaimedJob) error {
invitationID, err := responseDeadlinePayload(scheduled.Payload)
if err != nil {
return fmt.Errorf("%s - read payload: %w", responseDeadlineLocation, err)
}
current, err := unit.Invitations().GetForDeadline(ctx, invitationID)
if errors.Is(err, outbound.ErrInvitationNotFound) {
return nil
}
if err != nil {
return fmt.Errorf("%s - lock invitation: %w", responseDeadlineLocation, err)
}
if !current.AwaitsAnswer() {
return nil
}
now := job.clock().UTC().Truncate(time.Microsecond)
if !current.ResponseDeadlinePassed(now) {
return fmt.Errorf("%s - the response deadline has not passed by the application clock", responseDeadlineLocation)
}
if _, err := expireDueInvitation(ctx, unit, current, notBefore(now, current.UpdatedAt())); err != nil {
return fmt.Errorf("%s - expire invitation: %w", responseDeadlineLocation, err)
}
return nil
}
// responseDeadlinePayload reads the invitation that a job names. A payload that
// names no invitation can never run, so it is final.
func responseDeadlinePayload(payload json.RawMessage) (uuid.UUID, error) {
var fields struct {
InvitationID string `json:"invitation_id"`
}
if err := json.Unmarshal(payload, &fields); err != nil {
return uuid.Nil, fmt.Errorf("decode payload: %w", inbound.ErrJobRejected)
}
parsed, err := uuid.Parse(fields.InvitationID)
if err != nil || parsed == uuid.Nil {
return uuid.Nil, fmt.Errorf("payload names no invitation: %w", inbound.ErrJobRejected)
}
return parsed, nil
}
// scheduleResponseDeadline schedules the expiry of a delivered invitation at
// its response deadline. It runs in the delivery transaction, so the job exists
// exactly when the delivery committed. The first schedule of the key wins, and
// a key that already exists means the delivery ran twice, which is refused.
func scheduleResponseDeadline(ctx context.Context, unit outbound.UnitOfWork, delivered domain.Invitation) error {
snapshot := delivered.Snapshot()
if snapshot.ResponseDeadlineAt == nil {
return fmt.Errorf("%s - a delivered invitation has a response deadline: %w", scheduleDeadlineLocation, domain.ErrInvalidInvitation)
}
payload, err := json.Marshal(map[string]string{"invitation_id": snapshot.ID.String()})
if err != nil {
return fmt.Errorf("%s - encode payload: %w", scheduleDeadlineLocation, err)
}
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{
Kind: ResponseDeadlineJobKind, Key: snapshot.ID.String(), DueAt: *snapshot.ResponseDeadlineAt, Payload: payload,
})
if err != nil {
return fmt.Errorf("%s - build job: %w", scheduleDeadlineLocation, err)
}
scheduled, err := unit.ScheduledJobs().Schedule(ctx, job)
if err != nil {
return fmt.Errorf("%s - schedule job: %w", scheduleDeadlineLocation, err)
}
if !scheduled {
return fmt.Errorf("%s - the deadline job of the invitation exists already: %w", scheduleDeadlineLocation, domain.ErrInvalidInvitation)
}
return nil
}
// expireDueInvitation stores the expiry of an invitation whose deadline has
// passed at the given time, inside the caller's transaction, and returns the
// invitation as it stands afterwards. The caller holds the row lock. An
// invitation that is not due is returned unchanged.
func expireDueInvitation(
ctx context.Context,
unit outbound.UnitOfWork,
current domain.Invitation,
at time.Time,
) (domain.Invitation, error) {
expired, changed, err := current.Expire(at)
if err != nil {
return domain.Invitation{}, fmt.Errorf("expire invitation: %w", err)
}
if !changed {
return current, nil
}
event, err := expired.ExpiryEvent()
if err != nil {
return domain.Invitation{}, fmt.Errorf("build audit event: %w", err)
}
if err := unit.Invitations().Expire(ctx, current.Version(), expired, event); err != nil {
return domain.Invitation{}, fmt.Errorf("store expiry: %w", err)
}
return expired, nil
}
// settleCandidateEntry applies the due expiry to an invitation that a candidate
// read or command has locked or is about to read, at the time that command
// decided on. A read that found the invitation due must lock it first; the
// caller holds the lock.
func settleCandidateEntry(
ctx context.Context,
unit outbound.UnitOfWork,
entry outbound.CandidateInvitationEntry,
now time.Time,
) (outbound.CandidateInvitationEntry, error) {
current, err := expireDueInvitation(ctx, unit, entry.Invitation, notBefore(now, entry.Invitation.UpdatedAt()))
if err != nil {
return outbound.CandidateInvitationEntry{}, err
}
entry.Invitation = current
return entry, nil
}