Files
2026-12-01 21:25:01 +01:00

2865 lines
111 KiB
Go

package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/oapi-codegen/nullable"
"github.com/phishingclub/phishingclub/cache"
"github.com/phishingclub/phishingclub/data"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/errs"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/repository"
"github.com/phishingclub/phishingclub/testdb"
"github.com/phishingclub/phishingclub/utils"
"github.com/phishingclub/phishingclub/vo"
"go.uber.org/zap/zapcore"
"gorm.io/gorm"
)
// TestUpdateLocksAnonymousOnceEnrolled checks anonymity can not be flipped when
// people are enrolled, also before the start mark is stored
func TestUpdateLocksAnonymousOnceEnrolled(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"started_at": nil})
alice := p.recipient("alice@example.com")
p.enroll(programID, alice, 0)
incoming := &model.Program{}
incoming.Name.Set(*vo.NewString64Must("renamed"))
incoming.IsAnonymous.Set(true)
err := p.svc.UpdateByID(p.ctx, authorizedSession(t), &programID, incoming)
if err == nil {
t.Fatalf("expected anonymity locked once people are enrolled")
}
if p.loadProgram(programID).IsAnonymousOn() {
t.Fatalf("anonymity must not change")
}
}
// anonCloseFixture is an anonymous program with sends over several months
type anonCloseFixture struct {
*programTest
programID uuid.UUID
loc *time.Location
pseudonyms []uuid.UUID
unsent []uuid.UUID
months []time.Time
enrolled []*database.ProgramEnrollment
}
// newAnonCloseFixture seeds 12 people sent one template per month for four
// settled months, with clicks and reports, two never sent rows with an event,
// and the department and title kept on every send
func newAnonCloseFixture(t *testing.T) *anonCloseFixture {
p := newProgramLifecycleTest(t)
loc, err := time.LoadLocation("Europe/Copenhagen")
if err != nil {
loc = time.UTC
}
programID := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"is_anonymous": true, "time_zone": loc.String()})
f := &anonCloseFixture{programTest: p, programID: programID, loc: loc}
now := time.Now().In(loc)
for i := 5; i >= 2; i-- {
f.months = append(f.months, time.Date(now.Year(), now.Month()-time.Month(i), 1, 0, 0, 0, 0, loc))
}
steps := []uuid.UUID{p.step(programID, 0, true), p.step(programID, 1, true)}
campaigns := []uuid.UUID{}
for i := range f.months {
c := p.stepCampaign(programID, steps[i%2], i/2)
p.db.Model(&database.Campaign{}).Where("id = ?", c).Update("is_anonymous", true)
campaigns = append(campaigns, c)
}
open := p.stepCampaign(programID, steps[0], 2)
p.db.Model(&database.Campaign{}).Where("id = ?", open).Update("is_anonymous", true)
visit := timelineEventID(data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
reported := timelineEventID(data.EVENT_CAMPAIGN_RECIPIENT_REPORTED)
scheduled := timelineEventID(data.EVENT_CAMPAIGN_RECIPIENT_SCHEDULED)
event := func(campaignID, pseudonym, eventID uuid.UUID, at time.Time) {
id := uuid.New()
p.create(&database.CampaignEvent{
ID: &id, CreatedAt: &at, UpdatedAt: &at,
CampaignID: &campaignID, AnonymizedID: &pseudonym, EventID: &eventID,
})
}
for i := 0; i < 12; i++ {
rid := p.recipient(uuid.NewString() + "@example.com")
e := p.enroll(programID, rid, 1)
pseudonym := uuid.New()
f.pseudonyms = append(f.pseudonyms, pseudonym)
created := f.months[0].Add(time.Duration(i) * 7 * time.Hour)
fields := map[string]any{
"anonymized_id": pseudonym, "position": 2, "created_at": created.UTC(),
}
if i == 11 {
fields["status"] = model.ProgramEnrollmentExited
fields["exited_at"] = f.months[2].Add(50 * time.Hour).UTC()
}
p.setEnrollment(e.ID, fields)
f.enrolled = append(f.enrolled, e)
for m, c := range campaigns {
sentAt := f.months[m].AddDate(0, 0, 9).Add(time.Duration(i) * time.Hour)
id := p.send(c, rid, false)
p.db.Model(&database.CampaignRecipient{}).Where("id = ?", id).Updates(map[string]any{
"sent_at": utils.RFC3339UTC(sentAt), "send_at": utils.RFC3339UTC(sentAt),
"anonymized_id": pseudonym, "department": "Sales", "position": "Lead",
})
if (i+m)%2 == 0 {
event(c, pseudonym, visit, sentAt.Add(time.Hour))
}
if i >= 6 && m%2 == 1 {
event(c, pseudonym, reported, sentAt.Add(2*time.Hour))
}
}
if i < 2 {
id := p.send(open, rid, false)
p.db.Model(&database.CampaignRecipient{}).Where("id = ?", id).Updates(map[string]any{
"send_at": utils.RFC3339UTC(now.AddDate(0, 0, 3)), "anonymized_id": pseudonym,
})
f.unsent = append(f.unsent, id)
event(open, pseudonym, scheduled, time.Now().UTC())
}
}
return f
}
// results computes the results of every time range and of every month from
// a new read of the database, without the cache. The enrollment counts of
// the tiles are left out, a close stops the active people.
func (f *anonCloseFixture) results() string {
f.t.Helper()
program := f.loadProgram(f.programID)
now := time.Now()
st, err := f.svc.loadProgramFactsStore(f.ctx, program, now)
if err != nil {
f.t.Fatalf("load facts: %v", err)
}
out := map[string]any{}
for _, key := range []string{ProgramTimeRangeAll, ProgramTimeRange12Months, ProgramTimeRange90Days, ProgramTimeRange30Days} {
in, _, err := f.svc.programResultsInputs(f.ctx, program, now, nil, nil)
if err != nil {
f.t.Fatalf("inputs: %v", err)
}
r := st.programResults(in, &programTilesPeriod{key: key, from: programTimeRangeFrom(key, now, f.loc)}, false)
r.Tiles.Recipients, r.Tiles.Completed, r.Tiles.Removed = 0, 0, 0
out[key] = map[string]any{"summary": r.Summary, "months": r.Months, "templates": r.Templates, "tiles": r.Tiles}
}
for _, m := range f.months {
to := m.AddDate(0, 1, 0)
in, _, err := f.svc.programResultsInputs(f.ctx, program, now, &m, &to)
if err != nil {
f.t.Fatalf("inputs: %v", err)
}
out[m.Format("2006-01")] = st.programResults(in, nil, false).Summary
}
b, err := json.Marshal(out)
if err != nil {
f.t.Fatalf("marshal: %v", err)
}
return string(b)
}
// checkUnlinked checks no pseudonym holds more than one month of sends, no
// old pseudonym is left, every event with a pseudonym has its send in its
// campaign, the never sent rows and their events are gone, the department
// and title are cleared and the enrollments are rounded
func (f *anonCloseFixture) checkUnlinked() {
f.t.Helper()
var sends []database.CampaignRecipient
f.db.Where("campaign_id IN (?)", f.db.Model(&database.Campaign{}).Select("id").Where("program_id = ?", f.programID)).Find(&sends)
old := map[uuid.UUID]bool{}
for _, p := range f.pseudonyms {
old[p] = true
}
monthsOf := map[uuid.UUID]map[string]bool{}
sendOf := map[[2]uuid.UUID]bool{}
for _, s := range sends {
if s.SentAt == nil {
f.t.Fatalf("a never sent row is left: %v", s.ID)
}
if s.AnonymizedID == nil || old[*s.AnonymizedID] {
f.t.Fatalf("a send keeps no pseudonym or its old one: %v", s.AnonymizedID)
}
if s.Department != "" || s.Position != "" {
f.t.Fatalf("department and title must be cleared: %q %q", s.Department, s.Position)
}
if s.RecipientID != nil {
f.t.Fatalf("a closed anonymous send keeps no person")
}
month := s.SentAt.In(f.loc).Format("2006-01")
if monthsOf[*s.AnonymizedID] == nil {
monthsOf[*s.AnonymizedID] = map[string]bool{}
}
monthsOf[*s.AnonymizedID][month] = true
sendOf[[2]uuid.UUID{*s.CampaignID, *s.AnonymizedID}] = true
}
if len(sends) != 12*len(f.months) {
f.t.Fatalf("expected %d sends, got %d", 12*len(f.months), len(sends))
}
for p, months := range monthsOf {
if len(months) != 1 {
f.t.Fatalf("pseudonym %v holds %d months", p, len(months))
}
}
// two sends per person per month would share a pseudonym, here each
// person has one send a month
if len(monthsOf) != 12*len(f.months) {
f.t.Fatalf("expected a pseudonym per person and month, got %d", len(monthsOf))
}
var events []database.CampaignEvent
f.db.Where("campaign_id IN (?)", f.db.Model(&database.Campaign{}).Select("id").Where("program_id = ?", f.programID)).Find(&events)
for _, e := range events {
if e.AnonymizedID == nil {
continue
}
if old[*e.AnonymizedID] || !sendOf[[2]uuid.UUID{*e.CampaignID, *e.AnonymizedID}] {
f.t.Fatalf("an event is not on a send of its campaign: %+v", e)
}
}
var unsentEvents int64
f.db.Model(&database.CampaignEvent{}).Where("event_id = ?", timelineEventID(data.EVENT_CAMPAIGN_RECIPIENT_SCHEDULED)).
Where("anonymized_id IN ?", f.pseudonyms).Count(&unsentEvents)
if unsentEvents != 0 {
f.t.Fatalf("the events of never sent rows must go, %d left", unsentEvents)
}
for i, e := range f.enrolled {
row := f.enrollment(e.ID)
local := row.CreatedAt.In(f.loc)
if local.Day() != 1 || local.Hour() != 0 || local.Minute() != 0 {
f.t.Fatalf("enrollment time must be the start of its month: %v", local)
}
if row.ExitedAt != nil || row.Position != 0 || row.LoopCount != 0 || row.AnonymizedID != nil {
f.t.Fatalf("enrollment keeps a link: %+v", row)
}
if i == 11 && row.Status != model.ProgramEnrollmentExited {
f.t.Fatalf("the status is kept, got %s", row.Status)
}
}
}
// TestAnonymousCloseUnlinksAndKeepsResults checks the close of an anonymous
// program gives a new pseudonym per person and month, clears the department
// and title, deletes the never sent rows, rounds the enrollments, and leaves
// every result count of every range and month as it was. Running the unlink
// again, as a close that stopped half way does, changes no count either.
func TestAnonymousCloseUnlinksAndKeepsResults(t *testing.T) {
f := newAnonCloseFixture(t)
before := f.results()
var check struct {
All struct {
Summary *ProgramSummary `json:"summary"`
} `json:"all"`
}
if err := json.Unmarshal([]byte(before), &check); err != nil || check.All.Summary.Sent == nil ||
(check.All.Summary.ClickedLink == nil && check.All.Summary.Reported == nil) {
t.Fatalf("the fixture must show counts to compare: %s", before)
}
if err := f.svc.closeWait(f.ctx, authorizedSession(t), &f.programID); err != nil {
t.Fatalf("close: %v", err)
}
f.checkUnlinked()
if after := f.results(); after != before {
t.Fatalf("results changed by the close:\nbefore %s\nafter %s", before, after)
}
// a close that stopped half way runs the unlink again
if err := f.svc.unlinkAnonymousClose(f.ctx, &f.programID, f.loc, time.Now()); err != nil {
t.Fatalf("unlink again: %v", err)
}
f.checkUnlinked()
if after := f.results(); after != before {
t.Fatalf("results changed by a second unlink:\nbefore %s\nafter %s", before, after)
}
}
// TestAnonymousCloseResumesHalfWay checks a rotation that stopped after part
// of the pseudonyms leaves counts the same once the close runs again
func TestAnonymousCloseResumesHalfWay(t *testing.T) {
f := newAnonCloseFixture(t)
before := f.results()
if err := f.svc.ProgramRepository.RotateSendPseudonyms(f.ctx, &f.programID, f.pseudonyms[:5], f.loc, time.Now()); err != nil {
t.Fatalf("partial rotate: %v", err)
}
if after := f.results(); after != before {
t.Fatalf("results changed by a partial rotation:\nbefore %s\nafter %s", before, after)
}
if err := f.svc.closeWait(f.ctx, authorizedSession(t), &f.programID); err != nil {
t.Fatalf("close: %v", err)
}
f.checkUnlinked()
if after := f.results(); after != before {
t.Fatalf("results changed after the resumed close:\nbefore %s\nafter %s", before, after)
}
}
// TestNamedCloseKeepsSends checks a program that is not anonymous keeps its
// never sent rows, pseudonyms and enrollment dates at close
func TestNamedCloseKeepsSends(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
step := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, step, 0)
alice := p.recipient("alice@example.com")
e := p.enroll(programID, alice, 1)
p.setEnrollment(e.ID, map[string]any{"position": 1})
held := p.sendAt(campaignID, alice, time.Now().Add(time.Hour), false)
if err := p.svc.closeWait(p.ctx, authorizedSession(t), &programID); err != nil {
t.Fatalf("close: %v", err)
}
if row := p.campaignRecipient(held); row.CancelledAt == nil {
t.Fatal("the never sent row of a named program is cancelled and kept")
}
if row := p.enrollment(e.ID); row.Position != 1 || row.LoopCount != 1 {
t.Fatalf("a named program keeps its enrollment: %+v", row)
}
}
// TestProgramCloseClearsAnonymousSendTimes checks the close of an anonymous
// program removes the send times and round state of its enrollments, as they
// match the send times of the rows, while a named program keeps them
func TestProgramCloseClearsAnonymousSendTimes(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
at := time.Now().UTC().Add(-48 * time.Hour).Truncate(time.Second)
fields := map[string]any{
"last_send_at": at,
"last_step_id": uuid.New(),
"round_start_at": at,
"next_due_at": at.Add(72 * time.Hour),
"completed_at": at,
}
anonymous := p.program(model.ProgramLoopComplete)
p.setProgram(anonymous, map[string]any{"is_anonymous": true})
named := p.program(model.ProgramLoopComplete)
// one person was sent to and has a pseudonym, one has a planned round only
a := p.enroll(anonymous, p.recipient("anon@example.com"), 0)
planned := p.enroll(anonymous, p.recipient("planned@example.com"), 0)
n := p.enroll(named, p.recipient("named@example.com"), 0)
p.setEnrollment(a.ID, fields)
p.setEnrollment(a.ID, map[string]any{"anonymized_id": uuid.New()})
p.setEnrollment(planned.ID, map[string]any{"round_start_at": at})
p.setEnrollment(n.ID, fields)
for _, id := range []uuid.UUID{anonymous, named} {
if err := p.svc.closeWait(p.ctx, session, &id); err != nil {
t.Fatalf("close: %v", err)
}
}
row := p.enrollment(a.ID)
if row.LastSendAt != nil || row.LastStepID != nil || row.RoundStartAt != nil ||
row.NextDueAt != nil || row.CompletedAt != nil || row.AnonymizedID != nil {
t.Fatalf("the anonymous enrollment keeps send state: %+v", row)
}
if row := p.enrollment(planned.ID); row.RoundStartAt != nil || row.NextDueAt != nil {
t.Fatalf("the enrollment without a pseudonym keeps its round: %+v", row)
}
if kept := p.enrollment(n.ID); kept.LastSendAt == nil || kept.LastStepID == nil || kept.CompletedAt == nil {
t.Fatalf("a named program keeps its send state: %+v", kept)
}
}
// TestCloseReleasesKeptLureCode checks the lure code an unlinked anonymous
// program send keeps is released when its campaign is anonymized at close,
// so the code can be given out again
func TestCloseReleasesKeptLureCode(t *testing.T) {
p := newProgramServiceTest(t)
if err := p.db.AutoMigrate(&database.RecipientGroup{}); err != nil {
t.Fatalf("migrate: %v", err)
}
_, campaignID := p.anonymousStepCampaign()
sentAt := time.Now().UTC().Add(-20 * 24 * time.Hour)
sendID, _ := p.unlinkedSend(campaignID, sentAt, "KEPTCODE12")
// a send with only a message id left is cleared too
msgOnlyID, _ := p.unlinkedSend(campaignID, sentAt, "")
p.db.Model(&database.CampaignRecipient{}).Where("id IN ?", []string{sendID.String(), msgOnlyID.String()}).
Update("message_id", gorm.Expr("id"))
if err := p.svc.CampaignService.anonymizeCampaignRecipients(p.ctx, &campaignID); err != nil {
t.Fatalf("anonymize: %v", err)
}
for _, id := range []uuid.UUID{sendID, msgOnlyID} {
var row database.CampaignRecipient
if err := p.db.Where("id = ?", id).First(&row).Error; err != nil {
t.Fatalf("load: %v", err)
}
if row.LureCode != nil || row.MessageID != nil || row.AnonymizedID == nil {
t.Fatalf("the close must release the kept lure code and message id and keep the pseudonym: %+v", row)
}
}
}
// TestCountAudienceRefusesNullGroup checks a null group entry is a
// validation error, not a crash
func TestCountAudienceRefusesNullGroup(t *testing.T) {
p := newProgramLifecycleTest(t)
if _, err := p.svc.CountAudience(p.ctx, authorizedSession(t), nil, []*uuid.UUID{nil}); !isValidationError(err) {
t.Fatalf("expected a validation error, got %v", err)
}
}
// withAuditBuffer sends the audit events of the program service to a buffer
func (p *programTest) withAuditBuffer() *bytes.Buffer {
logger, buf := bufferLogger(zapcore.InfoLevel)
p.svc.AuditLogger = logger
p.svc.CampaignService.AuditLogger = logger
return buf
}
func eventDetails(t *testing.T, ev map[string]any) map[string]any {
t.Helper()
d, _ := ev["details"].(map[string]any)
if d == nil {
t.Fatalf("event has no details: %v", ev)
}
return d
}
// TestProgramEventsCarryID checks denied and failed events of a program
// change or read name the program
func TestProgramEventsCarryID(t *testing.T) {
p := newProgramLifecycleTest(t)
buf := p.withAuditBuffer()
id := uuid.New()
other := unauthorizedSession(t)
rename := &model.Program{Name: nullable.NewNullableWithValue(*mustString64(t, "renamed"))}
_ = p.svc.UpdateByID(p.ctx, other, &id, rename)
_ = p.svc.DeleteByID(p.ctx, other, &id)
_, _ = p.svc.GetByID(p.ctx, other, &id)
_, _ = p.svc.GetResults(p.ctx, other, &id, "")
// an update of a program that does not exist fails after the check
_ = p.svc.UpdateByID(p.ctx, authorizedSession(t), &id, rename)
for _, c := range []struct{ name, result string }{
{"Program.UpdateById", "denied"},
{"Program.DeleteById", "denied"},
{"Program.GetById", "denied"},
{"Program.GetResults", "denied"},
{"Program.UpdateById", "failed"},
} {
found := false
for _, ev := range auditEventsNamed(t, buf.String(), c.name) {
if ev["result"] == c.result {
found = true
if eventDetails(t, ev)["id"] != id.String() {
t.Errorf("%s %s has no program id: %v", c.name, c.result, ev)
}
}
}
if !found {
t.Errorf("no %s %s event", c.name, c.result)
}
}
}
// TestProgramCreateUnknownCompany checks a create for a company that does not
// exist is a validation error and stores nothing
func TestProgramCreateUnknownCompany(t *testing.T) {
p := newProgramWriteTest(t)
if err := p.db.AutoMigrate(&database.Company{}); err != nil {
t.Fatalf("migrate: %v", err)
}
p.svc.CompanyRepository = &repository.Company{DB: p.db}
templateID := p.stepTemplate(p.step(p.program(model.ProgramLoopComplete), 0, true))
req := newProgramRequest(t, "unknown company", templateID, p.group("staff"))
req.CompanyID = nullable.NewNullableWithValue(uuid.New())
if _, err := p.svc.Create(p.ctx, authorizedSession(t), req); err == nil || !isValidation(err) {
t.Fatalf("expected a validation error, got %v", err)
}
var count int64
p.db.Model(&database.Program{}).Where("name = ?", "unknown company").Count(&count)
if count != 0 {
t.Fatal("no program may be stored for an unknown company")
}
}
// TestPauseStopsResume checks a pause of a paused program stops a resume that
// is under way and keeps the program paused, and that a pause of a paused
// program with no resume is refused
func TestPauseStopsResume(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"paused_at": time.Now().UTC()})
err := p.svc.Pause(p.ctx, session, &programID)
var v errs.ValidationError
if !errors.As(err, &v) || v.Err != errProgramAlreadyPaused {
t.Fatalf("expected already paused, got %v", err)
}
token := p.svc.startResume(programID)
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause during resume: %v", err)
}
if p.svc.resumeLive(programID, token) {
t.Fatal("the pause must stop the resume")
}
if err := p.svc.resumeStopped(p.ctx, &programID, token); !errors.As(err, &v) || v.Err != errProgramPausedOnResume {
t.Fatalf("expected the resume stopped by the pause, got %v", err)
}
if !p.loadProgram(programID).IsPaused() {
t.Fatal("the program must stay paused")
}
p.svc.endResume(programID, token)
}
// TestPausedProgramKeepsItsStart checks a paused program that has not
// enrolled anyone can not be made a draft or given a later start
func TestPausedProgramKeepsItsStart(t *testing.T) {
p := newProgramWriteTest(t)
programID := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"started_at": nil, "paused_at": time.Now().UTC()})
draft := true
if err := p.update(programID, &model.Program{Draft: &draft}); err == nil || !strings.Contains(err.Error(), "paused program") {
t.Fatalf("a paused program must not be made a draft, got %v", err)
}
later := &model.Program{}
later.StartAt.Set(time.Now().Add(48 * time.Hour))
if err := p.update(programID, later); err == nil || !strings.Contains(err.Error(), "paused program") {
t.Fatalf("a paused program must not be given a later start, got %v", err)
}
if p.loadProgram(programID).StartAtTime() == nil {
t.Fatal("the start must be kept")
}
}
const programDataSavingRefused = "submitted data cannot be saved on an anonymous program"
// newProgramDataSavingTest is a write test that can also create hidden
// campaigns, which read the template through the campaign service
func newProgramDataSavingTest(t *testing.T) *programTest {
t.Helper()
p := newProgramWriteTest(t)
p.svc.CampaignService.CampaignTemplateService = p.svc.CampaignTemplateService
if cache.EventIDByName[data.EVENT_CAMPAIGN_RECIPIENT_SUBMITTED_DATA] == nil {
id := uuid.New()
cache.EventIDByName[data.EVENT_CAMPAIGN_RECIPIENT_SUBMITTED_DATA] = &id
}
return p
}
// createDataSavingProgram creates a draft program through the service
func (p *programTest) createDataSavingProgram(name string, anonymous bool, save bool) uuid.UUID {
p.t.Helper()
templateID := p.stepTemplate(p.step(p.program(model.ProgramLoopComplete), 0, true))
req := newProgramRequest(p.t, name, templateID, p.group(name+" group"))
req.IsAnonymous = nullable.NewNullableWithValue(anonymous)
req.SaveSubmittedData = nullable.NewNullableWithValue(save)
id, err := p.svc.Create(p.ctx, authorizedSession(p.t), req)
if err != nil {
p.t.Fatalf("create: %v", err)
}
return *id
}
// stepCampaignOf creates the hidden campaign of the first step of a program
func (p *programTest) stepCampaignOf(programID uuid.UUID, loop int) uuid.UUID {
p.t.Helper()
program := p.loadProgram(programID)
c, err := p.svc.getOrCreateStepCampaign(p.ctx, authorizedSession(p.t), program, program.Steps[0], loop, nil)
if err != nil {
p.t.Fatalf("step campaign: %v", err)
}
return c.ID.MustGet()
}
func (p *programTest) campaignSavesData(campaignID uuid.UUID) bool {
p.t.Helper()
var row database.Campaign
if err := p.db.Where("id = ?", campaignID).First(&row).Error; err != nil {
p.t.Fatalf("load campaign: %v", err)
}
return row.SaveSubmittedData
}
// TestProgramDataSavingAnonymousRule checks submitted data can not be saved on
// an anonymous program, refused on create, when turned on for an anonymous
// program and when a program that saves data is made anonymous
func TestProgramDataSavingAnonymousRule(t *testing.T) {
p := newProgramDataSavingTest(t)
session := authorizedSession(t)
both := &model.Program{
Name: nullable.NewNullableWithValue(*mustString64(t, "both")),
IsAnonymous: nullable.NewNullableWithValue(true),
SaveSubmittedData: nullable.NewNullableWithValue(true),
}
if err := both.Validate(); err == nil || !strings.Contains(err.Error(), programDataSavingRefused) {
t.Fatalf("validate must refuse data saving on an anonymous program, got %v", err)
}
templateID := p.stepTemplate(p.step(p.program(model.ProgramLoopComplete), 0, true))
req := newProgramRequest(t, "anonymous saving", templateID, p.group("staff"))
req.IsAnonymous = nullable.NewNullableWithValue(true)
req.SaveSubmittedData = nullable.NewNullableWithValue(true)
if _, err := p.svc.Create(p.ctx, session, req); err == nil || !strings.Contains(err.Error(), programDataSavingRefused) {
t.Fatalf("create must refuse data saving on an anonymous program, got %v", err)
}
anonID := p.createDataSavingProgram("anonymous", true, false)
turnOn := &model.Program{Name: p.loadProgram(anonID).Name, SaveSubmittedData: nullable.NewNullableWithValue(true)}
if err := p.svc.UpdateByID(p.ctx, session, &anonID, turnOn); err == nil || !strings.Contains(err.Error(), programDataSavingRefused) {
t.Fatalf("turning on data saving of an anonymous program must be refused, got %v", err)
}
if p.loadProgram(anonID).SaveSubmittedDataOn() {
t.Fatal("a refused update must not store data saving")
}
savingID := p.createDataSavingProgram("saving", false, true)
makeAnon := &model.Program{Name: p.loadProgram(savingID).Name, IsAnonymous: nullable.NewNullableWithValue(true)}
if err := p.svc.UpdateByID(p.ctx, session, &savingID, makeAnon); err == nil || !strings.Contains(err.Error(), programDataSavingRefused) {
t.Fatalf("making a program that saves data anonymous must be refused, got %v", err)
}
if p.loadProgram(savingID).IsAnonymousOn() {
t.Fatal("a refused update must not make the program anonymous")
}
// both changed together in the allowed direction is fine
switchBoth := &model.Program{
Name: p.loadProgram(savingID).Name,
IsAnonymous: nullable.NewNullableWithValue(true),
SaveSubmittedData: nullable.NewNullableWithValue(false),
}
if err := p.svc.UpdateByID(p.ctx, session, &savingID, switchBoth); err != nil {
t.Fatalf("anonymous with data saving off must be allowed: %v", err)
}
}
// programGone reports whether a program and all its hidden campaigns are
// deleted
func (p *programTest) programGone(programID uuid.UUID) bool {
p.t.Helper()
var programs, campaigns int64
p.db.Model(&database.Program{}).Where("id = ?", programID).Count(&programs)
p.db.Model(&database.Campaign{}).Where("program_id = ?", programID).Count(&campaigns)
return programs == 0 && campaigns == 0
}
// waitDeletes waits for the background delete pass to end
func (p *programTest) waitDeletes() {
p.t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := p.svc.waitForDeletes(ctx); err != nil {
p.t.Fatal("the delete pass did not end")
}
}
// TestProgramDeleteOutlivesRequest checks a delete whose request ends half
// way still removes every hidden campaign and the program
func TestProgramDeleteOutlivesRequest(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.manyCampaigns(programID, 4)
ctx, cancel := context.WithCancel(p.ctx)
defer cancel()
// the request ends when the first campaign is being removed
p.probe("delete", database.CAMPAIGN_EVENT_TABLE, cancel)
if err := p.svc.DeleteByID(ctx, session, &programID); err != nil {
t.Fatalf("delete: %v", err)
}
p.waitDeletes()
if !p.programGone(programID) {
t.Fatal("expected the program and its campaigns deleted after the request ended")
}
if !lockIsFree(p.svc) || p.svc.isStoppingNow(programID) {
t.Fatal("the delete must release the lock and its claim")
}
}
// TestSchedulerFinishesHalfDelete checks the scheduler finishes a delete that
// stopped half way, waits before it tries a failed one again, audits a
// failure once and the finished delete as a success, and leaves a delete
// that a request runs now alone
func TestSchedulerFinishesHalfDelete(t *testing.T) {
p := newProgramLifecycleTest(t)
buf := p.withAuditBuffer()
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
campaigns, _ := p.manyCampaigns(programID, 3)
other := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"deleting_at": time.Now().UTC(), "paused_at": time.Now().UTC()})
// a delete a request runs now is left to it
p.svc.claimStopping(programID)
if p.svc.finishDelete(p.ctx, session, time.Now()) {
t.Fatal("a delete under way in a request must be left alone")
}
p.svc.releaseStopping(programID)
// the second campaign can not be deleted, the pass fails
p.db.Model(&database.Campaign{}).Where("id = ?", campaigns[1]).Update("name", "blocked")
if err := testdb.CreateFailTrigger(p.db, "fail_delete", "BEFORE DELETE", "campaigns", "OLD.name = 'blocked'", "delete refused"); err != nil {
t.Fatalf("create trigger: %v", err)
}
now := time.Now()
if p.svc.finishDelete(p.ctx, session, now) {
t.Fatal("expected the pass to fail")
}
if p.programGone(programID) || p.svc.isStoppingNow(programID) {
t.Fatal("a failed pass keeps the program and releases its claim")
}
if err := testdb.DropFailTrigger(p.db, "fail_delete", "campaigns"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
// a failed program waits before it is tried again
if p.svc.finishDelete(p.ctx, session, now.Add(time.Minute)) {
t.Fatal("a failed delete must wait before it is tried again")
}
if !p.svc.finishDelete(p.ctx, session, now.Add(programDeleteRetryEvery)) {
t.Fatal("expected the delete finished")
}
if !p.programGone(programID) {
t.Fatal("expected the program and its campaigns deleted")
}
if _, err := p.svc.ProgramRepository.GetByID(p.ctx, &other, nil); err != nil {
t.Fatalf("the other program must stay: %v", err)
}
if !lockIsFree(p.svc) {
t.Fatal("the pass must release the lock")
}
ev := auditEventsNamed(t, buf.String(), "Program.DeleteById")
if len(ev) != 2 || ev[0]["result"] != "failed" || ev[1]["result"] != "success" {
t.Fatalf("expected a failed and a success event, got %v", ev)
}
if d := eventDetails(t, ev[1]); d["reason"] != "delete finished" || d["id"] != programID.String() {
t.Fatalf("delete event details: %v", d)
}
if strings.Count(buf.String(), `"Program.DeleteById"`) != 2 {
t.Fatalf("expected two delete events: %s", buf.String())
}
}
// TestTickStartsDeleteFinish checks the membership pass of a tick finishes a
// delete that stopped half way, on its own goroutine
func TestTickStartsDeleteFinish(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
p.manyCampaigns(programID, 2)
p.setProgram(programID, map[string]any{"deleting_at": time.Now().UTC(), "paused_at": time.Now().UTC()})
p.svc.lastRetentionAt = time.Now()
if err := p.svc.Tick(p.ctx, authorizedSession(t)); err != nil {
t.Fatalf("tick: %v", err)
}
p.waitForCloses(t)
p.waitDeletes()
if !p.programGone(programID) {
t.Fatal("expected the tick to finish the delete")
}
}
// TestCloseReleasesLureCodeOfRowUnlinkedMeanwhile checks the anonymize of a
// close releases the lure code of a row whose person link is cleared between
// the read and the write, as the identity retention of a program does
func TestCloseReleasesLureCodeOfRowUnlinkedMeanwhile(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
alice := p.recipient("alice@example.com")
sendID := p.sendAt(campaignID, alice, time.Now().Add(-time.Hour), true)
pseudonym := uuid.New()
p.db.Model(&database.CampaignRecipient{}).Where("id = ?", sendID).
Updates(map[string]any{"lure_code": "ABCD1234", "anonymized_id": pseudonym})
// the person link is cleared right before the first write of the anonymize
p.probe("update", database.CAMPAIGN_RECIPIENT_TABLE_NAME, func() {
p.db.Model(&database.CampaignRecipient{}).Where("id = ?", sendID).Update("recipient_id", nil)
})
if err := p.svc.CampaignService.anonymizeCampaignRecipients(p.ctx, &campaignID); err != nil {
t.Fatalf("anonymize: %v", err)
}
row := p.campaignRecipient(sendID)
if row.LureCode != nil {
t.Fatalf("expected the lure code released, got %v", *row.LureCode)
}
if row.AnonymizedID == nil || *row.AnonymizedID != pseudonym {
t.Fatalf("expected the pseudonym kept, got %v", row.AnonymizedID)
}
}
// TestProgramDeleteAnswersAtOnce checks a delete request returns once the
// program is marked, while the hidden campaigns are still being removed in
// the background, and that the request audits the start and the background
// part audits the finish as the system
func TestProgramDeleteAnswersAtOnce(t *testing.T) {
p := newProgramLifecycleTest(t)
buf := p.withAuditBuffer()
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.manyCampaigns(programID, 3)
release := make(chan struct{})
reached := make(chan struct{})
// the background part waits while it removes the first campaign
p.probe("delete", database.CAMPAIGN_EVENT_TABLE, func() {
close(reached)
<-release
})
if err := p.svc.DeleteByID(p.ctx, session, &programID); err != nil {
t.Fatalf("delete: %v", err)
}
select {
case <-reached:
case <-time.After(10 * time.Second):
close(release)
t.Fatal("the background delete did not start")
}
program := p.loadProgram(programID)
if program.DeletingAt == nil || !program.IsPaused() {
close(release)
t.Fatal("the request must leave the program marked and paused")
}
if !lockIsFree(p.svc) {
close(release)
t.Fatal("the background delete must not hold the lifecycle lock")
}
// a second request while the first runs is asked to wait
if err := p.svc.DeleteByID(p.ctx, session, &programID); !isProgramBusy(err) {
close(release)
t.Fatalf("a second delete must wait for the first, got %v", err)
}
close(release)
p.waitDeletes()
if !p.programGone(programID) {
t.Fatal("expected the program and its campaigns deleted")
}
ev := auditEventsNamed(t, buf.String(), "Program.DeleteById")
if len(ev) != 3 {
t.Fatalf("expected a start, a refused second request and a finish, got %v", ev)
}
if d := eventDetails(t, ev[0]); ev[0]["result"] != "success" || d["reason"] != "delete started" || d["actor"] == "system" {
t.Fatalf("start event: %v", ev[0])
}
if d := eventDetails(t, ev[2]); ev[2]["result"] != "success" || d["reason"] != "delete finished" || d["actor"] != "system" {
t.Fatalf("finish event: %v", ev[2])
}
}
// withShortDeleteWait makes DeleteByIDAndWait look often and give up after
// wait, for the length of a test
func withShortDeleteWait(t *testing.T, wait time.Duration) {
t.Helper()
oldWait, oldPoll := programDeleteBusyWait, programDeleteBusyPoll
programDeleteBusyWait, programDeleteBusyPoll = wait, 5*time.Millisecond
t.Cleanup(func() {
programDeleteBusyWait, programDeleteBusyPoll = oldWait, oldPoll
})
}
// TestDeleteAndWaitGoneIsDone checks a program that is already gone counts as
// deleted, as when a background delete finished it first
func TestDeleteAndWaitGoneIsDone(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
gone := uuid.New()
if err := p.svc.DeleteByIDAndWait(p.ctx, session, &gone); err != nil {
t.Fatalf("a program that is gone must count as deleted: %v", err)
}
}
// TestDeleteAndWaitWaitsForRunningDelete checks a delete that finds another
// delete of the same program running waits for it, whether that one removes
// the program or stops half way
func TestDeleteAndWaitWaitsForRunningDelete(t *testing.T) {
withShortDeleteWait(t, 10*time.Second)
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
// the running delete removes the program
finished := p.program(model.ProgramLoopComplete)
p.manyCampaigns(finished, 2)
p.setProgram(finished, map[string]any{"deleting_at": time.Now().UTC(), "paused_at": time.Now().UTC()})
p.svc.claimStopping(finished)
go func() {
defer p.svc.releaseStopping(finished)
time.Sleep(50 * time.Millisecond)
_ = p.svc.deleteProgramData(p.ctx, session, &finished)
}()
if err := p.svc.DeleteByIDAndWait(p.ctx, session, &finished); err != nil {
t.Fatalf("delete after a running delete finished: %v", err)
}
if !p.programGone(finished) {
t.Fatal("expected the program gone")
}
// the running one ends without removing the program, the wait deletes it
left := p.program(model.ProgramLoopComplete)
p.manyCampaigns(left, 2)
p.svc.claimStopping(left)
go func() {
time.Sleep(50 * time.Millisecond)
p.svc.releaseStopping(left)
}()
if err := p.svc.DeleteByIDAndWait(p.ctx, session, &left); err != nil {
t.Fatalf("delete after a running one ended: %v", err)
}
if !p.programGone(left) {
t.Fatal("expected the program and its campaigns deleted")
}
if !lockIsFree(p.svc) || p.svc.isStoppingNow(left) {
t.Fatal("the delete must release the lock and its claim")
}
}
// TestDeleteAndWaitBounded checks the wait for a running delete ends after
// programDeleteBusyWait with the busy refusal
func TestDeleteAndWaitBounded(t *testing.T) {
withShortDeleteWait(t, 50*time.Millisecond)
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.svc.claimStopping(programID)
defer p.svc.releaseStopping(programID)
start := time.Now()
err := p.svc.DeleteByIDAndWait(p.ctx, session, &programID)
if !isProgramBusy(err) {
t.Fatalf("expected the busy refusal, got %v", err)
}
if time.Since(start) > 5*time.Second {
t.Fatal("the wait must be bounded")
}
if p.programGone(programID) {
t.Fatal("a busy program must not be deleted")
}
}
// TestTrainingOnlyProgramAccepted checks a program may hold only training
// templates: a create with only a training step is stored, and an update of a
// program to a step list of only training templates is stored too
func TestTrainingOnlyProgramAccepted(t *testing.T) {
p := newProgramWriteTest(t)
training := p.trainingTemplate()
req := newProgramRequest(t, "training only", training, p.group("training staff"))
id, err := p.svc.Create(p.ctx, authorizedSession(t), req)
if err != nil {
t.Fatalf("a training only program must be accepted on create: %v", err)
}
if steps := p.loadProgram(*id).Steps; len(steps) != 1 || steps[0].CampaignTemplateID.MustGet() != training {
t.Fatalf("want the one training step stored, got %d steps", len(steps))
}
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, true)
other := p.trainingTemplate()
p.updateSteps(programID, newStep(training, 0), newStep(other, 1))
steps := p.loadProgram(programID).Steps
if len(steps) != 2 {
t.Fatalf("want two training steps after the update, got %d", len(steps))
}
for _, st := range steps {
if tid := st.CampaignTemplateID.MustGet(); tid != training && tid != other {
t.Fatalf("a step kept a template that is not training: %v", tid)
}
}
}
// TestUpdateLocksAnonymousZoneOnceStarted checks the time zone of an anonymous
// program can not change once people are enrolled, as the months of its
// results are cut in that zone, while the same zone, a program that is not
// anonymous and an anonymous program without people may change it
func TestUpdateLocksAnonymousZoneOnceStarted(t *testing.T) {
p := newProgramWriteTest(t)
session := authorizedSession(t)
zone := func(name string) *model.Program {
return &model.Program{
Name: nullable.NewNullableWithValue(*mustString64(t, "program "+uuid.NewString()[:8])),
TimeZone: nullable.NewNullableWithValue(name),
}
}
anon := p.program(model.ProgramLoopComplete)
p.setProgram(anon, map[string]any{"is_anonymous": true, "time_zone": "Europe/Copenhagen"})
if err := p.svc.UpdateByID(p.ctx, session, &anon, zone("America/New_York")); err == nil || !isValidation(err) {
t.Fatalf("a zone change of a started anonymous program must be refused, got %v", err)
}
if got := p.loadProgram(anon).TimeZone.MustGet(); got != "Europe/Copenhagen" {
t.Fatalf("the zone must not change, got %s", got)
}
if err := p.svc.UpdateByID(p.ctx, session, &anon, zone("Europe/Copenhagen")); err != nil {
t.Fatalf("sending the same zone must pass: %v", err)
}
// not started, but people enrolled by a first pass that stopped
enrolled := p.program(model.ProgramLoopComplete)
p.setProgram(enrolled, map[string]any{"is_anonymous": true, "started_at": nil})
p.enroll(enrolled, p.recipient("alice@example.com"), 0)
if err := p.svc.UpdateByID(p.ctx, session, &enrolled, zone("America/New_York")); err == nil {
t.Fatal("a zone change of an anonymous program with people must be refused")
}
empty := p.program(model.ProgramLoopComplete)
p.setProgram(empty, map[string]any{"is_anonymous": true, "started_at": nil, "start_at": nil})
if err := p.svc.UpdateByID(p.ctx, session, &empty, zone("America/New_York")); err != nil {
t.Fatalf("an anonymous program without people may change its zone: %v", err)
}
open := p.program(model.ProgramLoopComplete)
if err := p.svc.UpdateByID(p.ctx, session, &open, zone("America/New_York")); err != nil {
t.Fatalf("a program that is not anonymous may change its zone: %v", err)
}
}
// manySendsAt adds n unsent sends of new people to a campaign, all planned at
// the given time
func (p *programTest) manySendsAt(campaignID uuid.UUID, n int, at time.Time) {
p.t.Helper()
now := time.Now().UTC()
rows := make([]*database.CampaignRecipient, 0, n)
for i := 0; i < n; i++ {
id, rid := uuid.New(), uuid.New()
rows = append(rows, &database.CampaignRecipient{ID: &id, CreatedAt: &now, UpdatedAt: &now, CampaignID: &campaignID, RecipientID: &rid})
}
if err := p.db.CreateInBatches(rows, 500).Error; err != nil {
p.t.Fatalf("create sends: %v", err)
}
p.db.Model(&database.CampaignRecipient{}).Where("campaign_id = ?", campaignID).Update("send_at", utils.RFC3339UTC(at))
}
// unsentIn counts the sends of a campaign that are neither sent nor cancelled
func (p *programTest) unsentIn(campaignID uuid.UUID) int {
p.t.Helper()
n := 0
for _, cr := range p.sendsIn(campaignID) {
if cr.SentAt == nil && cr.CancelledAt == nil {
n++
}
}
return n
}
// lockFreeBetweenWrites reports, once the work is done, whether another
// caller got the lifecycle lock between two writes of campaign recipients.
// At the first write a waiter asks for the lock, a later write that finds the
// waiter done saw the lock let go in between.
func (p *programTest) lockFreeBetweenWrites() func() bool {
p.t.Helper()
var started, sawFree atomic.Bool
got := make(chan struct{})
name := "test:lock_waiter"
hook := func(db *gorm.DB) {
if db.Statement.Table != database.CAMPAIGN_RECIPIENT_TABLE_NAME {
return
}
if !started.Swap(true) {
go func() {
p.svc.lifecycleMu.Lock()
close(got)
p.svc.lifecycleMu.Unlock()
}()
return
}
select {
case <-got:
sawFree.Store(true)
default:
}
}
if err := p.db.Callback().Update().Before("gorm:begin_transaction").Register(name, hook); err != nil {
p.t.Fatalf("register hook: %v", err)
}
p.t.Cleanup(func() { _ = p.db.Callback().Update().Remove(name) })
return func() bool {
if started.Load() {
select {
case <-got:
case <-time.After(5 * time.Second):
p.t.Fatal("the lock waiter did not get the lock")
}
}
return sawFree.Load()
}
}
// TestUpdateEndCancelsWithLockFree checks a new end cancels every send planned
// at or after it in chunks, with the lifecycle lock let go between them, and
// keeps the sends before it
func TestUpdateEndCancelsWithLockFree(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
end := time.Now().UTC().Add(24 * time.Hour).Truncate(time.Second)
n := repository.ProgramWriteChunk + 5
p.manySendsAt(campaignID, n, end.Add(24*time.Hour))
before := p.sendAt(campaignID, p.recipient("before@example.com"), end.Add(-time.Hour), false)
sawFree := p.lockFreeBetweenWrites()
incoming := &model.Program{}
incoming.Name.Set(*vo.NewString64Must("renamed"))
incoming.EndAt.Set(end)
if err := p.svc.UpdateByID(p.ctx, authorizedSession(t), &programID, incoming); err != nil {
t.Fatalf("update: %v", err)
}
if !sawFree() {
t.Fatal("the cancel must let the lifecycle lock go between its chunks")
}
if left := p.unsentIn(campaignID); left != 1 {
t.Fatalf("expected only the send before the end left, %d unsent", left)
}
if p.campaignRecipient(before).CancelledAt != nil {
t.Fatal("a send before the end must be kept")
}
if !lockIsFree(p.svc) {
t.Fatal("the update must release the lock")
}
}
// TestEndCancelStopsOnNewEnd checks the chunked cancel of an end stops when
// the program gets another end in between, as that edit cancels for its own
func TestEndCancelStopsOnNewEnd(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
end := time.Now().UTC().Add(24 * time.Hour).Truncate(time.Second)
p.setProgram(programID, map[string]any{"end_at": end})
n := 2 * repository.ProgramWriteChunk
p.manySendsAt(campaignID, n, end.Add(time.Hour))
// the first chunk write moves the end later
p.probe("update", database.CAMPAIGN_RECIPIENT_TABLE_NAME, func() {
p.setProgram(programID, map[string]any{"end_at": end.Add(48 * time.Hour)})
})
cancelled, done, err := p.svc.cancelSendsFromEnd(p.ctx, &programID)
if err != nil || done {
t.Fatalf("expected the rest stopped: done %v err %v", done, err)
}
if cancelled != repository.ProgramWriteChunk {
t.Fatalf("expected one chunk cancelled, got %d", cancelled)
}
}
// TestResumeCancelsPastEndWhilePaused checks a resume cancels a held send at
// or after the end before it lets the program send again
func TestResumeCancelsPastEndWhilePaused(t *testing.T) {
p := newProgramLifecycleTest(t)
programID, campaignID := p.pausedWithBacklog(3)
end := time.Now().UTC().Add(7 * 24 * time.Hour).Truncate(time.Second)
p.setProgram(programID, map[string]any{"end_at": end})
late := p.sendAt(campaignID, p.recipient("late@example.com"), end.Add(24*time.Hour), false)
if err := p.svc.resumeWait(p.ctx, authorizedSession(t), &programID); err != nil {
t.Fatalf("resume: %v", err)
}
if p.campaignRecipient(late).CancelledAt == nil {
t.Fatal("a held send after the end must be cancelled")
}
for _, cr := range p.sendsIn(campaignID) {
if cr.SentAt == nil && cr.CancelledAt == nil && cr.SendAt != nil && !cr.SendAt.Before(end) {
t.Fatalf("no send may be left at or after the end, got %v", cr.SendAt)
}
}
if p.loadProgram(programID).IsPaused() {
t.Fatal("expected the program resumed")
}
if !lockIsFree(p.svc) {
t.Fatal("the resume must release the lock")
}
}
// TestCancelUnsentFrom checks only sends not yet sent at or after the time are
// cancelled
func TestCancelUnsentFrom(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
end := time.Now().UTC().Add(48 * time.Hour)
before := p.sendAt(campaignID, p.recipient("a@example.com"), end.Add(-time.Hour), false)
at := p.sendAt(campaignID, p.recipient("b@example.com"), end, false)
after := p.sendAt(campaignID, p.recipient("c@example.com"), end.Add(time.Hour), false)
if err := p.svc.ProgramRepository.CancelUnsentFrom(p.ctx, &programID, end); err != nil {
t.Fatalf("cancel: %v", err)
}
if p.campaignRecipient(before).CancelledAt != nil {
t.Fatalf("a send before the end must be kept")
}
if p.campaignRecipient(at).CancelledAt == nil || p.campaignRecipient(after).CancelledAt == nil {
t.Fatalf("sends at or after the end must be cancelled")
}
}
// TestUpdateRefusesPastEnd checks the update path refuses a new end that has
// passed and stores nothing
func TestUpdateRefusesPastEnd(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
incoming := &model.Program{}
incoming.Name.Set(*vo.NewString64Must("renamed"))
incoming.EndAt.Set(time.Now().Add(-time.Hour))
err := p.svc.UpdateByID(p.ctx, authorizedSession(t), &programID, incoming)
if err == nil || !strings.Contains(err.Error(), "The end must be in the future") {
t.Fatalf("expected a past end refused, got %v", err)
}
if p.loadProgram(programID).EndAtTime() != nil {
t.Fatalf("the end must not be stored")
}
}
// TestUpdateRefusesClosedProgramEnd checks a closed program cannot get an end
func TestUpdateRefusesClosedProgramEnd(t *testing.T) {
p := newProgramServiceTest(t)
programID := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"closed_at": time.Now().UTC()})
incoming := &model.Program{}
incoming.Name.Set(*vo.NewString64Must("renamed"))
incoming.EndAt.Set(time.Now().Add(24 * time.Hour))
if err := p.svc.UpdateByID(p.ctx, authorizedSession(t), &programID, incoming); err == nil {
t.Fatalf("a closed program cannot be changed")
}
}
// newProgramWriteTest is a lifecycle test with the template service a create
// and an update read the templates through
func newProgramWriteTest(t *testing.T) *programTest {
t.Helper()
p := newProgramLifecycleTest(t)
p.svc.CampaignTemplateService = &CampaignTemplate{
Common: p.svc.Common,
CampaignTemplateRepository: &repository.CampaignTemplate{DB: p.db},
}
return p
}
// stepTemplate returns the template of a step
func (p *programTest) stepTemplate(stepID uuid.UUID) uuid.UUID {
p.t.Helper()
var row database.ProgramStep
if err := p.db.Where("id = ?", stepID).First(&row).Error; err != nil {
p.t.Fatalf("load step: %v", err)
}
return *row.CampaignTemplateID
}
// group stores an empty static recipient group
func (p *programTest) group(name string) uuid.UUID {
p.t.Helper()
now := time.Now().UTC()
id := uuid.New()
p.create(&database.RecipientGroup{ID: &id, CreatedAt: &now, UpdatedAt: &now, Name: name})
return id
}
// newProgramRequest is a create request with one template and one group
func newProgramRequest(t *testing.T, name string, templateID, groupID uuid.UUID) *model.Program {
t.Helper()
draft := true
return &model.Program{
Name: nullable.NewNullableWithValue(*mustString64(t, name)),
CompanyID: nullable.NewNullNullable[uuid.UUID](),
Draft: &draft,
Steps: []*model.ProgramStep{{CampaignTemplateID: nullable.NewNullableWithValue(templateID)}},
RecipientGroupIDs: nullable.NewNullableWithValue([]*uuid.UUID{&groupID}),
}
}
// TestProgramPauseResumeGuards checks a pause of a paused program and a
// resume of a program that is not paused are refused and change nothing
func TestProgramPauseResumeGuards(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
if err := p.svc.resumeWait(p.ctx, session, &programID); err == nil || !strings.Contains(err.Error(), "not paused") {
t.Fatalf("a resume of a running program must be refused, got %v", err)
}
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
pausedAt := p.loadProgram(programID).PausedAt.MustGet()
if err := p.svc.Pause(p.ctx, session, &programID); err == nil || !strings.Contains(err.Error(), "already paused") {
t.Fatalf("a second pause must be refused, got %v", err)
}
if got := p.loadProgram(programID).PausedAt.MustGet(); !got.Equal(pausedAt) {
t.Fatalf("a refused pause must keep the pause time: %v %v", got, pausedAt)
}
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("resume: %v", err)
}
if p.loadProgram(programID).IsPaused() {
t.Fatal("expected the program running again")
}
}
// TestProgramCreateUpdateAtomic checks a failed child write leaves no program
// on create and the stored program unchanged on update
func TestProgramCreateUpdateAtomic(t *testing.T) {
p := newProgramWriteTest(t)
session := authorizedSession(t)
existingID := p.program(model.ProgramLoopComplete)
templateID := p.stepTemplate(p.step(existingID, 0, true))
groupID := p.group("staff")
// the settings table is gone, so the last child write fails
if err := p.db.Migrator().DropTable(&database.ProgramWebhook{}); err != nil {
t.Fatalf("drop: %v", err)
}
req := newProgramRequest(t, "half written", templateID, groupID)
req.Webhooks = nullable.NewNullableWithValue([]*model.CampaignWebhook{})
if _, err := p.svc.Create(p.ctx, session, req); err == nil {
t.Fatal("expected the create to fail")
}
var count int64
p.db.Model(&database.Program{}).Where("name = ?", "half written").Count(&count)
if count != 0 {
t.Fatal("a program must not be left without its settings")
}
var steps int64
p.db.Model(&database.ProgramStep{}).Count(&steps)
if steps != 1 {
t.Fatalf("the steps of the failed create must be rolled back, got %d", steps)
}
before := p.loadProgram(existingID)
update := &model.Program{
Name: nullable.NewNullableWithValue(*mustString64(t, "renamed")),
Webhooks: nullable.NewNullableWithValue([]*model.CampaignWebhook{}),
}
if err := p.svc.UpdateByID(p.ctx, session, &existingID, update); err == nil {
t.Fatal("expected the update to fail")
}
after := p.loadProgram(existingID)
if after.Name.MustGet().String() != before.Name.MustGet().String() {
t.Fatalf("the program row must be rolled back, name %q", after.Name.MustGet().String())
}
}
// TestProgramNameUnique checks a create, an update and a clone refuse a name
// another program of the scope has with a validation error
func TestProgramNameUnique(t *testing.T) {
p := newProgramWriteTest(t)
session := authorizedSession(t)
firstID := p.program(model.ProgramLoopComplete)
templateID := p.stepTemplate(p.step(firstID, 0, true))
groupID := p.group("staff")
p.create(&database.ProgramRecipientGroup{ProgramID: &firstID, RecipientGroupID: &groupID})
firstName := p.loadProgram(firstID).Name.MustGet().String()
if _, err := p.svc.Create(p.ctx, session, newProgramRequest(t, firstName, templateID, groupID)); err == nil ||
!isValidation(err) {
t.Fatalf("a duplicate name on create must be a validation error, got %v", err)
}
secondID, err := p.svc.Create(p.ctx, session, newProgramRequest(t, "second", templateID, groupID))
if err != nil {
t.Fatalf("create: %v", err)
}
rename := &model.Program{Name: nullable.NewNullableWithValue(*mustString64(t, firstName))}
if err := p.svc.UpdateByID(p.ctx, session, secondID, rename); err == nil || !isValidation(err) {
t.Fatalf("a duplicate name on update must be a validation error, got %v", err)
}
// keeping its own name is no conflict
same := &model.Program{Name: nullable.NewNullableWithValue(*mustString64(t, "second"))}
if err := p.svc.UpdateByID(p.ctx, session, secondID, same); err != nil {
t.Fatalf("an update keeping the name: %v", err)
}
if _, err := p.svc.Clone(p.ctx, session, &firstID, *vo.NewString64Must("second"), nil); err == nil || !isValidation(err) {
t.Fatalf("a duplicate name on clone must be a validation error, got %v", err)
}
}
// TestProgramListAndSingleReadAgree checks a single program read carries the
// same summary fields as the list
func TestProgramListAndSingleReadAgree(t *testing.T) {
p := newProgramWriteTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, false)
p.step(programID, 1, true)
single, err := p.svc.GetByID(p.ctx, session, &programID)
if err != nil {
t.Fatalf("get: %v", err)
}
list, err := p.svc.GetAll(p.ctx, session, nil, &repository.ProgramOption{QueryArgs: &vo.QueryArgs{}})
if err != nil || len(list.Rows) != 1 {
t.Fatalf("list: %v", err)
}
row := list.Rows[0]
if single.SimulationCount != 2 || single.SimulationCount != row.SimulationCount {
t.Fatalf("simulations: single %d list %d", single.SimulationCount, row.SimulationCount)
}
if !single.NeedsAttention || single.AttentionReason != row.AttentionReason || single.Status != row.Status {
t.Fatalf("attention: single %v %q list %v %q", single.NeedsAttention, single.AttentionReason, row.NeedsAttention, row.AttentionReason)
}
}
// TestProgramProgressAtCompletion checks a person who had the last template
// is shown with every template of the loop had
func TestProgramProgressAtCompletion(t *testing.T) {
p := newProgramWriteTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
p.stepCampaign(programID, stepID, 0)
alice := p.recipient("alice@example.com")
e := p.enroll(programID, alice, 0)
p.advance(programID, e)
row := p.enrollment(e.ID)
if row.Status != model.ProgramEnrollmentCompleted || row.Position != 1 || row.LastStepID == nil {
t.Fatalf("a completed person must keep the template count: %s %d %v", row.Status, row.Position, row.LastStepID)
}
// a row stored before the count was kept shows it from the sends
p.setEnrollment(e.ID, map[string]any{"position": 0})
view, err := p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{})
if err != nil {
t.Fatalf("view: %v", err)
}
if len(view.Rows) != 1 || view.Rows[0].Position != 1 || view.StepCount != 1 {
t.Fatalf("progress: %+v", view.Rows)
}
}
// TestProgramNextSendHiddenWhenAnonymous checks the next send of an
// anonymous program is never given out, while a normal program shows it
func TestProgramNextSendHiddenWhenAnonymous(t *testing.T) {
p := newProgramLifecycleTest(t)
next := time.Now().UTC().Add(5 * time.Hour)
normal := p.program(model.ProgramLoopComplete)
anonymous := p.program(model.ProgramLoopComplete)
p.setProgram(anonymous, map[string]any{"is_anonymous": true})
for _, id := range []uuid.UUID{normal, anonymous} {
p.step(id, 0, true)
e := p.enroll(id, p.recipient(uuid.NewString()+"@example.com"), 0)
p.setEnrollment(e.ID, map[string]any{"next_due_at": next})
}
programs := []*model.Program{p.loadProgram(normal), p.loadProgram(anonymous)}
if err := p.svc.applyListSummaries(p.ctx, programs); err != nil {
t.Fatalf("summaries: %v", err)
}
if programs[0].NextSendAt == nil {
t.Fatalf("a normal program shows its next send")
}
if programs[1].NextSendAt != nil {
t.Fatalf("an anonymous program must not show its next send")
}
if programs[1].Enrolled != 1 {
t.Fatalf("the other summaries stay, got %d enrolled", programs[1].Enrolled)
}
}
// lockIsFree reports whether the lifecycle lock can be taken within a second
func lockIsFree(s *Program) bool {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := s.lifecycleMu.LockContext(ctx); err != nil {
return false
}
s.lifecycleMu.Unlock()
return true
}
// probe runs fn once, the first time a statement of the given kind runs on the
// given table, before its transaction starts. It is removed when the test ends.
func (p *programTest) probe(kind string, table string, fn func()) {
p.t.Helper()
var done atomic.Bool
name := "test:probe_" + kind
hook := func(db *gorm.DB) {
if db.Statement.Table != table || done.Load() {
return
}
done.Store(true)
fn()
}
var err error
switch kind {
case "update":
err = p.db.Callback().Update().Before("gorm:begin_transaction").Register(name, hook)
p.t.Cleanup(func() { _ = p.db.Callback().Update().Remove(name) })
case "delete":
err = p.db.Callback().Delete().Before("gorm:begin_transaction").Register(name, hook)
p.t.Cleanup(func() { _ = p.db.Callback().Delete().Remove(name) })
}
if err != nil {
p.t.Fatalf("register probe: %v", err)
}
}
// stoppingChecks runs the lifecycle calls on the program that is being closed
// or deleted and on another program, while the long part of the close or
// delete runs
type stoppingChecks struct {
ran bool
otherPause error
selfPause error
selfResume error
selfStart error
selfClose error
selfDelete error
lockWasFree bool
}
func (p *programTest) checkWhileStopping(c *stoppingChecks, self, other uuid.UUID) func() {
return func() {
session := authorizedSession(p.t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
c.ran = true
c.lockWasFree = lockIsFree(p.svc)
c.otherPause = p.svc.Pause(ctx, session, &other)
c.selfPause = p.svc.Pause(ctx, session, &self)
c.selfResume = p.svc.resumeWait(ctx, session, &self)
c.selfStart = p.svc.startWait(ctx, session, &self)
c.selfClose = p.svc.closeWait(ctx, session, &self)
c.selfDelete = p.svc.DeleteByID(ctx, session, &self)
}
}
// manyCampaigns gives a program several steps, each with a hidden campaign
// holding a send not yet sent
func (p *programTest) manyCampaigns(programID uuid.UUID, n int) ([]uuid.UUID, []uuid.UUID) {
campaigns, sends := []uuid.UUID{}, []uuid.UUID{}
alice := p.recipient(uuid.NewString() + "@example.com")
for i := 0; i < n; i++ {
stepID := p.step(programID, i, true)
campaignID := p.stepCampaign(programID, stepID, 0)
campaigns = append(campaigns, campaignID)
sends = append(sends, p.sendAt(campaignID, alice, time.Now().Add(time.Duration(i+1)*time.Hour), false))
}
return campaigns, sends
}
// TestProgramCloseReleasesLockForBulk checks the sends of a close are
// cancelled and its hidden campaigns closed after the lifecycle lock is let
// go: another program can be paused meanwhile, while the program being closed
// refuses every other change
func TestProgramCloseReleasesLockForBulk(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
other := p.program(model.ProgramLoopComplete)
campaigns, sends := p.manyCampaigns(programID, 8)
checks := &stoppingChecks{}
// the cancel of the sends is the first write after the lock is let go
p.probe("update", database.CAMPAIGN_RECIPIENT_TABLE_NAME, p.checkWhileStopping(checks, programID, other))
if err := p.svc.closeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("close: %v", err)
}
if !checks.ran {
t.Fatalf("the probe did not run during the close")
}
if !checks.lockWasFree {
t.Fatalf("the close held the lifecycle lock while closing the hidden campaigns")
}
if checks.otherPause != nil {
t.Fatalf("another program must be paused while a close runs: %v", checks.otherPause)
}
for name, err := range map[string]error{
"pause": checks.selfPause, "resume": checks.selfResume, "start": checks.selfStart,
"close": checks.selfClose, "delete": checks.selfDelete,
} {
if !isValidationError(err) {
t.Fatalf("%s of a program being closed must be refused, got %v", name, err)
}
}
if !isProgramBusy(checks.selfClose) || !isProgramBusy(checks.selfDelete) {
t.Fatalf("a second close or delete must wait for the first: %v %v", checks.selfClose, checks.selfDelete)
}
program := p.loadProgram(programID)
if !program.IsClosed() || program.IsPaused() || program.ClosingAt != nil {
t.Fatalf("expected the program closed, got %s", program.Status)
}
for _, id := range campaigns {
if p.campaignRow(id).ClosedAt == nil {
t.Fatalf("every hidden campaign must be closed")
}
}
for _, id := range sends {
if p.campaignRecipient(id).CancelledAt == nil {
t.Fatalf("every send not yet sent must be cancelled")
}
}
if !p.loadProgram(other).IsPaused() {
t.Fatalf("the other program must be paused")
}
if p.svc.isStoppingNow(programID) {
t.Fatalf("the close must release its claim")
}
}
// failCampaignClose makes the database refuse to close a campaign, so a close
// fails in its long part. The returned function removes the refusal.
func failCampaignClose(t *testing.T, db *gorm.DB) func() {
t.Helper()
if err := testdb.CreateFailTrigger(db, "fail_campaign_close", "BEFORE UPDATE OF closed_at", "campaigns", "NEW.closed_at IS NOT NULL", "close refused"); err != nil {
t.Fatalf("create trigger: %v", err)
}
return func() {
if err := testdb.DropFailTrigger(db, "fail_campaign_close", "campaigns"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
}
}
// TestProgramCloseBulkFailureRetry checks a close that fails while closing
// the hidden campaigns leaves a program that sends nothing and is marked as
// closing, that no other change is allowed, and that the next tick finishes it
func TestProgramCloseBulkFailureRetry(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
campaigns, sends := p.manyCampaigns(programID, 3)
alice := p.recipient("alice@example.com")
e := p.enroll(programID, alice, 0)
restore := failCampaignClose(t, p.db)
// the request marks the close, the background close then fails
if err := p.svc.closeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("close: %v", err)
}
program := p.loadProgram(programID)
if program.IsClosed() || program.ClosingAt == nil || program.Status != model.ProgramStatusPaused {
t.Fatalf("expected a paused program marked as closing, got %s %v", program.Status, program.ClosingAt)
}
if p.svc.isStoppingNow(programID) {
t.Fatalf("a failed close must release its claim")
}
for _, id := range sends {
if p.campaignRecipient(id).CancelledAt == nil {
t.Fatalf("the sends must be cancelled before the long part")
}
}
if row := p.enrollment(e.ID); row.Status != model.ProgramEnrollmentStopped || row.NextDueAt != nil {
t.Fatalf("the people must be stopped before the long part: %s %v", row.Status, row.NextDueAt)
}
for name, call := range map[string]func() error{
"pause": func() error { return p.svc.Pause(p.ctx, session, &programID) },
"resume": func() error { return p.svc.resumeWait(p.ctx, session, &programID) },
"start": func() error { return p.svc.startWait(p.ctx, session, &programID) },
} {
if err := call(); !isValidationError(err) {
t.Fatalf("%s of a closing program must be refused, got %v", name, err)
}
}
// a tick while it still fails keeps the program closing
p.svc.lastMembershipAt = time.Now()
p.svc.lastRetentionAt = time.Now()
if err := p.svc.Tick(p.ctx, authorizedSession(t)); err != nil {
t.Fatalf("tick: %v", err)
}
p.waitForCloses(t)
if p.loadProgram(programID).IsClosed() {
t.Fatalf("the close must not finish while it fails")
}
restore()
// the failed close waits programCloseRetryEvery, the wait is skipped here
p.svc.closeRetryAt[programID] = time.Now().Add(-time.Second)
if err := p.svc.Tick(p.ctx, authorizedSession(t)); err != nil {
t.Fatalf("tick: %v", err)
}
p.waitForCloses(t)
program = p.loadProgram(programID)
if !program.IsClosed() || program.IsPaused() || program.ClosingAt != nil {
t.Fatalf("the next tick must finish the close, got %s", program.Status)
}
if program.EndedAutomatically {
t.Fatalf("a close finished by the scheduler is not an end by date")
}
for _, id := range campaigns {
if p.campaignRow(id).ClosedAt == nil {
t.Fatalf("every hidden campaign must be closed")
}
}
// an operator close finds it closed
if err := p.svc.closeWait(p.ctx, session, &programID); !isValidationError(err) {
t.Fatalf("a closed program can not be closed again, got %v", err)
}
}
// TestProgramDeleteReleasesLockForBulk checks the hidden campaigns of a
// delete are removed after the lifecycle lock is let go, and a delete that
// fails half way refuses every change but a new delete, which finishes it
func TestProgramDeleteReleasesLockForBulk(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
other := p.program(model.ProgramLoopComplete)
campaigns, _ := p.manyCampaigns(programID, 6)
checks := &stoppingChecks{}
// a campaign delete removes its events first, outside a transaction
p.probe("delete", database.CAMPAIGN_EVENT_TABLE, p.checkWhileStopping(checks, programID, other))
// the third campaign can not be deleted, so the delete stops half way
if err := p.db.Model(&database.Campaign{}).Where("id = ?", campaigns[2]).Update("name", "blocked").Error; err != nil {
t.Fatalf("name campaign: %v", err)
}
if err := testdb.CreateFailTrigger(p.db, "fail_delete", "BEFORE DELETE", "campaigns", "OLD.name = 'blocked'", "delete refused"); err != nil {
t.Fatalf("create trigger: %v", err)
}
if err := p.svc.DeleteByID(p.ctx, session, &programID); err != nil {
t.Fatalf("delete: %v", err)
}
p.waitDeletes()
if p.programGone(programID) {
t.Fatalf("expected the delete to fail")
}
if !checks.ran || !checks.lockWasFree {
t.Fatalf("the delete held the lifecycle lock while removing the hidden campaigns: ran %v", checks.ran)
}
if checks.otherPause != nil {
t.Fatalf("another program must be paused while a delete runs: %v", checks.otherPause)
}
if !isProgramBusy(checks.selfDelete) {
t.Fatalf("a second delete must wait for the first: %v", checks.selfDelete)
}
for name, err := range map[string]error{
"pause": checks.selfPause, "resume": checks.selfResume, "start": checks.selfStart, "close": checks.selfClose,
} {
if !isValidationError(err) {
t.Fatalf("%s of a program being deleted must be refused, got %v", name, err)
}
}
program := p.loadProgram(programID)
if program.DeletingAt == nil || !program.IsPaused() {
t.Fatalf("a delete that stopped half way must leave the program paused and marked")
}
if p.campaignRow(campaigns[2]).PausedAt == nil {
t.Fatalf("the hidden campaigns left must be paused")
}
// a half deleted program is not closed by the scheduler or an operator
if err := p.svc.closeWait(p.ctx, session, &programID); !isValidationError(err) {
t.Fatalf("a close of a program being deleted must be refused, got %v", err)
}
if err := p.svc.resumeWait(p.ctx, session, &programID); !isValidationError(err) {
t.Fatalf("a resume of a program being deleted must be refused, got %v", err)
}
p.svc.lastMembershipAt = time.Now()
p.svc.lastRetentionAt = time.Now()
if err := p.svc.Tick(p.ctx, authorizedSession(t)); err != nil {
t.Fatalf("tick: %v", err)
}
p.waitForCloses(t)
if p.loadProgram(programID).IsClosed() {
t.Fatalf("the scheduler must not close a program being deleted")
}
if err := testdb.DropFailTrigger(p.db, "fail_delete", "campaigns"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
if err := p.svc.DeleteByID(p.ctx, session, &programID); err != nil {
t.Fatalf("second delete: %v", err)
}
p.waitDeletes()
if _, err := p.svc.ProgramRepository.GetByID(p.ctx, &programID, nil); !errors.Is(err, gorm.ErrRecordNotFound) {
t.Fatalf("expected the program gone, got %v", err)
}
var count int64
p.db.Model(&database.Campaign{}).Where("program_id = ?", programID).Count(&count)
if count != 0 {
t.Fatalf("every hidden campaign must be deleted, %d left", count)
}
if p.svc.isStoppingNow(programID) {
t.Fatalf("the delete must release its claim")
}
// the other program is untouched besides its pause
if _, err := p.svc.ProgramRepository.GetByID(p.ctx, &other, nil); err != nil {
t.Fatalf("the other program must stay: %v", err)
}
}
// TestProgramStartEnrollsOverChunks checks a start whose group is larger than
// one chunk enrolls every member once and marks the program started
func TestProgramStartEnrollsOverChunks(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
n := repository.ProgramWriteChunk + 5
now := time.Now().UTC()
groupID := uuid.New()
p.create(&database.RecipientGroup{ID: &groupID, CreatedAt: &now, UpdatedAt: &now, Name: "group"})
recipients := make([]*database.Recipient, 0, n)
links := make([]*database.RecipientGroupRecipient, 0, n)
for i := 0; i < n; i++ {
id := uuid.New()
email := id.String() + "@example.com"
recipients = append(recipients, &database.Recipient{ID: &id, CreatedAt: &now, UpdatedAt: &now, Email: &email})
links = append(links, &database.RecipientGroupRecipient{RecipientID: &id, RecipientGroupID: &groupID})
}
if err := p.db.CreateInBatches(recipients, 500).Error; err != nil {
t.Fatalf("recipients: %v", err)
}
if err := p.db.CreateInBatches(links, 500).Error; err != nil {
t.Fatalf("links: %v", err)
}
programID := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"start_at": nil, "started_at": nil})
p.create(&database.ProgramRecipientGroup{ProgramID: &programID, RecipientGroupID: &groupID})
p.step(programID, 0, true)
p.svc.lastMembershipAt = time.Now()
if err := p.svc.startWait(p.ctx, session, &programID); err != nil {
t.Fatalf("start: %v", err)
}
if count, err := p.svc.ProgramRepository.CountActiveEnrollments(p.ctx, &programID); err != nil || count != int64(n) {
t.Fatalf("expected %d active people, got %d %v", n, count, err)
}
if p.loadProgram(programID).StartedAt == nil {
t.Fatalf("expected the program marked started")
}
if !lockIsFree(p.svc) {
t.Fatalf("the start must release the lock")
}
}
// lockFreeNow reports whether the lifecycle lock can be taken right away
func lockFreeNow(s *Program) bool {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if err := s.lifecycleMu.LockContext(ctx); err != nil {
return false
}
s.lifecycleMu.Unlock()
return true
}
// watchWrites runs fn before every update of the given tables until the test
// ends
func (p *programTest) watchWrites(name string, tables map[string]bool, fn func(table string)) {
p.t.Helper()
if err := p.db.Callback().Update().Before("gorm:begin_transaction").Register(name, func(db *gorm.DB) {
if tables[db.Statement.Table] {
fn(db.Statement.Table)
}
}); err != nil {
p.t.Fatalf("register hook: %v", err)
}
p.t.Cleanup(func() { _ = p.db.Callback().Update().Remove(name) })
}
// TestProgramCloseCancelsWithoutLock checks the sends of a close are
// cancelled and its people stopped after the lifecycle lock is let go, while
// the hidden campaigns are already paused, so nothing queued is sent meanwhile
func TestProgramCloseCancelsWithoutLock(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
campaigns, sends := p.manyCampaigns(programID, 3)
bob := p.recipient("bob@example.com")
e := p.enroll(programID, bob, 0)
var mu sync.Mutex
seen := map[string]bool{}
lockHeld := []string{}
unpaused := false
p.watchWrites("test:close_writes", map[string]bool{
database.CAMPAIGN_RECIPIENT_TABLE_NAME: true,
database.PROGRAM_ENROLLMENT_TABLE: true,
}, func(table string) {
mu.Lock()
defer mu.Unlock()
seen[table] = true
if !lockFreeNow(p.svc) {
lockHeld = append(lockHeld, table)
}
// a campaign is closed and its pause cleared at the end of the close
for _, id := range campaigns {
if row := p.campaignRow(id); row.ClosedAt == nil && row.PausedAt == nil {
unpaused = true
}
}
})
if err := p.svc.closeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("close: %v", err)
}
if !seen[database.CAMPAIGN_RECIPIENT_TABLE_NAME] || !seen[database.PROGRAM_ENROLLMENT_TABLE] {
t.Fatalf("the close must cancel sends and stop people: %v", seen)
}
if len(lockHeld) > 0 {
t.Fatalf("the close held the lifecycle lock while writing %v", lockHeld)
}
if unpaused {
t.Fatalf("the hidden campaigns must be paused before the sends are cancelled")
}
for _, id := range sends {
if p.campaignRecipient(id).CancelledAt == nil {
t.Fatalf("every send not yet sent must be cancelled")
}
}
if row := p.enrollment(e.ID); row.Status != model.ProgramEnrollmentStopped || row.NextDueAt != nil {
t.Fatalf("expected the person stopped: %s %v", row.Status, row.NextDueAt)
}
program := p.loadProgram(programID)
if !program.IsClosed() || program.IsPaused() || program.ClosingAt != nil {
t.Fatalf("expected the program closed, got %s", program.Status)
}
for _, id := range campaigns {
row := p.campaignRow(id)
if row.ClosedAt == nil || row.PausedAt != nil {
t.Fatalf("every hidden campaign must be closed and not paused")
}
}
}
// newProgramLifecycleTest is a program service test with the tables and
// repositories a resume and a delete use as well
func newProgramLifecycleTest(t *testing.T, more ...testdb.Step) *programTest {
t.Helper()
p := newProgramServiceTest(t, append([]testdb.Step{
testdb.AutoMigrate(
&database.RecipientGroup{},
&database.RecipientGroupRecipient{},
&database.CampaignWebhook{},
&database.CampaignScript{},
&database.CampaignAllowDeny{},
&database.CampaignRecipientGroup{},
&database.MicrosoftDeviceCode{},
&database.ProgramAllowDeny{},
&database.ProgramWebhook{},
&database.CampaignStats{},
),
}, more...)...)
p.svc.RecipientGroupRepository = &repository.RecipientGroup{DB: p.db}
p.svc.CampaignService.MicrosoftDeviceCodeRepository = &repository.MicrosoftDeviceCode{DB: p.db}
return p
}
// cancelledContext returns a context that has already ended
func cancelledContext() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
}
func mustString64(t *testing.T, v string) *vo.String64 {
t.Helper()
s, err := vo.NewString64(v)
if err != nil {
t.Fatalf("string64: %v", err)
}
return s
}
func (p *programTest) campaignRow(id uuid.UUID) database.Campaign {
p.t.Helper()
var row database.Campaign
if err := p.db.Where("id = ?", id).First(&row).Error; err != nil {
p.t.Fatalf("load campaign: %v", err)
}
return row
}
// TestProgramLifecyclePauseResumeCloseDelete walks a program through pause,
// resume, close and delete through the service, the way the API calls it
func TestProgramLifecyclePauseResumeCloseDelete(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
alice := p.recipient("alice@example.com")
e := p.enroll(programID, alice, 0)
pseudonym := uuid.New()
p.setEnrollment(e.ID, map[string]any{"anonymized_id": pseudonym})
held := p.sendAt(campaignID, alice, time.Now().Add(time.Hour), false)
// a refused pause changes nothing
if err := p.svc.Pause(p.ctx, unauthorizedSession(t), &programID); !errors.Is(err, errs.ErrAuthorizationFailed) {
t.Fatalf("expected a refused pause, got %v", err)
}
if p.loadProgram(programID).IsPaused() {
t.Fatalf("a refused pause must not pause")
}
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
if p.loadProgram(programID).Status != model.ProgramStatusPaused {
t.Fatalf("expected paused")
}
if p.campaignRow(campaignID).PausedAt == nil {
t.Fatalf("the hidden campaign must be paused with the program")
}
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("resume: %v", err)
}
if p.loadProgram(programID).Status != model.ProgramStatusActive {
t.Fatalf("expected active after resume")
}
if p.campaignRow(campaignID).PausedAt != nil {
t.Fatalf("the hidden campaign must send again after resume")
}
if err := p.svc.closeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("close: %v", err)
}
program := p.loadProgram(programID)
if !program.IsClosed() || program.IsPaused() {
t.Fatalf("expected closed and not paused, got %s", program.Status)
}
if p.campaignRow(campaignID).ClosedAt == nil {
t.Fatalf("the hidden campaign must be closed")
}
if p.campaignRecipient(held).CancelledAt == nil {
t.Fatalf("a send not yet sent must be cancelled on close")
}
row := p.enrollment(e.ID)
if row.Status != model.ProgramEnrollmentStopped || row.NextDueAt != nil || row.AnonymizedID != nil {
t.Fatalf("expected the person stopped, not due and without pseudonym: %s %v %v", row.Status, row.NextDueAt, row.AnonymizedID)
}
if n, err := p.svc.ProgramRepository.CountActiveEnrollments(p.ctx, &programID); err != nil || n != 0 {
t.Fatalf("nobody may be active in a closed program: %d %v", n, err)
}
// a closed program can not be paused, resumed, started or closed again
if err := p.svc.Pause(p.ctx, session, &programID); err == nil {
t.Fatalf("a closed program can not be paused")
}
if err := p.svc.resumeWait(p.ctx, session, &programID); err == nil {
t.Fatalf("a closed program can not be resumed")
}
if err := p.svc.startWait(p.ctx, session, &programID); err == nil {
t.Fatalf("a closed program can not be started")
}
if err := p.svc.closeWait(p.ctx, session, &programID); err == nil {
t.Fatalf("a closed program can not be closed again")
}
if err := p.svc.DeleteByID(p.ctx, session, &programID); err != nil {
t.Fatalf("delete: %v", err)
}
p.waitDeletes()
if _, err := p.svc.ProgramRepository.GetByID(p.ctx, &programID, nil); !errors.Is(err, gorm.ErrRecordNotFound) {
t.Fatalf("expected the program gone, got %v", err)
}
var count int64
p.db.Model(&database.Campaign{}).Where("id = ?", campaignID).Count(&count)
if count != 0 {
t.Fatalf("the hidden campaign must be deleted with the program")
}
p.db.Model(&database.ProgramEnrollment{}).Where("program_id = ?", programID).Count(&count)
if count != 0 {
t.Fatalf("the enrollments must be deleted with the program")
}
}
// TestProgramLifecycleWaitsForContext checks the lifecycle calls give up when
// the request ends while another call holds the lock
func TestProgramLifecycleWaitsForContext(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.svc.lifecycleMu.Lock()
defer p.svc.lifecycleMu.Unlock()
calls := map[string]func() error{
"start": func() error { return p.svc.startWait(cancelledContext(), session, &programID) },
"pause": func() error { return p.svc.Pause(cancelledContext(), session, &programID) },
"resume": func() error { return p.svc.resumeWait(cancelledContext(), session, &programID) },
"close": func() error { return p.svc.closeWait(cancelledContext(), session, &programID) },
"delete": func() error { return p.svc.DeleteByID(cancelledContext(), session, &programID) },
}
for name, call := range calls {
if err := call(); err == nil {
t.Fatalf("%s must give up when the request ends", name)
}
}
if p.loadProgram(programID).Status != model.ProgramStatusActive {
t.Fatalf("nothing may change")
}
}
// TestProgramStartRefusesPassedEnd checks a draft starts now, and a program
// whose end has passed is not started
func TestProgramStartRefusesPassedEnd(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
groupID := uuid.New()
now := time.Now().UTC()
p.create(&database.RecipientGroup{ID: &groupID, CreatedAt: &now, UpdatedAt: &now, Name: "group"})
draft := func() uuid.UUID {
id := p.program(model.ProgramLoopComplete)
p.setProgram(id, map[string]any{"start_at": nil, "started_at": nil})
p.create(&database.ProgramRecipientGroup{ProgramID: &id, RecipientGroupID: &groupID})
return id
}
ended := draft()
p.setProgram(ended, map[string]any{"end_at": now.Add(-time.Minute)})
err := p.svc.startWait(p.ctx, session, &ended)
if err == nil || !strings.Contains(err.Error(), "The end has passed") {
t.Fatalf("expected a start after the end refused, got %v", err)
}
if p.loadProgram(ended).StartAtTime() != nil {
t.Fatalf("the refused start must not be stored")
}
ok := draft()
p.setProgram(ok, map[string]any{"end_at": now.Add(48 * time.Hour)})
if err := p.svc.startWait(p.ctx, session, &ok); err != nil {
t.Fatalf("start: %v", err)
}
if p.loadProgram(ok).Status != model.ProgramStatusActive {
t.Fatalf("expected the draft started")
}
}
// failEnrollmentStop makes the database refuse to move enrollments to stopped,
// so a close fails after its hidden campaigns are closed. The returned
// function removes the refusal.
func failEnrollmentStop(t *testing.T, db *gorm.DB) func() {
t.Helper()
if err := testdb.CreateFailTrigger(db, "fail_stop", "BEFORE UPDATE OF status", "program_enrollments", "NEW.status = 'stopped'", "stop refused"); err != nil {
t.Fatalf("create trigger: %v", err)
}
return func() {
if err := testdb.DropFailTrigger(db, "fail_stop", "program_enrollments"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
}
}
// TestProgramClosePartialFailureRetry checks a close that fails while it
// stops the sending leaves a paused program marked as closing that is not
// closed, and a second close finishes it
func TestProgramClosePartialFailureRetry(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
alice := p.recipient("alice@example.com")
e := p.enroll(programID, alice, 0)
restore := failEnrollmentStop(t, p.db)
// the request marks the close, the background close then fails
if err := p.svc.closeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("close: %v", err)
}
program := p.loadProgram(programID)
if program.IsClosed() {
t.Fatalf("a close that failed must not mark the program closed")
}
if program.Status != model.ProgramStatusPaused {
t.Fatalf("a close that failed must leave the program paused, got %s", program.Status)
}
if program.ClosingAt == nil {
t.Fatalf("a close that failed must leave the program marked as closing")
}
if p.campaignRow(campaignID).ClosedAt != nil {
t.Fatalf("the hidden campaigns are closed only after the sending stopped")
}
// the scheduler does not advance the half closed program
due, err := p.svc.ProgramRepository.GetDueEnrollments(p.ctx, time.Now().Add(time.Hour), 10)
if err != nil || len(due) != 0 {
t.Fatalf("a half closed program must not be due: %d %v", len(due), err)
}
restore()
if err := p.svc.closeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("second close: %v", err)
}
program = p.loadProgram(programID)
if !program.IsClosed() || program.IsPaused() || program.ClosingAt != nil {
t.Fatalf("expected the second close to finish, got %s", program.Status)
}
if p.campaignRow(campaignID).ClosedAt == nil {
t.Fatalf("the second close must close the hidden campaign")
}
if row := p.enrollment(e.ID); row.Status != model.ProgramEnrollmentStopped {
t.Fatalf("expected the person stopped, got %s", row.Status)
}
}
// TestProgramDeletePausesCampaignsFirst checks a delete that stops half way
// leaves the hidden campaigns paused, so nothing queued is sent
func TestProgramDeletePausesCampaignsFirst(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
if err := testdb.CreateFailTrigger(p.db, "fail_delete", "BEFORE DELETE", "campaigns", "", "delete refused"); err != nil {
t.Fatalf("create trigger: %v", err)
}
if err := p.svc.DeleteByID(p.ctx, session, &programID); err != nil {
t.Fatalf("delete: %v", err)
}
p.waitDeletes()
if p.programGone(programID) {
t.Fatalf("expected the delete to fail")
}
if p.campaignRow(campaignID).PausedAt == nil {
t.Fatalf("the hidden campaign must be paused before it is deleted")
}
if err := testdb.DropFailTrigger(p.db, "fail_delete", "campaigns"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
// a new request tries again at once, even within the retry wait
if err := p.svc.DeleteByID(p.ctx, session, &programID); err != nil {
t.Fatalf("second delete: %v", err)
}
p.waitDeletes()
if !p.programGone(programID) {
t.Fatalf("expected the program deleted")
}
}
// TestProgramGroupCap checks the number of groups is capped on create, update
// and the audience count
func TestProgramGroupCap(t *testing.T) {
ids := make([]*uuid.UUID, model.ProgramMaxRecipientGroups+1)
for i := range ids {
id := uuid.New()
ids[i] = &id
}
p := &model.Program{}
p.Name.Set(*mustString64(t, "capped"))
p.RecipientGroupIDs = nullable.NewNullableWithValue(ids)
if err := p.Validate(); err == nil || !strings.Contains(err.Error(), "at most") {
t.Fatalf("expected too many groups refused, got %v", err)
}
p.RecipientGroupIDs = nullable.NewNullableWithValue(ids[:model.ProgramMaxRecipientGroups])
if err := p.Validate(); err != nil {
t.Fatalf("the cap itself is allowed: %v", err)
}
s := newProgramServiceTest(t)
if _, err := s.svc.CountAudience(s.ctx, authorizedSession(t), nil, ids); err == nil || !strings.Contains(err.Error(), "at most") {
t.Fatalf("expected the audience count capped, got %v", err)
}
}
// TestProgramCloseResumesAfterCancelFailure checks a close that fails while
// it cancels the sends is finished by the next tick
func TestProgramCloseResumesAfterCancelFailure(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
campaigns, sends := p.manyCampaigns(programID, 2)
if err := testdb.CreateFailTrigger(p.db, "fail_cancel", "BEFORE UPDATE OF cancelled_at", "campaign_recipients", "", "cancel refused"); err != nil {
t.Fatalf("create trigger: %v", err)
}
// the request marks the close, the background close then fails
if err := p.svc.closeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("close: %v", err)
}
program := p.loadProgram(programID)
if program.IsClosed() || program.ClosingAt == nil || !program.IsPaused() {
t.Fatalf("expected a paused program marked as closing, got %s", program.Status)
}
for _, id := range campaigns {
if p.campaignRow(id).PausedAt == nil {
t.Fatalf("the hidden campaigns must stay paused while the close is not done")
}
}
if err := testdb.DropFailTrigger(p.db, "fail_cancel", "campaign_recipients"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
// the failed close waits programCloseRetryEvery, the wait is skipped here
p.svc.closeRetryAt[programID] = time.Now().Add(-time.Second)
p.svc.lastMembershipAt = time.Now()
p.svc.lastRetentionAt = time.Now()
if err := p.svc.Tick(p.ctx, authorizedSession(t)); err != nil {
t.Fatalf("tick: %v", err)
}
p.waitForCloses(t)
if !p.loadProgram(programID).IsClosed() {
t.Fatalf("the tick must finish the close")
}
for _, id := range sends {
if p.campaignRecipient(id).CancelledAt == nil {
t.Fatalf("every send not yet sent must be cancelled")
}
}
}
// failCampaignPauseWrite makes the database refuse to set or clear the pause
// mark of a campaign. The returned function removes the refusal.
func failCampaignPauseWrite(t *testing.T, db *gorm.DB, set bool) func() {
t.Helper()
when, message := "NEW.paused_at IS NULL", "resume refused"
if set {
when, message = "NEW.paused_at IS NOT NULL", "pause refused"
}
if err := testdb.CreateFailTrigger(db, "fail_pause_write", "BEFORE UPDATE OF paused_at", "campaigns", when, message); err != nil {
t.Fatalf("create trigger: %v", err)
}
return func() {
if err := testdb.DropFailTrigger(db, "fail_pause_write", "campaigns"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
}
}
// TestProgramPauseResumeAllOrNothing checks a pause or resume that fails on
// the hidden campaigns changes nothing, so a retry works
func TestProgramPauseResumeAllOrNothing(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
campaigns, _ := p.manyCampaigns(programID, 2)
restore := failCampaignPauseWrite(t, p.db, true)
if err := p.svc.Pause(p.ctx, session, &programID); err == nil {
t.Fatalf("expected the pause to fail")
}
if p.loadProgram(programID).IsPaused() {
t.Fatalf("a failed pause must not pause the program")
}
restore()
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("a retried pause must work: %v", err)
}
for _, id := range campaigns {
if p.campaignRow(id).PausedAt == nil {
t.Fatalf("every hidden campaign must be paused")
}
}
restore = failCampaignPauseWrite(t, p.db, false)
if err := p.svc.resumeWait(p.ctx, session, &programID); err == nil {
t.Fatalf("expected the resume to fail")
}
if !p.loadProgram(programID).IsPaused() {
t.Fatalf("a failed resume must leave the program paused")
}
for _, id := range campaigns {
if p.campaignRow(id).PausedAt == nil {
t.Fatalf("a failed resume must leave every hidden campaign paused")
}
}
restore()
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("a retried resume must work: %v", err)
}
if p.loadProgram(programID).IsPaused() {
t.Fatalf("expected the program running")
}
for _, id := range campaigns {
if p.campaignRow(id).PausedAt != nil {
t.Fatalf("every hidden campaign must send again")
}
}
}
// TestProgramPauseOnlyRunning checks a draft or scheduled program can not be
// paused, a running one can
func TestProgramPauseOnlyRunning(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
draft := p.program(model.ProgramLoopComplete)
p.setProgram(draft, map[string]any{"start_at": nil, "started_at": nil})
scheduled := p.program(model.ProgramLoopComplete)
p.setProgram(scheduled, map[string]any{"start_at": time.Now().UTC().Add(time.Hour), "started_at": nil})
for name, id := range map[string]uuid.UUID{"draft": draft, "scheduled": scheduled} {
if err := p.svc.Pause(p.ctx, session, &id); !isValidationError(err) {
t.Fatalf("a %s program must not be paused, got %v", name, err)
}
if p.loadProgram(id).IsPaused() {
t.Fatalf("a refused pause of a %s program must change nothing", name)
}
}
running := p.program(model.ProgramLoopComplete)
if err := p.svc.Pause(p.ctx, session, &running); err != nil {
t.Fatalf("a running program must be paused: %v", err)
}
}
// TestProgramStartAfterPassedStart checks a scheduled program whose start
// passed before the scheduler picked it up starts now
func TestProgramStartAfterPassedStart(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
now := time.Now().UTC()
groupID := p.group("group")
alice := p.recipient("alice@example.com")
p.addToGroup(groupID, alice)
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, true)
p.assignGroup(programID, groupID)
start := now.Add(-time.Minute)
p.setProgram(programID, map[string]any{"start_at": start, "started_at": nil})
if err := p.svc.startWait(p.ctx, session, &programID); err != nil {
t.Fatalf("a passed start must start now: %v", err)
}
program := p.loadProgram(programID)
if program.StartedAt == nil {
t.Fatalf("the program must be marked started")
}
p.enrollmentOf(programID, alice)
if err := p.svc.startWait(p.ctx, session, &programID); err == nil || !strings.Contains(err.Error(), "already started") {
t.Fatalf("a started program can not start again, got %v", err)
}
}
// TestResumeCancelsSendsLeftByPeopleWhoLeft checks a resume cancels the held
// send of a person who exited before, whose cancel did not happen, instead of
// letting it out
func TestResumeCancelsSendsLeftByPeopleWhoLeft(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
alice := p.recipient("alice@example.com")
programID, campaignID := p.membershipProgram(alice)
now := time.Now().UTC()
p.enroll(programID, alice, 0)
bob := p.recipient("bob@example.com")
eb := p.enroll(programID, bob, 0)
p.setEnrollment(eb.ID, map[string]any{"status": model.ProgramEnrollmentExited, "exited_at": now, "next_due_at": nil})
bobSend := p.sendAt(campaignID, bob, now.Add(-time.Hour), false)
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("resume: %v", err)
}
if row := p.campaignRecipient(bobSend); row.CancelledAt == nil {
t.Fatal("the held send of a person who left must be cancelled on resume")
}
}
// TestResumeStaysPausedWhenMembersCanNotBeRead checks a resume whose member
// read fails keeps the program paused and the held sends as they are
func TestResumeStaysPausedWhenMembersCanNotBeRead(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
alice := p.recipient("alice@example.com")
programID, campaignID := p.membershipProgram(alice)
p.enroll(programID, alice, 0)
at := time.Now().Add(-time.Hour).UTC().Truncate(time.Second)
sendID := p.sendAt(campaignID, alice, at, false)
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
if err := p.db.Migrator().DropTable(&database.RecipientGroupRecipient{}); err != nil {
t.Fatalf("drop: %v", err)
}
if err := p.svc.resumeWait(p.ctx, session, &programID); err == nil {
t.Fatal("expected the resume to fail")
}
if !p.loadProgram(programID).IsPaused() {
t.Fatal("the program must stay paused")
}
if row := p.campaignRecipient(sendID); row.SendAt == nil || !row.SendAt.Equal(at) || row.CancelledAt != nil {
t.Fatalf("the held send must be left as it was, got %v %v", row.SendAt, row.CancelledAt)
}
}
// TestPauseAndStartStoreUTC checks the pause and the start mark are written in
// UTC like the other program times
func TestPauseAndStartStoreUTC(t *testing.T) {
// a server zone that is not UTC
local := time.Local
time.Local = time.FixedZone("server", 2*60*60)
defer func() { time.Local = local }()
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
alice := p.recipient("alice@example.com")
programID, _ := p.membershipProgram(alice)
p.setProgram(programID, map[string]any{"started_at": nil})
if err := p.svc.resolveListedProgram(p.ctx, p.listedProgram(programID)); err != nil {
t.Fatalf("membership pass: %v", err)
}
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
var row struct {
StartedAt string
PausedAt string
}
p.db.Model(&database.Program{}).Select("started_at", "paused_at").Where("id = ?", programID).Scan(&row)
for name, v := range map[string]string{"started_at": row.StartedAt, "paused_at": row.PausedAt} {
if testdb.IsPostgres() {
// postgres stores an instant without its zone and reads it back
// in the zone of the process, so only its presence is checked
if v == "" {
t.Fatalf("%s must be set", name)
}
continue
}
if v == "" || !(len(v) > 6 && (v[len(v)-6:] == "+00:00" || v[len(v)-1:] == "Z")) {
t.Fatalf("%s must be stored in UTC, got %q", name, v)
}
}
}
// TestResumeCancelsHeldSendOfCompletedLeaver checks a completed person whose
// last send is held by the pause and who leaves the groups during it gets
// nothing on resume
func TestResumeCancelsHeldSendOfCompletedLeaver(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
alice := p.recipient("alice@example.com")
programID, campaignID := p.membershipProgram(alice)
now := time.Now().UTC()
p.enroll(programID, alice, 0)
bob := p.recipient("bob@example.com")
eb := p.enroll(programID, bob, 0)
p.setEnrollment(eb.ID, map[string]any{"status": model.ProgramEnrollmentCompleted, "next_due_at": nil})
bobSend := p.sendAt(campaignID, bob, now.Add(-time.Hour), false)
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("resume: %v", err)
}
if row := p.campaignRecipient(bobSend); row.CancelledAt == nil {
t.Fatal("the held last send of a completed person who left must be cancelled on resume")
}
}
// pausedWithBacklog makes a paused program whose group holds n people, each
// with a held send whose time passed during the pause and a round that came
// due during it
func (p *programTest) pausedWithBacklog(n int) (uuid.UUID, uuid.UUID) {
p.t.Helper()
now := time.Now().UTC()
past := now.Add(-48 * time.Hour)
programID := p.program(model.ProgramLoopComplete)
p.setProgram(programID, map[string]any{"paused_at": now.Add(-72 * time.Hour)})
stepID := p.step(programID, 0, true)
p.step(programID, 1, true)
campaignID := p.stepCampaign(programID, stepID, 0)
p.db.Model(&database.Campaign{}).Where("id = ?", campaignID).Update("paused_at", utils.RFC3339UTC(now))
groupID := uuid.New()
p.create(&database.RecipientGroup{ID: &groupID, CreatedAt: &now, UpdatedAt: &now, Name: "group " + groupID.String()})
p.create(&database.ProgramRecipientGroup{ProgramID: &programID, RecipientGroupID: &groupID})
recipients := make([]*database.Recipient, 0, n)
links := make([]*database.RecipientGroupRecipient, 0, n)
enrollments := make([]*database.ProgramEnrollment, 0, n)
sends := make([]*database.CampaignRecipient, 0, n)
for i := 0; i < n; i++ {
id, eid, sid := uuid.New(), uuid.New(), uuid.New()
email := id.String() + "@example.com"
recipients = append(recipients, &database.Recipient{ID: &id, CreatedAt: &now, UpdatedAt: &now, Email: &email})
links = append(links, &database.RecipientGroupRecipient{RecipientID: &id, RecipientGroupID: &groupID})
enrollments = append(enrollments, &database.ProgramEnrollment{
ID: &eid, CreatedAt: &now, UpdatedAt: &now, ProgramID: &programID, RecipientID: &id,
RoundStartAt: &past, NextDueAt: &past, Status: model.ProgramEnrollmentActive,
})
sends = append(sends, &database.CampaignRecipient{ID: &sid, CreatedAt: &now, UpdatedAt: &now, CampaignID: &campaignID, RecipientID: &id})
}
for _, rows := range []any{recipients, links, enrollments, sends} {
if err := p.db.CreateInBatches(rows, 500).Error; err != nil {
p.t.Fatalf("create: %v", err)
}
}
// stored as RFC3339 text, the same as the campaign send path
p.db.Model(&database.CampaignRecipient{}).Where("campaign_id = ?", campaignID).Update("send_at", utils.RFC3339UTC(past))
return programID, campaignID
}
// heldBefore counts the held sends of a campaign planned before t
func (p *programTest) heldBefore(campaignID uuid.UUID, t time.Time) int {
p.t.Helper()
n := 0
for _, cr := range p.sendsIn(campaignID) {
if cr.SentAt == nil && cr.CancelledAt == nil && cr.SendAt != nil && cr.SendAt.Before(t) {
n++
}
}
return n
}
// dueBefore counts the active people of a program due before t
func (p *programTest) dueBefore(programID uuid.UUID, t time.Time) int64 {
p.t.Helper()
var n int64
p.db.Model(&database.ProgramEnrollment{}).
Where("program_id = ? AND status = ? AND next_due_at < ?", programID, model.ProgramEnrollmentActive, t).
Count(&n)
return n
}
// TestProgramResumeOverChunks checks a resume with more held sends and due
// people than one chunk plans them all again, clears the pause on the program
// and its campaigns and lets the lock go
func TestProgramResumeOverChunks(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
n := repository.ProgramWriteChunk + 5
programID, campaignID := p.pausedWithBacklog(n)
before := time.Now().Add(-time.Second)
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("resume: %v", err)
}
if left := p.heldBefore(campaignID, before); left != 0 {
t.Fatalf("expected every held send planned again, %d left in the past", left)
}
if left := p.dueBefore(programID, before); left != 0 {
t.Fatalf("expected every due person planned again, %d left in the past", left)
}
if p.loadProgram(programID).IsPaused() {
t.Fatal("expected the program resumed")
}
if p.campaignRow(campaignID).PausedAt != nil {
t.Fatal("expected the campaign resumed")
}
if !lockIsFree(p.svc) {
t.Fatal("the resume must release the lock")
}
}
// TestProgramResumeStopsWhenClosed checks a close that begins while a resume
// writes its chunks stops the rest, and the program and its campaigns stay
// paused so no held send goes out on its old time
func TestProgramResumeStopsWhenClosed(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
n := repository.ProgramWriteChunk + 5
programID, campaignID := p.pausedWithBacklog(n)
// the first held send write marks the program as being closed
p.probe("update", database.CAMPAIGN_RECIPIENT_TABLE_NAME, func() {
p.setProgram(programID, map[string]any{"closing_at": time.Now().UTC()})
})
before := time.Now().Add(-time.Second)
// a close that ends a resume is not a failure of the resume
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("a resume a close ended must not fail, got %v", err)
}
if left := p.heldBefore(campaignID, before); left != n-repository.ProgramWriteChunk {
t.Fatalf("expected only the first chunk moved, %d left in the past", left)
}
if left := p.dueBefore(programID, before); left != int64(n) {
t.Fatalf("expected no person planned again, %d left in the past", left)
}
if !p.loadProgram(programID).IsPaused() || p.campaignRow(campaignID).PausedAt == nil {
t.Fatal("expected the program and its campaign still paused")
}
if !lockIsFree(p.svc) {
t.Fatal("the resume must release the lock")
}
}
// TestProgramResumeJoinersOutsideLock checks a resume with many people who
// joined the groups during the pause writes them in chunks, each under the
// lock for its own write only, so another writer gets the lock between two
// chunks, and every joiner is enrolled once
func TestProgramResumeJoinersOutsideLock(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID, _ := p.pausedWithBacklog(5)
var link database.ProgramRecipientGroup
if err := p.db.Where("program_id = ?", programID).First(&link).Error; err != nil {
t.Fatalf("group link: %v", err)
}
joiners := 2*repository.ProgramWriteChunk + 5
now := time.Now().UTC()
recipients := make([]*database.Recipient, 0, joiners)
links := make([]*database.RecipientGroupRecipient, 0, joiners)
for i := 0; i < joiners; i++ {
id := uuid.New()
email := id.String() + "@example.com"
recipients = append(recipients, &database.Recipient{ID: &id, CreatedAt: &now, UpdatedAt: &now, Email: &email})
links = append(links, &database.RecipientGroupRecipient{RecipientID: &id, RecipientGroupID: link.RecipientGroupID})
}
for _, rows := range []any{recipients, links} {
if err := p.db.CreateInBatches(rows, 500).Error; err != nil {
t.Fatalf("create: %v", err)
}
}
// on the first enrollment insert another writer waits for the lock. It
// gets the lock when the first chunk lets it go, before the next chunk
var seen int64 = -1
contender := make(chan struct{})
var started atomic.Bool
if err := p.db.Callback().Create().Before("gorm:begin_transaction").Register("test:contend", func(db *gorm.DB) {
if db.Statement.Table != database.PROGRAM_ENROLLMENT_TABLE || started.Swap(true) {
return
}
go func() {
defer close(contender)
_ = p.svc.withLifecycleLock(context.Background(), func() error {
p.db.Model(&database.ProgramEnrollment{}).Where("program_id = ?", programID).Count(&seen)
return nil
})
}()
time.Sleep(50 * time.Millisecond)
}); err != nil {
t.Fatalf("register hook: %v", err)
}
t.Cleanup(func() { _ = p.db.Callback().Create().Remove("test:contend") })
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("resume: %v", err)
}
<-contender
total := int64(5 + joiners)
if seen <= 5 || seen >= total {
t.Fatalf("expected the lock let go between the joiner chunks, the other writer saw %d of %d people", seen, total)
}
var count int64
p.db.Model(&database.ProgramEnrollment{}).Where("program_id = ? AND status = ?", programID, model.ProgramEnrollmentActive).Count(&count)
if count != total {
t.Fatalf("expected %d active people, got %d", total, count)
}
if p.loadProgram(programID).IsPaused() {
t.Fatal("expected the program resumed")
}
if !lockIsFree(p.svc) {
t.Fatal("the resume must release the lock")
}
}
// TestResumeStopsWhenEditedBetweenChunks checks an edit stored while a resume
// plans its chunks stops the resume, so the edit is not overwritten and the
// program stays paused
func TestResumeStopsWhenEditedBetweenChunks(t *testing.T) {
p := newProgramLifecycleTest(t)
programID, _ := p.pausedWithBacklog(repository.ProgramWriteChunk + 5)
program := p.loadProgram(programID)
stillPaused := func(pr *model.Program) bool {
return checkResumable(pr) == nil && sameTime(pr.UpdatedAt, program.UpdatedAt)
}
chunks := 0
done, err := p.svc.writeInChunks(p.ctx, &programID, 3*repository.ProgramWriteChunk, stillPaused, func(start, end int) error {
chunks++
// an edit lands between the chunks
p.setProgram(programID, map[string]any{"updated_at": utils.NowRFC3339UTC(), "name": "edited"})
return nil
})
if err != nil || done || chunks != 1 {
t.Fatalf("expected the rest skipped after an edit: done %v chunks %d err %v", done, chunks, err)
}
}
// TestResumeCatchUpKeepsCompleted checks the resume catch up writes only
// people who are still active
func TestResumeCatchUpKeepsCompleted(t *testing.T) {
p := newProgramLifecycleTest(t)
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, true)
e := p.enroll(programID, p.recipient("alice@example.com"), 0)
past := time.Now().Add(-time.Hour).UTC()
p.setEnrollment(e.ID, map[string]any{"next_due_at": past})
plans, err := p.svc.resumeCatchUpPlans(p.ctx, p.loadProgram(programID), time.Now())
if err != nil || len(plans) != 1 {
t.Fatalf("expected one catch up plan, got %d %v", len(plans), err)
}
// the person completes before the plan is written
p.setEnrollment(e.ID, map[string]any{"status": model.ProgramEnrollmentCompleted, "next_due_at": nil})
if err := p.svc.ProgramRepository.PlanEnrollments(p.ctx, plans, nil, model.ProgramEnrollmentActive); err != nil {
t.Fatalf("plan: %v", err)
}
if row := p.enrollment(e.ID); row.NextDueAt != nil || row.Status != model.ProgramEnrollmentCompleted {
t.Fatalf("a completed person must keep their plan, got %s %v", row.Status, row.NextDueAt)
}
}
// TestTemplateWarningsNameSendingProfile checks that the warning for a template
// that can not be sent names the SMTP configuration and API sender too
func TestTemplateWarningsNameSendingProfile(t *testing.T) {
p := newProgramServiceTest(t)
p.svc.CampaignTemplateService = &CampaignTemplate{
Common: p.svc.Common,
CampaignTemplateRepository: &repository.CampaignTemplate{DB: p.db},
}
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, false)
p.step(programID, 1, true)
warnings := p.svc.templateWarnings(p.ctx, authorizedSession(t), p.loadProgram(programID))
if len(warnings) != 1 {
t.Fatalf("want 1 warning, got %d: %v", len(warnings), warnings)
}
if !strings.Contains(warnings[0], "missing a domain, email, page, or an SMTP configuration or API sender") {
t.Fatalf("warning does not name the sending profile: %q", warnings[0])
}
}
// TestProgramCloseAnswersBeforeTheWork checks a close request marks the
// program as closing and stops all sending, and the background close
// finishes it
func TestProgramCloseAnswersBeforeTheWork(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
stepID := p.step(programID, 0, true)
campaignID := p.stepCampaign(programID, stepID, 0)
alice := p.recipient("alice@example.com")
p.enroll(programID, alice, 0)
held := p.sendAt(campaignID, alice, time.Now().Add(time.Hour), false)
if err := p.svc.Close(p.ctx, session, &programID); err != nil {
t.Fatalf("close: %v", err)
}
program := p.loadProgram(programID)
if program.ClosingAt == nil && !program.IsClosed() {
t.Fatalf("the request must mark the close")
}
if !program.IsPaused() && !program.IsClosed() {
t.Fatalf("the request must stop all sending")
}
mustSettle(t, p.svc)
program = p.loadProgram(programID)
if !program.IsClosed() || program.ClosingAt != nil {
t.Fatalf("the background close must finish, got %s", program.Status)
}
if p.campaignRecipient(held).CancelledAt == nil {
t.Fatalf("the send not yet sent must be cancelled")
}
if p.svc.isStoppingNow(programID) {
t.Fatalf("the close must release its claim")
}
}
// TestProgramResumeFailureIsShown checks a resume that fails in the
// background leaves the program paused and shows the failure, and that a new
// resume clears it
func TestProgramResumeFailureIsShown(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, true)
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
if err := testdb.CreateFailTrigger(p.db, "fail_resume", "BEFORE UPDATE OF paused_at", "programs", "NEW.paused_at IS NULL", "resume refused"); err != nil {
t.Fatalf("create trigger: %v", err)
}
if err := p.svc.Resume(p.ctx, session, &programID); err != nil {
t.Fatalf("the request must answer before the work: %v", err)
}
mustSettle(t, p.svc)
program := p.loadProgram(programID)
if !program.IsPaused() {
t.Fatalf("a failed resume must leave the program paused")
}
p.svc.applyRunState(program)
if program.Resuming {
t.Fatalf("the resume has ended")
}
if program.ActionFailure == nil || program.ActionFailure.Action != programActionResume || program.ActionFailure.Reason == "" {
t.Fatalf("the failure must be shown, got %+v", program.ActionFailure)
}
if err := testdb.DropFailTrigger(p.db, "fail_resume", "programs"); err != nil {
t.Fatalf("drop trigger: %v", err)
}
if err := p.svc.resumeWait(p.ctx, session, &programID); err != nil {
t.Fatalf("second resume: %v", err)
}
program = p.loadProgram(programID)
if program.IsPaused() {
t.Fatalf("the second resume must clear the pause")
}
p.svc.applyRunState(program)
if program.ActionFailure != nil {
t.Fatalf("a new resume must clear the failure")
}
}
// TestProgramResumeRefusedWhileResuming checks a second resume of a program
// that is being resumed is refused, and a pause stops the resume without a
// failure
func TestProgramResumeRefusedWhileResuming(t *testing.T) {
p := newProgramLifecycleTest(t)
session := authorizedSession(t)
programID := p.program(model.ProgramLoopComplete)
p.step(programID, 0, true)
if err := p.svc.Pause(p.ctx, session, &programID); err != nil {
t.Fatalf("pause: %v", err)
}
token := p.svc.startResume(programID)
var v errs.ValidationError
if err := p.svc.Resume(p.ctx, session, &programID); !errors.As(err, &v) || v.Err != errProgramResuming {
t.Fatalf("expected a refused resume, got %v", err)
}
program := p.loadProgram(programID)
p.svc.applyRunState(program)
if !program.Resuming {
t.Fatalf("the read must show the resume")
}
p.svc.endResume(programID, token)
// a resume stopped by a pause is not a failure
p.svc.finishAction(programID, programActionResume, session, "Program.Resume",
errs.NewValidationError(errProgramPausedOnResume), false)
if p.svc.lastActionErr(programID) != nil {
t.Fatalf("a resume stopped by a pause is not a failure")
}
}