- Add go.mod and go.sum for dependency management - Implement models for List, Field, Item, ItemValue, SyncRequest, SyncResponse, and NotificationEvent - Create notification handling functions including enqueueNotification and ignoreNotificationError - Implement sync functionality to handle data synchronization between client and server - Add web data handling and notification polling endpoints - Include tests for timestamp normalization and sync logic - Embed web assets for serving the frontend application
330 lines
9.3 KiB
Go
330 lines
9.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// DB owns the PostgreSQL pool. The schema deliberately uses the same physical
|
|
// column names as the existing Node service: PostgreSQL lowercases unquoted
|
|
// camelCase identifiers, so createdAt is stored as createdat, etc.
|
|
type DB struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func connectDB(ctx context.Context, connectionString string) (*DB, error) {
|
|
pool, err := pgxpool.New(ctx, connectionString)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create pool: %w", err)
|
|
}
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping database: %w", err)
|
|
}
|
|
return &DB{pool: pool}, nil
|
|
}
|
|
|
|
func (d *DB) close() {
|
|
d.pool.Close()
|
|
}
|
|
|
|
func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
|
tx, err := d.pool.Begin(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("begin transaction: %w", err)
|
|
}
|
|
defer tx.Rollback(ctx) // harmless after a successful commit
|
|
|
|
if err := fn(tx); err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return fmt.Errorf("commit transaction: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
|
// be used by the Go server without a separate migration step.
|
|
func (d *DB) initSchema(ctx context.Context) error {
|
|
_, err := d.pool.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS lists (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
createdat BIGINT NOT NULL,
|
|
updatedat BIGINT NOT NULL,
|
|
isdeleted INTEGER NOT NULL DEFAULT 0
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS fields (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
fieldtype TEXT NOT NULL,
|
|
fieldoptions TEXT,
|
|
alignment TEXT NOT NULL DEFAULT 'start',
|
|
listid TEXT NOT NULL,
|
|
"order" INTEGER NOT NULL,
|
|
createdat BIGINT NOT NULL,
|
|
updatedat BIGINT NOT NULL,
|
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS items (
|
|
id TEXT PRIMARY KEY,
|
|
listid TEXT NOT NULL,
|
|
createdat BIGINT NOT NULL,
|
|
updatedat BIGINT NOT NULL,
|
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS item_values (
|
|
id TEXT PRIMARY KEY,
|
|
itemid TEXT NOT NULL,
|
|
fieldid TEXT NOT NULL,
|
|
value TEXT,
|
|
updatedat BIGINT NOT NULL,
|
|
FOREIGN KEY (itemid) REFERENCES items(id),
|
|
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_fields_listid ON fields(listid);
|
|
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
|
|
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
|
|
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
|
|
|
|
CREATE TABLE IF NOT EXISTS notifications (
|
|
id TEXT PRIMARY KEY,
|
|
deviceidorigin TEXT,
|
|
eventtype TEXT NOT NULL,
|
|
entitytype TEXT NOT NULL,
|
|
entityid TEXT,
|
|
listid TEXT,
|
|
createdat BIGINT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_notifications_createdat ON notifications(createdat);
|
|
CREATE INDEX IF NOT EXISTS idx_notifications_listid ON notifications(listid);
|
|
|
|
ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';
|
|
|
|
CREATE TABLE IF NOT EXISTS auth_users (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
username TEXT NOT NULL UNIQUE,
|
|
password_hash TEXT NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
|
|
|
CREATE TABLE IF NOT EXISTS auth_sessions (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions(expires_at);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions(user_id);
|
|
|
|
CREATE TABLE IF NOT EXISTS api_tokens (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
|
`)
|
|
if err != nil {
|
|
return fmt.Errorf("initialize schema: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
|
ticker := time.NewTicker(time.Hour)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
|
fmt.Printf("[db] session prune failed: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (d *DB) cleanupNotifications(ctx context.Context) {
|
|
retention := envInt64("NOTIF_RETENTION_MS", 7*24*60*60*1000)
|
|
if retention < 0 {
|
|
retention = 0
|
|
}
|
|
ticker := time.NewTicker(time.Hour)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
cutoff := time.Now().UnixMilli() - retention
|
|
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
|
fmt.Printf("[db] notification cleanup failed: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
type AuthUser struct {
|
|
ID int64
|
|
Username string
|
|
PasswordHash string
|
|
}
|
|
|
|
var ErrSingletonUserExists = errors.New("a user already exists")
|
|
|
|
func (d *DB) countUsers(ctx context.Context) (int, error) {
|
|
var count int
|
|
if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
|
|
return 0, fmt.Errorf("count users: %w", err)
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
func (d *DB) createUser(ctx context.Context, username, passwordHash string) (*AuthUser, error) {
|
|
var user AuthUser
|
|
err := d.pool.QueryRow(ctx, `
|
|
INSERT INTO auth_users (username, password_hash, updated_at)
|
|
VALUES ($1, $2, now())
|
|
RETURNING id, username
|
|
`, username, passwordHash).Scan(&user.ID, &user.Username)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return nil, ErrSingletonUserExists
|
|
}
|
|
return nil, fmt.Errorf("create user: %w", err)
|
|
}
|
|
user.PasswordHash = passwordHash
|
|
return &user, nil
|
|
}
|
|
|
|
func (d *DB) getUserByUsername(ctx context.Context, username string) (*AuthUser, error) {
|
|
var user AuthUser
|
|
err := d.pool.QueryRow(ctx, `
|
|
SELECT id, username, password_hash
|
|
FROM auth_users
|
|
WHERE username = $1
|
|
`, username).Scan(&user.ID, &user.Username, &user.PasswordHash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get user: %w", err)
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
|
|
var user AuthUser
|
|
err := d.pool.QueryRow(ctx, `
|
|
SELECT u.id, u.username, u.password_hash
|
|
FROM auth_sessions s
|
|
JOIN auth_users u ON u.id = s.user_id
|
|
WHERE s.token_hash = $1 AND s.expires_at > now()
|
|
`, tokenHash).Scan(&user.ID, &user.Username, &user.PasswordHash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get session user: %w", err)
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
func (d *DB) createSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
|
|
_, err := d.pool.Exec(ctx, `
|
|
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
|
|
VALUES ($1, $2, $3)
|
|
`, userID, tokenHash, expiresAt)
|
|
if err != nil {
|
|
return fmt.Errorf("create session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
|
|
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash)
|
|
if err != nil {
|
|
return fmt.Errorf("delete session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, passwordHash string) error {
|
|
_, err := d.pool.Exec(ctx, `
|
|
UPDATE auth_users
|
|
SET username = $1, password_hash = $2, updated_at = now()
|
|
WHERE id = $3
|
|
`, username, passwordHash, userID)
|
|
if err != nil {
|
|
return fmt.Errorf("update user credentials: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error {
|
|
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID)
|
|
if err != nil {
|
|
return fmt.Errorf("delete sessions for user: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *DB) hasAPIToken(ctx context.Context, userID int64) (bool, error) {
|
|
var exists bool
|
|
if err := d.pool.QueryRow(ctx, `
|
|
SELECT EXISTS(SELECT 1 FROM api_tokens WHERE user_id = $1)
|
|
`, userID).Scan(&exists); err != nil {
|
|
return false, fmt.Errorf("check API token: %w", err)
|
|
}
|
|
return exists, nil
|
|
}
|
|
|
|
func (d *DB) regenerateAPIToken(ctx context.Context, userID int64, tokenHash string) error {
|
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
|
if _, err := tx.Exec(ctx, `DELETE FROM api_tokens WHERE user_id = $1`, userID); err != nil {
|
|
return fmt.Errorf("delete old API token: %w", err)
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO api_tokens (user_id, token_hash)
|
|
VALUES ($1, $2)
|
|
`, userID, tokenHash); err != nil {
|
|
return fmt.Errorf("insert API token: %w", err)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func (d *DB) getAPITokenUserID(ctx context.Context, tokenHash string) (int64, error) {
|
|
var userID int64
|
|
err := d.pool.QueryRow(ctx, `
|
|
SELECT user_id FROM api_tokens WHERE token_hash = $1
|
|
`, tokenHash).Scan(&userID)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return 0, nil
|
|
}
|
|
if err != nil {
|
|
return 0, fmt.Errorf("get API token owner: %w", err)
|
|
}
|
|
return userID, nil
|
|
}
|