Files
plezy/lib/connection/connection_registry.dart
edde746 cb55134cef fix(startup): move optional work off the launch gate
Cold start on the target TV box reaches its first frame 21 ms after `dart_main`,
so nothing Dart-side gates the splash. Everything below is on the path to the
first *useful* frame, which is a strictly serial chain and where the viewer
actually waits.

- `monoTheme` is a pure function of two bools that builds a full `ColorScheme`, an
  applied-and-copied 15-style `TextTheme`, ~14 sub-themes and then clones the whole
  `ThemeData` again. It was rebuilt five times per cold start, two of them before
  `runApp`, and twice more per app-shell rebuild. It is memoized now, keyed by
  palette plus `TargetPlatform` -- the platform matters because `ThemeData()`
  derives tap target size, visual density and typography from
  `defaultTargetPlatform`, so a palette-only key would be wrong under a debug or
  test platform override.
- `initializeDateFormatting` ignores its locale argument and builds CLDR symbols
  and patterns for all 121 locales synchronously. It blocked the gate ahead of the
  database open for data that only content screens use.
- `DownloadStorageService.initialize` ended in a `path_provider` round trip plus
  mkdir at the tail of the gate, contradicting the comment above it that already
  explained offline artwork is not a launch requirement.
- `recoverInterruptedDownloads()` and `TrackerCoordinator.initialize()` ran from
  `initState` of the widget whose first build produces the first app frame, and
  the RSS watchdog installed a periodic timer there whose first useful sample is
  15 s away regardless.
- `CredentialVault` decrypted every token with pure-Dart AES-GCM on the main
  isolate, uncached, on every registry read and on every Drift re-emit -- and the
  binder writes tokens during the startup sweep, so writes re-triggered reads.
  Decryption is memoized by ciphertext, with `invalidateCache()` wired into the
  preference-store repair path so a repaired install cannot serve stale plaintext.
- `reloadFromStorage` now coalesces in-flight callers. The two serial awaits around
  the legacy migration are deliberately not merged; only genuinely concurrent
  callers share a snapshot.
- `_sameConnections` ran two `jsonEncode` calls per connection on every Drift emit
  purely to compare, allocating two maps and two strings each time.
- The splash rendered one `CircularProgressIndicator` per pending server on top of
  the aggregate one, so N+1 tickers scheduled a frame every vsync for the whole of
  `awaitBindingSettle` -- competing with the startup work they were reporting on.

Measured on device in a settled dexopt state: time to `main_screen` 1495 -> 1400 ms,
`credentials_loaded` 1238 -> 1128 ms, `database_ready` 501 -> 443 ms. First frame is
unchanged at ~18 ms, as expected.
2026-08-23 18:13:39 +02:00

149 lines
5.9 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:drift/drift.dart';
import '../database/app_database.dart';
import '../media/media_backend.dart';
import '../services/credential_vault.dart';
import '../utils/app_logger.dart';
import 'connection.dart';
/// CRUD over the persisted [Connections] table. The registry is the source
/// of truth for which connections the user has added; the runtime
/// `MultiServerManager` populates per-server clients from these records.
class ConnectionRegistry {
ConnectionRegistry(this._db);
final AppDatabase _db;
static const DeepCollectionEquality _configEquality = DeepCollectionEquality();
final Expando<Map<String, Object?>> _decryptedConfigs = Expando<Map<String, Object?>>(
'ConnectionRegistry.decryptedConfigs',
);
/// Compares the decrypted persisted config projections retained while rows
/// are decoded. The fallback covers models supplied outside this registry.
bool hasSameConfig(Connection a, Connection b) {
final aConfig = _decryptedConfigs[a] ??= a.toConfigJson();
final bConfig = _decryptedConfigs[b] ??= b.toConfigJson();
return _configEquality.equals(aConfig, bConfig);
}
/// Emits the current set of connections after every mutation. Drift's
/// `watch()` provides this for free.
Stream<List<Connection>> watchConnections() {
return (_db.select(_db.connections)..orderBy([(t) => OrderingTerm.asc(t.createdAt)])).watch().asyncMap(
(rows) async => (await Future.wait(rows.map(_rowToConnection))).whereType<Connection>().toList(),
);
}
/// One-shot fetch of all stored connections.
Future<List<Connection>> list() async {
final rows = await (_db.select(_db.connections)..orderBy([(t) => OrderingTerm.asc(t.createdAt)])).get();
return (await Future.wait(rows.map(_rowToConnection))).whereType<Connection>().toList();
}
/// Lookup a connection by id.
Future<Connection?> get(String id) async {
final row = await (_db.select(_db.connections)..where((t) => t.id.equals(id))).getSingleOrNull();
if (row == null) return null;
return _rowToConnection(row);
}
/// Insert or replace [connection]. Re-upserting an existing row keeps the
/// row's current `createdAt` (so token/metadata refreshes don't restamp
/// creation order).
///
/// Creation order is behaviour, not bookkeeping: it decides which
/// connection lends a profile its picture. Re-authenticating rebuilds the
/// model with `DateTime.now()` and reuses the same stable id, so without
/// this the originally-first connection would jump to last on every
/// re-sign-in.
Future<void> upsert(Connection connection) async {
await _db.runIdentityMutation(() async {
final existing = await (_db.select(_db.connections)..where((t) => t.id.equals(connection.id))).getSingleOrNull();
final createdAt = existing?.createdAt ?? connection.createdAt.millisecondsSinceEpoch;
final protectedConfig = await CredentialVault.protectConnectionConfig(
connection.kind.id,
connection.toConfigJson(),
);
final row = ConnectionsCompanion(
id: Value(connection.id),
kind: Value(connection.kind.id),
displayName: Value(connection.displayName),
configJson: Value(jsonEncode(protectedConfig)),
createdAt: Value(createdAt),
lastAuthenticatedAt: Value(connection.lastAuthenticatedAt?.millisecondsSinceEpoch),
);
await _db.into(_db.connections).insertOnConflictUpdate(row);
});
appLogger.d('ConnectionRegistry: upserted ${connection.kind.id}/${connection.id}');
}
/// Remove a stored connection.
Future<void> remove(String id) async {
await _db.runIdentityMutation(() async {
await (_db.delete(_db.connections)..where((t) => t.id.equals(id))).go();
});
appLogger.d('ConnectionRegistry: removed $id');
}
Future<void> clear() async {
await _db.runIdentityMutation(() async {
await _db.delete(_db.connections).go();
});
}
/// All Plex accounts in insertion order. Convenience over
/// `(await list()).whereType<PlexAccountConnection>()` — cuts ~3 lines from
/// every caller that needs to filter by backend.
Future<List<PlexAccountConnection>> listPlexAccounts() async {
final all = await list();
return all.whereType<PlexAccountConnection>().toList();
}
/// Lookup a [PlexAccountConnection] by id. Returns `null` if no row
/// matches OR the row exists but isn't a Plex account.
Future<PlexAccountConnection?> getPlexAccount(String id) async {
final c = await get(id);
return c is PlexAccountConnection ? c : null;
}
Future<Connection?> _rowToConnection(ConnectionRow row) async {
try {
final json = jsonDecode(row.configJson) as Map<String, dynamic>;
final kind = MediaBackend.fromId(row.kind);
final revealed = await CredentialVault.revealConnectionConfig(kind.id, json);
final createdAt = DateTime.fromMillisecondsSinceEpoch(row.createdAt);
final lastAuth = row.lastAuthenticatedAt == null
? null
: DateTime.fromMillisecondsSinceEpoch(row.lastAuthenticatedAt!);
final connection = switch (kind) {
MediaBackend.plex => PlexAccountConnection.fromConfigJson(
id: row.id,
json: revealed.config,
createdAt: createdAt,
lastAuthenticatedAt: lastAuth,
),
MediaBackend.jellyfin || MediaBackend.emby => JellyfinConnection.fromConfigJson(
id: row.id,
json: revealed.config,
createdAt: createdAt,
lastAuthenticatedAt: lastAuth,
dialect: kind.dialect!,
),
};
_decryptedConfigs[connection] = revealed.config;
if (revealed.migrated) {
await upsert(connection);
}
return connection;
} catch (e, st) {
appLogger.e('ConnectionRegistry: failed to decode connection ${row.id}', error: e, stackTrace: st);
return null;
}
}
}