A multi-session build turning Pete's read-only web UI into something people return to. Five phases, signed-in features keyed off the OIDC subject; anonymous visitors keep the reverse-chron feed and localStorage-only state. Phase 1 — per-user read + bookmark state: user_story_state table + storage/userstate.go; auth-gated /api/read, /api/bookmark, /api/state and a /bookmarks page; reader.js syncs state server-side for signed-in users. Also hides the Matrix-posting UI when posting.enabled=false (web-only mode). Phase 2 — outbound feeds: storage.ListForFeed + web/feed.go hand-build RSS 2.0 (content:encoded) and JSON Feed 1.1 (no new dep); /feed.xml, /feed.json and per-channel variants; <link rel=alternate> discovery tags. Phase 3 — "For you" + related: storage/rank.go scores recent unread candidates by channel/source affinity + recency decay; RelatedStories via FTS5. ForYou rail + /for-you page; public /api/related feeds the reader's "You might also like". Phase 4 — source-health dashboard: source_health table + storage/sourcehealth.go (RecordPollResult, ListSourceHealth, SourceContentStats), written by the poller; admin-gated /status page behind web.admin_subs. Phase 5 — PWA + offline reader + Web Push: root-scoped manifest.webmanifest and sw.js (app-shell precache, /api/article runtime cache for offline reading, offline fallback, push/notificationclick handlers); PNG icons from pete.avif; pwa.js registers the SW and drives a notifications toggle. Web Push adds webpush-go, a [web.push] config block (pete -genvapid mints VAPID keys), a push_subscriptions table, auth-gated subscribe/unsubscribe endpoints, and a digest sender that pings each subscriber "N new stories" past their watermark, honoring disabled-sources and pruning gone endpoints. Tests added beside each new storage/web file; go test ./... and go vet clean.
153 lines
4.6 KiB
Go
153 lines
4.6 KiB
Go
package storage
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
var (
|
|
mu sync.RWMutex
|
|
globalDB *sql.DB
|
|
)
|
|
|
|
// Init opens (or creates) the SQLite database and runs migrations.
|
|
func Init(dbPath string) error {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
if globalDB != nil {
|
|
return nil
|
|
}
|
|
|
|
dir := filepath.Dir(dbPath)
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return fmt.Errorf("create data dir: %w", err)
|
|
}
|
|
|
|
d, err := sql.Open("sqlite", dbPath+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=foreign_keys(ON)")
|
|
if err != nil {
|
|
return fmt.Errorf("open database: %w", err)
|
|
}
|
|
|
|
d.SetMaxOpenConns(1)
|
|
|
|
if err := runMigrations(d); err != nil {
|
|
return fmt.Errorf("run migrations: %w", err)
|
|
}
|
|
|
|
globalDB = d
|
|
slog.Info("database initialized", "path", dbPath)
|
|
return nil
|
|
}
|
|
|
|
// Get returns the global database handle. Panics if Init was not called.
|
|
func Get() *sql.DB {
|
|
mu.RLock()
|
|
db := globalDB
|
|
mu.RUnlock()
|
|
if db == nil {
|
|
panic("storage.Get() called before storage.Init()")
|
|
}
|
|
return db
|
|
}
|
|
|
|
// Close closes the global database handle.
|
|
func Close() error {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if globalDB != nil {
|
|
err := globalDB.Close()
|
|
globalDB = nil
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func runMigrations(d *sql.DB) error {
|
|
if _, err := d.Exec(schema); err != nil {
|
|
return fmt.Errorf("create schema: %w", err)
|
|
}
|
|
|
|
// Idempotent column adds for DBs created before the dedup columns existed.
|
|
// SQLite errors with "duplicate column name" when the column is already there;
|
|
// we swallow that specifically.
|
|
addColumnIfMissing(d, "stories", "url_canonical", "TEXT")
|
|
addColumnIfMissing(d, "stories", "headline_norm", "TEXT")
|
|
addColumnIfMissing(d, "stories", "paywalled", "INTEGER NOT NULL DEFAULT 0")
|
|
// content holds the full article text (feed content:encoded when present,
|
|
// else the body scraped during paywall detection) for reader mode. Stories
|
|
// ingested before this column existed simply have NULL and fall back to lede.
|
|
addColumnIfMissing(d, "stories", "content", "TEXT")
|
|
addColumnIfMissing(d, "stories", "published_at", "INTEGER")
|
|
addColumnIfMissing(d, "post_log", "url_canonical", "TEXT")
|
|
addColumnIfMissing(d, "post_log", "forced", "INTEGER NOT NULL DEFAULT 0")
|
|
addColumnIfMissing(d, "round_robin_state", "last_channel", "TEXT")
|
|
|
|
// FTS5 virtual tables don't support IF NOT EXISTS reliably.
|
|
// Check sqlite_master before creating.
|
|
var ftsExists int
|
|
if err := d.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='stories_fts'`).Scan(&ftsExists); err != nil {
|
|
return fmt.Errorf("probe FTS5 table: %w", err)
|
|
}
|
|
if ftsExists == 0 {
|
|
if _, err := d.Exec(ftsSchema); err != nil {
|
|
return fmt.Errorf("create FTS5 table: %w", err)
|
|
}
|
|
if _, err := d.Exec(ftsTriggers); err != nil {
|
|
return fmt.Errorf("create FTS5 triggers: %w", err)
|
|
}
|
|
slog.Info("created FTS5 search index")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// RunMaintenance prunes stale data. Called periodically.
|
|
func RunMaintenance() {
|
|
// Prune old stories (30 days) and their post logs / reactions
|
|
storyCutoff := nowUnix() - int64(30*86400)
|
|
exec("prune old stories",
|
|
`DELETE FROM stories WHERE seen_at < ? AND classified = 1`, storyCutoff)
|
|
exec("prune old post_log",
|
|
`DELETE FROM post_log WHERE posted_at < ?`, storyCutoff)
|
|
exec("prune old reactions",
|
|
`DELETE FROM reactions WHERE reacted_at < ?`, storyCutoff)
|
|
|
|
// Drop per-user read/bookmark rows whose story has been pruned above, so the
|
|
// table can't accumulate dangling references as stories age out.
|
|
exec("prune orphan user_story_state",
|
|
`DELETE FROM user_story_state WHERE story_id NOT IN (SELECT id FROM stories)`)
|
|
|
|
// Daily unique tokens are only useful for the recent window; their salts are
|
|
// long gone. page_views is kept forever (tiny aggregate, all-time totals).
|
|
exec("prune old daily_visitors",
|
|
`DELETE FROM daily_visitors WHERE day < ?`, unixDay()-30)
|
|
|
|
exec("wal checkpoint", "PRAGMA wal_checkpoint(TRUNCATE)")
|
|
exec("optimize", "PRAGMA optimize")
|
|
}
|
|
|
|
// exec is a fire-and-forget helper that logs errors.
|
|
func exec(label, query string, args ...any) {
|
|
if _, err := Get().Exec(query, args...); err != nil {
|
|
slog.Error("db exec failed", "op", label, "err", err)
|
|
}
|
|
}
|
|
|
|
func addColumnIfMissing(d *sql.DB, table, column, columnType string) {
|
|
q := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, column, columnType)
|
|
if _, err := d.Exec(q); err != nil {
|
|
// SQLite returns "duplicate column name" when the column already exists.
|
|
if !strings.Contains(err.Error(), "duplicate column name") {
|
|
slog.Error("alter table failed", "table", table, "column", column, "err", err)
|
|
}
|
|
}
|
|
}
|