Files
iptvnator/libs/shared/database
4grayandClaude Opus 5.5 b88a1c81e5 feat(self-hosted): server storage API in web-backend (#1898)
* feat(interfaces): add the server storage HTTP contract

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(web-backend): read server storage configuration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(web-backend): open the server database and track revisions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(web-backend): playlist and user-state repositories

Playlist documents use the shared desktop row codec, so the server writes
the same rows. keepPayload upserts take the stored playlist/items/header
fields when the client leaves them out. Xtream user data lives in the
server-only server_user_state table, one JSON value per namespace and
playlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(web-backend): storage error mapping and access token guard

Storage errors map to JSON status bodies and are logged by name and code
only. An optional bearer token guards every route except /, /health,
/config.js and /v1/instance, provider proxy routes included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(web-backend): serve the /v1 server storage API

/v1/instance is always public and reports whether server storage is on.
With storage, /v1/playlists serves whole documents with ETags and 304s,
accepts keepPayload upserts, and deletes playlists with their user state;
/v1/user-state and /v1/app-state store the rest. The proxy routes are
unchanged unless an access token is configured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(web-backend): open server storage on start and close on shutdown

With IPTVNATOR_STORAGE=server, main.ts opens the database before it
listens and exits with a clear message when the data directory is not
writable. SIGTERM and SIGINT close the server and the database. The
native better-sqlite3 module stays outside the esbuild bundle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web-backend): match weakened ETags on playlist reads

nginx weakens the ETag of a gzipped response, and clients send the weak
form back in If-None-Match. The route now compares tags weakly, as RFC 9110
requires for GET, so it answers 304 before reading the document.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(docker): persist server storage on a volume

The image builds better-sqlite3 in a native stage per target platform,
enables server storage on the /data volume, and raises the nginx body
limit to 64 MB for /api with gzip for JSON. The compose file mounts a
named volume and documents the optional access token. The PWA does not
use the storage yet; docs say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(web-backend): type the storage route responses

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web-backend): harden server storage reads, deletes and app state

- Metadata reads return the stored document without its payload fields,
  so fields that live only in the JSON survive a metadata round-trip.
- A conditional GET checks that the playlist exists before answering 304.
- Deleting a playlist and its user state commits in one transaction; the
  ETag moves only after the commit.
- Browser app state is stored under a client: prefix and the instance id
  is repaired when empty, so a client write cannot stop the backend.
- User-state buckets have no prototype, so ids like __proto__ round-trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(self-hosted): keep the access token unset until the PWA sends it

Add the release note for the Docker server storage volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web-backend): bound shutdown and reject padded playlist ids

- SIGTERM closes idle connections at once and cuts the rest after five
  seconds, so a long provider download cannot keep the backend running.
- Playlist ids with surrounding whitespace are rejected: the row codec
  trims ids, so storage and ETags would track different keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web-backend): clear optional columns on whole-document upserts

The row codec maps empty values to undefined, which ON CONFLICT DO UPDATE
skips, so a cleared User-Agent, Referrer or credential kept its old column
value and came back on the next read. Server upserts now write NULL to
every replaceable column the document no longer sets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(self-hosted): linear token parsing, no-store app state, longer start

- The access guard reads the Bearer token by string scanning instead of a
  regular expression that CodeQL flagged as polynomial on long whitespace.
- GET /v1/app-state/:key sends Cache-Control: no-store like the other
  state routes, so devices never reuse a stale value.
- The entrypoint waits up to IPTVNATOR_BACKEND_START_TIMEOUT (300 s) for
  /health, because the backend migrates its database before it listens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(self-hosted): metadata reads skip payloads, redact JSON parse warnings

List playlist metadata from a server-only payload-free copy of each
document instead of running json_remove over every payload blob, and log
only the error name when a stored JSON value fails to parse, since the
parser's message quotes the stored text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web-backend): copy carried-over panel clock into playlist metadata

When an upsert keeps the stored serverTimezone, build the metadata copy
from the saved payload so metadata and full reads agree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 00:05:35 +02:00
..

Database

Shared database library for IPTVnator providing Drizzle ORM schema and connection utilities.

Usage

// Full access (electron-backend)
import { getDatabase, initDatabase } from '@iptvnator/shared/database';

// Read-only access (agent-backend)
import { getReadOnlyDatabase } from '@iptvnator/shared/database';

// Schema and types
import { content, categories, playlists, type Content } from '@iptvnator/shared/database';

Exports

Schema (schema.ts)

  • Tables: playlists, categories, content, recentlyViewed, favorites
  • Types: Playlist, Category, Content, RecentlyViewed, Favorite (and New* variants)

Connection (connection.ts)

  • getDatabase(options?) - Full read-write access
  • getReadOnlyDatabase() - Read-only access for agent queries
  • initDatabase(options?) - Initialize with custom options
  • closeDatabase() - Close connection
  • getDatabasePath() - Get database file path

Connection observer (connection-observer.ts)

  • setDatabaseConnectionObserver(observer | null) - Called by initDatabase with each connection it opens, before any statement runs on it. The Electron main process registers one only with IPTVNATOR_PERF_CAPTURE=1, to count main-thread SQL statements. The module has no runtime dependencies and is also importable as @iptvnator/shared/database/connection-observer.

Database Location

The SQLite database is stored at <data root>/databases/iptvnator.db. The data root is resolved in this order:

  1. IPTVNATOR_E2E_DATA_DIR (E2E runs only)
  2. IPTVNATOR_DATA_DIR (an operator-selected data root for deployments with a mounted volume, for example /data)
  3. ~/.iptvnator

Upgrade Compatibility And Migrations

Users may skip releases. The application must apply every required migration in dependency order when opening an older database, preserving user data without requiring intermediate application installations or a database reset. This is the repository policy mirrored in AGENTS.md and CLAUDE.md.

src/lib/connection.ts owns initialization: createTables() creates missing schema objects, then runMigrations() applies column/index migrations and dedicated schema/data upgrades. One-off data migrations can record completion in app_state. Keep existing migration paths when adding new ones.

When changing initialization:

  • Create required tables before migrating them. CREATE TABLE IF NOT EXISTS leaves existing columns unchanged.
  • Add missing columns before creating indexes or triggers, or running queries, that depend on those columns. Put indexes depending on migrated columns in INDEX_MIGRATION_STATEMENTS, after COLUMN_MIGRATION_STATEMENTS, rather than in the earlier schema creation phase.
  • Preserve existing data and make migrations safe on repeated startup. Record completion only after the associated migration succeeds.
  • Exercise the actual initialization path with real SQLite and historical schema fixtures containing representative playlists, favorites, history, and playback positions. Verify both schema changes and preservation of those rows; mocked SQL calls alone do not establish upgrade compatibility.
  • Include direct upgrades across skipped releases, the previous release, a fresh install, and repeated startup. If a release changes migration ordering, cover each distinct affected historical schema.

Two startup costs found on a 4 GB profile (3.9M catalog titles, 182 playlists) are guarded in runMigrations():

  • deduplicateXtreamCache() returns at once when both unique indexes (src/lib/xtream-cache-unique-indexes.ts: categories_playlist_type_xtream_unique, content_category_type_xtream_unique) exist: they make duplicates impossible, and its two GROUP BY ... HAVING COUNT(*) > 1 scans cost a full pass over content on every launch otherwise (7.8 s cold on that profile). A profile whose unique index could not be created yet still gets the repair.
  • payload must be the last column of playlists (PLAYLISTS_COLUMNS in src/lib/playlists-table.ts): SQLite reads a row's columns in order and walks the overflow pages of every column before the one it needs, so a column after an M3U payload costs the whole payload on each read (getAppPlaylistMetas took 4-22 s for 70 MB of payloads). Tables created before 0.19 got payload appended by ALTER TABLE with the EPG URL columns after it, and fresh installs up to 0.24 created last_usage after it; ensurePlaylistsPayloadLast() rebuilds such a table once (new table, copy, drop, rename, with foreign keys off) and is a no-op afterwards. It commits only if the tables referencing playlists hold no more foreign key violations than before; rows a legacy profile already orphaned do not block it. src/lib/playlists-table.spec.ts runs the rebuild and its rollback on real SQLite. The rebuild rewrites every payload, about 4 s on that profile; later starts open the database in about 40 ms instead of 5-8 s. Never append a column after payload; add it to PLAYLISTS_COLUMNS before payload and to COLUMN_MIGRATION_STATEMENTS, and the rebuild moves it on the next start.

The #1580 index-ordering fix is included in 0.24 through PR #1550. src/lib/connection-upgrades.spec.ts exercises initDatabase() with real SQLite under the Electron runtime, using fresh-install schema snapshots from tags 0.19–0.23 and a fresh current database. The epg_channel_id column is absent in 0.19, present from 0.20, and indexed from 0.23. Each case checks current Drizzle tables, columns/types, and named indexes/uniqueness, as well as preserved user rows, foreign keys, database integrity, index availability, and repeated startup; an existing EPG index must keep its definition and root page, and payload must end up as the last playlists column (the 0.19 snapshot reaches the current schema through the ALTER list, so it reproduces an upgraded profile's order). Snapshots live in src/lib/testing/fixtures/ and are independent of the current schema, so moving the index ahead of its column migration makes the 0.19 case fail again.

Run this coverage with pnpm nx test database --runInBand. The Electron UI and worker upgrade flow is also covered by pnpm nx run electron-backend-e2e:e2e-ci--src/legacy-playlist-migration.e2e.ts.