| 1 | package mail |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/carlosframework/platform/internal/release" |
| 12 | ) |
| 13 | |
| 14 | // The sweep is what finally removes email.json, a release after the |
| 15 | // migration stopped writing it. It is off by default and it never deletes a |
| 16 | // legacy record for an app that has not been migrated, because that record |
| 17 | // is still the only copy of that app's email. |
| 18 | func TestSweepLegacyRecordsOnlyRemovesMigratedApps(t *testing.T) { |
| 19 | ctx := context.Background() |
| 20 | s := release.NewDirStore(t.TempDir()) |
| 21 | now := time.Date(2026, 9, 15, 12, 0, 0, 0, time.UTC) |
| 22 | seed := func(app string, migrated bool) { |
| 23 | body, _ := json.Marshal(&Record{Schema: Schema, App: app, |
| 24 | Declared: &Declared{EnvPrefix: "P", From: "noreply@x.com", At: now, By: "o@example.test"}}) |
| 25 | if _, err := s.Put(ctx, LegacyKey("bag", app), body, ""); err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | if migrated { |
| 29 | if _, err := PutSender(ctx, s, "bag", app, &Sender{ID: SenderAppID, Scope: ScopeApp, Source: SourceDomain}, ""); err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | seed("migrated", true) |
| 35 | seed("untouched", false) |
| 36 | |
| 37 | // Off by default: the flag is the whole guard, and a console that has |
| 38 | // not been told to sweep sweeps nothing. |
| 39 | if n, err := SweepLegacyRecords(ctx, s, false); n != 0 || err != nil { |
| 40 | t.Fatalf("the sweep ran while disabled: %d %v", n, err) |
| 41 | } |
| 42 | if _, _, err := s.Get(ctx, LegacyKey("bag", "migrated")); err != nil { |
| 43 | t.Fatalf("the disabled sweep deleted something: %v", err) |
| 44 | } |
| 45 | |
| 46 | n, err := SweepLegacyRecords(ctx, s, true) |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | if n != 1 { |
| 51 | t.Fatalf("deleted %d, want 1", n) |
| 52 | } |
| 53 | if _, _, err := s.Get(ctx, LegacyKey("bag", "migrated")); !errors.Is(err, os.ErrNotExist) { |
| 54 | t.Fatalf("the migrated app's email.json survived: %v", err) |
| 55 | } |
| 56 | if _, _, err := s.Get(ctx, LegacyKey("bag", "untouched")); err != nil { |
| 57 | t.Fatalf("an unmigrated app's only record was deleted: %v", err) |
| 58 | } |
| 59 | // Running it twice is a no-op, which is what makes it safe at every start. |
| 60 | if n, err := SweepLegacyRecords(ctx, s, true); n != 0 || err != nil { |
| 61 | t.Fatalf("a second sweep = %d %v, want 0 and no error", n, err) |
| 62 | } |
| 63 | } |
| 64 | |