feat(routing): 客户端 model + AccountApi + AsyncNotifier provider
- RoutingProfile/RoutingRule/Builtin 手写 fromJson/toJson/copyWith,对齐服务端 GET/POST /v1/me/routing 契约;enabled 缺省容错默认 true,toJson 恒输出该字段 - AccountApi.routingProfile()/saveRoutingProfile() 封装两端点 - RoutingProfileNotifier(AsyncNotifier):addRule/removeRule/updateRule/reorder/ setMode/setBuiltin 均本地乐观更新后落盘;save() 失败整体回退到变更前 state 并 rethrow(不静默吞,交调用方处理)——Riverpod asyncTransition 的 seamless copyWithPrevious 会用当前已存 state 覆盖手动挂的错误值,故不用 AsyncError 路径,改走显式回退
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
// routing_profile.dart — 可配置分流档案(GET/POST /v1/me/routing)。
|
||||
//
|
||||
// 对齐后端契约(server/internal/httpapi 分流端点):
|
||||
// {mode, builtin:{china_direct,lan_direct,private_via_tunnel}, rules:[...], final}。
|
||||
// 手写 fromJson/toJson(项目无 json_serializable,仿 lib/models/me.dart)。
|
||||
|
||||
/// 分流模式。
|
||||
/// 'rule' = 按规则(内置 + 自定义) | 'global' = 全局代理 | 'direct' = 全局直连。
|
||||
typedef RoutingMode = String;
|
||||
|
||||
/// 规则匹配类型。
|
||||
const kRuleTypes = [
|
||||
'domain',
|
||||
'domain_suffix',
|
||||
'domain_keyword',
|
||||
'ip_cidr',
|
||||
'geoip',
|
||||
'geosite',
|
||||
];
|
||||
|
||||
/// 规则命中动作。
|
||||
const kRuleActions = ['direct', 'proxy', 'reject'];
|
||||
|
||||
/// 内置分流开关(与自定义规则叠加,内置项在服务端渲染时排在自定义规则前/后由服务端决定)。
|
||||
class Builtin {
|
||||
const Builtin({
|
||||
this.chinaDirect = true,
|
||||
this.lanDirect = true,
|
||||
this.privateViaTunnel = true,
|
||||
});
|
||||
|
||||
final bool chinaDirect;
|
||||
final bool lanDirect;
|
||||
final bool privateViaTunnel;
|
||||
|
||||
factory Builtin.fromJson(Map<String, dynamic> m) => Builtin(
|
||||
chinaDirect: m['china_direct'] as bool? ?? true,
|
||||
lanDirect: m['lan_direct'] as bool? ?? true,
|
||||
privateViaTunnel: m['private_via_tunnel'] as bool? ?? true,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'china_direct': chinaDirect,
|
||||
'lan_direct': lanDirect,
|
||||
'private_via_tunnel': privateViaTunnel,
|
||||
};
|
||||
|
||||
Builtin copyWith({
|
||||
bool? chinaDirect,
|
||||
bool? lanDirect,
|
||||
bool? privateViaTunnel,
|
||||
}) =>
|
||||
Builtin(
|
||||
chinaDirect: chinaDirect ?? this.chinaDirect,
|
||||
lanDirect: lanDirect ?? this.lanDirect,
|
||||
privateViaTunnel: privateViaTunnel ?? this.privateViaTunnel,
|
||||
);
|
||||
}
|
||||
|
||||
/// 单条自定义分流规则。
|
||||
///
|
||||
/// **enabled 语义**(计划裁决):构造默认 `true`;[toJson] 恒输出 `enabled` 字段
|
||||
/// (服务端不修正缺省值,契约靠客户端保证);[fromJson] 缺失时容错默认 `true`。
|
||||
class RoutingRule {
|
||||
const RoutingRule({
|
||||
required this.type,
|
||||
required this.value,
|
||||
required this.action,
|
||||
this.note,
|
||||
this.enabled = true,
|
||||
});
|
||||
|
||||
/// domain | domain_suffix | domain_keyword | ip_cidr | geoip | geosite
|
||||
final String type;
|
||||
final String value;
|
||||
|
||||
/// direct | proxy | reject
|
||||
final String action;
|
||||
final String? note;
|
||||
final bool enabled;
|
||||
|
||||
factory RoutingRule.fromJson(Map<String, dynamic> m) => RoutingRule(
|
||||
type: m['type'] as String? ?? '',
|
||||
value: m['value'] as String? ?? '',
|
||||
action: m['action'] as String? ?? 'proxy',
|
||||
note: m['note'] as String?,
|
||||
enabled: m['enabled'] as bool? ?? true,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'type': type,
|
||||
'value': value,
|
||||
'action': action,
|
||||
if (note != null) 'note': note,
|
||||
'enabled': enabled,
|
||||
};
|
||||
|
||||
RoutingRule copyWith({
|
||||
String? type,
|
||||
String? value,
|
||||
String? action,
|
||||
String? note,
|
||||
bool? enabled,
|
||||
}) =>
|
||||
RoutingRule(
|
||||
type: type ?? this.type,
|
||||
value: value ?? this.value,
|
||||
action: action ?? this.action,
|
||||
note: note ?? this.note,
|
||||
enabled: enabled ?? this.enabled,
|
||||
);
|
||||
}
|
||||
|
||||
/// 分流档案(账户级,单份)。
|
||||
class RoutingProfile {
|
||||
const RoutingProfile({
|
||||
this.mode = 'rule',
|
||||
this.builtin = const Builtin(),
|
||||
this.rules = const [],
|
||||
this.finalAction = 'proxy',
|
||||
});
|
||||
|
||||
final RoutingMode mode;
|
||||
final Builtin builtin;
|
||||
final List<RoutingRule> rules;
|
||||
|
||||
/// 兜底动作(JSON key 为保留字 `final`,Dart 侧改名)。'proxy' | 'direct'。
|
||||
final String finalAction;
|
||||
|
||||
factory RoutingProfile.fromJson(Map<String, dynamic> m) => RoutingProfile(
|
||||
mode: m['mode'] as String? ?? 'rule',
|
||||
builtin: m['builtin'] != null
|
||||
? Builtin.fromJson(m['builtin'] as Map<String, dynamic>)
|
||||
: const Builtin(),
|
||||
rules: ((m['rules'] as List<dynamic>?) ?? const [])
|
||||
.map((e) => RoutingRule.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
finalAction: m['final'] as String? ?? 'proxy',
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'mode': mode,
|
||||
'builtin': builtin.toJson(),
|
||||
'rules': rules.map((r) => r.toJson()).toList(),
|
||||
'final': finalAction,
|
||||
};
|
||||
|
||||
RoutingProfile copyWith({
|
||||
RoutingMode? mode,
|
||||
Builtin? builtin,
|
||||
List<RoutingRule>? rules,
|
||||
String? finalAction,
|
||||
}) =>
|
||||
RoutingProfile(
|
||||
mode: mode ?? this.mode,
|
||||
builtin: builtin ?? this.builtin,
|
||||
rules: rules ?? this.rules,
|
||||
finalAction: finalAction ?? this.finalAction,
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import '../models/device.dart';
|
||||
import '../models/device_usage.dart';
|
||||
import '../models/me.dart';
|
||||
import '../models/plan.dart';
|
||||
import '../models/routing_profile.dart';
|
||||
import '../models/usage_point.dart';
|
||||
import 'api_client.dart';
|
||||
|
||||
@@ -107,6 +108,17 @@ class AccountApi {
|
||||
minutesRemaining: (body['minutes_remaining'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
/// GET /v1/me/routing — 可配置分流档案(无档案时服务端返回默认)。
|
||||
Future<RoutingProfile> routingProfile() async =>
|
||||
RoutingProfile.fromJson(await _c.getJson('/v1/me/routing'));
|
||||
|
||||
/// POST /v1/me/routing — 保存分流档案。非法规则由服务端 400 拒绝
|
||||
/// (body: `{code,message_zh,message_en,errors:[{index,field,reason}]}`,经 ApiClient
|
||||
/// 统一包装为 AuthApiException)。
|
||||
Future<void> saveRoutingProfile(RoutingProfile p) async {
|
||||
await _c.postJson('/v1/me/routing', p.toJson());
|
||||
}
|
||||
}
|
||||
|
||||
/// 看广告加时结果(POST /v1/ads/unlock 响应)。
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// routing_provider.dart — 可配置分流档案(GET/POST /v1/me/routing)状态层。
|
||||
//
|
||||
// 仿 account_providers.dart:DevicesNotifier 的 AsyncNotifier + invalidateSelf 范式,
|
||||
// 但变更类操作(addRule/removeRule/reorder/setMode)采用「本地乐观更新 → 落盘」:
|
||||
// 先改 state 再 saveRoutingProfile,失败则把 state 还原到变更前并 rethrow(不静默吞,
|
||||
// 由调用方 catch 后提示用户;仿 DevicesNotifier.remove/rename 等「失败即抛」范式)。
|
||||
//
|
||||
// 注:不用 `state = AsyncError(...).copyWithPrevious(...)` 手动挂错误 ——
|
||||
// Riverpod AsyncNotifier 的 `state=` setter 内部 asyncTransition() 总会用
|
||||
// **当前已存的 state**(此时已是乐观更新后的 next)重新 copyWithPrevious 一次,
|
||||
// 会把我们想还原的旧值又覆盖回 next,达不到「回退」效果。故失败时直接整体
|
||||
// `state = AsyncData(previous)`(纯回退,无错误标记)+ rethrow 传递异常。
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../models/routing_profile.dart';
|
||||
import 'account_providers.dart';
|
||||
import 'auth_provider.dart';
|
||||
|
||||
/// 当前账户的分流档案。未登录返回默认档案(不打后端)。
|
||||
class RoutingProfileNotifier extends AsyncNotifier<RoutingProfile> {
|
||||
@override
|
||||
Future<RoutingProfile> build() async {
|
||||
final auth = ref.watch(authProvider);
|
||||
if (!auth.isLoggedIn) return const RoutingProfile();
|
||||
return ref.read(accountApiProvider).routingProfile();
|
||||
}
|
||||
|
||||
/// 显式保存当前 state(供批量编辑后统一保存的场景;单条变更类方法已自带保存)。
|
||||
Future<void> save() async {
|
||||
final profile = state.valueOrNull;
|
||||
if (profile == null) return;
|
||||
await _persist(profile, previous: profile);
|
||||
}
|
||||
|
||||
/// 切换分流模式(rule/global/direct)。
|
||||
Future<void> setMode(String mode) => _mutateAndSave((p) => p.copyWith(mode: mode));
|
||||
|
||||
/// 切换内置分流开关。
|
||||
Future<void> setBuiltin(Builtin builtin) => _mutateAndSave((p) => p.copyWith(builtin: builtin));
|
||||
|
||||
/// 追加一条自定义规则(默认追到末尾,规则命中顺序 = 列表顺序)。
|
||||
Future<void> addRule(RoutingRule rule) =>
|
||||
_mutateAndSave((p) => p.copyWith(rules: [...p.rules, rule]));
|
||||
|
||||
/// 删除第 index 条规则。
|
||||
Future<void> removeRule(int index) => _mutateAndSave((p) {
|
||||
final rules = [...p.rules]..removeAt(index);
|
||||
return p.copyWith(rules: rules);
|
||||
});
|
||||
|
||||
/// 替换第 index 条规则(如切换 enabled / 编辑字段)。
|
||||
Future<void> updateRule(int index, RoutingRule rule) => _mutateAndSave((p) {
|
||||
final rules = [...p.rules];
|
||||
rules[index] = rule;
|
||||
return p.copyWith(rules: rules);
|
||||
});
|
||||
|
||||
/// 拖拽排序(语义对齐 Flutter `ReorderableListView.onReorder`:newIndex 是移除
|
||||
/// oldIndex 之前的目标下标)。
|
||||
Future<void> reorder(int oldIndex, int newIndex) => _mutateAndSave((p) {
|
||||
final rules = [...p.rules];
|
||||
var target = newIndex;
|
||||
if (oldIndex < newIndex) target -= 1;
|
||||
final item = rules.removeAt(oldIndex);
|
||||
rules.insert(target, item);
|
||||
return p.copyWith(rules: rules);
|
||||
});
|
||||
|
||||
Future<void> _mutateAndSave(RoutingProfile Function(RoutingProfile) transform) async {
|
||||
final prev = state.valueOrNull ?? const RoutingProfile();
|
||||
final next = transform(prev);
|
||||
state = AsyncData(next); // 乐观更新,UI 立即反映
|
||||
await _persist(next, previous: prev);
|
||||
}
|
||||
|
||||
/// 落盘;失败回退 state 到 [previous] 并 rethrow(不静默吞,由调用方 catch 提示)。
|
||||
Future<void> _persist(RoutingProfile profile, {required RoutingProfile previous}) async {
|
||||
try {
|
||||
await ref.read(accountApiProvider).saveRoutingProfile(profile);
|
||||
} catch (_) {
|
||||
state = AsyncData(previous);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final routingProfileProvider =
|
||||
AsyncNotifierProvider<RoutingProfileNotifier, RoutingProfile>(RoutingProfileNotifier.new);
|
||||
@@ -0,0 +1,39 @@
|
||||
// routing_profile_model_test.dart — RoutingProfile/RoutingRule JSON 无损往返。
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pangolin_vpn/models/routing_profile.dart';
|
||||
|
||||
void main() {
|
||||
test('RoutingProfile round-trips json', () {
|
||||
const j = {
|
||||
'mode': 'rule',
|
||||
'builtin': {'china_direct': true, 'lan_direct': true, 'private_via_tunnel': true},
|
||||
'rules': [
|
||||
{'type': 'domain_suffix', 'value': 'x.com', 'action': 'direct', 'note': 'ci', 'enabled': true}
|
||||
],
|
||||
'final': 'proxy',
|
||||
};
|
||||
final p = RoutingProfile.fromJson(j);
|
||||
expect(p.mode, 'rule');
|
||||
expect(p.rules.single.value, 'x.com');
|
||||
expect(p.toJson(), j); // 无损往返
|
||||
});
|
||||
|
||||
test('RoutingRule enabled 缺省容错默认 true', () {
|
||||
final r = RoutingRule.fromJson({'type': 'domain', 'value': 'a.com', 'action': 'proxy'});
|
||||
expect(r.enabled, isTrue);
|
||||
});
|
||||
|
||||
test('RoutingRule 构造默认 enabled=true 且 toJson 恒输出 enabled 字段', () {
|
||||
const r = RoutingRule(type: 'domain', value: 'a.com', action: 'proxy');
|
||||
expect(r.enabled, isTrue);
|
||||
expect(r.toJson().containsKey('enabled'), isTrue);
|
||||
expect(r.toJson()['enabled'], isTrue);
|
||||
});
|
||||
|
||||
test('RoutingProfile.fromJson 无档案默认(builtin 缺省)容错', () {
|
||||
final p = RoutingProfile.fromJson({'mode': 'global', 'rules': [], 'final': 'direct'});
|
||||
expect(p.builtin.chinaDirect, isTrue);
|
||||
expect(p.builtin.lanDirect, isTrue);
|
||||
expect(p.builtin.privateViaTunnel, isTrue);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// routing_provider_test.dart — 分流档案 provider:乐观更新 + 保存调用 + 失败回退。
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pangolin_vpn/models/routing_profile.dart';
|
||||
import 'package:pangolin_vpn/services/account_api.dart';
|
||||
import 'package:pangolin_vpn/services/api_client.dart';
|
||||
import 'package:pangolin_vpn/services/token_store.dart';
|
||||
import 'package:pangolin_vpn/state/account_providers.dart';
|
||||
import 'package:pangolin_vpn/state/auth_provider.dart';
|
||||
import 'package:pangolin_vpn/state/routing_provider.dart';
|
||||
|
||||
/// 已登录的桩 TokenStore(无平台依赖,仿 nodes_provider_test 的 _NullTokenStore)。
|
||||
class _LoggedInTokenStore implements TokenStore {
|
||||
const _LoggedInTokenStore();
|
||||
@override
|
||||
Future<void> saveTokens({required String access, required String refresh}) async {}
|
||||
@override
|
||||
Future<String?> loadAccessToken() async => 'test-token';
|
||||
@override
|
||||
Future<String?> loadRefreshToken() async => 'test-refresh';
|
||||
@override
|
||||
Future<void> clear() async {}
|
||||
@override
|
||||
Future<void> markOnboarded() async {}
|
||||
@override
|
||||
Future<bool> isOnboarded() async => true;
|
||||
@override
|
||||
Future<void> saveLastEmail(String email) async {}
|
||||
@override
|
||||
Future<String?> loadLastEmail() async => null;
|
||||
}
|
||||
|
||||
/// 轮询等 authProvider 的异步 _loadFromStore() 落地已登录态。
|
||||
Future<void> _waitLoggedIn(ProviderContainer c) async {
|
||||
for (var i = 0; i < 60; i++) {
|
||||
if (c.read(authProvider).isLoggedIn) return;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
}
|
||||
throw StateError('authProvider 未在预期时间内进入已登录态');
|
||||
}
|
||||
|
||||
/// 假 AccountApi:只桩 routingProfile()/saveRoutingProfile(),记录调用便于断言。
|
||||
class _FakeAccountApi extends AccountApi {
|
||||
_FakeAccountApi()
|
||||
: super(ApiClient(
|
||||
baseUrl: 'http://test.local',
|
||||
getToken: () => null,
|
||||
refresh: () async => false,
|
||||
));
|
||||
|
||||
RoutingProfile initial = const RoutingProfile();
|
||||
final List<RoutingProfile> saved = [];
|
||||
|
||||
/// 非 null 时 saveRoutingProfile 抛此异常(用于测失败回退)。
|
||||
Exception? saveError;
|
||||
|
||||
@override
|
||||
Future<RoutingProfile> routingProfile() async => initial;
|
||||
|
||||
@override
|
||||
Future<void> saveRoutingProfile(RoutingProfile p) async {
|
||||
final err = saveError;
|
||||
if (err != null) throw err;
|
||||
saved.add(p);
|
||||
}
|
||||
}
|
||||
|
||||
ProviderContainer _makeContainer(_FakeAccountApi api) => ProviderContainer(overrides: [
|
||||
tokenStoreProvider.overrideWithValue(const _LoggedInTokenStore()),
|
||||
accountApiProvider.overrideWithValue(api),
|
||||
]);
|
||||
|
||||
void main() {
|
||||
test('addRule 乐观更新 state 并调用 saveRoutingProfile', () async {
|
||||
final api = _FakeAccountApi();
|
||||
final c = _makeContainer(api);
|
||||
addTearDown(c.dispose);
|
||||
|
||||
await _waitLoggedIn(c);
|
||||
await c.read(routingProfileProvider.future); // 等初次加载
|
||||
|
||||
const rule = RoutingRule(type: 'domain_suffix', value: 'x.com', action: 'direct');
|
||||
await c.read(routingProfileProvider.notifier).addRule(rule);
|
||||
|
||||
final state = c.read(routingProfileProvider).value!;
|
||||
expect(state.rules, hasLength(1));
|
||||
expect(state.rules.single.value, 'x.com');
|
||||
expect(state.rules.single.action, 'direct');
|
||||
|
||||
expect(api.saved, hasLength(1), reason: '应调用 saveRoutingProfile 落盘');
|
||||
expect(api.saved.single.rules.single.value, 'x.com');
|
||||
});
|
||||
|
||||
test('removeRule / setMode / reorder 均乐观更新 + 落盘', () async {
|
||||
final api = _FakeAccountApi()
|
||||
..initial = const RoutingProfile(rules: [
|
||||
RoutingRule(type: 'domain', value: 'a.com', action: 'direct'),
|
||||
RoutingRule(type: 'domain', value: 'b.com', action: 'proxy'),
|
||||
]);
|
||||
final c = _makeContainer(api);
|
||||
addTearDown(c.dispose);
|
||||
await _waitLoggedIn(c);
|
||||
await c.read(routingProfileProvider.future);
|
||||
|
||||
await c.read(routingProfileProvider.notifier).setMode('global');
|
||||
expect(c.read(routingProfileProvider).value!.mode, 'global');
|
||||
|
||||
await c.read(routingProfileProvider.notifier).reorder(0, 2);
|
||||
expect(c.read(routingProfileProvider).value!.rules.map((r) => r.value).toList(),
|
||||
['b.com', 'a.com']);
|
||||
|
||||
await c.read(routingProfileProvider.notifier).removeRule(0);
|
||||
expect(c.read(routingProfileProvider).value!.rules.single.value, 'a.com');
|
||||
|
||||
expect(api.saved, hasLength(3));
|
||||
});
|
||||
|
||||
test('保存失败:回退到变更前 state 且 rethrow,不静默吞', () async {
|
||||
final api = _FakeAccountApi();
|
||||
final c = _makeContainer(api);
|
||||
addTearDown(c.dispose);
|
||||
await _waitLoggedIn(c);
|
||||
await c.read(routingProfileProvider.future);
|
||||
|
||||
final before = c.read(routingProfileProvider).value!;
|
||||
api.saveError = Exception('network down');
|
||||
|
||||
const rule = RoutingRule(type: 'domain', value: 'fail.com', action: 'proxy');
|
||||
await expectLater(
|
||||
c.read(routingProfileProvider.notifier).addRule(rule),
|
||||
throwsA(isA<Exception>()),
|
||||
);
|
||||
|
||||
// 不静默吞:异常已通过 expectLater 的 throwsA 断言被抛出给调用方。
|
||||
final after = c.read(routingProfileProvider);
|
||||
expect(after.hasError, isFalse, reason: '失败走「整体回退」而非挂错误态');
|
||||
expect(after.value, before, reason: '应回退到变更前 state');
|
||||
expect(api.saved, isEmpty);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user