package webdav import ( "context" "database/sql" "errors" "fmt" "log" "math/rand/v2" "net/url" "path" "strings" "time" "gitea.federated.computer/Federated_Computer/brain/internal/config" crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto" "gitea.federated.computer/Federated_Computer/brain/internal/db" "gitea.federated.computer/Federated_Computer/brain/internal/outbound" ) const ( tick = 5 * time.Minute // engine cadence syncEvery = 30 * time.Minute // per-connection freshness target perTick = 10 // connections claimed per tick syncTimeout = 3 * time.Minute // one full reconcile lastErrCap = 500 dialBudget = 10 // outbound.Reserve window per owner (tests + syncs) dialWindow = time.Minute connectorKey = "webdav" // entitlements Connectors allowlist name ) // Connection is one stored WebDavConnection row plus its DECRYPTED password, // as handed to SyncOne. Callers own the plaintext lifetime. type Connection struct { ID, OwnerID, TenantID string Name, URL, Username string Password string CollectionID sql.NullString } // Result summarizes one reconcile pass. type Result struct { Files int `json:"files"` 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 notify/agent: // 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("webdav: tick failed: %v", err) } } } } // RunOnce syncs every due connection once. A global advisory lease keeps // multiple app instances from double-syncing (agent's pattern); a failed // lease is a silent skip. 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('webdav-tick',0))`).Scan(&locked); err != nil { return err } if !locked { return nil } defer conn.ExecContext(context.WithoutCancel(ctx), `SELECT pg_advisory_unlock(hashtextextended('webdav-tick',0))`) rows, err := d.QueryContext(ctx, ` SELECT c.id, c."ownerId", COALESCE(u."tenantId",''), c.name, c.url, c.username, c.secret, c."collectionId" FROM "WebDavConnection" 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, &c.CollectionID); err != nil { return err } // A row whose secret no longer decrypts is surfaced via lastError and // skipped; the key rotation story is "back up ENCRYPTION_KEY". 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("webdav: sync %s: %v", c.ID, err) } } return nil } // SyncOne reconciles one share into its Collection: every file becomes (or // reuses) a Bookmark carrying the file's DAV URL and joins the collection; // the WebDavItem ledger keeps paths stable so re-runs are idempotent, a // user-deleted bookmark stays deleted (tombstones never resurrect), and // disappeared files detach membership without destroying the bookmark — // pages-and-trash semantics. Bookkeeping columns (collectionId, // lastSyncedAt, lastError) never bump version: engine-owned, like // AgentTask.lastCheckedAt. // // 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("webdav:"+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) list, err := List(sctx, Conn{BaseURL: c.URL, Username: c.Username, Password: c.Password}) cancel() if err != nil { markError(ctx, d, c.ID, err.Error()) return res, err } err = db.Transaction(ctx, d, func(tx *sql.Tx) error { colID, reauthored, e := ensureCollection(ctx, tx, c) if e != nil { return e } existing, e := loadItems(ctx, tx, c.ID) if e != nil { return e } seen := make(map[string]bool, len(list.Files)) // membership inserts position: max+1 in one statement (the pages // link-add pattern). 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 } for _, f := range list.Files { seen[f.Path] = true row := existing[f.Path] switch { case !row.exists: fileURL, e := FileURL(c.URL, f.Path) if e != nil { return e } bid, reused, e := bookmarkFor(ctx, tx, c.OwnerID, fileURL, f.Path) if e != nil { return e } if reused { res.Reused++ } else { res.Created++ } if _, e := tx.ExecContext(ctx, `INSERT INTO "WebDavItem" (id,"connectionId",path,"bookmarkId",etag,"sizeBytes","modifiedAt") VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT ("connectionId",path) DO NOTHING`, db.NewID(), c.ID, f.Path, bid, f.ETag, f.Size, modArg(f.Modified)); e != nil { return e } // Membership is created with materialization. The user // removing it later is a decision, not drift — ordinary syncs // never re-add. The ONE exception is a freshly re-created // collection (below): the owner deleted the collection, not // these members, and the share promises (re)materialization. if e := addMembership(bid); e != nil { return e } case row.bookmarkID == "": // Tombstone: the owner deleted this file's bookmark. Never // resurrect; keep the ledger row so the tombstone survives. res.Kept++ default: if row.etag != f.ETag { // Content changed: refresh the ledger only. Title/notes/tags // belong to the user now — sync does not touch bookmarks after // creation (URL identity is stable; DAV paths are the key). if _, e := tx.ExecContext(ctx, `UPDATE "WebDavItem" SET etag=$2,"sizeBytes"=$3,"modifiedAt"=$4,"updatedAt"=now() WHERE id=$1`, row.id, f.ETag, f.Size, modArg(f.Modified)); e != nil { return e } res.Updated++ } else { res.Kept++ } if reauthored { if e := addMembership(row.bookmarkID); e != nil { return e } } } } if !list.Truncated { for p, row := range existing { 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 "WebDavItem" WHERE id=$1`, row.id); e != nil { return e } res.Removed++ } } res.Files = len(list.Files) res.Truncated = list.Truncated if _, e := tx.ExecContext(ctx, `UPDATE "WebDavConnection" 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 } // ensureCollection returns the share's collection, materializing (and // attaching) one when missing — including after the user deleted the old one // (FK ON DELETE SET NULL). reauthored is true exactly when a NEW collection // was created, so the caller re-links every still-tracked file (the owner // deleted the collection, not its members) — while plain per-member removals // stay respected on ordinary syncs. func ensureCollection(ctx context.Context, tx *sql.Tx, c Connection) (id string, reauthored bool, err error) { if c.CollectionID.Valid { var existing string err = tx.QueryRowContext(ctx, `SELECT id FROM "Collection" WHERE id=$1 AND "ownerId"=$2`, c.CollectionID.String, c.OwnerID).Scan(&existing) if err == nil { return existing, false, nil } if !errors.Is(err, sql.ErrNoRows) { return "", false, err } } id = db.NewID() if _, err = db.Insert(ctx, tx, "Collection", db.Object{ "id": id, "ownerId": c.OwnerID, "name": c.Name, "description": "WebDAV share — " + hostOf(c.URL), }); err != nil { return "", false, err } // Same default view as every new collection (collections.go create). if _, err = db.Insert(ctx, tx, "CollectionView", db.Object{ "id": db.NewID(), "collectionId": id, "name": "Table", "type": "TABLE", "position": 0, }); err != nil { return "", false, err } if _, err = tx.ExecContext(ctx, `UPDATE "WebDavConnection" SET "collectionId"=$2,"updatedAt"=now() WHERE id=$1`, c.ID, id); err != nil { return "", false, err } return id, true, nil } // bookmarkFor reuses the owner's existing bookmark with the exact same URL // (the URL-identity invariant from the pages flow) or creates one titled // with the file name. func bookmarkFor(ctx context.Context, tx *sql.Tx, ownerID, fileURL, relPath string) (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, fileURL).Scan(&id) if err == nil { return id, true, nil } if !errors.Is(err, sql.ErrNoRows) { return "", false, err } id = db.NewID() title := path.Base(relPath) if title == "." || title == "/" || title == "" { title = relPath } if _, err := db.Insert(ctx, tx, "Bookmark", db.Object{ "id": id, "ownerId": ownerID, "url": fileURL, "title": title, }); 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, connID string) (map[string]itemRow, error) { rows, err := tx.QueryContext(ctx, `SELECT id, path, etag, COALESCE("bookmarkId",'') FROM "WebDavItem" WHERE "connectionId"=$1`, connID) 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 "WebDavConnection" SET "lastError"=$2,"updatedAt"=now() WHERE id=$1`, id, msg); err != nil { log.Printf("webdav: marking %s failed: %v", id, err) } } func modArg(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.") }