2026-07-27 08:16:20 +12:00
|
|
|
// Package store persists gateway sessions in Postgres.
|
|
|
|
|
package store
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
_ "embed"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
//go:embed schema.sql
|
|
|
|
|
var schema string
|
|
|
|
|
|
|
|
|
|
// ErrNotFound is returned when a token does not match a live session.
|
|
|
|
|
var ErrNotFound = errors.New("store: session not found")
|
2026-07-27 21:06:51 +12:00
|
|
|
var ErrDeviceLimit = errors.New("store: device limit reached")
|
2026-07-27 08:16:20 +12:00
|
|
|
|
|
|
|
|
type Session struct {
|
2026-07-29 15:26:27 +12:00
|
|
|
TokenHash []byte
|
|
|
|
|
EmbyUserID string
|
|
|
|
|
EmbyToken string
|
|
|
|
|
Username string
|
|
|
|
|
ServerID string
|
|
|
|
|
DeviceID string
|
|
|
|
|
DeviceName string
|
|
|
|
|
ClientVersion string
|
|
|
|
|
ClientProtocol string
|
|
|
|
|
LastSeenAt time.Time
|
2026-07-27 08:16:20 +12:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type Store struct {
|
|
|
|
|
pool *pgxpool.Pool
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func Open(ctx context.Context, databaseURL string) (*Store, error) {
|
|
|
|
|
pool, err := pgxpool.New(ctx, databaseURL)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("store: connect: %w", err)
|
|
|
|
|
}
|
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
|
|
|
pool.Close()
|
|
|
|
|
return nil, fmt.Errorf("store: ping: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return &Store{pool: pool}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *Store) Close() { s.pool.Close() }
|
|
|
|
|
|
|
|
|
|
func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(ctx) }
|
|
|
|
|
|
2026-07-29 15:26:27 +12:00
|
|
|
// RecordSearch stores a normalized query for future per-user ranking analysis.
|
|
|
|
|
func (s *Store) RecordSearch(ctx context.Context, userID, query string) error {
|
|
|
|
|
_, err := s.pool.Exec(ctx,
|
|
|
|
|
`WITH inserted AS (
|
|
|
|
|
INSERT INTO search_history (emby_user_id, query) VALUES ($1, $2)
|
|
|
|
|
RETURNING id
|
|
|
|
|
)
|
|
|
|
|
DELETE FROM search_history
|
|
|
|
|
WHERE emby_user_id = $1
|
|
|
|
|
AND occurred_at < now() - interval '30 days'`,
|
|
|
|
|
userID, query)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RecentSearches returns a user's distinct queries in most-recently-used order.
|
|
|
|
|
// Case-only duplicates collapse to the spelling used most recently.
|
|
|
|
|
func (s *Store) RecentSearches(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
userID string,
|
|
|
|
|
since time.Time,
|
|
|
|
|
limit int,
|
|
|
|
|
) ([]string, error) {
|
|
|
|
|
rows, err := s.pool.Query(ctx, `
|
|
|
|
|
SELECT query
|
|
|
|
|
FROM (
|
|
|
|
|
SELECT DISTINCT ON (lower(query)) query, occurred_at
|
|
|
|
|
FROM search_history
|
|
|
|
|
WHERE emby_user_id = $1 AND occurred_at >= $2
|
|
|
|
|
ORDER BY lower(query), occurred_at DESC
|
|
|
|
|
) AS latest
|
|
|
|
|
ORDER BY occurred_at DESC
|
|
|
|
|
LIMIT $3`,
|
|
|
|
|
userID, since, limit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("store: recent searches: %w", err)
|
|
|
|
|
}
|
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
|
|
queries := make([]string, 0, limit)
|
|
|
|
|
for rows.Next() {
|
|
|
|
|
var query string
|
|
|
|
|
if err := rows.Scan(&query); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("store: scan recent search: %w", err)
|
|
|
|
|
}
|
|
|
|
|
queries = append(queries, query)
|
|
|
|
|
}
|
|
|
|
|
if err := rows.Err(); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("store: read recent searches: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return queries, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-27 08:16:20 +12:00
|
|
|
// Migrate applies the schema. It is idempotent, so it runs on every boot.
|
|
|
|
|
func (s *Store) Migrate(ctx context.Context) error {
|
|
|
|
|
if _, err := s.pool.Exec(ctx, schema); err != nil {
|
|
|
|
|
return fmt.Errorf("store: migrate: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-27 21:06:51 +12:00
|
|
|
// CreateSession enforces a user's device allowance under a per-user transaction lock.
|
|
|
|
|
// Re-authenticating the same stable device replaces its token and never consumes a slot.
|
|
|
|
|
// The replaced hash is returned so its Redis entry can be invalidated immediately.
|
|
|
|
|
func (s *Store) CreateSession(ctx context.Context, sess Session, maxClients int) ([]byte, int, error) {
|
|
|
|
|
tx, err := s.pool.Begin(ctx)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, fmt.Errorf("store: begin session: %w", err)
|
|
|
|
|
}
|
|
|
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
|
|
|
|
|
|
|
|
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, sess.EmbyUserID); err != nil {
|
|
|
|
|
return nil, 0, fmt.Errorf("store: lock user sessions: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var previousHash []byte
|
|
|
|
|
err = tx.QueryRow(ctx, `
|
|
|
|
|
SELECT token_hash FROM sessions
|
|
|
|
|
WHERE emby_user_id = $1 AND device_id = $2`,
|
|
|
|
|
sess.EmbyUserID, sess.DeviceID).Scan(&previousHash)
|
|
|
|
|
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
|
|
|
|
return nil, 0, fmt.Errorf("store: find device session: %w", err)
|
|
|
|
|
}
|
|
|
|
|
existingDevice := err == nil
|
|
|
|
|
|
|
|
|
|
var activeClients int
|
|
|
|
|
if err := tx.QueryRow(ctx,
|
|
|
|
|
`SELECT count(*) FROM sessions WHERE emby_user_id = $1`,
|
|
|
|
|
sess.EmbyUserID).Scan(&activeClients); err != nil {
|
|
|
|
|
return nil, 0, fmt.Errorf("store: count user sessions: %w", err)
|
|
|
|
|
}
|
|
|
|
|
if !existingDevice && activeClients >= maxClients {
|
|
|
|
|
return nil, activeClients, ErrDeviceLimit
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
|
|
|
INSERT INTO sessions (
|
2026-07-29 15:26:27 +12:00
|
|
|
token_hash, emby_user_id, emby_token, username, server_id, device_id, device_name,
|
|
|
|
|
client_version, client_protocol
|
2026-07-27 21:06:51 +12:00
|
|
|
)
|
2026-07-29 15:26:27 +12:00
|
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
2026-07-27 21:06:51 +12:00
|
|
|
ON CONFLICT (emby_user_id, device_id) DO UPDATE SET
|
|
|
|
|
token_hash = EXCLUDED.token_hash,
|
2026-07-27 08:16:20 +12:00
|
|
|
emby_token = EXCLUDED.emby_token,
|
|
|
|
|
username = EXCLUDED.username,
|
|
|
|
|
server_id = EXCLUDED.server_id,
|
2026-07-27 21:06:51 +12:00
|
|
|
device_name = EXCLUDED.device_name,
|
2026-07-29 15:26:27 +12:00
|
|
|
client_version = EXCLUDED.client_version,
|
|
|
|
|
client_protocol = EXCLUDED.client_protocol,
|
2026-07-27 08:16:20 +12:00
|
|
|
last_seen_at = now()`,
|
2026-07-27 21:06:51 +12:00
|
|
|
sess.TokenHash, sess.EmbyUserID, sess.EmbyToken, sess.Username,
|
2026-07-29 15:26:27 +12:00
|
|
|
sess.ServerID, sess.DeviceID, sess.DeviceName, sess.ClientVersion, sess.ClientProtocol)
|
2026-07-27 08:16:20 +12:00
|
|
|
if err != nil {
|
2026-07-27 21:06:51 +12:00
|
|
|
return nil, 0, fmt.Errorf("store: create session: %w", err)
|
2026-07-27 08:16:20 +12:00
|
|
|
}
|
2026-07-27 21:06:51 +12:00
|
|
|
if !existingDevice {
|
|
|
|
|
activeClients++
|
|
|
|
|
}
|
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
|
|
|
return nil, 0, fmt.Errorf("store: commit session: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return previousHash, activeClients, nil
|
2026-07-27 08:16:20 +12:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *Store) SessionByTokenHash(ctx context.Context, hash []byte) (Session, error) {
|
|
|
|
|
var sess Session
|
|
|
|
|
err := s.pool.QueryRow(ctx, `
|
2026-07-29 15:26:27 +12:00
|
|
|
SELECT token_hash, emby_user_id, emby_token, username, server_id, device_id,
|
|
|
|
|
device_name, client_version, client_protocol, last_seen_at
|
2026-07-27 08:16:20 +12:00
|
|
|
FROM sessions WHERE token_hash = $1`, hash).
|
|
|
|
|
Scan(&sess.TokenHash, &sess.EmbyUserID, &sess.EmbyToken, &sess.Username,
|
2026-07-29 15:26:27 +12:00
|
|
|
&sess.ServerID, &sess.DeviceID, &sess.DeviceName, &sess.ClientVersion,
|
|
|
|
|
&sess.ClientProtocol, &sess.LastSeenAt)
|
2026-07-27 08:16:20 +12:00
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
|
|
|
return Session{}, ErrNotFound
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return Session{}, fmt.Errorf("store: load session: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return sess, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Touch records activity. Cheap enough to call on the auth path, and it is what the
|
|
|
|
|
// idle-expiry sweep reads.
|
|
|
|
|
func (s *Store) Touch(ctx context.Context, hash []byte) error {
|
|
|
|
|
_, err := s.pool.Exec(ctx, `UPDATE sessions SET last_seen_at = now() WHERE token_hash = $1`, hash)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 15:26:27 +12:00
|
|
|
// UpdateSessionClientIdentity remembers the last non-empty identity supplied by a TV.
|
|
|
|
|
// Headerless image requests can then still be attributed to the correct app build.
|
|
|
|
|
func (s *Store) UpdateSessionClientIdentity(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
hash []byte,
|
|
|
|
|
version, protocol string,
|
|
|
|
|
) error {
|
|
|
|
|
_, err := s.pool.Exec(ctx, `
|
|
|
|
|
UPDATE sessions
|
|
|
|
|
SET client_version = CASE WHEN $2 <> '' THEN $2 ELSE client_version END,
|
|
|
|
|
client_protocol = CASE WHEN $3 <> '' THEN $3 ELSE client_protocol END,
|
|
|
|
|
last_seen_at = now()
|
|
|
|
|
WHERE token_hash = $1`,
|
|
|
|
|
hash, version, protocol)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-27 08:16:20 +12:00
|
|
|
func (s *Store) DeleteSession(ctx context.Context, hash []byte) error {
|
|
|
|
|
_, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash = $1`, hash)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DeleteIdleSessions retires tokens unused for longer than idle, returning how many went.
|
|
|
|
|
func (s *Store) DeleteIdleSessions(ctx context.Context, idle time.Duration) (int64, error) {
|
|
|
|
|
tag, err := s.pool.Exec(ctx,
|
|
|
|
|
`DELETE FROM sessions WHERE last_seen_at < now() - $1::interval`,
|
|
|
|
|
fmt.Sprintf("%d seconds", int64(idle.Seconds())))
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
return tag.RowsAffected(), nil
|
|
|
|
|
}
|
2026-07-27 21:06:51 +12:00
|
|
|
|
|
|
|
|
// TrimSessionsToLimit brings data created under an older, more generous policy back
|
|
|
|
|
// within the current allowance. The most recently active devices survive.
|
|
|
|
|
func (s *Store) TrimSessionsToLimit(ctx context.Context, maxClients int) ([]Session, error) {
|
|
|
|
|
rows, err := s.pool.Query(ctx, `
|
|
|
|
|
WITH ranked AS (
|
|
|
|
|
SELECT token_hash,
|
|
|
|
|
row_number() OVER (
|
|
|
|
|
PARTITION BY emby_user_id
|
|
|
|
|
ORDER BY last_seen_at DESC, created_at DESC, token_hash DESC
|
|
|
|
|
) AS device_rank
|
|
|
|
|
FROM sessions
|
|
|
|
|
),
|
|
|
|
|
retired AS (
|
|
|
|
|
DELETE FROM sessions current
|
|
|
|
|
USING ranked
|
|
|
|
|
WHERE current.token_hash = ranked.token_hash
|
|
|
|
|
AND ranked.device_rank > $1
|
|
|
|
|
RETURNING current.token_hash, current.emby_user_id, current.emby_token,
|
|
|
|
|
current.username, current.server_id, current.device_id,
|
2026-07-29 15:26:27 +12:00
|
|
|
current.device_name, current.client_version, current.client_protocol,
|
|
|
|
|
current.last_seen_at
|
2026-07-27 21:06:51 +12:00
|
|
|
)
|
|
|
|
|
SELECT token_hash, emby_user_id, emby_token, username, server_id,
|
2026-07-29 15:26:27 +12:00
|
|
|
device_id, device_name, client_version, client_protocol, last_seen_at
|
2026-07-27 21:06:51 +12:00
|
|
|
FROM retired`,
|
|
|
|
|
maxClients,
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("store: trim sessions: %w", err)
|
|
|
|
|
}
|
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
|
|
var retired []Session
|
|
|
|
|
for rows.Next() {
|
|
|
|
|
var sess Session
|
|
|
|
|
if err := rows.Scan(
|
|
|
|
|
&sess.TokenHash, &sess.EmbyUserID, &sess.EmbyToken, &sess.Username,
|
2026-07-29 15:26:27 +12:00
|
|
|
&sess.ServerID, &sess.DeviceID, &sess.DeviceName, &sess.ClientVersion,
|
|
|
|
|
&sess.ClientProtocol, &sess.LastSeenAt,
|
2026-07-27 21:06:51 +12:00
|
|
|
); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("store: scan trimmed session: %w", err)
|
|
|
|
|
}
|
|
|
|
|
retired = append(retired, sess)
|
|
|
|
|
}
|
|
|
|
|
if err := rows.Err(); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("store: trim sessions rows: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return retired, nil
|
|
|
|
|
}
|