Files

273 lines
12 KiB
Go

package invitation
import (
"context"
"encoding/json"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
func (repository testInvitations) GetForDeadline(_ context.Context, invitationID uuid.UUID) (domain.Invitation, error) {
invitation, ok := repository.state.invitations[invitationID]
if !ok {
return domain.Invitation{}, outbound.ErrInvitationNotFound
}
return invitation, nil
}
func (repository testInvitations) Expire(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error {
current, ok := repository.state.invitations[next.ID()]
if !ok || current.Version() != expectedVersion || !current.ExpiryDue(next.UpdatedAt()) {
return outbound.ErrInvitationVersionConflict
}
repository.state.invitations[next.ID()] = next
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) CountPendingNeedInvitations(_ context.Context, organizationID, needID uuid.UUID) (int64, error) {
var count int64
for _, invitation := range repository.state.invitations {
need := invitation.Snapshot().Need
if invitation.OrganizationID() != organizationID || need == nil || need.NeedID != needID {
continue
}
if state := invitation.State(); state == domain.InvitationDelivered || state == domain.InvitationViewed || state == domain.InvitationCounter {
count++
}
}
return count, nil
}
func (repository testInvitations) LatestDeclineTime(_ context.Context, organizationID, candidateID uuid.UUID) (time.Time, bool, error) {
var latest time.Time
found := false
for _, invitation := range repository.state.invitations {
if invitation.OrganizationID() != organizationID || invitation.CandidateID() != candidateID || invitation.State() != domain.InvitationDeclined {
continue
}
if at := *invitation.Snapshot().RespondedAt; !found || at.After(latest) {
latest, found = at, true
}
}
return latest, found, nil
}
// deadlineJob returns the scheduled deadline job of an invitation, which the
// delivery stored in the transaction of the send.
func (test *harness) deadlineJob(t *testing.T, invitationID uuid.UUID) domain.ScheduledJob {
t.Helper()
job, ok := test.transactor.snapshot().jobs[ResponseDeadlineJobKind+"\x00"+invitationID.String()]
if !ok {
t.Fatalf("no deadline job for invitation %s", invitationID)
}
return job
}
// runDeadlineJob runs the handler on a claimed job in its own transaction, as
// the worker does, with the given application clock.
func (test *harness) runDeadlineJob(t *testing.T, claimed outbound.ClaimedJob, clock func() time.Time) error {
t.Helper()
handler := NewResponseDeadlineJob(clock)
return test.transactor.WithinTransaction(t.Context(), func(ctx context.Context, unit outbound.UnitOfWork) error {
return handler.Handle(ctx, unit, claimed)
})
}
// claimOf turns a stored job into the claim that the worker hands to a handler.
func claimOf(job domain.ScheduledJob) outbound.ClaimedJob {
return outbound.ClaimedJob{Kind: job.Kind(), Key: job.Key(), DueAt: job.DueAt(), Payload: job.Payload()}
}
func (test *harness) acceptCommand(candidateID, invitationID uuid.UUID, version int64, key string) AcceptCommand {
return AcceptCommand{
ActorID: candidateID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version,
TermsVersion: 1, TextVersion: "c4-2026-10-01", Fields: []domain.ContactField{domain.ContactFieldEmail},
}
}
func expiryEvents(state testState) []domain.InvitationEvent {
var events []domain.InvitationEvent
for _, event := range state.events {
if event.Kind == domain.InvitationEventExpired {
events = append(events, event)
}
}
return events
}
func TestDeliveryScheduleTheExpiryJobAtTheResponseDeadline(t *testing.T) {
test := newHarness(t)
sent, _ := test.deliveredTo(t)
job := test.deadlineJob(t, sent.ID)
if job.Kind() != ResponseDeadlineJobKind || job.Key() != sent.ID.String() || !job.DueAt().Equal(*sent.ResponseDeadlineAt) {
t.Fatalf("deadline job = %s/%s due %v, want the invitation key due at its deadline %v",
job.Kind(), job.Key(), job.DueAt(), *sent.ResponseDeadlineAt)
}
var payload map[string]string
if err := json.Unmarshal(job.Payload(), &payload); err != nil || len(payload) != 1 || payload["invitation_id"] != sent.ID.String() {
t.Fatalf("job payload = %s, want only the invitation identifier", job.Payload())
}
}
func TestCandidateReadAtTheDeadlineExpiresTheInvitationOnceWithoutAGrant(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
deadline := *sent.ResponseDeadlineAt
charges := len(test.transactor.snapshot().charged)
test.setTime(deadline.Add(-time.Microsecond))
before, err := test.service.GetMine(t.Context(), candidate, sent.ID)
if err != nil || before.State != domain.InvitationDelivered {
t.Fatalf("GetMine(one microsecond before the deadline) = %v, %v; want delivered", before.State, err)
}
test.setTime(deadline)
expired, err := test.service.GetMine(t.Context(), candidate, sent.ID)
if err != nil || expired.State != domain.InvitationExpired || expired.ExpiryReason == nil || *expired.ExpiryReason != domain.InvitationExpiryTimeout {
t.Fatalf("GetMine(at the deadline) = %v, %v; want expired by the timeout", expired.State, err)
}
if !expired.ResponseDeadlineAt.Equal(deadline) || expired.ContactGrant != nil || expired.ContactConsent != nil {
t.Fatalf("expired view has deadline %v, grant %v, and offer %v; want the deadline and no consent or grant",
expired.ResponseDeadlineAt, expired.ContactGrant, expired.ContactConsent)
}
state := test.transactor.snapshot()
if len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.charged) != charges {
t.Fatalf("expiry created %d grants and %d consents and charged %d; want no grant, no consent, and the same charges",
len(state.grants), len(state.consentRecords), len(state.charged))
}
events := expiryEvents(state)
if len(events) != 1 || events[0].ActorID != uuid.Nil || events[0].Version != expired.Version {
t.Fatalf("expiry events = %+v, want one system event of the expired version", events)
}
// Later reads show the same invitation and write nothing more.
again, err := test.service.GetMine(t.Context(), candidate, sent.ID)
if err != nil || again.State != domain.InvitationExpired || again.Version != expired.Version || len(expiryEvents(test.transactor.snapshot())) != 1 {
t.Fatalf("second GetMine = %v, %v; want the same expired invitation and no second event", again.State, err)
}
}
func TestAcceptAtTheDeadlineIsRefusedAndStoresTheExpiry(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
command := test.acceptCommand(candidate, sent.ID, sent.Version, "accept-late")
if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("AcceptMine(at the deadline) error = %v, want ErrAnswerBlocked", err)
}
state := test.transactor.snapshot()
if state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.grants) != 0 || len(state.consentRecords) != 0 {
t.Fatalf("late acceptance left state %v with %d grants and %d consents",
state.invitations[sent.ID].State(), len(state.grants), len(state.consentRecords))
}
// The refusal is stored under the key, and the replay refuses the same way.
if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("AcceptMine(replay) error = %v, want the stored ErrAnswerBlocked", err)
}
}
func TestViewAndDeclineAtTheDeadlineFindTheExpiry(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
viewed, err := test.service.ViewMine(t.Context(), candidate, sent.ID)
if err != nil || viewed.State != domain.InvitationExpired {
t.Fatalf("ViewMine(at the deadline) = %v, %v; want the expired invitation", viewed.State, err)
}
declineCommand := DeclineCommand{
ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-late", ExpectedVersion: viewed.Version,
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther},
}
if _, err := test.service.DeclineMine(t.Context(), declineCommand); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("DeclineMine(expired) error = %v, want ErrAnswerBlocked", err)
}
if declines := len(test.transactor.snapshot().declines); declines != 0 {
t.Fatalf("a late decline stored %d declines", declines)
}
}
func TestResponseDeadlineJobExpiresADueInvitationExactlyOnce(t *testing.T) {
test := newHarness(t)
sent, _ := test.deliveredTo(t)
deadline := *sent.ResponseDeadlineAt
claimed := claimOf(test.deadlineJob(t, sent.ID))
clock := deadline.Add(-time.Second)
now := func() time.Time { return clock }
if err := test.runDeadlineJob(t, claimed, now); err == nil {
t.Fatal("the deadline job completed before the deadline, want a retry")
}
if state := test.transactor.snapshot(); state.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatalf("a job before the deadline changed the invitation to %v", state.invitations[sent.ID].State())
}
clock = deadline
if err := test.runDeadlineJob(t, claimed, now); err != nil {
t.Fatalf("deadline job at the deadline error = %v", err)
}
state := test.transactor.snapshot()
if state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.grants) != 0 || len(state.charged) != 1 {
t.Fatalf("job left %v with %d grants and %d charges", state.invitations[sent.ID].State(), len(state.grants), len(state.charged))
}
if events := expiryEvents(state); len(events) != 1 {
t.Fatalf("job wrote %d expiry events, want one", len(events))
}
// A repeat, such as a retry after a crash, finds nothing left to expire.
clock = deadline.Add(time.Hour)
if err := test.runDeadlineJob(t, claimed, now); err != nil {
t.Fatalf("repeated deadline job error = %v", err)
}
if events := expiryEvents(test.transactor.snapshot()); len(events) != 1 {
t.Fatalf("a repeated job wrote %d expiry events, want still one", len(events))
}
}
func TestResponseDeadlineJobLeavesAnAnsweredInvitationAlone(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
deadline := *sent.ResponseDeadlineAt
claimed := claimOf(test.deadlineJob(t, sent.ID))
declined, err := test.service.DeclineMine(t.Context(), DeclineCommand{
ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-before-deadline", ExpectedVersion: sent.Version,
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther},
})
if err != nil {
t.Fatalf("DeclineMine() error = %v", err)
}
if err := test.runDeadlineJob(t, claimed, func() time.Time { return deadline }); err != nil {
t.Fatalf("deadline job for a declined invitation error = %v", err)
}
state := test.transactor.snapshot()
if state.invitations[sent.ID].State() != domain.InvitationDeclined || state.invitations[sent.ID].Version() != declined.Version || len(expiryEvents(state)) != 0 {
t.Fatalf("the job changed a declined invitation to %v at version %d", state.invitations[sent.ID].State(), state.invitations[sent.ID].Version())
}
}
func TestResponseDeadlineJobRefusesAPayloadThatNamesNoInvitation(t *testing.T) {
for name, payload := range map[string]json.RawMessage{
"not an object": json.RawMessage(`[1]`),
"no identifier": json.RawMessage(`{}`),
"nil identifier": json.RawMessage(`{"invitation_id":"00000000-0000-0000-0000-000000000000"}`),
} {
t.Run(name, func(t *testing.T) {
test := newHarness(t)
err := test.runDeadlineJob(t, outbound.ClaimedJob{Kind: ResponseDeadlineJobKind, Payload: payload}, time.Now)
if !errors.Is(err, inbound.ErrJobRejected) {
t.Fatalf("Handle(%s) error = %v, want ErrJobRejected", payload, err)
}
})
}
}