Add relay node management and pin manager header layout
- server: add, delete and set-default node endpoints writing cluster.json with validation - deploy: grant ads-server write access to /etc/ads - flutter: relay node page with admin token plumbing, stop reconnecting devices removed from device list - flutter: fixed header heights and strut so tab switching never shifts refresh/notice
This commit is contained in:
1 parent
e12cb76d68
commit
0a04d5990f
9 files changed
+606
-75
No files matched your search
@@ -16,6 +16,7 @@ NoNewPrivileges=true
|
|||||||
PrivateTmp=true
|
PrivateTmp=true
|
||||||
ProtectSystem=strict
|
ProtectSystem=strict
|
||||||
ProtectHome=true
|
ProtectHome=true
|
||||||
|
ReadWritePaths=/etc/ads
|
||||||
MemoryMax=256M
|
MemoryMax=256M
|
||||||
LimitNOFILE=8192
|
LimitNOFILE=8192
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ typedef JsonMap = Map<String, Object?>;
|
|||||||
|
|
||||||
abstract interface class AgentApi {
|
abstract interface class AgentApi {
|
||||||
String get connectionKey;
|
String get connectionKey;
|
||||||
|
String get adminToken;
|
||||||
Future<List<JsonMap>> list();
|
Future<List<JsonMap>> list();
|
||||||
Future<Object?> request(String agent, JsonMap operation);
|
Future<Object?> request(String agent, JsonMap operation);
|
||||||
Future<Object?> local(String config, JsonMap operation);
|
Future<Object?> local(String config, JsonMap operation);
|
||||||
@@ -29,6 +30,8 @@ class AgentService implements AgentApi {
|
|||||||
String _token = '';
|
String _token = '';
|
||||||
final Set<String> _secrets = {};
|
final Set<String> _secrets = {};
|
||||||
@override
|
@override
|
||||||
|
String get adminToken => _token;
|
||||||
|
@override
|
||||||
String redact(String message) {
|
String redact(String message) {
|
||||||
for (final secret in _secrets) {
|
for (final secret in _secrets) {
|
||||||
message = message.replaceAll(secret, '[REDACTED]');
|
message = message.replaceAll(secret, '[REDACTED]');
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ class Session {
|
|||||||
bool screenEmbedded = false;
|
bool screenEmbedded = false;
|
||||||
String state = '连接中', route = '协商中';
|
String state = '连接中', route = '协商中';
|
||||||
bool ready = false, stopping = false, exited = false;
|
bool ready = false, stopping = false, exited = false;
|
||||||
|
int missingPasses = 0;
|
||||||
Session(this.id, this.tunnel, this.adb, this.statusFile, this.process);
|
Session(this.id, this.tunnel, this.adb, this.statusFile, this.process);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,6 +195,7 @@ class ManagerRepository {
|
|||||||
String? bearer,
|
String? bearer,
|
||||||
Map<String, Object?>? payload,
|
Map<String, Object?>? payload,
|
||||||
Map<String, String>? query,
|
Map<String, String>? query,
|
||||||
|
String? method,
|
||||||
}) async {
|
}) async {
|
||||||
final authorization = bearer ?? token;
|
final authorization = bearer ?? token;
|
||||||
if (authorization.length < 32) {
|
if (authorization.length < 32) {
|
||||||
@@ -231,9 +233,10 @@ class ManagerRepository {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
final uri = settings.uri(suffix).replace(queryParameters: query);
|
final uri = settings.uri(suffix).replace(queryParameters: query);
|
||||||
final request = payload == null
|
final request = await client.openUrl(
|
||||||
? await client.getUrl(uri)
|
method ?? (payload == null ? 'GET' : 'POST'),
|
||||||
: await client.postUrl(uri);
|
uri,
|
||||||
|
);
|
||||||
request.followRedirects = false;
|
request.followRedirects = false;
|
||||||
request.headers.set('Authorization', 'Bearer $authorization');
|
request.headers.set('Authorization', 'Bearer $authorization');
|
||||||
if (payload != null) {
|
if (payload != null) {
|
||||||
@@ -250,8 +253,14 @@ class ManagerRepository {
|
|||||||
if (suffix == 'v2/nodes' && response.statusCode == 404) {
|
if (suffix == 'v2/nodes' && response.statusCode == 404) {
|
||||||
return {'nodes': <dynamic>[]};
|
return {'nodes': <dynamic>[]};
|
||||||
}
|
}
|
||||||
if (response.statusCode != 200) {
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||||
throw HttpException('控制中心 HTTP ${response.statusCode}');
|
final detail = body.trim();
|
||||||
|
throw HttpException(
|
||||||
|
'控制中心 HTTP ${response.statusCode}${detail.isEmpty ? '' : ':${detail.length > 200 ? detail.substring(0, 200) : detail}'}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (body.trim().isEmpty) {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
return jsonDecode(body);
|
return jsonDecode(body);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -483,7 +492,32 @@ class ManagerRepository {
|
|||||||
|
|
||||||
Future<void> monitor() async {
|
Future<void> monitor() async {
|
||||||
final listings = <String, String>{};
|
final listings = <String, String>{};
|
||||||
|
Set<String>? online;
|
||||||
|
if (sessions.values.any((s) => s.usb != null)) {
|
||||||
|
try {
|
||||||
|
online = (await devices()).map((d) => d.id).toSet();
|
||||||
|
} catch (_) {
|
||||||
|
// Inventory unavailable; keep the current connection states.
|
||||||
|
}
|
||||||
|
}
|
||||||
for (final s in sessions.values.toList()) {
|
for (final s in sessions.values.toList()) {
|
||||||
|
if (s.stopping) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (online != null && s.usb != null) {
|
||||||
|
if (online.contains(s.id)) {
|
||||||
|
s.missingPasses = 0;
|
||||||
|
} else {
|
||||||
|
s.missingPasses++;
|
||||||
|
if (s.missingPasses >= 3) {
|
||||||
|
log('[${s.id}] 设备已不在设备列表,停止自动重连');
|
||||||
|
await disconnect(s.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
s.state = '设备已下线 · 等待恢复';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
if (s.usb == null && !s.stopping && s.exited) {
|
if (s.usb == null && !s.stopping && s.exited) {
|
||||||
await disconnect(s.id);
|
await disconnect(s.id);
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import '../data/agent_service.dart';
|
|||||||
class AgentModel extends ChangeNotifier {
|
class AgentModel extends ChangeNotifier {
|
||||||
AgentModel(this.repository);
|
AgentModel(this.repository);
|
||||||
final AgentRepository repository;
|
final AgentRepository repository;
|
||||||
|
String get adminToken => repository.api.adminToken;
|
||||||
void Function(String)? onLog;
|
void Function(String)? onLog;
|
||||||
List<ManagedAgent> _agents = [];
|
List<ManagedAgent> _agents = [];
|
||||||
List<ManagedAgent> get agents => List.unmodifiable(_agents);
|
List<ManagedAgent> get agents => List.unmodifiable(_agents);
|
||||||
|
|||||||
@@ -149,6 +149,45 @@ class ManagerModel extends ChangeNotifier {
|
|||||||
await repository.connect(d.id);
|
await repository.connect(d.id);
|
||||||
log('已启动 ${d.id} 的连接');
|
log('已启动 ${d.id} 的连接');
|
||||||
});
|
});
|
||||||
|
String get nodeCredentialHint =>
|
||||||
|
agents.adminToken.isEmpty ? '节点管理需要管理员凭据,请先在 Agent 管理导入 admin.env' : '';
|
||||||
|
Future<void> addNode({
|
||||||
|
required String id,
|
||||||
|
required String url,
|
||||||
|
required String address,
|
||||||
|
required int priority,
|
||||||
|
}) => action(() async {
|
||||||
|
await repository.requestJson(
|
||||||
|
'v2/nodes',
|
||||||
|
bearer: agents.adminToken,
|
||||||
|
payload: {
|
||||||
|
'id': id,
|
||||||
|
'url': url,
|
||||||
|
if (address.isNotEmpty) 'connect_address': address,
|
||||||
|
'priority': priority,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await refresh();
|
||||||
|
log('已新增中继节点 $id');
|
||||||
|
});
|
||||||
|
Future<void> removeNode(String id) => action(() async {
|
||||||
|
await repository.requestJson(
|
||||||
|
'v2/nodes/${Uri.encodeComponent(id)}',
|
||||||
|
bearer: agents.adminToken,
|
||||||
|
method: 'DELETE',
|
||||||
|
);
|
||||||
|
await refresh();
|
||||||
|
log('已删除中继节点 $id');
|
||||||
|
});
|
||||||
|
Future<void> defaultNode(String id) => action(() async {
|
||||||
|
await repository.requestJson(
|
||||||
|
'v2/nodes/default',
|
||||||
|
bearer: agents.adminToken,
|
||||||
|
payload: {'id': id},
|
||||||
|
);
|
||||||
|
await refresh();
|
||||||
|
log('已将 $id 设为默认中继节点');
|
||||||
|
});
|
||||||
Future<void> disconnect(String id) =>
|
Future<void> disconnect(String id) =>
|
||||||
deviceAction(id, () => repository.disconnect(id));
|
deviceAction(id, () => repository.disconnect(id));
|
||||||
Future<void> localAdb() => action(() async {
|
Future<void> localAdb() => action(() async {
|
||||||
|
|||||||
@@ -24,7 +24,36 @@ class _ManagerViewState extends State<ManagerView> {
|
|||||||
int page = 0;
|
int page = 0;
|
||||||
String? screenDevice;
|
String? screenDevice;
|
||||||
String search = '';
|
String search = '';
|
||||||
|
bool addingNode = false;
|
||||||
|
final nodeId = TextEditingController();
|
||||||
|
final nodeUrl = TextEditingController();
|
||||||
|
final nodeAddress = TextEditingController();
|
||||||
|
final nodePriority = TextEditingController(text: '100');
|
||||||
ManagerModel get m => widget.model;
|
ManagerModel get m => widget.model;
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
for (final c in [nodeId, nodeUrl, nodeAddress, nodePriority]) {
|
||||||
|
c.dispose();
|
||||||
|
}
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> submitNode() async {
|
||||||
|
setState(() => addingNode = true);
|
||||||
|
try {
|
||||||
|
await m.addNode(
|
||||||
|
id: nodeId.text.trim(),
|
||||||
|
url: nodeUrl.text.trim(),
|
||||||
|
address: nodeAddress.text.trim(),
|
||||||
|
priority: int.tryParse(nodePriority.text.trim()) ?? 100,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
if (mounted) {
|
||||||
|
setState(() => addingNode = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) => ListenableBuilder(
|
Widget build(BuildContext context) => ListenableBuilder(
|
||||||
listenable: m,
|
listenable: m,
|
||||||
@@ -141,50 +170,71 @@ class _ManagerViewState extends State<ManagerView> {
|
|||||||
Container(
|
Container(
|
||||||
color: Colors.white,
|
color: Colors.white,
|
||||||
padding: const EdgeInsets.symmetric(
|
padding: const EdgeInsets.symmetric(
|
||||||
horizontal: 28,
|
horizontal: 24,
|
||||||
vertical: 20,
|
vertical: 20,
|
||||||
),
|
),
|
||||||
child: Row(
|
child: SizedBox(
|
||||||
children: [
|
height: 67,
|
||||||
Expanded(
|
child: Row(
|
||||||
child: Column(
|
children: [
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
Expanded(
|
||||||
children: [
|
child: Column(
|
||||||
Text(
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
[
|
children: [
|
||||||
'设备工作台',
|
SizedBox(
|
||||||
'中继节点',
|
height: 30,
|
||||||
'本机 ADB',
|
child: Text(
|
||||||
'连接配置',
|
[
|
||||||
'运行日志',
|
'设备工作台',
|
||||||
'Agent 管理',
|
'中继节点',
|
||||||
'内嵌投屏',
|
'本机 ADB',
|
||||||
][page],
|
'连接配置',
|
||||||
style: const TextStyle(
|
'运行日志',
|
||||||
fontSize: 24,
|
'Agent 管理',
|
||||||
fontWeight: FontWeight.w700,
|
'内嵌投屏',
|
||||||
|
][page],
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 24,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
height: 1.25,
|
||||||
|
),
|
||||||
|
strutStyle: const StrutStyle(
|
||||||
|
fontSize: 24,
|
||||||
|
height: 1.25,
|
||||||
|
forceStrutHeight: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
const SizedBox(height: 5),
|
||||||
const SizedBox(height: 5),
|
SizedBox(
|
||||||
Text(
|
height: 32,
|
||||||
m.notice,
|
child: Text(
|
||||||
maxLines: 2,
|
m.notice,
|
||||||
overflow: TextOverflow.ellipsis,
|
maxLines: 2,
|
||||||
style: const TextStyle(
|
overflow: TextOverflow.ellipsis,
|
||||||
color: Color(0xFF66758D),
|
style: const TextStyle(
|
||||||
fontSize: 12,
|
color: Color(0xFF66758D),
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.3,
|
||||||
|
),
|
||||||
|
strutStyle: const StrutStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.3,
|
||||||
|
forceStrutHeight: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
],
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
),
|
const SizedBox(width: 12),
|
||||||
const SizedBox(width: 12),
|
OutlinedButton.icon(
|
||||||
OutlinedButton.icon(
|
onPressed: m.refreshing ? null : m.refresh,
|
||||||
onPressed: m.refreshing ? null : m.refresh,
|
icon: const Icon(Icons.refresh, size: 18),
|
||||||
icon: const Icon(Icons.refresh, size: 18),
|
label: Text(m.refreshing ? '同步中' : '刷新'),
|
||||||
label: Text(m.refreshing ? '同步中' : '刷新'),
|
),
|
||||||
),
|
],
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
SizedBox(
|
SizedBox(
|
||||||
@@ -508,27 +558,244 @@ class _ManagerViewState extends State<ManagerView> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget nodes() => m.nodes.isEmpty
|
Widget nodes() {
|
||||||
? const Center(child: Text('暂无中继节点,或服务尚未启用 v2 节点接口'))
|
final hint = m.nodeCredentialHint;
|
||||||
: ListView.separated(
|
return Column(
|
||||||
itemCount: m.nodes.length,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
separatorBuilder: (_, index) => const SizedBox(height: 12),
|
children: [
|
||||||
itemBuilder: (_, i) {
|
Card(
|
||||||
final n = m.nodes[i];
|
child: Padding(
|
||||||
return Card(
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||||
child: ListTile(
|
child: Row(
|
||||||
contentPadding: const EdgeInsets.all(20),
|
children: [
|
||||||
leading: Icon(
|
const Icon(
|
||||||
Icons.hub,
|
Icons.hub_outlined,
|
||||||
color: n['healthy'] == true ? Colors.teal : Colors.grey,
|
size: 20,
|
||||||
|
color: Color(0xFF305DDB),
|
||||||
),
|
),
|
||||||
title: Text('${n["id"]}'),
|
const SizedBox(width: 12),
|
||||||
subtitle: Text(n['healthy'] == true ? '在线' : '不可用'),
|
const Expanded(
|
||||||
trailing: Text('通道 ${n["sessions"]} / ${n["capacity"]}'),
|
child: Text(
|
||||||
),
|
'中继节点由控制中心管理:新增、删除和设置默认节点会写入服务端 cluster.json,并影响后续连接优先尝试的路由。',
|
||||||
);
|
style: TextStyle(
|
||||||
},
|
fontSize: 12,
|
||||||
);
|
color: Color(0xFF66758D),
|
||||||
|
height: 1.4,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
const Text(
|
||||||
|
'新增节点',
|
||||||
|
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Wrap(
|
||||||
|
spacing: 12,
|
||||||
|
runSpacing: 12,
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 150,
|
||||||
|
child: TextField(
|
||||||
|
controller: nodeId,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: '节点 ID',
|
||||||
|
hintText: 'relay-3',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 320,
|
||||||
|
child: TextField(
|
||||||
|
controller: nodeUrl,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: '中继 URL',
|
||||||
|
hintText: 'wss://example.com/ads-relay',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 210,
|
||||||
|
child: TextField(
|
||||||
|
controller: nodeAddress,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: '直连地址(可留空)',
|
||||||
|
hintText: '1.2.3.4:443',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 110,
|
||||||
|
child: TextField(
|
||||||
|
controller: nodePriority,
|
||||||
|
decoration: const InputDecoration(labelText: '优先级'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
if (hint.isNotEmpty)
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
hint,
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Color(0xFFB26A00),
|
||||||
|
fontSize: 12,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
const Spacer(),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed: addingNode || hint.isNotEmpty
|
||||||
|
? null
|
||||||
|
: submitNode,
|
||||||
|
icon: const Icon(Icons.add, size: 18),
|
||||||
|
label: Text(addingNode ? '提交中' : '添加节点'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Expanded(
|
||||||
|
child: m.nodes.isEmpty
|
||||||
|
? const Center(child: Text('暂无中继节点,或服务尚未启用 v2 节点接口'))
|
||||||
|
: ListView.separated(
|
||||||
|
itemCount: m.nodes.length,
|
||||||
|
separatorBuilder: (_, index) => const SizedBox(height: 12),
|
||||||
|
itemBuilder: (_, i) {
|
||||||
|
final n = m.nodes[i];
|
||||||
|
final id = '${n['id']}';
|
||||||
|
final busy = m.pending.contains('node:$id');
|
||||||
|
final online = n['healthy'] == true;
|
||||||
|
final isDefault = n['default'] == true;
|
||||||
|
final address = '${n['connect_address'] ?? ''}';
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 20,
|
||||||
|
vertical: 14,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.hub,
|
||||||
|
color: online ? Colors.teal : Colors.grey,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 16),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
id,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 15,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (isDefault)
|
||||||
|
Container(
|
||||||
|
margin: const EdgeInsets.only(
|
||||||
|
left: 8,
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 8,
|
||||||
|
vertical: 2,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: const Color(0xFFE3EBFF),
|
||||||
|
borderRadius: BorderRadius.circular(
|
||||||
|
10,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Text(
|
||||||
|
'默认',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
color: Color(0xFF305DDB),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
'${n['url']}${address.isEmpty ? '' : ' · $address'}',
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: Color(0xFF66758D),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
'${online ? '在线' : '不可用'} · 通道 ${n['sessions']} / ${n['capacity']}',
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: Color(0xFF66758D),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
if (!isDefault)
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: busy
|
||||||
|
? null
|
||||||
|
: () => m.deviceAction(
|
||||||
|
'node:$id',
|
||||||
|
() => m.defaultNode(id),
|
||||||
|
),
|
||||||
|
icon: const Icon(Icons.star_border, size: 16),
|
||||||
|
label: const Text('设为默认'),
|
||||||
|
),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: busy
|
||||||
|
? null
|
||||||
|
: () => m.deviceAction(
|
||||||
|
'node:$id',
|
||||||
|
() => m.removeNode(id),
|
||||||
|
),
|
||||||
|
icon: const Icon(
|
||||||
|
Icons.delete_outline,
|
||||||
|
size: 16,
|
||||||
|
color: Color(0xFFB3261E),
|
||||||
|
),
|
||||||
|
label: const Text(
|
||||||
|
'删除',
|
||||||
|
style: TextStyle(color: Color(0xFFB3261E)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Widget adb() => Column(
|
Widget adb() => Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import 'package:ads_manager/ui/agent_view.dart';
|
|||||||
class FakeApi implements AgentApi {
|
class FakeApi implements AgentApi {
|
||||||
@override
|
@override
|
||||||
String connectionKey = 'first-center';
|
String connectionKey = 'first-center';
|
||||||
|
@override
|
||||||
|
String adminToken = '';
|
||||||
final calls = <JsonMap>[];
|
final calls = <JsonMap>[];
|
||||||
Completer<List<JsonMap>>? pending;
|
Completer<List<JsonMap>>? pending;
|
||||||
JsonMap status(String id) => {
|
JsonMap status(String id) => {
|
||||||
|
|||||||
+192
-11
@@ -27,6 +27,7 @@ type NodeConfig struct {
|
|||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
ConnectAddress string `json:"connect_address,omitempty"`
|
ConnectAddress string `json:"connect_address,omitempty"`
|
||||||
Priority int `json:"priority"`
|
Priority int `json:"priority"`
|
||||||
|
Default bool `json:"default,omitempty"`
|
||||||
}
|
}
|
||||||
type clusterConfig struct {
|
type clusterConfig struct {
|
||||||
Nodes []NodeConfig `json:"nodes"`
|
Nodes []NodeConfig `json:"nodes"`
|
||||||
@@ -41,6 +42,8 @@ type nodeHealth struct {
|
|||||||
type cluster struct {
|
type cluster struct {
|
||||||
config clusterConfig
|
config clusterConfig
|
||||||
secret string
|
secret string
|
||||||
|
path string
|
||||||
|
allowInsecure bool
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
health map[string]nodeHealth
|
health map[string]nodeHealth
|
||||||
signalingBytes atomic.Int64
|
signalingBytes atomic.Int64
|
||||||
@@ -52,6 +55,19 @@ type route struct {
|
|||||||
Ticket string `json:"ticket"`
|
Ticket string `json:"ticket"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateNode(node NodeConfig, allowInsecure bool) error {
|
||||||
|
u, err := url.Parse(node.URL)
|
||||||
|
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "wss" && !(allowInsecure && u.Scheme == "ws")) || !validID(node.ID) {
|
||||||
|
return errors.New("invalid relay node id or URL")
|
||||||
|
}
|
||||||
|
if node.ConnectAddress != "" {
|
||||||
|
if _, _, err = net.SplitHostPort(node.ConnectAddress); err != nil {
|
||||||
|
return errors.New("invalid node connect_address")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func loadCluster(path, secret string, allowInsecure bool) (*cluster, error) {
|
func loadCluster(path, secret string, allowInsecure bool) (*cluster, error) {
|
||||||
if len(secret) < 32 {
|
if len(secret) < 32 {
|
||||||
return nil, errors.New("cluster mode requires ADS_RELAY_SECRET (32+ characters)")
|
return nil, errors.New("cluster mode requires ADS_RELAY_SECRET (32+ characters)")
|
||||||
@@ -77,24 +93,25 @@ func loadCluster(path, secret string, allowInsecure bool) (*cluster, error) {
|
|||||||
return nil, errors.New("p2p_timeout_ms must be 1000–30000")
|
return nil, errors.New("p2p_timeout_ms must be 1000–30000")
|
||||||
}
|
}
|
||||||
seen := map[string]bool{}
|
seen := map[string]bool{}
|
||||||
|
defaults := 0
|
||||||
for _, node := range config.Nodes {
|
for _, node := range config.Nodes {
|
||||||
u, e := url.Parse(node.URL)
|
if err = validateNode(node, allowInsecure); err != nil || seen[node.ID] {
|
||||||
if e != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "wss" && !(allowInsecure && u.Scheme == "ws")) || !validID(node.ID) || seen[node.ID] {
|
|
||||||
return nil, errors.New("invalid or duplicate relay node")
|
return nil, errors.New("invalid or duplicate relay node")
|
||||||
}
|
}
|
||||||
if node.ConnectAddress != "" {
|
if node.Default {
|
||||||
if _, _, e = net.SplitHostPort(node.ConnectAddress); e != nil {
|
defaults++
|
||||||
return nil, errors.New("invalid node connect_address")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
seen[node.ID] = true
|
seen[node.ID] = true
|
||||||
}
|
}
|
||||||
|
if defaults > 1 {
|
||||||
|
return nil, errors.New("at most one default relay node")
|
||||||
|
}
|
||||||
for _, ice := range config.ICEServers {
|
for _, ice := range config.ICEServers {
|
||||||
if !strings.HasPrefix(ice, "stun:") {
|
if !strings.HasPrefix(ice, "stun:") {
|
||||||
return nil, errors.New("only STUN URLs are accepted; fallback uses WSS relay nodes")
|
return nil, errors.New("only STUN URLs are accepted; fallback uses WSS relay nodes")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return &cluster{config: config, secret: secret, health: map[string]nodeHealth{}}, nil
|
return &cluster{config: config, secret: secret, path: path, allowInsecure: allowInsecure, health: map[string]nodeHealth{}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func nodeHTTP(node NodeConfig, path string) (*http.Client, string) {
|
func nodeHTTP(node NodeConfig, path string) (*http.Client, string) {
|
||||||
@@ -114,10 +131,20 @@ func nodeHTTP(node NodeConfig, path string) (*http.Client, string) {
|
|||||||
return &http.Client{Transport: transport, Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, u.String()
|
return &http.Client{Transport: transport, Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, u.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *cluster) snapshot() clusterConfig {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
config := c.config
|
||||||
|
config.Nodes = append([]NodeConfig{}, c.config.Nodes...)
|
||||||
|
config.ICEServers = append([]string{}, c.config.ICEServers...)
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
func (c *cluster) monitor(ctx context.Context) {
|
func (c *cluster) monitor(ctx context.Context) {
|
||||||
probe := func() {
|
probe := func() {
|
||||||
|
nodes := c.snapshot().Nodes
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
for _, node := range c.config.Nodes {
|
for _, node := range nodes {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func(node NodeConfig) {
|
go func(node NodeConfig) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
@@ -158,13 +185,16 @@ func (c *cluster) monitor(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *cluster) routes(session, lease, side string) []route {
|
func (c *cluster) routes(session, lease, side string) []route {
|
||||||
nodes := append([]NodeConfig(nil), c.config.Nodes...)
|
nodes := c.snapshot().Nodes
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
sort.SliceStable(nodes, func(i, j int) bool {
|
sort.SliceStable(nodes, func(i, j int) bool {
|
||||||
a, b := c.health[nodes[i].ID], c.health[nodes[j].ID]
|
a, b := c.health[nodes[i].ID], c.health[nodes[j].ID]
|
||||||
if a.Healthy != b.Healthy {
|
if a.Healthy != b.Healthy {
|
||||||
return a.Healthy
|
return a.Healthy
|
||||||
}
|
}
|
||||||
|
if nodes[i].Default != nodes[j].Default {
|
||||||
|
return nodes[i].Default
|
||||||
|
}
|
||||||
if nodes[i].Priority != nodes[j].Priority {
|
if nodes[i].Priority != nodes[j].Priority {
|
||||||
return nodes[i].Priority < nodes[j].Priority
|
return nodes[i].Priority < nodes[j].Priority
|
||||||
}
|
}
|
||||||
@@ -185,7 +215,7 @@ func (c *cluster) revoke(lease string) {
|
|||||||
}
|
}
|
||||||
body, _ := json.Marshal(map[string]string{"lease": lease})
|
body, _ := json.Marshal(map[string]string{"lease": lease})
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
for _, node := range c.config.Nodes {
|
for _, node := range c.snapshot().Nodes {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func(node NodeConfig) {
|
go func(node NodeConfig) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
@@ -202,6 +232,156 @@ func (c *cluster) revoke(lease string) {
|
|||||||
wg.Wait()
|
wg.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var errNodeNotFound = errors.New("relay node not found")
|
||||||
|
|
||||||
|
// mutate applies fn to a copy of the configuration and persists it before publishing.
|
||||||
|
func (c *cluster) mutate(fn func(*clusterConfig) error) error {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
next := c.config
|
||||||
|
next.Nodes = append([]NodeConfig{}, c.config.Nodes...)
|
||||||
|
next.ICEServers = append([]string{}, c.config.ICEServers...)
|
||||||
|
if err := fn(&next); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err := json.MarshalIndent(next, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tmp := c.path + ".tmp"
|
||||||
|
if err = os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = os.Rename(tmp, c.path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.config = next
|
||||||
|
for id := range c.health {
|
||||||
|
kept := false
|
||||||
|
for _, node := range next.Nodes {
|
||||||
|
if node.ID == id {
|
||||||
|
kept = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !kept {
|
||||||
|
delete(c.health, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *broker) addNodeEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if b.cluster == nil {
|
||||||
|
http.Error(w, "cluster not configured", 404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var node NodeConfig
|
||||||
|
if err := json.NewDecoder(io.LimitReader(r.Body, 8192)).Decode(&node); err != nil {
|
||||||
|
http.Error(w, "invalid JSON body", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
node.ID = strings.TrimSpace(node.ID)
|
||||||
|
node.URL = strings.TrimSpace(node.URL)
|
||||||
|
node.ConnectAddress = strings.TrimSpace(node.ConnectAddress)
|
||||||
|
if node.Priority <= 0 {
|
||||||
|
node.Priority = 100
|
||||||
|
}
|
||||||
|
err := b.cluster.mutate(func(config *clusterConfig) error {
|
||||||
|
if err := validateNode(node, b.cluster.allowInsecure); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, existing := range config.Nodes {
|
||||||
|
if existing.ID == node.ID {
|
||||||
|
return errors.New("relay node id already exists")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(config.Nodes) >= 32 {
|
||||||
|
return errors.New("at most 32 relay nodes")
|
||||||
|
}
|
||||||
|
if node.Default {
|
||||||
|
for i := range config.Nodes {
|
||||||
|
config.Nodes[i].Default = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
config.Nodes = append(config.Nodes, node)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *broker) deleteNodeEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if b.cluster == nil {
|
||||||
|
http.Error(w, "cluster not configured", 404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := r.PathValue("id")
|
||||||
|
err := b.cluster.mutate(func(config *clusterConfig) error {
|
||||||
|
index := -1
|
||||||
|
for i := range config.Nodes {
|
||||||
|
if config.Nodes[i].ID == id {
|
||||||
|
index = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if index < 0 {
|
||||||
|
return errNodeNotFound
|
||||||
|
}
|
||||||
|
if len(config.Nodes) <= 1 {
|
||||||
|
return errors.New("keep at least one relay node")
|
||||||
|
}
|
||||||
|
config.Nodes = append(config.Nodes[:index], config.Nodes[index+1:]...)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
status := 400
|
||||||
|
if errors.Is(err, errNodeNotFound) {
|
||||||
|
status = 404
|
||||||
|
}
|
||||||
|
http.Error(w, err.Error(), status)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *broker) defaultNodeEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if b.cluster == nil {
|
||||||
|
http.Error(w, "cluster not configured", 404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&body); err != nil {
|
||||||
|
http.Error(w, "invalid JSON body", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err := b.cluster.mutate(func(config *clusterConfig) error {
|
||||||
|
found := false
|
||||||
|
for i := range config.Nodes {
|
||||||
|
config.Nodes[i].Default = config.Nodes[i].ID == body.ID
|
||||||
|
found = found || config.Nodes[i].Default
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return errNodeNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
status := 400
|
||||||
|
if errors.Is(err, errNodeNotFound) {
|
||||||
|
status = 404
|
||||||
|
}
|
||||||
|
http.Error(w, err.Error(), status)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
func (b *broker) nodesEndpoint(w http.ResponseWriter, r *http.Request) {
|
func (b *broker) nodesEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
if b.cluster == nil {
|
if b.cluster == nil {
|
||||||
http.Error(w, "cluster not configured", 404)
|
http.Error(w, "cluster not configured", 404)
|
||||||
@@ -256,9 +436,10 @@ func (b *broker) clusterConnectEndpoint(w http.ResponseWriter, r *http.Request)
|
|||||||
}
|
}
|
||||||
defer client.CloseNow()
|
defer client.CloseNow()
|
||||||
publicOnly := r.URL.Query().Get("public_only") == "1"
|
publicOnly := r.URL.Query().Get("public_only") == "1"
|
||||||
|
config := b.cluster.snapshot()
|
||||||
manifest := func(side string) map[string]any {
|
manifest := func(side string) map[string]any {
|
||||||
return map[string]any{"type": "session", "protocol": 2, "session": s.id,
|
return map[string]any{"type": "session", "protocol": 2, "session": s.id,
|
||||||
"ice_servers": b.cluster.config.ICEServers, "p2p_timeout_ms": b.cluster.config.P2PTimeoutMS, "public_only": publicOnly, "routes": b.cluster.routes(s.id, l.id, side)}
|
"ice_servers": config.ICEServers, "p2p_timeout_ms": config.P2PTimeoutMS, "public_only": publicOnly, "routes": b.cluster.routes(s.id, l.id, side)}
|
||||||
}
|
}
|
||||||
if writeJSON(ctx, client, manifest("client")) != nil {
|
if writeJSON(ctx, client, manifest("client")) != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -386,6 +386,9 @@ func (b *broker) handler() http.Handler {
|
|||||||
mux.HandleFunc("GET /v1/lease", b.auth(b.clientToken, b.leaseEndpoint))
|
mux.HandleFunc("GET /v1/lease", b.auth(b.clientToken, b.leaseEndpoint))
|
||||||
mux.HandleFunc("GET /v1/connect", b.auth(b.clientToken, b.connectEndpoint))
|
mux.HandleFunc("GET /v1/connect", b.auth(b.clientToken, b.connectEndpoint))
|
||||||
mux.HandleFunc("GET /v2/nodes", b.auth(b.clientToken, b.nodesEndpoint))
|
mux.HandleFunc("GET /v2/nodes", b.auth(b.clientToken, b.nodesEndpoint))
|
||||||
|
mux.HandleFunc("POST /v2/nodes", b.managementAuth(b.addNodeEndpoint))
|
||||||
|
mux.HandleFunc("DELETE /v2/nodes/{id}", b.managementAuth(b.deleteNodeEndpoint))
|
||||||
|
mux.HandleFunc("POST /v2/nodes/default", b.managementAuth(b.defaultNodeEndpoint))
|
||||||
mux.HandleFunc("GET /v2/connect", b.auth(b.clientToken, b.clusterConnectEndpoint))
|
mux.HandleFunc("GET /v2/connect", b.auth(b.clientToken, b.clusterConnectEndpoint))
|
||||||
mux.HandleFunc("GET /v2/signal", b.auth(b.agentToken, b.signalEndpoint))
|
mux.HandleFunc("GET /v2/signal", b.auth(b.agentToken, b.signalEndpoint))
|
||||||
return mux
|
return mux
|
||||||
|
|||||||
Reference in new issue
Block a user