package operator import ( "bytes" "context" "path/filepath" "testing" "testing/fstest" "time" sharedseal "amadan.net/oficina/home/handoff/seal" rdb "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" ) func TestExistingPlanMigrationPreservesOldPendingAndOpen(t *testing.T) { for _, role := range []string{"credential", "directory"} { t.Run(role, func(t *testing.T) { ctx := context.Background() db, err := rdb.Open(filepath.Join(t.TempDir(), "old.db"), nil) if err != nil { t.Fatal(err) } defer db.Close() old, err := httpMigrations.ReadFile("http_migrations/" + role + "/migrations/0001_operator_http.sql") if err != nil { t.Fatal(err) } fs := fstest.MapFS{"migrations/0001_operator_http.sql": &fstest.MapFile{Data: old}} if _, err = migrate.Apply(ctx, db, migrate.MustFromFS(fs, "oficina_"+role+"_operator_http")); err != nil { t.Fatal(err) } now := time.Unix(2000000000, 0) for i, state := range []string{"pending", "open"} { var window any if state == "open" { window = now.Unix() + 600 } if role == "credential" { _, err = db.Writer().Exec("INSERT INTO operator_plans(plan_id,state,kind,apps,expires_at,window_expires_at) VALUES(?,?,'add-apps','docs',?,?)", token(byte(i+20)), state, now.Unix()+600, window) } else { _, err = db.Writer().Exec("INSERT INTO operator_plans(plan_id,state,kind,label,apps,expires_at,window_expires_at) VALUES(?,?,'add-apps','alpha','docs',?,?)", token(byte(i+20)), state, now.Unix()+600, window) } if err != nil { t.Fatal(err) } } if _, err = migrate.Apply(ctx, db, httpSchema(role)); err != nil { t.Fatal("upgrade", err) } sealer, _ := sharedseal.New(bytes.Repeat([]byte{6}, 32), "oficina/operator") store, _ := NewPlanStore(db.Writer(), role, sealer) pending, err := store.Pending(ctx, now) if err != nil || pending.ExistingTeam != "" || pending.Kind != "add-apps" { t.Fatal("old plan changed", err) } conn, err := db.Writer().Conn(ctx) if err != nil { t.Fatal(err) } opened, _, err := window(ctx, conn, role, now.Unix()) conn.Close() if err != nil || opened.ExistingTeam != "" || opened.State != "open" { t.Fatal("old window changed", err) } if err = store.Sweep(ctx, now.Add(600*time.Second)); err != nil || countRows(t, db.Writer(), "operator_plans") != 0 { t.Fatal("expiry", err) } }) } }