The Gitea repository was renamed brain -> superbrain (server-side redirect already in place; local origin updated at 0.3.5). Carry the rename through for accurate identity, the 0.3.2 precedent: go.mod + every internal import, the agent's outbound User-Agent contact URL, README/RUNNING clone URLs and local notes. CHANGELOG history entries stay as written. Pure identifier rename, no runtime behavior change; verified with build + vet + unit tests and the full database integration suite under -race.
435 lines
14 KiB
Go
435 lines
14 KiB
Go
package carddav
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"math/rand/v2"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/config"
|
|
crypt "gitea.federated.computer/Federated_Computer/superbrain/internal/crypto"
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/db"
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/outbound"
|
|
)
|
|
|
|
const (
|
|
tick = 5 * time.Minute // engine cadence
|
|
syncEvery = 30 * time.Minute // per-connection freshness target
|
|
perTick = 8 // connections claimed per tick
|
|
syncTimeout = 4 * time.Minute // one full reconcile
|
|
lastErrCap = 500
|
|
dialBudget = 10 // outbound.Reserve window per owner
|
|
dialWindow = time.Minute
|
|
connectorKey = "carddav" // entitlements Connectors allowlist name
|
|
)
|
|
|
|
// Connection is one stored CardDavConnection 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 address book.
|
|
type Result struct {
|
|
Books int `json:"books"`
|
|
Cards int `json:"cards"`
|
|
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 the sibling
|
|
// DAV loops: 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("carddav: tick failed: %v", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// RunOnce syncs every due connection once under its own global advisory
|
|
// lease (webdav-tick / caldav-tick / carddav-tick 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('carddav-tick',0))`).Scan(&locked); err != nil {
|
|
return err
|
|
}
|
|
if !locked {
|
|
return nil
|
|
}
|
|
defer conn.ExecContext(context.WithoutCancel(ctx), `SELECT pg_advisory_unlock(hashtextextended('carddav-tick',0))`)
|
|
|
|
rows, err := d.QueryContext(ctx, `
|
|
SELECT c.id, c."ownerId", COALESCE(u."tenantId",''), c.name, c.url, c.username, c.secret
|
|
FROM "CardDavConnection" 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("carddav: sync %s: %v", c.ID, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SyncOne reconciles one CardDAV connection: every discovered address book
|
|
// becomes its own Collection (named by the server's display name) and every
|
|
// card becomes a Bookmark carrying the card's DAV .vcf URL — FN as title,
|
|
// email/phone in the description as display sugar only. The CardDavItem
|
|
// ledger keeps (book href, card path) stable: re-runs are idempotent,
|
|
// user-deleted bookmarks stay deleted (tombstones never resurrect), removed
|
|
// cards detach membership without destroying the bookmark, and a re-deleted
|
|
// Collection is re-created with every live card re-linked. The plan gate
|
|
// re-runs at every sync (a downgrade suppresses, never deletes).
|
|
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("carddav:"+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}
|
|
books, err := Discover(sctx, conn)
|
|
if err != nil {
|
|
markError(ctx, d, c.ID, err.Error())
|
|
return res, err
|
|
}
|
|
type bookCards struct {
|
|
book Addressbook
|
|
cards *CardResult
|
|
collectErr error
|
|
}
|
|
fetched := make([]bookCards, 0, len(books))
|
|
for _, bk := range books {
|
|
cr, e := Cards(sctx, conn, bk.URL)
|
|
if e != nil {
|
|
log.Printf("carddav: address book %s of %s: %v", bk.Href, c.ID, e)
|
|
fetched = append(fetched, bookCards{book: bk, collectErr: e})
|
|
continue
|
|
}
|
|
fetched = append(fetched, bookCards{book: bk, cards: cr})
|
|
res.Truncated = res.Truncated || cr.Truncated
|
|
}
|
|
|
|
err = db.Transaction(ctx, d, func(tx *sql.Tx) error {
|
|
existingBooks, e := loadBooks(ctx, tx, c.ID)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
seenBook := map[string]bool{}
|
|
for _, fb := range fetched {
|
|
seenBook[fb.book.Href] = true
|
|
if fb.collectErr != nil {
|
|
continue // an unreachable book keeps its ledger; never mass-detach
|
|
}
|
|
bookID, colID, reauthored, e := ensureBookCollection(ctx, tx, c, fb.book, existingBooks[fb.book.Href])
|
|
if e != nil {
|
|
return e
|
|
}
|
|
res.Books++
|
|
items, e := loadItems(ctx, tx, bookID)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
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 _, cd := range fb.cards.Cards {
|
|
seen[cd.Path] = true
|
|
row := items[cd.Path]
|
|
switch {
|
|
case !row.exists:
|
|
bid, reused, e := cardBookmark(ctx, tx, c.OwnerID, cd)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if reused {
|
|
res.Reused++
|
|
} else {
|
|
res.Created++
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `INSERT INTO "CardDavItem"
|
|
(id,"addressbookId",path,"bookmarkId",etag,uid)
|
|
VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT ("addressbookId",path) DO NOTHING`,
|
|
db.NewID(), bookID, cd.Path, bid, cd.ETag, cd.UID); e != nil {
|
|
return e
|
|
}
|
|
if e := addMembership(bid); e != nil {
|
|
return e
|
|
}
|
|
case row.bookmarkID == "":
|
|
res.Kept++ // tombstone: the owner deleted this contact's bookmark
|
|
default:
|
|
if row.etag != cd.ETag {
|
|
if _, e := tx.ExecContext(ctx, `UPDATE "CardDavItem" SET etag=$2,uid=$3,"updatedAt"=now() WHERE id=$1`,
|
|
row.id, cd.ETag, cd.UID); e != nil {
|
|
return e
|
|
}
|
|
res.Updated++
|
|
} else {
|
|
res.Kept++
|
|
}
|
|
if reauthored {
|
|
if e := addMembership(row.bookmarkID); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
}
|
|
}
|
|
res.Cards += len(fb.cards.Cards)
|
|
if !fb.cards.Truncated {
|
|
for p, row := range items {
|
|
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 "CardDavItem" WHERE id=$1`, row.id); e != nil {
|
|
return e
|
|
}
|
|
res.Removed++
|
|
}
|
|
}
|
|
}
|
|
// Address books that disappeared server-side: detach their cards'
|
|
// membership (bookmarks survive), then drop the ledger rows.
|
|
for href, row := range existingBooks {
|
|
if seenBook[href] {
|
|
continue
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `DELETE FROM "CollectionItem" WHERE "bookmarkId" IN
|
|
(SELECT "bookmarkId" FROM "CardDavItem" WHERE "addressbookId"=$1 AND "bookmarkId" IS NOT NULL)`, row.id); e != nil {
|
|
return e
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `DELETE FROM "CardDavAddressbook" WHERE id=$1`, row.id); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `UPDATE "CardDavConnection" 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 bookRow struct {
|
|
id string
|
|
collectionID string // "" == NULL
|
|
exists bool
|
|
}
|
|
|
|
func loadBooks(ctx context.Context, tx *sql.Tx, connID string) (map[string]bookRow, error) {
|
|
rows, err := tx.QueryContext(ctx, `SELECT id, href, COALESCE("collectionId",'') FROM "CardDavAddressbook" WHERE "connectionId"=$1`, connID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := map[string]bookRow{}
|
|
for rows.Next() {
|
|
var r bookRow
|
|
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()
|
|
}
|
|
|
|
// ensureBookCollection returns the book's ledger row + Collection,
|
|
// creating either when missing. reauthored marks a freshly created
|
|
// Collection, whose members are all re-linked.
|
|
func ensureBookCollection(ctx context.Context, tx *sql.Tx, c Connection, bk Addressbook, row bookRow) (bookID, colID string, reauthored bool, err error) {
|
|
name := bk.DisplayName
|
|
if strings.TrimSpace(name) == "" {
|
|
name = niceSegment(bk.Href)
|
|
}
|
|
bookID = row.id
|
|
if !row.exists {
|
|
bookID = db.NewID()
|
|
if _, err = db.Insert(ctx, tx, "CardDavAddressbook", db.Object{
|
|
"id": bookID, "connectionId": c.ID, "href": bk.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 bookID, 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": "CardDAV address book — " + 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 "CardDavAddressbook" SET "collectionId"=$2,"displayName"=$3,"updatedAt"=now() WHERE id=$1`, bookID, colID, name); err != nil {
|
|
return "", "", false, err
|
|
}
|
|
return bookID, colID, true, nil
|
|
}
|
|
|
|
// cardBookmark reuses the owner's exact-URL bookmark (URL identity) or
|
|
// creates one titled with the contact name; email/phone ride along in the
|
|
// description for display only — later syncs never rewrite them.
|
|
func cardBookmark(ctx context.Context, tx *sql.Tx, ownerID string, cd Card) (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, cd.URL).Scan(&id)
|
|
if err == nil {
|
|
return id, true, nil
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return "", false, err
|
|
}
|
|
id = db.NewID()
|
|
data := db.Object{"id": id, "ownerId": ownerID, "url": cd.URL, "title": cd.Name}
|
|
desc := make([]string, 0, 2)
|
|
if cd.Email != "" {
|
|
desc = append(desc, "Email: "+cd.Email)
|
|
}
|
|
if cd.Phone != "" {
|
|
desc = append(desc, "Phone: "+cd.Phone)
|
|
}
|
|
if len(desc) > 0 {
|
|
data["description"] = strings.Join(desc, "\n")
|
|
}
|
|
if _, err := db.Insert(ctx, tx, "Bookmark", data); err != nil {
|
|
return "", false, err
|
|
}
|
|
return id, false, nil
|
|
}
|
|
|
|
type itemRow struct {
|
|
id string
|
|
path string
|
|
etag string
|
|
bookmarkID string // "" == NULL (tombstone)
|
|
exists bool
|
|
}
|
|
|
|
func loadItems(ctx context.Context, tx *sql.Tx, bookID string) (map[string]itemRow, error) {
|
|
rows, err := tx.QueryContext(ctx, `SELECT id, path, etag, COALESCE("bookmarkId",'') FROM "CardDavItem" WHERE "addressbookId"=$1`, bookID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := map[string]itemRow{}
|
|
for rows.Next() {
|
|
var r itemRow
|
|
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 "CardDavConnection" SET "lastError"=$2,"updatedAt"=now() WHERE id=$1`, id, msg); err != nil {
|
|
log.Printf("carddav: marking %s failed: %v", id, err)
|
|
}
|
|
}
|
|
|
|
func hostOf(raw string) string {
|
|
// Shared with the client's helpers; trimmed here for the sync description.
|
|
if at := strings.Index(raw, "://"); at >= 0 {
|
|
rest := raw[at+3:]
|
|
if slash := strings.IndexByte(rest, '/'); slash >= 0 {
|
|
rest = rest[:slash]
|
|
}
|
|
return strings.TrimPrefix(strings.Split(rest, ":")[0], "www.")
|
|
}
|
|
return raw
|
|
}
|