Add immutable server catalog and versioned preference store

This commit is contained in:
2026-10-24 02:23:49 +01:00
parent 54f74ade33
commit 289a971b73
4 changed files with 515 additions and 0 deletions
+137
View File
@@ -0,0 +1,137 @@
import '../transport/server_url.dart';
/// One logical server; endpoints are primary first, then ordered backups.
class SavedServer {
SavedServer._(this.id, this.name, Iterable<String> endpoints)
: endpoints = List.unmodifiable(endpoints);
factory SavedServer.validated({
required String id,
required String name,
required Iterable<String> endpoints,
}) {
final cleanId = id.trim();
final cleanName = name.trim();
if (cleanId.isEmpty || cleanName.isEmpty) {
throw const FormatException('A server needs a nonempty id and name.');
}
final normalized = <String>{};
for (final endpoint in endpoints) {
normalized.add(ServerUrl.validate(endpoint).wsUrl);
}
if (normalized.isEmpty) {
throw const FormatException('A server needs at least one endpoint.');
}
return SavedServer._(cleanId, cleanName, normalized);
}
final String id;
final String name;
final List<String> endpoints;
Map<String, Object?> toJson() => {
'id': id,
'name': name,
'endpoints': endpoints.toList(),
};
factory SavedServer.fromJson(Map<String, dynamic> json) {
final id = json['id'];
final name = json['name'];
final endpoints = json['endpoints'];
if (id is! String ||
name is! String ||
endpoints is! List ||
endpoints.any((endpoint) => endpoint is! String)) {
throw const FormatException('Invalid saved server.');
}
return SavedServer.validated(
id: id,
name: name,
endpoints: endpoints.cast<String>(),
);
}
}
/// Immutable profiles with no implicit switching between logical servers.
class ServerCatalog {
factory ServerCatalog({
List<SavedServer> servers = const [],
String? selectedId,
}) {
final ids = <String>{};
final endpoints = <String>{};
for (final server in servers) {
if (!ids.add(server.id)) {
throw const FormatException('Duplicate server id.');
}
for (final endpoint in server.endpoints) {
if (!endpoints.add(endpoint)) {
throw const FormatException(
'An endpoint cannot belong to multiple servers.',
);
}
}
}
if (selectedId != null && !ids.contains(selectedId)) {
throw const FormatException('Selected server does not exist.');
}
return ServerCatalog._(servers, selectedId);
}
ServerCatalog._(Iterable<SavedServer> servers, this.selectedId)
: servers = List.unmodifiable(servers);
final List<SavedServer> servers;
final String? selectedId;
SavedServer? get active {
for (final server in servers) {
if (server.id == selectedId) return server;
}
return null;
}
/// Replacing a profile retains its position and the explicit selection.
ServerCatalog upsert(SavedServer server) {
final updated = servers.toList();
final index = updated.indexWhere((entry) => entry.id == server.id);
if (index < 0) {
updated.add(server);
} else {
updated[index] = server;
}
return ServerCatalog(servers: updated, selectedId: selectedId);
}
ServerCatalog select(String id) =>
ServerCatalog(servers: servers, selectedId: id);
/// Never fall back to a different logical server when removing a profile.
ServerCatalog remove(String id) => ServerCatalog(
servers: servers.where((server) => server.id != id).toList(),
selectedId: selectedId == id ? null : selectedId,
);
Map<String, Object?> toJson() => {
'servers': servers.map((server) => server.toJson()).toList(),
'selectedId': selectedId,
};
factory ServerCatalog.fromJson(Map<String, dynamic> json) {
final servers = json['servers'];
final selectedId = json['selectedId'];
if (servers is! List || (selectedId != null && selectedId is! String)) {
throw const FormatException('Invalid server catalog.');
}
return ServerCatalog(
servers: servers.map((server) {
if (server is! Map<String, dynamic>) {
throw const FormatException('Invalid saved server.');
}
return SavedServer.fromJson(server);
}).toList(),
selectedId: selectedId as String?,
);
}
}
@@ -0,0 +1,85 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'server_catalog.dart';
const String serverCatalogKey = 'pipelines.next.serverCatalog.v1';
abstract interface class ServerCatalogStore {
Future<ServerCatalog> load({String legacyEndpoint = ''});
Future<bool> save(ServerCatalog catalog);
}
ServerCatalog _migrate(String legacyEndpoint) {
if (legacyEndpoint.trim().isEmpty) return ServerCatalog();
return ServerCatalog(
servers: [
SavedServer.validated(
id: 'legacy-server',
name: 'My server',
endpoints: [legacyEndpoint],
),
],
selectedId: 'legacy-server',
);
}
/// A single versioned JSON value keeps profiles and selection together.
///
/// Load is read-only, including legacy migration. The caller explicitly saves
/// the migrated catalog; the old endpoint preference is never changed here.
/// Read failures (including corruption or unknown versions) are surfaced, not
/// disguised as an empty catalog that a subsequent save could overwrite.
class SharedPreferencesServerCatalogStore implements ServerCatalogStore {
const SharedPreferencesServerCatalogStore();
@override
Future<ServerCatalog> load({String legacyEndpoint = ''}) async {
final preferences = await SharedPreferences.getInstance();
if (!preferences.containsKey(serverCatalogKey)) {
return _migrate(legacyEndpoint);
}
final raw = preferences.get(serverCatalogKey);
if (raw is! String) {
throw const FormatException('Saved server catalog is not JSON text.');
}
final json = jsonDecode(raw);
if (json is! Map<String, dynamic> || json['version'] != 1) {
throw const FormatException('Unsupported server catalog format.');
}
return ServerCatalog.fromJson(json);
}
@override
Future<bool> save(ServerCatalog catalog) async {
try {
final preferences = await SharedPreferences.getInstance();
return await preferences.setString(
serverCatalogKey,
jsonEncode({'version': 1, ...catalog.toJson()}),
);
} catch (_) {
return false;
}
}
}
/// Isolated test/preview persistence; failed saves preserve the prior catalog.
class MemoryServerCatalogStore implements ServerCatalogStore {
MemoryServerCatalogStore({this.catalog});
ServerCatalog? catalog;
bool failSaves = false;
@override
Future<ServerCatalog> load({String legacyEndpoint = ''}) async =>
catalog ?? _migrate(legacyEndpoint);
@override
Future<bool> save(ServerCatalog catalog) async {
if (failSaves) return false;
this.catalog = catalog;
return true;
}
}