Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 27 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<RFC 3339>`
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
Expand Down Expand Up @@ -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
Expand Down
54 changes: 51 additions & 3 deletions internal/booking/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved

// 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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 ?"
Expand Down
234 changes: 234 additions & 0 deletions internal/booking/list_feed_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Loading
Loading