Files
superbrain/main.go
T
Andrew S Erwin 4f919033d1 CardDAV address books: each server book a Collection, each contact a URL bookmark
Settings -> CardDAV connects an external CardDAV endpoint (any RFC 6352
service; on Core the deployment's NEXTCLOUD_URL adds a Nextcloud-contacts
one-click prefill, composed visibly with the username so the URL shown is
the URL saved). Each server address book materializes as its own Collection
and every contact becomes a Bookmark carrying the card's DAV .vcf URL — FN
as title, email/phone in the description as display sugar set once.

internal/carddav mirrors the WebDAV/CalDAV siblings:
- client.go — discovery accepts a single book or a home (resourcetype
  <card:addressbook/>), addressbook-query REPORT bounded at 50 books /
  2000 cards, netguard-pinned, Basic auth in the header only, redirects
  refused, folded-vCard parser;
- sync.go — RunLoop/RunOnce under a dedicated carddav-tick advisory lease;
  full ledger discipline: idempotent re-runs, etag refreshes never touch
  user-edited bookmark fields, vanished cards detach membership but keep
  the bookmark, user-deleted bookmarks are tombstones that never
  resurrect, a re-deleted Collection is re-created and re-linked, a
  truncated listing never reconciles deletions, one unreadable book does
  not abort the rest.

CardDAV dials pin to 443 only and require https — CardDAV ships
Basic-auth credentials, and the Contacts sync's review rulings (M-3/CR-01)
stand; the INTEGRATIONS_ALLOW_PRIVATE escape hatch keeps loopback fakes
working. This surface is deliberately separate from the single-config
Contacts sync (Contact rows powering contact-linking): same transport,
different product model, stated in API.md and the UI copy.

Three tables (CardDavConnection/CardDavAddressbook/CardDavItem) via
migration 022 + schema.sql. Handlers expose /api/carddav/connections CRUD
+ /test + /sync with the house credential (encrypted, masked, write-only),
version (409 on stale) and AllowConnector("carddav") plan gate on creation
AND every sync; cap 10; wired as the sixth background loop.

Settings -> CardDAV tab (web/components/carddav-settings.tsx): masked
write-only password, version on PATCH, per-row address-book list,
verbatim test/sync results, Core suggestion prefill, allowed flag drives
the plan notice.

Verification: full Go integration suite green incl. TestCardDavLifecycle
(materialize/URL+title checks, idempotency, etag refresh, detach-but-
survive, tombstone, version contract, 502+lastError, owner scoping) and
TestCardDavSuggestion; carddav unit tests on httptest fakes;
make db-converge passes; browser regressions all 19 PASS incl. the new
CardDAV walkthrough (and a deterministic Sonner-toast drain before the
sign-out assertion, which the added toasts had made racy); web lint/SSR-
lint/build clean. API.md contract section, AGENTS invariant, env docs and
the Core installer wording updated for the three-way DAV prefill.
2026-11-16 03:47:51 -06:00

113 lines
3.8 KiB
Go

package main
import (
"context"
"errors"
"github.com/andrew/superbrain/internal/agent"
"github.com/andrew/superbrain/internal/caldav"
"github.com/andrew/superbrain/internal/carddav"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/http"
"github.com/andrew/superbrain/internal/notify"
"github.com/andrew/superbrain/internal/scripts"
"github.com/andrew/superbrain/internal/signals"
"github.com/andrew/superbrain/internal/webdav"
"log"
stdhttp "net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
if len(os.Args) > 1 && os.Args[1] == "--healthcheck" {
client := stdhttp.Client{Timeout: 3 * time.Second}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
res, err := client.Get("http://127.0.0.1:" + port + "/readyz")
if err != nil {
os.Exit(1)
}
res.Body.Close()
if res.StatusCode != 200 {
os.Exit(1)
}
return
}
cfg := config.Load()
if err := cfg.Validate(); err != nil {
log.Fatalf("config: %v", err)
}
d, err := db.New(cfg)
if err != nil {
log.Fatalf("db: %v", err)
}
defer d.Close()
// Tenancy phase 1: make sure the implicit tenant exists with the
// tier-derived plan and adopt any tenantless users (self-heal twin of
// migration 012). Best-effort: user creation re-ensures per transaction,
// so a failure here must not keep the API down.
if err := db.NewTenantRepo(d).Bootstrap(context.Background()); err != nil {
log.Printf("tenancy bootstrap: %v", err)
}
if len(os.Args) > 1 && os.Args[1] == "--seed" {
if err := scripts.Seed(context.Background(), d); err != nil {
log.Fatal(err)
}
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Shutdown order is owned by main (review OPS-01): drain in-flight HTTP
// requests first, then await the background loops, and only afterwards let
// the deferred db close run. Previously Shutdown raced ListenAndServe's
// return and the process exited mid-drain.
workersDone := make(chan struct{})
go func() {
defer close(workersDone)
var wg sync.WaitGroup
wg.Add(6)
go func() { defer wg.Done(); signals.RunLoop(ctx, d) }()
// Notification engine (DESIGN_NOTIFICATIONS.md): scans rules and
// delivers through channels; shares the shutdown contract with
// signals — drain HTTP first, then the loops, then close the db.
go func() { defer wg.Done(); notify.RunLoop(ctx, d) }()
// Agent automations ("hey superbrain"): evaluates compiled tasks on
// their own poll schedules under a global advisory lease.
go func() { defer wg.Done(); agent.RunLoop(ctx, d) }()
// WebDAV shares (Settings → WebDAV): reconciles connected file shares
// into Collections of per-file bookmark URLs under the same lease and
// shutdown discipline as the other loops.
go func() { defer wg.Done(); webdav.RunLoop(ctx, d) }()
// CalDAV calendars (Settings → CalDAV): reconciles each server
// calendar into a Collection of per-event bookmark URLs, on its own
// advisory lease so the two DAV loops never block each other.
go func() { defer wg.Done(); caldav.RunLoop(ctx, d) }()
// CardDAV address books (Settings -> CardDAV): each server book becomes a
// Collection of per-contact bookmark URLs, on its own advisory lease.
go func() { defer wg.Done(); carddav.RunLoop(ctx, d) }()
wg.Wait()
}()
srv := http.NewServer(cfg, d)
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, stdhttp.ErrServerClosed) {
log.Fatalf("server failed: %v", err)
}
}()
log.Printf("superbrain API listening on %s", srv.Addr)
<-ctx.Done()
stop()
shutdown, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(shutdown); err != nil {
log.Printf("shutdown: %v", err)
}
<-workersDone
}