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
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/etc/ads
|
||||
MemoryMax=256M
|
||||
LimitNOFILE=8192
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ typedef JsonMap = Map<String, Object?>;
|
||||
|
||||
abstract interface class AgentApi {
|
||||
String get connectionKey;
|
||||
String get adminToken;
|
||||
Future<List<JsonMap>> list();
|
||||
Future<Object?> request(String agent, JsonMap operation);
|
||||
Future<Object?> local(String config, JsonMap operation);
|
||||
@@ -29,6 +30,8 @@ class AgentService implements AgentApi {
|
||||
String _token = '';
|
||||
final Set<String> _secrets = {};
|
||||
@override
|
||||
String get adminToken => _token;
|
||||
@override
|
||||
String redact(String message) {
|
||||
for (final secret in _secrets) {
|
||||
message = message.replaceAll(secret, '[REDACTED]');
|
||||
|
||||
@@ -85,6 +85,7 @@ class Session {
|
||||
bool screenEmbedded = false;
|
||||
String state = '连接中', route = '协商中';
|
||||
bool ready = false, stopping = false, exited = false;
|
||||
int missingPasses = 0;
|
||||
Session(this.id, this.tunnel, this.adb, this.statusFile, this.process);
|
||||
}
|
||||
|
||||
@@ -194,6 +195,7 @@ class ManagerRepository {
|
||||
String? bearer,
|
||||
Map<String, Object?>? payload,
|
||||
Map<String, String>? query,
|
||||
String? method,
|
||||
}) async {
|
||||
final authorization = bearer ?? token;
|
||||
if (authorization.length < 32) {
|
||||
@@ -231,9 +233,10 @@ class ManagerRepository {
|
||||
}
|
||||
try {
|
||||
final uri = settings.uri(suffix).replace(queryParameters: query);
|
||||
final request = payload == null
|
||||
? await client.getUrl(uri)
|
||||
: await client.postUrl(uri);
|
||||
final request = await client.openUrl(
|
||||
method ?? (payload == null ? 'GET' : 'POST'),
|
||||
uri,
|
||||
);
|
||||
request.followRedirects = false;
|
||||
request.headers.set('Authorization', 'Bearer $authorization');
|
||||
if (payload != null) {
|
||||
@@ -250,8 +253,14 @@ class ManagerRepository {
|
||||
if (suffix == 'v2/nodes' && response.statusCode == 404) {
|
||||
return {'nodes': <dynamic>[]};
|
||||
}
|
||||
if (response.statusCode != 200) {
|
||||
throw HttpException('控制中心 HTTP ${response.statusCode}');
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
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);
|
||||
} finally {
|
||||
@@ -483,7 +492,32 @@ class ManagerRepository {
|
||||
|
||||
Future<void> monitor() async {
|
||||
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()) {
|
||||
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) {
|
||||
await disconnect(s.id);
|
||||
continue;
|
||||
|
||||
@@ -12,6 +12,7 @@ import '../data/agent_service.dart';
|
||||
class AgentModel extends ChangeNotifier {
|
||||
AgentModel(this.repository);
|
||||
final AgentRepository repository;
|
||||
String get adminToken => repository.api.adminToken;
|
||||
void Function(String)? onLog;
|
||||
List<ManagedAgent> _agents = [];
|
||||
List<ManagedAgent> get agents => List.unmodifiable(_agents);
|
||||
|
||||
@@ -149,6 +149,45 @@ class ManagerModel extends ChangeNotifier {
|
||||
await repository.connect(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) =>
|
||||
deviceAction(id, () => repository.disconnect(id));
|
||||
Future<void> localAdb() => action(() async {
|
||||
|
||||
@@ -24,7 +24,36 @@ class _ManagerViewState extends State<ManagerView> {
|
||||
int page = 0;
|
||||
String? screenDevice;
|
||||
String search = '';
|
||||
bool addingNode = false;
|
||||
final nodeId = TextEditingController();
|
||||
final nodeUrl = TextEditingController();
|
||||
final nodeAddress = TextEditingController();
|
||||
final nodePriority = TextEditingController(text: '100');
|
||||
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
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: m,
|
||||
@@ -141,50 +170,71 @@ class _ManagerViewState extends State<ManagerView> {
|
||||
Container(
|
||||
color: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 28,
|
||||
horizontal: 24,
|
||||
vertical: 20,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
[
|
||||
'设备工作台',
|
||||
'中继节点',
|
||||
'本机 ADB',
|
||||
'连接配置',
|
||||
'运行日志',
|
||||
'Agent 管理',
|
||||
'内嵌投屏',
|
||||
][page],
|
||||
style: const TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w700,
|
||||
child: SizedBox(
|
||||
height: 67,
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 30,
|
||||
child: Text(
|
||||
[
|
||||
'设备工作台',
|
||||
'中继节点',
|
||||
'本机 ADB',
|
||||
'连接配置',
|
||||
'运行日志',
|
||||
'Agent 管理',
|
||||
'内嵌投屏',
|
||||
][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),
|
||||
Text(
|
||||
m.notice,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF66758D),
|
||||
fontSize: 12,
|
||||
const SizedBox(height: 5),
|
||||
SizedBox(
|
||||
height: 32,
|
||||
child: Text(
|
||||
m.notice,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF66758D),
|
||||
fontSize: 12,
|
||||
height: 1.3,
|
||||
),
|
||||
strutStyle: const StrutStyle(
|
||||
fontSize: 12,
|
||||
height: 1.3,
|
||||
forceStrutHeight: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: m.refreshing ? null : m.refresh,
|
||||
icon: const Icon(Icons.refresh, size: 18),
|
||||
label: Text(m.refreshing ? '同步中' : '刷新'),
|
||||
),
|
||||
],
|
||||
const SizedBox(width: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: m.refreshing ? null : m.refresh,
|
||||
icon: const Icon(Icons.refresh, size: 18),
|
||||
label: Text(m.refreshing ? '同步中' : '刷新'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
@@ -508,27 +558,244 @@ class _ManagerViewState extends State<ManagerView> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget nodes() => 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];
|
||||
return Card(
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.all(20),
|
||||
leading: Icon(
|
||||
Icons.hub,
|
||||
color: n['healthy'] == true ? Colors.teal : Colors.grey,
|
||||
Widget nodes() {
|
||||
final hint = m.nodeCredentialHint;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.hub_outlined,
|
||||
size: 20,
|
||||
color: Color(0xFF305DDB),
|
||||
),
|
||||
title: Text('${n["id"]}'),
|
||||
subtitle: Text(n['healthy'] == true ? '在线' : '不可用'),
|
||||
trailing: Text('通道 ${n["sessions"]} / ${n["capacity"]}'),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
const SizedBox(width: 12),
|
||||
const Expanded(
|
||||
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(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
|
||||
@@ -10,6 +10,8 @@ import 'package:ads_manager/ui/agent_view.dart';
|
||||
class FakeApi implements AgentApi {
|
||||
@override
|
||||
String connectionKey = 'first-center';
|
||||
@override
|
||||
String adminToken = '';
|
||||
final calls = <JsonMap>[];
|
||||
Completer<List<JsonMap>>? pending;
|
||||
JsonMap status(String id) => {
|
||||
|
||||
+192
-11
@@ -27,6 +27,7 @@ type NodeConfig struct {
|
||||
URL string `json:"url"`
|
||||
ConnectAddress string `json:"connect_address,omitempty"`
|
||||
Priority int `json:"priority"`
|
||||
Default bool `json:"default,omitempty"`
|
||||
}
|
||||
type clusterConfig struct {
|
||||
Nodes []NodeConfig `json:"nodes"`
|
||||
@@ -41,6 +42,8 @@ type nodeHealth struct {
|
||||
type cluster struct {
|
||||
config clusterConfig
|
||||
secret string
|
||||
path string
|
||||
allowInsecure bool
|
||||
mu sync.Mutex
|
||||
health map[string]nodeHealth
|
||||
signalingBytes atomic.Int64
|
||||
@@ -52,6 +55,19 @@ type route struct {
|
||||
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) {
|
||||
if len(secret) < 32 {
|
||||
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")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
defaults := 0
|
||||
for _, node := range config.Nodes {
|
||||
u, e := url.Parse(node.URL)
|
||||
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] {
|
||||
if err = validateNode(node, allowInsecure); err != nil || seen[node.ID] {
|
||||
return nil, errors.New("invalid or duplicate relay node")
|
||||
}
|
||||
if node.ConnectAddress != "" {
|
||||
if _, _, e = net.SplitHostPort(node.ConnectAddress); e != nil {
|
||||
return nil, errors.New("invalid node connect_address")
|
||||
}
|
||||
if node.Default {
|
||||
defaults++
|
||||
}
|
||||
seen[node.ID] = true
|
||||
}
|
||||
if defaults > 1 {
|
||||
return nil, errors.New("at most one default relay node")
|
||||
}
|
||||
for _, ice := range config.ICEServers {
|
||||
if !strings.HasPrefix(ice, "stun:") {
|
||||
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) {
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
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) {
|
||||
probe := func() {
|
||||
nodes := c.snapshot().Nodes
|
||||
var wg sync.WaitGroup
|
||||
for _, node := range c.config.Nodes {
|
||||
for _, node := range nodes {
|
||||
wg.Add(1)
|
||||
go func(node NodeConfig) {
|
||||
defer wg.Done()
|
||||
@@ -158,13 +185,16 @@ func (c *cluster) monitor(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (c *cluster) routes(session, lease, side string) []route {
|
||||
nodes := append([]NodeConfig(nil), c.config.Nodes...)
|
||||
nodes := c.snapshot().Nodes
|
||||
c.mu.Lock()
|
||||
sort.SliceStable(nodes, func(i, j int) bool {
|
||||
a, b := c.health[nodes[i].ID], c.health[nodes[j].ID]
|
||||
if a.Healthy != b.Healthy {
|
||||
return a.Healthy
|
||||
}
|
||||
if nodes[i].Default != nodes[j].Default {
|
||||
return nodes[i].Default
|
||||
}
|
||||
if 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})
|
||||
var wg sync.WaitGroup
|
||||
for _, node := range c.config.Nodes {
|
||||
for _, node := range c.snapshot().Nodes {
|
||||
wg.Add(1)
|
||||
go func(node NodeConfig) {
|
||||
defer wg.Done()
|
||||
@@ -202,6 +232,156 @@ func (c *cluster) revoke(lease string) {
|
||||
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) {
|
||||
if b.cluster == nil {
|
||||
http.Error(w, "cluster not configured", 404)
|
||||
@@ -256,9 +436,10 @@ func (b *broker) clusterConnectEndpoint(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
defer client.CloseNow()
|
||||
publicOnly := r.URL.Query().Get("public_only") == "1"
|
||||
config := b.cluster.snapshot()
|
||||
manifest := func(side string) map[string]any {
|
||||
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 {
|
||||
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/connect", b.auth(b.clientToken, b.connectEndpoint))
|
||||
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/signal", b.auth(b.agentToken, b.signalEndpoint))
|
||||
return mux
|
||||
|
||||
Reference in new issue
Block a user