package calendartest import ( "context" "errors" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "strings" "testing" "time" calendar "amadan.net/oficina/calendar/internal/calendar" "amadan.net/rastrillo/rastrillo/carlos" ) func TestPersistedWorkRegistersAtBootBeforeAnyRequest(t *testing.T) { control := controlForTest(t) dir := t.TempDir() app := calendar.NewForTest(t, dir) due := time.Now().Add(-time.Minute).Unix() if _, err := app.DBForTest().Exec(`INSERT INTO reminder_queues (reminder_id, occurrence_key, due_at, attempts, late_by_sec) VALUES (1, 'boot', ?, 0, 0)`, due); err != nil { t.Fatal(err) } if err := app.Close(); err != nil { t.Fatal(err) } app = calendar.NewForTest(t, dir) at, _ := control.snapshot() if at.Unix() < due || at.After(time.Now()) || at.IsZero() { t.Fatalf("boot did not register persisted work: got %v, want %d", at, due) } if body, _ := app.LastMailForTest(); body != "" { t.Fatal("startup delivered mail outside a held request") } } func TestScheduledHTTPDeliversWithoutAVisitorAndRearmsRecurrence(t *testing.T) { control := controlForTest(t) app, session := signedIn(t, "someone@example.com") start := time.Now().UTC().Add(2 * time.Minute) createEvent(t, app.Handler(), session, url.Values{ "title": {"Scheduled standup"}, "start": {start.Format("2006-01-02T15:04")}, "end": {start.Add(15 * time.Minute).Format("2006-01-02T15:04")}, "kind": {"meeting"}, "status": {"confirmed"}, "repeat": {"daily"}, }) expected := app.StoreForTest().NextDueAt(context.Background()) control.waitArmed(t) before, _ := control.snapshot() if before.Before(expected) || before.After(time.Now()) { t.Fatalf("event POST failed to arm its overdue reminder: %v, expected %v", before, expected) } req := httptest.NewRequest(http.MethodPost, "/jobs/reminders", nil) req.Header.Set("Authorization", "Bearer test-token") req.Header.Set("X-Carlos-Schedule", "calendar-next-due") rec := httptest.NewRecorder() app.Handler().ServeHTTP(rec, req) if rec.Code != http.StatusNoContent { t.Fatalf("scheduled request = %d: %s", rec.Code, rec.Body.String()) } body, _ := app.LastMailForTest() if !strings.Contains(body, "Scheduled standup") { t.Fatal("scheduled HTTP did not deliver the reminder") } next, _ := control.snapshot() expected = app.StoreForTest().NextDueAt(context.Background()) if !next.Equal(expected) || !next.After(time.Now()) { t.Fatalf("next recurrence not armed before completion: %v, expected %v", next, expected) } } func TestPublicBookingPostRegistersItsHoldAndMail(t *testing.T) { control := controlForTest(t) app, _, path, _ := publishedPage(t) _, starts := futureDaySlots(t, app.Handler(), path) strangerPost(t, app.Handler(), path, holdForm(starts[0], "A", "a@example.com")) expected := app.StoreForTest().NextDueAt(context.Background()) control.waitArmed(t) at, _ := control.snapshot() if expected.IsZero() || !at.Equal(expected) { t.Fatalf("public booking did not register scheduled work: got %v, expected %v", at, expected) } } func TestTickRegistrationFailureReturnsRetryAndRecoversWithoutAVisitor(t *testing.T) { control := controlForTest(t) app := calendar.NewForTest(t, t.TempDir()) due := time.Now().Add(time.Hour).Unix() if _, err := app.DBForTest().Exec(`INSERT INTO reminder_queues (reminder_id, occurrence_key, due_at, attempts, late_by_sec) VALUES (1, 'retry', ?, 0, 0)`, due); err != nil { t.Fatal(err) } control.mu.Lock() control.fail = true control.mu.Unlock() rec := tick(t, app.Handler()) if rec.Code != http.StatusInternalServerError || strings.TrimSpace(rec.Body.String()) != "retry" { t.Fatalf("registration failure acknowledged: %d %s", rec.Code, rec.Body.String()) } control.mu.Lock() control.fail = false control.mu.Unlock() deadline := time.After(4 * time.Second) for { at, _ := control.snapshot() if at.Unix() == due { break } select { case <-deadline: t.Fatal("registration did not recover without a visitor") case <-time.After(10 * time.Millisecond): } } } func TestDatabaseFailureCannotCancelTheTimer(t *testing.T) { control := controlForTest(t) app := calendar.NewForTest(t, t.TempDir()) due := time.Now().Add(time.Hour).Unix() if _, err := app.DBForTest().Exec(`INSERT INTO reminder_queues (reminder_id, occurrence_key, due_at, attempts, late_by_sec) VALUES (1, 'failure', ?, 0, 0)`, due); err != nil { t.Fatal(err) } if got := app.NextDue(); got.Unix() != due { t.Fatal(got) } if _, err := app.DBForTest().Exec(`DROP TABLE booking_mails`); err != nil { t.Fatal(err) } got := app.NextDue() at, _ := control.snapshot() if got.IsZero() || got.After(time.Now()) || at.Unix() != due { t.Fatalf("failed due query erased wake: probe %v, timer %v", got, at) } } func TestProductionRefusesMissingControlSocket(t *testing.T) { t.Setenv("CARLOS_CONTROL_SOCKET", "") _, err := calendar.New(calendar.Config{DBPath: filepath.Join(t.TempDir(), "calendar.db"), Env: "production", Origin: calendar.TestOrigin, InstanceKey: "01234567890123456789012345678901", DEK: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", AllowedAddresses: "person@example.com", Mailer: &pickyMailer{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) if !errors.Is(err, carlos.ErrNotOnCarlos) { t.Fatalf("production startup error = %v, want missing platform scheduling", err) } } func TestScheduledHTTPRearmsAFullSweepBacklog(t *testing.T) { control := controlForTest(t) app := calendar.NewForTest(t, t.TempDir()) due := time.Now().Add(-time.Minute).Unix() _, err := app.DBForTest().Exec(`WITH RECURSIVE rows(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM rows WHERE n<501) INSERT INTO bookings (page_id,event_id,token_hash,state,booker_address_fp,booker_zone,hold_expires_at,cancelled_by,ip_fp,ip_forget_at,reschedules,created_at,updated_at) SELECT 0,0,CAST(n AS TEXT),'expired','','UTC',0,'','test',?,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP FROM rows`, due) if err != nil { t.Fatal(err) } if rec := tick(t, app.Handler()); rec.Code != http.StatusNoContent { t.Fatalf("tick = %d", rec.Code) } var remaining int if err := app.DBForTest().QueryRow(`SELECT COUNT(*) FROM bookings WHERE ip_fp IS NOT NULL`).Scan(&remaining); err != nil { t.Fatal(err) } at, _ := control.snapshot() if remaining != 1 || at.Unix() < due || at.After(time.Now()) || at.IsZero() { t.Fatalf("backlog = %d, timer = %v", remaining, at) } if rec := tick(t, app.Handler()); rec.Code != http.StatusNoContent { t.Fatalf("second tick = %d", rec.Code) } if at, _ := control.snapshot(); !at.IsZero() { t.Fatalf("finished backlog remains armed at %v", at) } } func TestScheduledHTTPKeepsRetryAndLeaseDeadlines(t *testing.T) { control := controlForTest(t) app := calendar.NewForTest(t, t.TempDir()) now := time.Now().Unix() _, err := app.DBForTest().Exec(`INSERT INTO reminder_queues (reminder_id,occurrence_key,due_at,claimed_at,retry_at,attempts,late_by_sec) VALUES (1,'leased',?,?,?,0,0)`, now-60, now, now+600) if err != nil { t.Fatal(err) } if rec := tick(t, app.Handler()); rec.Code != http.StatusNoContent { t.Fatalf("tick = %d", rec.Code) } if at, _ := control.snapshot(); at.Unix() != now+600 { t.Fatalf("retry time lost: %v", at) } if _, err := app.DBForTest().Exec(`UPDATE reminder_queues SET retry_at = NULL`); err != nil { t.Fatal(err) } if rec := tick(t, app.Handler()); rec.Code != http.StatusNoContent { t.Fatalf("second tick = %d", rec.Code) } if at, _ := control.snapshot(); at.Unix() != now+300 { t.Fatalf("lease time lost: %v", at) } }