From 7084cd63f3987ca097b96afead596190a1cec856 Mon Sep 17 00:00:00 2001 From: Dominik Myszkowski Date: Thu, 26 Nov 2026 17:52:39 +0100 Subject: [PATCH 1/2] feat(api): updated_since change feed for GET /v1/bookings (#262) GET /v1/bookings?updated_since= returns every booking changed at or after that instant, cancelled ones included, ordered by (updated_at, id). after_id (the last item's id) turns it into an exact keyset cursor, so ties on updated_at are neither repeated nor skipped. Combines with the existing filters and limit/offset. updated_at could not carry this before: only 5 of 23 UPDATEs on bookings set it (payment transitions, the worker releasing unpaid holds, meeting links and RSVPs did not), and the column mixed the DEFAULT's millisecond form with Go's RFC3339Nano, which don't sort lexicographically. Migration 00075 normalises existing values to whole-second RFC 3339 (the string the API returns), adds an (updated_at, id) index, and hands the column to triggers: any UPDATE of a booking, or of its attendee's RSVP, stamps it. The feed holds back the current second, so a later write in that second can't sort in behind a cursor already handed out. --- CHANGELOG.md | 9 + docs/ARCHITECTURE.md | 28 ++- internal/booking/list.go | 54 +++- internal/booking/list_feed_test.go | 234 ++++++++++++++++++ internal/booking/service.go | 10 +- .../00075_bookings_updated_at_feed.sql | 68 +++++ internal/handler/booking_filter_test.go | 47 ++++ internal/handler/booking_handler.go | 26 +- 8 files changed, 465 insertions(+), 11 deletions(-) create mode 100644 internal/booking/list_feed_test.go create mode 100644 internal/db/migrations/00075_bookings_updated_at_feed.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 1149229b..4f87b0d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,15 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad ### Added +- **Change feed for `GET /v1/bookings`: `updated_since` (+ `after_id`).** Returns every booking + changed at or after an RFC 3339 instant, cancelled ones included, ordered by + `(updated_at, id)`. Pass the last item's `updated_at` and `id` back as `updated_since` and + `after_id` to resume without repeats or gaps. It combines with the existing filters and + `limit`/`offset`. A poller no longer has to refetch the whole window and infer cancellations + from bookings disappearing, and a webhook consumer can use it to catch up on missed + deliveries. Migration `00075` normalises `bookings.updated_at` to whole-second RFC 3339 and + hands it to triggers, so every change to a booking (payment transitions, meeting links, + RSVPs included) now moves it. - **Delete a booking for an erasure request.** Owners and admins can now permanently remove a booking from the Bookings list (trash icon, confirmation dialog; `DELETE /v1/bookings/{id}`). It removes the booking with its attendees, answers, manage links and host assignments, plus the diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 599c7672..7dba5f13 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -459,6 +459,30 @@ The `phone_outbound` location type ("we'll call you") is the outbound counterpar - **Teams resolve through membership**, not `event_types.team_id`: that column exists but nothing writes it, because a team is a shortcut for populating `event_type_hosts`. A member of two teams therefore appears under both. + - **Change feed: `updated_since` (+ `after_id`).** `GET /v1/bookings?updated_since=` + returns every booking whose row changed at or after that instant, **cancelled + ones included** (an explicit `status` still narrows), ordered by + `(updated_at, id)` ascending; `order=desc` is refused. It combines with the other + filters and with `limit`/`offset`. To resume exactly, pass the last item's + `updated_at` as `updated_since` and its `id` as `after_id`: the bound becomes the + keyset `(updated_at, id) > (updated_since, after_id)`, so ties neither repeat nor + get skipped. Without `after_id` the bound is inclusive (boundary rows come back; + dedupe by id). It is the catch-up path next to webhooks (§13), not a replacement. + An erasure delete (`DELETE /v1/bookings/{id}`) leaves no row, so it never appears + in the feed. An upcoming booking has to be cancelled before it can be deleted, so the + feed has already reported that cancellation; a consumer that mirrors past bookings + has to treat the feed as additive. + - `updated_at` is owned by triggers (migration 00075): any UPDATE of a bookings + row, and an RSVP on its organizer attendee, stamps it, so a write path that + forgets the column can't hide a change. Values are whole-second RFC 3339, the + same string the API returns, so an item's `updated_at` is usable verbatim; + 00075 normalised the previously mixed formats (DEFAULT ms vs Go RFC3339Nano), + which didn't sort lexicographically. Index `(updated_at, id)`. + - **The current second is held back** (`updated_at < now`, truncated to the + second): a later write in that second would share its `updated_at` and could + sort in behind a cursor already handed out. Writes are serialised on the single + connection (§17), so once a second has passed its group is complete. Cost: a + change shows up to ~1 s late. - **Public-surface abuse controls:** the `/slots` endpoint is rate-limited (60/min/IP, `slotsRL`) and `POST /v1/bookings` (20/min/IP, `bookingRL`); a per-email hourly cap (`maxBookingsPerEmailPerHour`) backstops rotating-IP spam; and the booking form has a @@ -814,7 +838,9 @@ as the desired state: selection. It is enqueued **before** the email with `EnqueueOnce`: the delivery ID is derived from (webhook, booking, `hours_before`, `start_at`) and inserted with `INSERT OR IGNORE`, so a job retried after a failed email collapses instead of - delivering twice, while a reschedule (new `start_at`) gets its own event. Deliveries are signed + delivering twice, while a reschedule (new `start_at`) gets its own event. A delivery can be + missed (receiver down past the retries), so a consumer that must converge pairs the + webhooks with the `GET /v1/bookings?updated_since=` change feed (§9) as catch-up. Deliveries are signed **HMAC-SHA256**, header `X-Calnode-Signature` (+ `X-Calnode-Event`/`-Delivery`), secret stored encrypted. The worker's HTTP client is **SSRF-guarded** (resolves DNS, blocks private/loopback/CGNAT/ULA IPs, dials the resolved IP to avoid diff --git a/internal/booking/list.go b/internal/booking/list.go index d1067265..2b9f4b20 100644 --- a/internal/booking/list.go +++ b/internal/booking/list.go @@ -44,8 +44,31 @@ type ListFilter struct { Limit int // 0 means unlimited - only the internal wrappers should use that Offset int + + // UpdatedSince turns the listing into a change feed: bookings whose row changed at + // or after this instant (updated_at >= UpdatedSince), ordered by (updated_at, id) + // ascending, cancelled ones included unless Status says otherwise - a cancellation + // is the change a poller most needs to see. Order is ignored. + // + // AfterID makes the bound exclusive as a keyset cursor: (updated_at, id) strictly + // after (UpdatedSince, AfterID). updated_at has whole-second resolution (migration + // 00075), so several bookings can share one; resuming from the last item's + // updated_at and id neither repeats nor skips any of them. Without AfterID the + // bound is inclusive, so a client that keeps only a timestamp sees the boundary + // rows again rather than losing one. + // + // The current second (from Now) is held back: a write later in this second would + // share its updated_at and could sort before a cursor already handed out. Holding + // it back means a second's group is complete before anyone sees it, at the cost of + // changes appearing up to a second late. Writes are serialised on the single + // connection (§17), so a later write never gets an earlier second. + UpdatedSince time.Time + AfterID string } +// feed reports whether f is a change-feed listing (UpdatedSince set). +func (f ListFilter) feed() bool { return !f.UpdatedSince.IsZero() } + // Counts reports how many bookings match a filter on each side of "now", ignoring // the filter's own When, Limit and Offset. The bookings page needs both numbers for // its tab labels, and deriving them client-side is exactly what pagination removes. @@ -96,12 +119,31 @@ func (f ListFilter) where(includeWhen bool) (string, []any) { var conds []string var args []any - if f.Status != "" { + switch { + case f.Status != "": conds = append(conds, "bookings.status = ?") args = append(args, f.Status) - } else { + case f.feed(): + // No default exclusion: the feed must report cancellations. + default: conds = append(conds, "bookings.status != 'cancelled'") } + if f.feed() { + since := sqlTime(f.UpdatedSince) + if f.AfterID != "" { + conds = append(conds, "(bookings.updated_at > ? OR (bookings.updated_at = ? AND bookings.id > ?))") + args = append(args, since, since, f.AfterID) + } else { + conds = append(conds, "bookings.updated_at >= ?") + args = append(args, since) + } + now := f.Now + if now.IsZero() { + now = time.Now() + } + conds = append(conds, "bookings.updated_at < ?") + args = append(args, sqlTime(now)) + } if f.ViewerID != "" { conds = append(conds, hostsBooking) args = append(args, f.ViewerID, f.ViewerID) @@ -149,9 +191,15 @@ func (s *Service) List(ctx context.Context, f ListFilter) ([]Booking, error) { // start_at is not unique, so a second key keeps paging stable across requests - // without it two bookings at the same time can swap places between pages and one // of them is never shown. + orderBy := `start_at ` + order + `, id ` + order + if f.feed() { + // The feed's cursor is (updated_at, id), so it must be the sort key too, and + // always ascending (idx_bookings_updated). + orderBy = `updated_at ASC, id ASC` + } q := `SELECT ` + bookingColumns + ` FROM bookings ` + whereSQL + ` - ORDER BY start_at ` + order + `, id ` + order //#nosec G202 -- whereSQL is assembled from literal fragments only; every value is bound via args + ORDER BY ` + orderBy //#nosec G202 -- whereSQL and orderBy are assembled from literal fragments only; every value is bound via args if f.Limit > 0 { q += "\n\t\tLIMIT ? OFFSET ?" diff --git a/internal/booking/list_feed_test.go b/internal/booking/list_feed_test.go new file mode 100644 index 00000000..7ca4b145 --- /dev/null +++ b/internal/booking/list_feed_test.go @@ -0,0 +1,234 @@ +package booking_test + +import ( + "context" + "database/sql" + "regexp" + "sort" + "testing" + "time" + + "github.com/calnode/calnode/internal/booking" +) + +// wholeSecond is the only form updated_at may take after migration 00075. +var wholeSecond = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$`) + +func createAt(t *testing.T, svc *booking.Service, etID, hostID string, h int) *booking.Booking { + t.Helper() + b, err := svc.Create(context.Background(), booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: slot(h, 0), + EndAt: slot(h, 30), + Organizer: booking.Attendee{Name: "Alice", Email: "alice@example.com", IANATimezone: "UTC"}, + }) + if err != nil { + t.Fatalf("Create: %v", err) + } + return b +} + +func rawUpdatedAt(t *testing.T, database *sql.DB, id string) string { + t.Helper() + var s string + if err := database.QueryRow(`SELECT updated_at FROM bookings WHERE id = ?`, id).Scan(&s); err != nil { + t.Fatalf("read updated_at: %v", err) + } + return s +} + +// Every change to a booking must move updated_at, including the UPDATEs that never set +// it themselves, or a poller misses the change for good. +func TestUpdatedAt_everyChangeBumpsIt(t *testing.T) { + database := newTestDB(t) + svc := booking.New(database) + hostID := seedHost(t, database) + etID := seedEventType(t, database, hostID) + + changes := map[string]string{ + // The worker releasing an unpaid hold: a cancellation that never set updated_at. + "hold released": `UPDATE bookings SET status = 'cancelled', cancellation_reason = 'payment not completed' WHERE id = ?`, + "payment": `UPDATE bookings SET payment_status = 'paid' WHERE id = ?`, + "meet link": `UPDATE bookings SET location_value = 'https://meet.google.com/abc' WHERE id = ?`, + "rsvp": `UPDATE booking_attendees SET rsvp_status = 'accepted' WHERE booking_id = ?`, + // A caller writing its own (stale) value doesn't get to keep it. + "explicit stale value": `UPDATE bookings SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?`, + } + ids := map[string]string{} + before := map[string]string{} + h := 9 + for name := range changes { + b := createAt(t, svc, etID, hostID, h) + h++ + ids[name] = b.ID + before[name] = rawUpdatedAt(t, database, b.ID) + if !wholeSecond.MatchString(before[name]) { + t.Fatalf("%s: updated_at on insert = %q; want whole-second RFC 3339", name, before[name]) + } + } + untouched := createAt(t, svc, etID, hostID, h).ID + untouchedBefore := rawUpdatedAt(t, database, untouched) + + time.Sleep(1100 * time.Millisecond) // updated_at has whole-second resolution + + for name, q := range changes { + if _, err := database.Exec(q, ids[name]); err != nil { + t.Fatalf("%s: %v", name, err) + } + after := rawUpdatedAt(t, database, ids[name]) + if !wholeSecond.MatchString(after) { + t.Errorf("%s: updated_at = %q; want whole-second RFC 3339", name, after) + } + if after <= before[name] { + t.Errorf("%s: updated_at = %q, was %q; want it moved forward", name, after, before[name]) + } + } + if got := rawUpdatedAt(t, database, untouched); got != untouchedBefore { + t.Errorf("untouched booking: updated_at = %q, was %q; want unchanged", got, untouchedBefore) + } +} + +func TestList_updatedSince_includesCancelledInUpdateOrder(t *testing.T) { + database := newTestDB(t) + svc := booking.New(database) + hostID := seedHost(t, database) + etID := seedEventType(t, database, hostID) + ctx := context.Background() + + b1 := createAt(t, svc, etID, hostID, 9) + b2 := createAt(t, svc, etID, hostID, 10) + if err := svc.Cancel(ctx, hostID, b2.ID, "changed plans"); err != nil { + t.Fatalf("Cancel: %v", err) + } + + // The default listing hides the cancellation; the feed must not. + plain, err := svc.List(ctx, booking.ListFilter{}) + if err != nil { + t.Fatalf("List: %v", err) + } + if len(plain) != 1 { + t.Fatalf("plain list: %d bookings; want 1 (cancelled excluded)", len(plain)) + } + + got, err := svc.List(ctx, booking.ListFilter{ + UpdatedSince: time.Now().Add(-time.Hour), + Now: time.Now().Add(2 * time.Second), // past the held-back second + }) + if err != nil { + t.Fatalf("List feed: %v", err) + } + if len(got) != 2 { + t.Fatalf("feed: %d bookings; want 2", len(got)) + } + seen := map[string]string{} + for i, b := range got { + seen[b.ID] = b.Status + if i > 0 { + prev := got[i-1] + if b.UpdatedAt.Before(prev.UpdatedAt) || (b.UpdatedAt.Equal(prev.UpdatedAt) && b.ID < prev.ID) { + t.Errorf("feed not ordered by (updated_at, id): %v then %v", prev.ID, b.ID) + } + } + } + if seen[b1.ID] != "confirmed" || seen[b2.ID] != "cancelled" { + t.Errorf("feed statuses = %v; want %s confirmed and %s cancelled", seen, b1.ID, b2.ID) + } + + // An explicit status still narrows the feed. + onlyCancelled, err := svc.List(ctx, booking.ListFilter{ + UpdatedSince: time.Now().Add(-time.Hour), + Now: time.Now().Add(2 * time.Second), + Status: "cancelled", + }) + if err != nil { + t.Fatalf("List feed cancelled: %v", err) + } + if len(onlyCancelled) != 1 || onlyCancelled[0].ID != b2.ID { + t.Errorf("feed with status=cancelled = %d items; want just %s", len(onlyCancelled), b2.ID) + } +} + +// Bookings created together share one updated_at. Paging one at a time with the +// (updated_at, id) cursor must visit each exactly once. +func TestList_updatedSince_cursorWalksTiesExactlyOnce(t *testing.T) { + database := newTestDB(t) + svc := booking.New(database) + hostID := seedHost(t, database) + etID := seedEventType(t, database, hostID) + ctx := context.Background() + + var want []string + for h := 9; h < 14; h++ { + want = append(want, createAt(t, svc, etID, hostID, h).ID) + } + sort.Strings(want) + + now := time.Now().Add(2 * time.Second) + f := booking.ListFilter{UpdatedSince: time.Now().Add(-time.Hour), Now: now, Limit: 1} + var walked []string + for range 10 { + page, err := svc.List(ctx, f) + if err != nil { + t.Fatalf("List: %v", err) + } + if len(page) == 0 { + break + } + last := page[0] + walked = append(walked, last.ID) + f.UpdatedSince, f.AfterID = last.UpdatedAt, last.ID + } + sort.Strings(walked) + if len(walked) != len(want) { + t.Fatalf("walked %d bookings %v; want %d %v", len(walked), walked, len(want), want) + } + for i := range want { + if walked[i] != want[i] { + t.Fatalf("walked %v; want %v", walked, want) + } + } + + // Without after_id the bound is inclusive: the last item comes back, nothing is lost. + f.AfterID = "" + again, err := svc.List(ctx, f) + if err != nil { + t.Fatalf("List inclusive: %v", err) + } + if len(again) == 0 { + t.Error("inclusive updated_since returned nothing; want the boundary rows again") + } +} + +// A change in the current second is held back until that second is over, so a later +// write in the same second can't sort in behind a cursor already handed out. +func TestList_updatedSince_holdsBackCurrentSecond(t *testing.T) { + database := newTestDB(t) + svc := booking.New(database) + hostID := seedHost(t, database) + etID := seedEventType(t, database, hostID) + ctx := context.Background() + + b := createAt(t, svc, etID, hostID, 9) + stamped, err := time.Parse(time.RFC3339, rawUpdatedAt(t, database, b.ID)) + if err != nil { + t.Fatalf("parse updated_at: %v", err) + } + + for _, tc := range []struct { + name string + now time.Time + want int + }{ + {"same second", stamped.Add(900 * time.Millisecond), 0}, + {"next second", stamped.Add(time.Second), 1}, + } { + got, err := svc.List(ctx, booking.ListFilter{UpdatedSince: stamped.Add(-time.Hour), Now: tc.now}) + if err != nil { + t.Fatalf("%s: List: %v", tc.name, err) + } + if len(got) != tc.want { + t.Errorf("%s: %d bookings; want %d", tc.name, len(got), tc.want) + } + } +} diff --git a/internal/booking/service.go b/internal/booking/service.go index aae6c77d..57f76082 100644 --- a/internal/booking/service.go +++ b/internal/booking/service.go @@ -244,7 +244,7 @@ func (s *Service) clearNeedsSync(ctx context.Context, bookingID string) { // if the booking does not exist or belongs to a different host, and // ErrAlreadyCancelled if it is already in that state. func (s *Service) Cancel(ctx context.Context, hostID, id, reason string) error { - now := time.Now().UTC().Format(time.RFC3339Nano) + now := sqlTime(time.Now()) // whole seconds, the form the updated_at triggers write (00075) res, err := s.db.ExecContext(ctx, ` UPDATE bookings SET status = 'cancelled', cancellation_reason = ?, updated_at = ? @@ -276,7 +276,7 @@ func (s *Service) Cancel(ctx context.Context, hostID, id, reason string) error { // resolving a departing member's meetings during archiving. Ownership is // enforced by the caller (admin check in the handler), not here. func (s *Service) CancelByID(ctx context.Context, id, reason string) error { - now := time.Now().UTC().Format(time.RFC3339Nano) + now := sqlTime(time.Now()) // whole seconds, the form the updated_at triggers write (00075) res, err := s.db.ExecContext(ctx, ` UPDATE bookings SET status = 'cancelled', cancellation_reason = ?, updated_at = ? @@ -525,7 +525,7 @@ func (s *Service) Reschedule(ctx context.Context, bookingID string, newStart, ne } } - now := time.Now().UTC().Format(time.RFC3339Nano) + now := sqlTime(time.Now()) // whole seconds, the form the updated_at triggers write (00075) if _, err := tx.ExecContext(ctx, ` UPDATE bookings SET start_at = ?, end_at = ?, updated_at = ? WHERE id = ?`, startStr, endStr, now, bookingID); err != nil { @@ -592,7 +592,7 @@ func (s *Service) ReassignHost(ctx context.Context, bookingID, newHostID string) return nil, ErrHostAlreadyAssigned } - now := time.Now().UTC().Format(time.RFC3339Nano) + now := sqlTime(time.Now()) // whole seconds, the form the updated_at triggers write (00075) if _, err := tx.ExecContext(ctx, ` UPDATE bookings SET host_id = ?, updated_at = ? WHERE id = ?`, newHostID, now, bookingID); err != nil { @@ -643,7 +643,7 @@ func (s *Service) CancelByToken(ctx context.Context, rawToken, reason string) (* if b.Status == "cancelled" { return nil, ErrAlreadyCancelled } - now := time.Now().UTC().Format(time.RFC3339Nano) + now := sqlTime(time.Now()) // whole seconds, the form the updated_at triggers write (00075) res, err := s.db.ExecContext(ctx, ` UPDATE bookings SET status = 'cancelled', cancellation_reason = ?, updated_at = ? WHERE id = ? AND status != 'cancelled'`, diff --git a/internal/db/migrations/00075_bookings_updated_at_feed.sql b/internal/db/migrations/00075_bookings_updated_at_feed.sql new file mode 100644 index 00000000..59b5a297 --- /dev/null +++ b/internal/db/migrations/00075_bookings_updated_at_feed.sql @@ -0,0 +1,68 @@ +-- +goose Up +-- bookings.updated_at becomes a change feed for GET /v1/bookings?updated_since=, which +-- only works if every change to a booking moves it and every value compares correctly. +-- Neither held before: +-- +-- * Only five of the UPDATEs on bookings set updated_at. Payment transitions, the +-- worker releasing an unpaid hold (a cancellation), Meet/Zoom/LiveKit links in +-- location_value, confirm_failed and invite fields all left it alone, and a poller +-- that misses a change never converges. Rather than audit every current and future +-- UPDATE, the triggers below own the column: any UPDATE of a bookings row stamps it, +-- whatever the statement set. +-- * Two formats were mixed in one TEXT column: the DEFAULT wrote +-- 2026-01-02T10:00:00.123Z and Go wrote RFC3339Nano (10:00:00Z, 10:00:00.5Z, ...). +-- Comparison is lexicographic and '.' sorts below 'Z', so those don't order. The +-- column is now always whole-second RFC3339, the same form start_at uses and the +-- same string the API returns, so an item's updated_at is directly usable as a cursor. +-- +-- Whole seconds produce ties, which the API breaks with (updated_at, id); the feed also +-- holds back the current second so a tie group is complete before anyone sees it +-- (booking.ListFilter.UpdatedSince). +UPDATE bookings SET updated_at = COALESCE( + strftime('%Y-%m-%dT%H:%M:%SZ', updated_at), + strftime('%Y-%m-%dT%H:%M:%SZ', created_at), + strftime('%Y-%m-%dT%H:%M:%SZ', 'now')); + +-- Serves the feed's ORDER BY updated_at, id and its keyset condition. +CREATE INDEX IF NOT EXISTS idx_bookings_updated ON bookings (updated_at, id); + +-- The column DEFAULT keeps milliseconds and SQLite can't ALTER a DEFAULT without a +-- rebuild of bookings (see 00071 for why that is avoided), so new rows are normalised here. +-- +goose StatementBegin +CREATE TRIGGER bookings_insert_updated_at AFTER INSERT ON bookings +FOR EACH ROW +WHEN NEW.updated_at IS NOT strftime('%Y-%m-%dT%H:%M:%SZ', 'now') +BEGIN + UPDATE bookings SET updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = NEW.id; +END; +-- +goose StatementEnd + +-- 'now' is fixed for the whole statement, triggers included, so the inner UPDATE writes +-- exactly the value the WHEN compares against: it can't re-fire this trigger even with +-- recursive_triggers on. +-- +goose StatementBegin +CREATE TRIGGER bookings_touch_updated_at AFTER UPDATE ON bookings +FOR EACH ROW +WHEN NEW.updated_at IS NOT strftime('%Y-%m-%dT%H:%M:%SZ', 'now') +BEGIN + UPDATE bookings SET updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = NEW.id; +END; +-- +goose StatementEnd + +-- The booker's RSVP lives on booking_attendees and is part of the listed booking +-- (rsvp_status), so an answer is a change to the booking too. +-- +goose StatementBegin +CREATE TRIGGER booking_attendees_touch_booking AFTER UPDATE ON booking_attendees +FOR EACH ROW +BEGIN + UPDATE bookings SET updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = NEW.booking_id; +END; +-- +goose StatementEnd + +-- +goose Down +-- The normalised values stay: older code reads updated_at with RFC3339Nano, which +-- parses them. +DROP TRIGGER IF EXISTS booking_attendees_touch_booking; +DROP TRIGGER IF EXISTS bookings_touch_updated_at; +DROP TRIGGER IF EXISTS bookings_insert_updated_at; +DROP INDEX IF EXISTS idx_bookings_updated; diff --git a/internal/handler/booking_filter_test.go b/internal/handler/booking_filter_test.go index 249adbb0..677fc846 100644 --- a/internal/handler/booking_filter_test.go +++ b/internal/handler/booking_filter_test.go @@ -6,7 +6,9 @@ import ( "fmt" "net/http" "net/http/httptest" + "net/url" "testing" + "time" "github.com/calnode/calnode/internal/handler" ) @@ -19,6 +21,7 @@ type listResp struct { Status string `json:"status"` HostID string `json:"host_id"` EventTypeSlug string `json:"event_type_slug"` + UpdatedAt string `json:"updated_at"` } `json:"items"` Total int `json:"total"` Counts struct { @@ -292,6 +295,8 @@ func TestListBookings_rejectsBadParameters(t *testing.T) { for _, q := range []string{ "?status=banana", "?when=someday", "?from=07-2027", "?to=nonsense", "?limit=0", "?limit=-1", "?limit=abc", "?offset=-1", + "?updated_since=yesterday", "?updated_since=2027-07-01", + "?after_id=b-ok", "?updated_since=2027-07-01T00:00:00Z&order=desc", } { req := authReq(http.MethodGet, "/v1/bookings"+q, "", key) rec := httptest.NewRecorder() @@ -301,3 +306,45 @@ func TestListBookings_rejectsBadParameters(t *testing.T) { } } } + +// TestListBookings_updatedSinceFeed walks the change feed over HTTP the way a poller +// would: cancelled bookings included, one item per page, resuming from the last +// item's updated_at and id, and each booking seen exactly once. +func TestListBookings_updatedSinceFeed(t *testing.T) { + h, database, key, ownerID := setupWorkspaceWithDB(t) + _, etID := seedEventTypeHTTP(t, h, key) + seedBooking(t, database, "b-ok", etID, ownerID, "2027-07-01T10:00:00Z", "2027-07-01T10:30:00Z", "confirmed") + seedBooking(t, database, "b-gone", etID, ownerID, "2027-07-02T10:00:00Z", "2027-07-02T10:30:00Z", "cancelled") + seedBooking(t, database, "b-past", etID, ownerID, "2020-07-02T10:00:00Z", "2020-07-02T10:30:00Z", "confirmed") + + // The feed holds back the current second; let the seeded rows settle. + time.Sleep(1100 * time.Millisecond) + + since := "2000-01-01T00:00:00Z" + all := listBookings(t, h, key, "?updated_since="+url.QueryEscape(since)) + if all.Total != 3 || len(all.Items) != 3 { + t.Fatalf("feed: total %d, %d items; want 3 (cancelled and past included)", all.Total, len(all.Items)) + } + + seen := map[string]string{} + afterID := "" + for range 10 { + q := "?limit=1&updated_since=" + url.QueryEscape(since) + if afterID != "" { + q += "&after_id=" + url.QueryEscape(afterID) + } + page := listBookings(t, h, key, q) + if len(page.Items) == 0 { + break + } + it := page.Items[0] + if _, dup := seen[it.ID]; dup { + t.Fatalf("booking %s returned twice", it.ID) + } + seen[it.ID] = it.Status + since, afterID = it.UpdatedAt, it.ID + } + if len(seen) != 3 || seen["b-gone"] != "cancelled" { + t.Errorf("walked %v; want b-ok, b-gone (cancelled) and b-past once each", seen) + } +} diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index e1f54313..f0c14625 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -1582,6 +1582,27 @@ func (h *Handler) parseBookingListFilter(ctx context.Context, q url.Values, user f.To = f.To.AddDate(0, 0, 1) // "to" names a day, and the whole of it is included } + // updated_since turns the list into a change feed (booking.ListFilter.UpdatedSince): + // every booking changed since then, cancelled ones included, ordered by + // (updated_at, id). after_id, the id of the last item processed, makes it an + // exact cursor. + if v := q.Get("updated_since"); v != "" { + t, err := time.Parse(time.RFC3339Nano, v) + if err != nil { + return f, fmt.Errorf("updated_since must be an RFC 3339 timestamp") + } + if f.Order == "desc" { + return f, fmt.Errorf("updated_since lists oldest change first; order=desc is not supported with it") + } + f.UpdatedSince = t + } + if v := q.Get("after_id"); v != "" { + if f.UpdatedSince.IsZero() { + return f, fmt.Errorf("after_id requires updated_since") + } + f.AfterID = v + } + if v := q.Get("limit"); v != "" { n, err := strconv.Atoi(v) if err != nil || n < 1 { @@ -1623,8 +1644,9 @@ func parseDayStart(s string) (time.Time, error) { // ListBookings handles GET /v1/bookings (admin — lists bookings for the current user). // Returns bookings enriched with event_type_slug and the organizer attendee. // -// Filters (event_type, host, team, status, when, from, to) and pagination are applied -// in SQL by booking.List; see parseBookingListFilter for the visibility rule. +// Filters (event_type, host, team, status, when, from, to, updated_since/after_id) and +// pagination are applied in SQL by booking.List; see parseBookingListFilter for the +// visibility rule. func (h *Handler) ListBookings(w http.ResponseWriter, r *http.Request) { user, _ := userFromContext(r.Context()) From f27efd3775225cce60e8e60360ffa28f8eed2ba2 Mon Sep 17 00:00:00 2001 From: Dominik Myszkowski Date: Tue, 1 Dec 2026 09:56:18 +0100 Subject: [PATCH 2/2] fix(api): treat a pre-epoch updated_since as the start of the feed A client that seeds its cursor from a zero time value sends 0001-01-01T00:00:00Z, which booking.ListFilter reads as no feed at all: the request got the plain listing, cancelled bookings left out, and after_id was refused. Clamp anything before the Unix epoch to it. --- internal/handler/booking_filter_test.go | 20 ++++++++++++++++++++ internal/handler/booking_handler.go | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/internal/handler/booking_filter_test.go b/internal/handler/booking_filter_test.go index 677fc846..3ca1a90f 100644 --- a/internal/handler/booking_filter_test.go +++ b/internal/handler/booking_filter_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "slices" "testing" "time" @@ -348,3 +349,22 @@ func TestListBookings_updatedSinceFeed(t *testing.T) { t.Errorf("walked %v; want b-ok, b-gone (cancelled) and b-past once each", seen) } } + +// A client that seeds its cursor from a zero time value sends 0001-01-01T00:00:00Z. That +// must still be the feed (cancelled included, after_id accepted), not the plain listing. +func TestListBookings_updatedSinceZeroInstantIsStillAFeed(t *testing.T) { + h, database, key, ownerID := setupWorkspaceWithDB(t) + _, etID := seedEventTypeHTTP(t, h, key) + seedBooking(t, database, "b-ok", etID, ownerID, "2027-07-01T10:00:00Z", "2027-07-01T10:30:00Z", "confirmed") + seedBooking(t, database, "b-gone", etID, ownerID, "2027-07-02T10:00:00Z", "2027-07-02T10:30:00Z", "cancelled") + time.Sleep(1100 * time.Millisecond) + + zero := url.QueryEscape(time.Time{}.Format(time.RFC3339)) + all := listBookings(t, h, key, "?updated_since="+zero) + if all.Total != 2 || !slices.Contains(listIDs(all), "b-gone") { + t.Fatalf("zero instant: %v (total %d); want both bookings, the cancelled one included", listIDs(all), all.Total) + } + // after_id needs updated_since; with the zero instant it must be accepted, not + // refused as if updated_since were missing (listBookings fails on a non-200). + listBookings(t, h, key, "?updated_since="+zero+"&after_id=b-gone") +} diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index f0c14625..9d2bb254 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -1594,6 +1594,14 @@ func (h *Handler) parseBookingListFilter(ctx context.Context, q url.Values, user if f.Order == "desc" { return f, fmt.Errorf("updated_since lists oldest change first; order=desc is not supported with it") } + // The zero instant (0001-01-01T00:00:00Z, what a client's zero time value formats + // as) is a natural "from the beginning" cursor, but a zero UpdatedSince means "no + // feed" to booking.ListFilter. Anything before the Unix epoch is clamped to it: no + // row can have changed earlier, so the result is the same, and the request stays a + // feed with cancelled bookings included. + if epoch := time.Unix(0, 0).UTC(); t.Before(epoch) { + t = epoch + } f.UpdatedSince = t } if v := q.Get("after_id"); v != "" {