merge: persisted named server profiles
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/servers/server_catalog.dart';
|
||||
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
ServerCatalog fixture() => ServerCatalog(
|
||||
servers: [
|
||||
SavedServer.validated(
|
||||
id: 'home',
|
||||
name: 'Home',
|
||||
endpoints: ['ws://home.test', 'wss://backup.test'],
|
||||
),
|
||||
],
|
||||
selectedId: 'home',
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const store = SharedPreferencesServerCatalogStore();
|
||||
|
||||
setUp(() => SharedPreferences.setMockInitialValues({}));
|
||||
|
||||
test('empty storage gives empty catalog and never writes on load', () async {
|
||||
expect((await store.load()).servers, isEmpty);
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
expect(preferences.getKeys(), isEmpty);
|
||||
});
|
||||
|
||||
test('one versioned preference roundtrips all catalog data', () async {
|
||||
final catalog = fixture();
|
||||
expect(await store.save(catalog), isTrue);
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
expect(preferences.getKeys(), {serverCatalogKey});
|
||||
final json = jsonDecode(preferences.getString(serverCatalogKey)!);
|
||||
expect(json['version'], 1);
|
||||
expect(json['servers'], catalog.toJson()['servers']);
|
||||
expect((await store.load()).toJson(), catalog.toJson());
|
||||
});
|
||||
|
||||
test('legacy migration is stable, selected and preserves old keys', () async {
|
||||
const legacyKey = 'pipelines.next.serverUrl.v1';
|
||||
const legacy = ' ws://legacy.test/ ';
|
||||
SharedPreferences.setMockInitialValues({
|
||||
legacyKey: legacy,
|
||||
'pipelines.next.workspace.v1': '/keep/workspace',
|
||||
});
|
||||
final migrated = await store.load(legacyEndpoint: legacy);
|
||||
expect(migrated.selectedId, 'legacy-server');
|
||||
expect(migrated.active!.name, 'My server');
|
||||
expect(migrated.active!.endpoints, ['ws://legacy.test/connect']);
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
expect(preferences.containsKey(serverCatalogKey), isFalse);
|
||||
expect(await store.save(migrated), isTrue);
|
||||
expect(preferences.getString(legacyKey), legacy);
|
||||
expect(
|
||||
preferences.getString('pipelines.next.workspace.v1'),
|
||||
'/keep/workspace',
|
||||
);
|
||||
expect(
|
||||
(await store.load(legacyEndpoint: 'invalid')).toJson(),
|
||||
migrated.toJson(),
|
||||
);
|
||||
});
|
||||
|
||||
test('existing empty catalog takes priority over legacy migration', () async {
|
||||
await store.save(ServerCatalog());
|
||||
expect(
|
||||
(await store.load(legacyEndpoint: 'ws://old.test')).servers,
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test('corrupt, invalid and future data surface without mutation', () async {
|
||||
for (final raw in <Object>[
|
||||
'{broken',
|
||||
'',
|
||||
7,
|
||||
'[]',
|
||||
'{"version":2,"servers":[]}',
|
||||
'{"version":1,"servers":[],"selectedId":"missing"}',
|
||||
'{"version":1,"servers":[{"id":"a","name":"A","endpoints":[]}]}',
|
||||
]) {
|
||||
SharedPreferences.setMockInitialValues({serverCatalogKey: raw});
|
||||
await expectLater(
|
||||
store.load(legacyEndpoint: 'ws://old.test'),
|
||||
throwsFormatException,
|
||||
);
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
expect(preferences.get(serverCatalogKey), raw);
|
||||
expect(preferences.getKeys(), {serverCatalogKey});
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid legacy endpoint reports error without writing', () async {
|
||||
await expectLater(
|
||||
store.load(legacyEndpoint: 'https://old.test'),
|
||||
throwsFormatException,
|
||||
);
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
expect(preferences.getKeys(), isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'memory store roundtrip and failed writes preserve prior data',
|
||||
() async {
|
||||
final original = fixture();
|
||||
final memory = MemoryServerCatalogStore(catalog: original);
|
||||
memory.failSaves = true;
|
||||
expect(await memory.save(ServerCatalog()), isFalse);
|
||||
expect((await memory.load()).toJson(), original.toJson());
|
||||
memory.failSaves = false;
|
||||
final changed = original.remove('home');
|
||||
expect(await memory.save(changed), isTrue);
|
||||
expect(
|
||||
(await memory.load(legacyEndpoint: 'ws://ignored.test')).servers,
|
||||
isEmpty,
|
||||
);
|
||||
expect(original.active!.id, 'home');
|
||||
},
|
||||
);
|
||||
|
||||
test('memory store follows the same read-only migration contract', () async {
|
||||
final memory = MemoryServerCatalogStore();
|
||||
expect((await memory.load()).servers, isEmpty);
|
||||
final migrated = await memory.load(legacyEndpoint: 'wss://old.test');
|
||||
expect(migrated.active!.id, 'legacy-server');
|
||||
memory.failSaves = true;
|
||||
expect(await memory.save(migrated), isFalse);
|
||||
expect((await memory.load()).servers, isEmpty);
|
||||
memory.failSaves = false;
|
||||
expect(await memory.save(migrated), isTrue);
|
||||
expect((await memory.load()).toJson(), migrated.toJson());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/servers/server_catalog.dart';
|
||||
|
||||
SavedServer server(String id) => SavedServer.validated(
|
||||
id: id,
|
||||
name: 'Server $id',
|
||||
endpoints: ['wss://$id.test'],
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('normalizes, deduplicates and retains primary/backup order', () {
|
||||
final value = SavedServer.validated(
|
||||
id: ' home ',
|
||||
name: ' Home ',
|
||||
endpoints: [
|
||||
' WS://HOME.test/ ',
|
||||
'wss://backup.test',
|
||||
'ws://home.test/connect',
|
||||
],
|
||||
);
|
||||
expect(value.id, 'home');
|
||||
expect(value.name, 'Home');
|
||||
expect(value.endpoints, [
|
||||
'ws://home.test/connect',
|
||||
'wss://backup.test/connect',
|
||||
]);
|
||||
});
|
||||
|
||||
test('rejects blank identity, empty endpoints and invalid URLs', () {
|
||||
for (final id in ['', ' ']) {
|
||||
expect(
|
||||
() => SavedServer.validated(id: id, name: 'Name', endpoints: []),
|
||||
throwsFormatException,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
() => SavedServer.validated(id: 'a', name: ' ', endpoints: ['ws://a']),
|
||||
throwsFormatException,
|
||||
);
|
||||
expect(
|
||||
() => SavedServer.validated(id: 'a', name: 'A', endpoints: []),
|
||||
throwsFormatException,
|
||||
);
|
||||
for (final url in [
|
||||
'',
|
||||
'https://a.test',
|
||||
'ws://user:secret@a.test',
|
||||
'ws://a.test/#fragment',
|
||||
'ws://',
|
||||
]) {
|
||||
expect(
|
||||
() => SavedServer.validated(id: 'a', name: 'A', endpoints: [url]),
|
||||
throwsFormatException,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('roundtrips catalog JSON with multiple ordered endpoints', () {
|
||||
final first = SavedServer.validated(
|
||||
id: 'a',
|
||||
name: 'A',
|
||||
endpoints: ['ws://primary.test', 'wss://backup.test'],
|
||||
);
|
||||
final catalog = ServerCatalog(
|
||||
servers: [first, server('b')],
|
||||
selectedId: 'a',
|
||||
);
|
||||
final decoded = ServerCatalog.fromJson(
|
||||
jsonDecode(jsonEncode(catalog.toJson())) as Map<String, dynamic>,
|
||||
);
|
||||
expect(decoded.toJson(), catalog.toJson());
|
||||
expect(decoded.active!.endpoints, first.endpoints);
|
||||
expect(ServerCatalog().active, isNull);
|
||||
});
|
||||
|
||||
test('rejects duplicate IDs and cross-profile normalized addresses', () {
|
||||
final a = server('a');
|
||||
expect(() => ServerCatalog(servers: [a, a]), throwsFormatException);
|
||||
final alias = SavedServer.validated(
|
||||
id: 'alias',
|
||||
name: 'Alias',
|
||||
endpoints: ['WSS://A.TEST/'],
|
||||
);
|
||||
expect(() => ServerCatalog(servers: [a, alias]), throwsFormatException);
|
||||
expect(
|
||||
() => ServerCatalog(servers: [a]).upsert(alias),
|
||||
throwsFormatException,
|
||||
);
|
||||
});
|
||||
|
||||
test('selection is explicit; upsert/remove never switch servers', () {
|
||||
final a = server('a');
|
||||
final b = server('b');
|
||||
final original = ServerCatalog(servers: [a, b]);
|
||||
expect(original.upsert(server('c')).active, isNull);
|
||||
final selected = original.select('a');
|
||||
final replacement = SavedServer.validated(
|
||||
id: 'a',
|
||||
name: 'Renamed',
|
||||
endpoints: ['ws://new.test', 'wss://new-backup.test'],
|
||||
);
|
||||
final updated = selected.upsert(replacement);
|
||||
expect(updated.active, same(replacement));
|
||||
expect(updated.servers.map((entry) => entry.id), ['a', 'b']);
|
||||
expect(updated.remove('b').active, same(replacement));
|
||||
expect(updated.remove('a').active, isNull);
|
||||
expect(updated.remove('a').servers, [b]);
|
||||
expect(updated.remove('missing').toJson(), updated.toJson());
|
||||
expect(() => original.select('missing'), throwsFormatException);
|
||||
expect(selected.active, same(a));
|
||||
expect(original.active, isNull);
|
||||
});
|
||||
|
||||
test('copies inputs and exposes no mutable collection aliases', () {
|
||||
final endpoints = ['ws://a.test'];
|
||||
final a = SavedServer.validated(id: 'a', name: 'A', endpoints: endpoints);
|
||||
endpoints.add('ws://injected.test');
|
||||
final servers = [a];
|
||||
final catalog = ServerCatalog(servers: servers, selectedId: 'a');
|
||||
servers.clear();
|
||||
expect(catalog.servers, [a]);
|
||||
expect(a.endpoints, ['ws://a.test/connect']);
|
||||
expect(() => a.endpoints.clear(), throwsUnsupportedError);
|
||||
expect(() => catalog.servers.clear(), throwsUnsupportedError);
|
||||
(a.toJson()['endpoints'] as List).clear();
|
||||
(catalog.toJson()['servers'] as List).clear();
|
||||
expect(catalog.active!.endpoints, ['ws://a.test/connect']);
|
||||
});
|
||||
|
||||
test('malformed JSON cannot bypass catalog validation', () {
|
||||
for (final json in <Map<String, dynamic>>[
|
||||
{},
|
||||
{'servers': 'wrong'},
|
||||
{
|
||||
'servers': [null],
|
||||
},
|
||||
{'servers': [], 'selectedId': 'missing'},
|
||||
{'servers': [], 'selectedId': 1},
|
||||
{
|
||||
'servers': [server('a').toJson(), server('a').toJson()],
|
||||
},
|
||||
{
|
||||
'servers': [
|
||||
{
|
||||
'id': 'a',
|
||||
'name': 'A',
|
||||
'endpoints': [1],
|
||||
},
|
||||
],
|
||||
},
|
||||
]) {
|
||||
expect(() => ServerCatalog.fromJson(json), throwsFormatException);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user