Phase F of the AFFiNE plan (ADR-16): - Calendars: people subscribe to iCal feeds (webcal, Google's secret address, Outlook) or CalDAV accounts in account settings; their events show at the top of journal pages in the reader's time zone. Repeats, moved and cancelled occurrences, IANA and Windows zones are handled. Events are read on demand and kept in memory for 15 minutes; passwords are sealed with DOCWELL_SECRET_KEY; sources follow the webhook address rules. New calendar_accounts collection. - Importers: zips of Markdown (Obsidian vaults, Bear TextBundles and .bear2bk, Readwise's Markdown, Docwell's own space export) keep folders as pages, resolve [[wikilinks]] and embeds by name, and turn front matter and #tags into properties and tags. OneNote .mht exports, Readwise CSV, and any other CSV as a database page. - Exports: PNG of a page drawn in the browser, print styles that print only the page in the light theme, and workspace snapshots (records, Yjs states, JSON and files in one zip) that restore as a new workspace. Old ids are swapped byte for byte inside the Yjs updates, so links point at the restored pages and comments stay anchored. - Web-Clipper/: a Manifest V3 extension for Chrome, Edge and Firefox that saves the article or the selection as Markdown through the import API with a personal API token. - OpenAPI, generated clients, translations and user docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
267 lines
9.7 KiB
Go
267 lines
9.7 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Command docwell-server runs the Docwell API, collaboration relay and admin panel.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"runtime"
|
|
"syscall"
|
|
"time"
|
|
|
|
"docwell/server/internal/admin"
|
|
"docwell/server/internal/ai"
|
|
"docwell/server/internal/audit"
|
|
"docwell/server/internal/auth"
|
|
"docwell/server/internal/calendar"
|
|
"docwell/server/internal/collab"
|
|
"docwell/server/internal/config"
|
|
"docwell/server/internal/directory"
|
|
"docwell/server/internal/httpapi"
|
|
"docwell/server/internal/instance"
|
|
"docwell/server/internal/jobs"
|
|
"docwell/server/internal/mail"
|
|
"docwell/server/internal/pbschema"
|
|
"docwell/server/internal/push"
|
|
"docwell/server/internal/search"
|
|
"docwell/server/internal/settings"
|
|
"docwell/server/internal/store/pocketbase"
|
|
"docwell/server/internal/unfurl"
|
|
"docwell/server/internal/webhooks"
|
|
"docwell/server/internal/ycrdt"
|
|
)
|
|
|
|
// Version is set at build time with -ldflags "-X main.Version=...".
|
|
var Version = "dev"
|
|
|
|
func main() {
|
|
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
|
if err := run(log); err != nil {
|
|
log.Error("fatal", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run(log *slog.Logger) error {
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
db := pocketbase.New(cfg.PocketBaseURL, cfg.PocketBaseEmail, cfg.PocketBasePassword)
|
|
// docwell-db is a stock PocketBase: the server brings its schema up to date
|
|
// before anything else touches it.
|
|
if err := preparePocketBase(db, log); err != nil {
|
|
return err
|
|
}
|
|
// Docwell's own emails go out over SMTP with PocketBase's mail settings.
|
|
var settingsSvc *settings.Service
|
|
mailer := &mail.SMTPSender{Config: func(ctx context.Context) (mail.Config, error) {
|
|
return settingsSvc.MailConfig(ctx)
|
|
}}
|
|
settingsSvc = settings.New(db, settings.Signup{Enabled: cfg.SignupEnabled, Domains: cfg.SignupDomains}, mailer)
|
|
envCtx, cancelEnv := context.WithTimeout(context.Background(), time.Minute)
|
|
err = settingsSvc.ApplyEnv(envCtx, settings.Env{
|
|
AppName: cfg.AppName, WebURL: cfg.WebURL, MailFrom: cfg.MailFrom,
|
|
SMTPHost: cfg.SMTP.Host, SMTPPort: cfg.SMTP.Port, SMTPUsername: cfg.SMTP.Username,
|
|
SMTPPassword: cfg.SMTP.Password, SMTPTLS: cfg.SMTP.TLS,
|
|
S3: cfg.S3.Enabled, S3Bucket: cfg.S3.Bucket, S3Endpoint: cfg.S3.Endpoint, S3Region: cfg.S3.Region,
|
|
S3AccessKey: cfg.S3.AccessKey, S3Secret: cfg.S3.Secret, S3ForcePathStyle: cfg.S3.ForcePathStyle,
|
|
})
|
|
cancelEnv()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
authSvc := auth.NewService(db, auth.Options{
|
|
Rules: func(ctx context.Context) (bool, []string, error) {
|
|
rules, err := settingsSvc.Signup(ctx)
|
|
return rules.Enabled, rules.Domains, err
|
|
},
|
|
// Providers send people back to the web app, or to the desktop app's link.
|
|
OAuthRedirects: []string{cfg.WebURL + "/oauth/callback", "docwell://oauth/callback"},
|
|
})
|
|
settingsSvc.SetOAuthCallback(cfg.WebURL + "/oauth/callback")
|
|
if cfg.AdminEmail != "" {
|
|
adminCtx, cancelAdmin := context.WithTimeout(context.Background(), time.Minute)
|
|
created, err := authSvc.EnsureSuperadmin(adminCtx, cfg.AdminEmail, cfg.AdminPassword, cfg.AdminName)
|
|
cancelAdmin()
|
|
switch {
|
|
case err != nil:
|
|
return fmt.Errorf("create superadmin from DOCWELL_ADMIN_EMAIL: %w", err)
|
|
case created:
|
|
log.Info("created superadmin from DOCWELL_ADMIN_EMAIL", "email", cfg.AdminEmail)
|
|
default:
|
|
log.Info("accounts already exist; DOCWELL_ADMIN_EMAIL left unused")
|
|
}
|
|
}
|
|
auditLog := audit.New(db, log)
|
|
defer auditLog.Close()
|
|
hooks := webhooks.New(db, log, webhooks.Options{AllowLocal: cfg.WebhooksAllowLocal})
|
|
|
|
// yrs.wasm compiles once; the cache makes later starts fast (ADR-3).
|
|
cacheDir, _ := os.UserCacheDir()
|
|
if cacheDir != "" {
|
|
cacheDir = filepath.Join(cacheDir, "docwell", "wazero")
|
|
}
|
|
yrs, err := ycrdt.New(context.Background(), cacheDir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
hub := collab.NewHub(collab.Options{
|
|
Store: collab.NewPBStore(db), Docs: ycrdt.NewPool(yrs, max(2, runtime.GOMAXPROCS(0))), Log: log,
|
|
})
|
|
dirSvc := directory.New(db, authSvc.Forget, hub)
|
|
hub.OnSaved(func(page, editor string, doc []byte) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
|
defer cancel()
|
|
dirSvc.PageSaved(ctx, page, editor, doc)
|
|
})
|
|
// The search index follows PocketBase and can be rebuilt from it at any time.
|
|
index, err := search.Open(cfg.DataDir, db, log)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer index.Close()
|
|
reg := jobs.New()
|
|
reg.Register("search.index", "Adds changed pages to the search index", 3*time.Second, nil)
|
|
reg.Register("search.sweep", "Removes deleted pages from the search index", 10*time.Minute, index.Sweep)
|
|
reg.Register("search.rebuild", "Rebuilds the whole search index from the database", 0, index.Rebuild)
|
|
reg.Register("notify.digest", "Emails people their unread notifications", 5*time.Minute, dirSvc.SendDigests)
|
|
reg.Register("notify.prune", "Deletes read notifications and sent reminders older than 90 days", 24*time.Hour, dirSvc.PruneNotifications)
|
|
reg.Register("notify.reminders", "Sends reminders for dates in pages that are due", time.Minute, dirSvc.SendReminders)
|
|
reg.Register("links.backfill", "Works out page links for pages saved before backlinks existed", 0, dirSvc.BackfillLinks)
|
|
index.Track(reg.Track)
|
|
indexCtx, stopIndex := context.WithCancel(context.Background())
|
|
defer stopIndex()
|
|
go index.Run(indexCtx, 3*time.Second, 10*time.Minute)
|
|
go reg.Every(indexCtx, "notify.digest", 5*time.Minute)
|
|
go reg.Every(indexCtx, "notify.prune", 24*time.Hour)
|
|
go reg.Every(indexCtx, "notify.reminders", time.Minute)
|
|
_ = reg.Run("links.backfill")
|
|
dirSvc.UseSearch(index)
|
|
dirSvc.UseWebhooks(hooks)
|
|
go hooks.Run(indexCtx)
|
|
// Phones get pushes through UnifiedPush; endpoints follow the webhook address rules.
|
|
pushSvc := push.New(db, log, push.Options{AllowLocal: cfg.WebhooksAllowLocal})
|
|
dirSvc.UsePush(pushSvc)
|
|
go pushSvc.Run(indexCtx)
|
|
reg.Register("webhooks.prune", "Deletes webhook deliveries older than 30 days", 24*time.Hour, hooks.Prune)
|
|
go reg.Every(indexCtx, "webhooks.prune", 24*time.Hour)
|
|
if days := cfg.AuditRetentionDays; days > 0 {
|
|
reg.Register("audit.prune", fmt.Sprintf("Deletes audit log entries older than %d days", days), 24*time.Hour,
|
|
func(ctx context.Context) error { return auditLog.Prune(ctx, time.Duration(days)*24*time.Hour) })
|
|
go reg.Every(indexCtx, "audit.prune", 24*time.Hour)
|
|
}
|
|
// AI (ADR-15): provider keys are sealed with DOCWELL_SECRET_KEY, or with a
|
|
// key derived from the PocketBase password when it is not set.
|
|
secret := cfg.SecretKey
|
|
if secret == "" {
|
|
secret = "pb:" + cfg.PocketBasePassword
|
|
}
|
|
aiSvc, err := ai.New(db, dirSvc, log, ai.Options{Secret: secret, DataDir: cfg.DataDir, AllowLocal: cfg.WebhooksAllowLocal,
|
|
MediaURL: cfg.MediaURL, MediaToken: cfg.MediaToken})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer aiSvc.Close()
|
|
aiSvc.Track(reg.Track)
|
|
reg.Register("ai.index", "Embeds changed pages of workspaces with AI indexing on", 30*time.Second,
|
|
func(ctx context.Context) error { return aiSvc.IndexPass(ctx, true) })
|
|
go aiSvc.Run(indexCtx, 30*time.Second, 10*time.Minute)
|
|
// Calendars (ADR-16): passwords are sealed with the same secret as AI keys;
|
|
// sources follow the webhook address rules.
|
|
calSvc := calendar.New(db, calendar.Options{Secret: secret, AllowLocal: cfg.WebhooksAllowLocal})
|
|
dirSvc.SetPublicURL(cfg.PublicURL)
|
|
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
|
|
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
|
|
b, _ := settingsSvc.Branding(ctx)
|
|
return b.AppName
|
|
}})
|
|
|
|
srv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: httpapi.NewRouter(httpapi.Deps{
|
|
Version: Version,
|
|
CORSOrigins: cfg.CORSOrigins,
|
|
DB: db,
|
|
Auth: authSvc,
|
|
Directory: dirSvc,
|
|
Settings: settingsSvc,
|
|
// Derived from the PocketBase password, so links survive restarts
|
|
// without another secret to configure.
|
|
FileTokens: auth.NewFileTokens(cfg.PocketBasePassword, time.Hour),
|
|
MaxUpload: int64(cfg.MaxUploadMB) << 20,
|
|
Instance: instance.New(db, Version, hub, index, reg),
|
|
Collab: hub,
|
|
Audit: auditLog,
|
|
Previews: unfurl.New(),
|
|
Calendars: calSvc,
|
|
Push: pushSvc,
|
|
AI: aiSvc,
|
|
Admin: admin.Handler("/admin"),
|
|
Log: log,
|
|
}),
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
errCh := make(chan error, 1)
|
|
go func() {
|
|
log.Info("docwell-server listening", "addr", cfg.Addr, "version", Version, "pocketbase", cfg.PocketBaseURL)
|
|
errCh <- srv.ListenAndServe()
|
|
}()
|
|
|
|
select {
|
|
case err := <-errCh:
|
|
if !errors.Is(err, http.ErrServerClosed) {
|
|
return err
|
|
}
|
|
case <-ctx.Done():
|
|
log.Info("shutting down")
|
|
}
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
|
defer cancel()
|
|
// Open WebSockets are hijacked and not tracked by Shutdown; closing the hub
|
|
// saves every open page, and the process exit then drops the sockets.
|
|
err = srv.Shutdown(shutdownCtx)
|
|
if herr := hub.Close(shutdownCtx); herr != nil {
|
|
log.Error("collab: saving open pages", "err", herr)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// preparePocketBase waits for PocketBase to answer, then applies Docwell's
|
|
// collections to it (pbschema).
|
|
func preparePocketBase(db *pocketbase.Client, log *slog.Logger) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
for {
|
|
err := db.Health(ctx)
|
|
if err == nil {
|
|
break
|
|
}
|
|
log.Info("waiting for PocketBase", "err", err)
|
|
select {
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("pocketbase did not answer: %w", err)
|
|
case <-time.After(2 * time.Second):
|
|
}
|
|
}
|
|
start := time.Now()
|
|
if err := pbschema.Apply(ctx, db); err != nil {
|
|
return err
|
|
}
|
|
log.Info("pocketbase schema applied", "dur", time.Since(start).String())
|
|
return nil
|
|
}
|