Settings -> CalDAV connects an external CalDAV endpoint (any RFC 4791
service; on Core the deployment's NEXTCLOUD_URL adds a Nextcloud-calendars
one-click prefill alongside the existing files one). Each server calendar
materializes as its own Collection and every in-window event becomes a
Bookmark carrying the event's DAV .ics URL.
internal/caldav mirrors internal/webdav:
- client.go — PROPFIND discovery (accepts a calendar home via
calendar-home-set or a single calendar), REPORT calendar-query over a
rolling window (last 30d .. next 180d), netguard-pinned 80/443, Basic
auth in the header only, redirects refused, bounded (50 calendars /
500 events);
- ics.go — RFC 5545 unfolding + first-VEVENT parse (UID/SUMMARY/DTSTART);
- sync.go — RunLoop/RunOnce under a dedicated advisory lease, reconciling
each calendar to a Collection and each event to a bookmark via the
CalDavEvent ledger. Same tombstone/detach discipline as WebDAV: a
vanished OR out-of-window event detaches membership but keeps the
bookmark; a user-deleted event never resurrects; a re-deleted collection
is recreated and re-linked; a truncated window never reconciles
deletions; one unreadable calendar does not abort the rest.
Three tables (CalDavConnection/CalDavCalendar/CalDavEvent) via migration 021
+ schema.sql. Handlers expose /api/caldav/connections CRUD + /test + /sync
with the house credential (encrypted, masked, write-only), version (409 on
stale), and AllowConnector("caldav") plan gate on creation AND every sync.
Wired as the fifth background loop in main.go.
Settings -> CalDAV tab (web/components/caldav-settings.tsx): masked
write-only password, version on PATCH, per-row calendar list, verbatim
test/sync results, Core suggestion prefill with the viewer's email
local-part, allowed flag drives the plan notice.
Verification: full Go integration suite green incl. four TestCalDav*
(lifecycle, collection-recreation, plan gate + suggestion) on an httptest
fake CalDAV server; make db-converge passes; browser regressions all 18
PASS incl. the new CalDAV settings walkthrough; web lint/SSR-lint/build
clean. API.md, README, .env.example, Core installer and local AGENTS
documents updated.
449 lines
14 KiB
Go
449 lines
14 KiB
Go
package caldav
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"math/rand/v2"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/andrew/superbrain/internal/config"
|
|
crypt "github.com/andrew/superbrain/internal/crypto"
|
|
"github.com/andrew/superbrain/internal/db"
|
|
"github.com/andrew/superbrain/internal/outbound"
|
|
)
|
|
|
|
const (
|
|
tick = 5 * time.Minute // engine cadence
|
|
syncEvery = 30 * time.Minute // per-connection freshness target
|
|
perTick = 8 // connections claimed per tick (each fans out)
|
|
syncTimeout = 4 * time.Minute // one full reconcile (discovery + all calendars)
|
|
lastErrCap = 500
|
|
dialBudget = 10 // outbound.Reserve window per owner (tests + syncs)
|
|
dialWindow = time.Minute
|
|
connectorKey = "caldav" // entitlements Connectors allowlist name
|
|
)
|
|
|
|
// Connection is one stored CalDavConnection row plus its DECRYPTED password.
|
|
type Connection struct {
|
|
ID, OwnerID, TenantID string
|
|
Name, URL, Username string
|
|
Password string
|
|
}
|
|
|
|
// Result summarizes one reconcile pass across every calendar of a connection.
|
|
type Result struct {
|
|
Calendars int `json:"calendars"`
|
|
Events int `json:"events"`
|
|
Created int `json:"created"`
|
|
Reused int `json:"reused"`
|
|
Updated int `json:"updated"`
|
|
Kept int `json:"kept"`
|
|
Removed int `json:"removed"`
|
|
Truncated bool `json:"truncated"`
|
|
}
|
|
|
|
// RunLoop drives the background sync until ctx ends. Mirrors webdav/notify:
|
|
// jittered ticks, failures logged not fatal.
|
|
func RunLoop(ctx context.Context, d *db.DB) {
|
|
time.Sleep(time.Duration(rand.IntN(5000)) * time.Millisecond)
|
|
t := time.NewTicker(tick + time.Duration(rand.IntN(20000))*time.Millisecond)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
if err := RunOnce(ctx, d); err != nil {
|
|
log.Printf("caldav: tick failed: %v", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// RunOnce syncs every due connection once under a global advisory lease
|
|
// (distinct key from webdav so the two loops never block each other).
|
|
// Exported for tests.
|
|
func RunOnce(ctx context.Context, d *db.DB) error {
|
|
conn, err := d.Conn(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer conn.Close()
|
|
var locked bool
|
|
if err := conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock(hashtextextended('caldav-tick',0))`).Scan(&locked); err != nil {
|
|
return err
|
|
}
|
|
if !locked {
|
|
return nil
|
|
}
|
|
defer conn.ExecContext(context.WithoutCancel(ctx), `SELECT pg_advisory_unlock(hashtextextended('caldav-tick',0))`)
|
|
|
|
rows, err := d.QueryContext(ctx, `
|
|
SELECT c.id, c."ownerId", COALESCE(u."tenantId",''), c.name, c.url, c.username, c.secret
|
|
FROM "CalDavConnection" c
|
|
LEFT JOIN "User" u ON u.id = c."ownerId"
|
|
WHERE c.enabled AND (c."lastSyncedAt" IS NULL
|
|
OR c."lastSyncedAt" < now() - make_interval(mins => $1))
|
|
ORDER BY c."lastSyncedAt" NULLS FIRST
|
|
LIMIT $2`, int(syncEvery.Minutes()), perTick)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rows.Close()
|
|
var due []Connection
|
|
for rows.Next() {
|
|
var c Connection
|
|
var secretEnc string
|
|
if err := rows.Scan(&c.ID, &c.OwnerID, &c.TenantID, &c.Name, &c.URL, &c.Username, &secretEnc); err != nil {
|
|
return err
|
|
}
|
|
pw, err := crypt.Decrypt(secretEnc, config.Load().EncryptionSecret())
|
|
if err != nil {
|
|
markError(ctx, d, c.ID, "stored password could not be decrypted")
|
|
continue
|
|
}
|
|
c.Password = pw
|
|
due = append(due, c)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return err
|
|
}
|
|
for _, c := range due {
|
|
if _, err := SyncOne(ctx, d, c); err != nil {
|
|
log.Printf("caldav: sync %s: %v", c.ID, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SyncOne reconciles one CalDAV connection: every server calendar becomes a
|
|
// Collection (its own, named by the server's display name) and every in-window
|
|
// VEVENT becomes a Bookmark carrying the event's DAV .ics URL. The
|
|
// CalDavEvent ledger keeps (calendar href, event path) stable so re-runs are
|
|
// idempotent, a user-deleted bookmark stays deleted (tombstones never
|
|
// resurrect), and events that vanish OR scroll past the 30-day window detach
|
|
// membership without destroying the bookmark — the pages-and-trash semantics
|
|
// of internal/webdav, one level deeper. Bookkeeping columns never bump
|
|
// version.
|
|
//
|
|
// The plan gate re-runs HERE, not only at creation: a downgrade suppresses
|
|
// syncs the same way the notification engine suppresses deliveries.
|
|
func SyncOne(ctx context.Context, d *db.DB, c Connection) (Result, error) {
|
|
var res Result
|
|
lim, err := db.NewTenantRepo(d).Limits(ctx, c.TenantID)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
if !lim.AllowConnector(connectorKey) {
|
|
markError(ctx, d, c.ID, "Not available on your plan")
|
|
return res, errors.New("Not available on your plan")
|
|
}
|
|
release, _, ok := outbound.Reserve("caldav:"+c.OwnerID, dialBudget, dialWindow)
|
|
if !ok {
|
|
return res, fmt.Errorf("outbound limit reached for this user; retry shortly")
|
|
}
|
|
defer release()
|
|
|
|
sctx, cancel := context.WithTimeout(ctx, syncTimeout)
|
|
defer cancel()
|
|
conn := Conn{BaseURL: c.URL, Username: c.Username, Password: c.Password}
|
|
cals, err := Discover(sctx, conn)
|
|
if err != nil {
|
|
markError(ctx, d, c.ID, err.Error())
|
|
return res, err
|
|
}
|
|
// Fetch every calendar's in-window events BEFORE the write transaction:
|
|
// no network round-trips inside a DB transaction (webdav's discipline).
|
|
type calEvents struct {
|
|
cal Calendar
|
|
res *EventResult
|
|
collectErr error
|
|
}
|
|
fetched := make([]calEvents, 0, len(cals))
|
|
for _, cal := range cals {
|
|
er, e := Events(sctx, conn, cal.URL)
|
|
if e != nil {
|
|
// One unreadable calendar must not abort the whole connection;
|
|
// surface it and reconcile the rest.
|
|
log.Printf("caldav: calendar %s of %s: %v", cal.Href, c.ID, e)
|
|
fetched = append(fetched, calEvents{cal: cal, collectErr: e})
|
|
continue
|
|
}
|
|
fetched = append(fetched, calEvents{cal: cal, res: er})
|
|
res.Truncated = res.Truncated || er.Truncated
|
|
}
|
|
|
|
err = db.Transaction(ctx, d, func(tx *sql.Tx) error {
|
|
existingCals, e := loadCalendars(ctx, tx, c.ID)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
seenCal := map[string]bool{}
|
|
for _, fe := range fetched {
|
|
seenCal[fe.cal.Href] = true
|
|
if fe.collectErr != nil {
|
|
// Leave the prior ledger/collection intact; do not treat an
|
|
// unreachable calendar as emptied and detach everything.
|
|
continue
|
|
}
|
|
calID, colID, reauthored, e := ensureCalendarCollection(ctx, tx, c, fe.cal, existingCals[fe.cal.Href])
|
|
if e != nil {
|
|
return e
|
|
}
|
|
res.Calendars++
|
|
events, e := loadEvents(ctx, tx, calID)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
// A freshly created collection re-links every live event; ordinary
|
|
// syncs respect member removals and tombstones (see webdav.go).
|
|
addMembership := func(bid string) error {
|
|
_, e := tx.ExecContext(ctx, `INSERT INTO "CollectionItem"
|
|
(id,"collectionId","bookmarkId",position)
|
|
SELECT $1,$2,$3,COALESCE(max(position),-1)+1 FROM "CollectionItem" WHERE "collectionId"=$2
|
|
ON CONFLICT ("collectionId","bookmarkId") DO NOTHING`, db.NewID(), colID, bid)
|
|
return e
|
|
}
|
|
seen := map[string]bool{}
|
|
for _, ev := range fe.res.Events {
|
|
seen[ev.Path] = true
|
|
row := events[ev.Path]
|
|
switch {
|
|
case !row.exists:
|
|
bid, reused, e := eventBookmark(ctx, tx, c.OwnerID, ev)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if reused {
|
|
res.Reused++
|
|
} else {
|
|
res.Created++
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `INSERT INTO "CalDavEvent"
|
|
(id,"calendarId",path,"bookmarkId",etag,uid,"startAt")
|
|
VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT ("calendarId",path) DO NOTHING`,
|
|
db.NewID(), calID, ev.Path, bid, ev.ETag, ev.UID, timeArg(ev.Start)); e != nil {
|
|
return e
|
|
}
|
|
if e := addMembership(bid); e != nil {
|
|
return e
|
|
}
|
|
case row.bookmarkID == "":
|
|
res.Kept++ // tombstone: owner deleted this event's bookmark
|
|
default:
|
|
if row.etag != ev.ETag {
|
|
if _, e := tx.ExecContext(ctx, `UPDATE "CalDavEvent" SET etag=$2,uid=$3,"startAt"=$4,"updatedAt"=now() WHERE id=$1`,
|
|
row.id, ev.ETag, ev.UID, timeArg(ev.Start)); e != nil {
|
|
return e
|
|
}
|
|
res.Updated++
|
|
} else {
|
|
res.Kept++
|
|
}
|
|
if reauthored {
|
|
if e := addMembership(row.bookmarkID); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
}
|
|
}
|
|
res.Events += len(fe.res.Events)
|
|
if !fe.res.Truncated {
|
|
for p, row := range events {
|
|
if seen[p] {
|
|
continue
|
|
}
|
|
if row.bookmarkID != "" {
|
|
if _, e := tx.ExecContext(ctx, `DELETE FROM "CollectionItem" WHERE "collectionId"=$1 AND "bookmarkId"=$2`, colID, row.bookmarkID); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `DELETE FROM "CalDavEvent" WHERE id=$1`, row.id); e != nil {
|
|
return e
|
|
}
|
|
res.Removed++
|
|
}
|
|
}
|
|
}
|
|
// Calendars that disappeared server-side: detach their events'
|
|
// membership (bookmarks survive), then drop the calendar row (cascades
|
|
// its event ledger).
|
|
for href, row := range existingCals {
|
|
if seenCal[href] {
|
|
continue
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `DELETE FROM "CollectionItem" WHERE "bookmarkId" IN
|
|
(SELECT "bookmarkId" FROM "CalDavEvent" WHERE "calendarId"=$1 AND "bookmarkId" IS NOT NULL) AND
|
|
"collectionId" IS NOT DISTINCT FROM (SELECT "collectionId" FROM "CalDavCalendar" WHERE id=$1)`, row.id); e != nil {
|
|
return e
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `DELETE FROM "CalDavCalendar" WHERE id=$1`, row.id); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `UPDATE "CalDavConnection" SET "lastSyncedAt"=now(),"lastError"=NULL,"updatedAt"=now() WHERE id=$1`, c.ID); e != nil {
|
|
return e
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
markError(ctx, d, c.ID, err.Error())
|
|
return res, err
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
type calRow struct {
|
|
id string
|
|
collectionID string // "" == NULL
|
|
exists bool
|
|
}
|
|
|
|
func loadCalendars(ctx context.Context, tx *sql.Tx, connID string) (map[string]calRow, error) {
|
|
rows, err := tx.QueryContext(ctx, `SELECT id, href, COALESCE("collectionId",'') FROM "CalDavCalendar" WHERE "connectionId"=$1`, connID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := map[string]calRow{}
|
|
for rows.Next() {
|
|
var r calRow
|
|
var href string
|
|
if err := rows.Scan(&r.id, &href, &r.collectionID); err != nil {
|
|
return nil, err
|
|
}
|
|
r.exists = true
|
|
out[href] = r
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// ensureCalendarCollection makes (or returns) the ledger row + collection
|
|
// for one server calendar. reauthored is true when a NEW collection was
|
|
// created (fresh calendar, or the owner deleted the old collection — FK
|
|
// SET NULL), so the caller re-links every live event; plain per-member
|
|
// removals stay respected on ordinary syncs.
|
|
func ensureCalendarCollection(ctx context.Context, tx *sql.Tx, c Connection, cal Calendar, row calRow) (calID, colID string, reauthored bool, err error) {
|
|
name := cal.DisplayName
|
|
if strings.TrimSpace(name) == "" {
|
|
name = niceSegment(cal.Href)
|
|
}
|
|
calID = row.id
|
|
if !row.exists {
|
|
calID = db.NewID()
|
|
if _, err = db.Insert(ctx, tx, "CalDavCalendar", db.Object{
|
|
"id": calID, "connectionId": c.ID, "href": cal.Href, "displayName": name,
|
|
}); err != nil {
|
|
return "", "", false, err
|
|
}
|
|
}
|
|
if row.collectionID != "" {
|
|
var existing string
|
|
err = tx.QueryRowContext(ctx, `SELECT id FROM "Collection" WHERE id=$1 AND "ownerId"=$2`, row.collectionID, c.OwnerID).Scan(&existing)
|
|
if err == nil {
|
|
return calID, existing, false, nil
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return "", "", false, err
|
|
}
|
|
}
|
|
colID = db.NewID()
|
|
if _, err = db.Insert(ctx, tx, "Collection", db.Object{
|
|
"id": colID, "ownerId": c.OwnerID, "name": name,
|
|
"description": "CalDAV calendar — " + hostOf(c.URL),
|
|
}); err != nil {
|
|
return "", "", false, err
|
|
}
|
|
if _, err = db.Insert(ctx, tx, "CollectionView", db.Object{
|
|
"id": db.NewID(), "collectionId": colID, "name": "Table", "type": "TABLE", "position": 0,
|
|
}); err != nil {
|
|
return "", "", false, err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `UPDATE "CalDavCalendar" SET "collectionId"=$2,"displayName"=$3,"updatedAt"=now() WHERE id=$1`, calID, colID, name); err != nil {
|
|
return "", "", false, err
|
|
}
|
|
return calID, colID, true, nil
|
|
}
|
|
|
|
// eventBookmark reuses the owner's bookmark with the exact event URL or
|
|
// creates one titled with the event summary (the calendar's own name is the
|
|
// fallback so a bookmark is never an opaque UID).
|
|
func eventBookmark(ctx context.Context, tx *sql.Tx, ownerID string, ev Event) (string, bool, error) {
|
|
var id string
|
|
err := tx.QueryRowContext(ctx, `SELECT id FROM "Bookmark" WHERE "ownerId"=$1 AND url=$2 ORDER BY "createdAt" LIMIT 1`, ownerID, ev.URL).Scan(&id)
|
|
if err == nil {
|
|
return id, true, nil
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return "", false, err
|
|
}
|
|
title := strings.TrimSpace(ev.Summary)
|
|
if title == "" {
|
|
title = niceSegment(ev.Path)
|
|
}
|
|
id = db.NewID()
|
|
if _, err := db.Insert(ctx, tx, "Bookmark", db.Object{
|
|
"id": id, "ownerId": ownerID, "url": ev.URL, "title": title,
|
|
}); err != nil {
|
|
return "", false, err
|
|
}
|
|
return id, false, nil
|
|
}
|
|
|
|
type eventRow struct {
|
|
id string
|
|
path string
|
|
etag string
|
|
bookmarkID string // "" == NULL (tombstone)
|
|
exists bool
|
|
}
|
|
|
|
func loadEvents(ctx context.Context, tx *sql.Tx, calID string) (map[string]eventRow, error) {
|
|
rows, err := tx.QueryContext(ctx, `SELECT id, path, etag, COALESCE("bookmarkId",'') FROM "CalDavEvent" WHERE "calendarId"=$1`, calID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := map[string]eventRow{}
|
|
for rows.Next() {
|
|
var r eventRow
|
|
if err := rows.Scan(&r.id, &r.path, &r.etag, &r.bookmarkID); err != nil {
|
|
return nil, err
|
|
}
|
|
r.exists = true
|
|
out[r.path] = r
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// markError records the engine-visible failure without touching version.
|
|
func markError(ctx context.Context, d *db.DB, id string, msg string) {
|
|
msg = strings.TrimSpace(msg)
|
|
if r := []rune(msg); len(r) > lastErrCap {
|
|
msg = string(r[:lastErrCap])
|
|
}
|
|
if _, err := d.ExecContext(ctx, `UPDATE "CalDavConnection" SET "lastError"=$2,"updatedAt"=now() WHERE id=$1`, id, msg); err != nil {
|
|
log.Printf("caldav: marking %s failed: %v", id, err)
|
|
}
|
|
}
|
|
|
|
func timeArg(t time.Time) any {
|
|
if t.IsZero() {
|
|
return nil
|
|
}
|
|
return t
|
|
}
|
|
|
|
func hostOf(raw string) string {
|
|
u, err := url.Parse(strings.TrimSpace(raw))
|
|
if err != nil {
|
|
return raw
|
|
}
|
|
return strings.TrimPrefix(u.Hostname(), "www.")
|
|
}
|