diff --git a/luci/graph.js b/luci/graph.js index 136a57b..07eb1e6 100644 --- a/luci/graph.js +++ b/luci/graph.js @@ -464,32 +464,56 @@ // --- live state (mihomo API) ------------------------------------------------- - // live(m, proxies, connections) -> what each group uses, alive nodes per provider and - // where the connections go: { now: {id: name}, edges: {i: {n, rate}}, nodes: {id: {n}}, ... } - // proxies: GET /proxies .proxies; connections: GET /connections .connections - // prev: the previous result (byte counters -> rates) - function live(m, proxies, connections, prev) { + // live(m, proxies, connections, prev, providers) -> what each group uses, alive nodes per + // provider and where the connections go: + // { now: {id: name}, nowProv: {id: provider id}, edges: {i: {n, rate}}, nodes: {id: {n}}, ... } + // proxies: GET /proxies .proxies (groups and the config's proxies only); + // providers: GET /providers/proxies .providers (the subscriptions' nodes); + // connections: GET /connections .connections; prev: the previous result (byte counters -> rates) + function live(m, proxies, connections, prev, providers) { proxies = proxies || {}; - var L = { now: {}, delay: {}, provider: {}, edges: {}, nodes: {}, bytes: {}, total: 0, unmatched: 0, at: Date.now() }; + var L = { now: {}, nowProv: {}, delay: {}, provider: {}, edges: {}, nodes: {}, bytes: {}, + total: 0, unmatched: 0, unmatchedRules: {}, at: Date.now() }; var edgeIndex = {}; m.edges.forEach(function(e, i) { edgeIndex[e.from + '\n' + e.to] = i; }); var lastDelay = function(p) { var h = p && p.history; return h && h.length ? h[h.length - 1].delay : 0; }; - Object.keys(proxies).forEach(function(name) { - var p = proxies[name]; - if (m.groups[name] && p.now != null) { - L.now['g:' + name] = p.now; - L.delay['g:' + name] = lastDelay(proxies[p.now]); - } - var pv = p['provider-name']; - if (pv && m.providers[pv] && !m.groups[name]) { - var s = L.provider['v:' + pv] = L.provider['v:' + pv] || { n: 0, alive: 0 }; + // nodes per provider of this config: {provider: {name: proxy}} + var inProv = {}; + Object.keys(providers || {}).forEach(function(v) { + if (!m.providers[v]) + return; + var set = inProv[v] = {}, s = L.provider['v:' + v] = { n: 0, alive: 0 }; + (providers[v].proxies || []).forEach(function(p) { + set[p.name] = p; s.n++; if (p.alive) s.alive++; - } + }); + }); + // a node name as a group uses it: { p: the API's proxy, v: its provider }; the same + // name in two subscriptions -> the one in the group's use + var find = function(name, user) { + if (proxies[name] && !inProv[proxies[name]['provider-name']]) + return { p: proxies[name] }; + var g = m.nodes[user] && m.nodes[user].kind == 'group' && m.nodes[user].data.def; + var vs = (g && g.use || []).concat(Object.keys(inProv)); + for (var i = 0; i < vs.length; i++) + if (inProv[vs[i]] && inProv[vs[i]][name]) + return { p: inProv[vs[i]][name], v: vs[i] }; + return null; + }; + Object.keys(proxies).forEach(function(name) { + var p = proxies[name]; + if (!m.groups[name] || p.now == null) + return; + var id = 'g:' + name, f = find(p.now, id); + L.now[id] = p.now; + L.delay[id] = lastDelay(f && f.p); + if (f && f.v) + L.nowProv[id] = 'v:' + f.v; }); // a proxy name of the API -> node id: groups, own proxies, provider nodes, built-ins var idOf = function(name, user) { @@ -497,9 +521,9 @@ return 'g:' + name; if (m.proxies[name]) return 'p:' + name; - var p = proxies[name]; - if (p && p['provider-name'] && m.providers[p['provider-name']]) - return 'v:' + p['provider-name']; + var f = find(name, user); + if (f && f.v) + return 'v:' + f.v; return 'b:' + name + '@' + user; }; // from a node on: the dialer-proxy chain and the groups' current choice @@ -529,6 +553,8 @@ var rid = m.ruleIndex[ruleKey(c.rule || '', c.rulePayload || '')]; if (!rid) { L.unmatched++; + var u = (c.rule || 'без правила') + (c.rulePayload ? ' ' + c.rulePayload : ''); + L.unmatchedRules[u] = (L.unmatchedRules[u] || 0) + 1; return; } var b = (c.upload || 0) + (c.download || 0); @@ -700,11 +726,13 @@ var fit = function() { if (!lay) return; - var W = stage.clientWidth || 800, H = stage.clientHeight || 500, pad = 16; + // as wide as the box, at most 72% of the window high; the box no taller than the graph + var W = stage.clientWidth || 800, H = Math.max(360, (window.innerHeight || 800) * 0.72), pad = 16; view.k = Math.min(1.2, (W - pad * 2) / Math.max(lay.width, 1), (H - pad * 2) / Math.max(lay.height, 1)); view.k = Math.max(view.k, 0.35); + stage.style.height = Math.round(Math.min(H, Math.max(360, lay.height * view.k + pad * 2 + 40))) + 'px'; view.x = pad; - view.y = Math.max(pad, (H - lay.height * view.k) / 2); + view.y = pad; apply(); }; stage.appendChild(el('div', { 'class': 'mkg-zoom' }, [ @@ -950,7 +978,7 @@ if (now != null && (e.kind == 'member' || e.kind == 'use')) { var target = m.nodes[e.to]; isNow = target && (target.label == now && e.kind == 'member' || - e.kind == 'use' && L.nodeOfNow && L.nodeOfNow[e.from] == e.to); + e.kind == 'use' && L.nowProv[e.from] == e.to); isOff = !isNow; } var f = on && L.edges[i]; @@ -988,6 +1016,10 @@ }); stat.textContent = on ? 'соединений: ' + L.total + (L.unmatched ? ' (без правила в графе: ' + L.unmatched + ')' : '') + ' · обновлено ' + new Date(L.at).toLocaleTimeString() : ''; + stat.title = on && L.unmatched ? 'правила этих соединений (mihomo ' + + 'сам или правило не из профиля):\n' + Object.keys(L.unmatchedRules).map(function(k) { + return k + ' — ' + L.unmatchedRules[k]; + }).join('\n') : ''; if (selected) focus(selected); if (selected && m.nodes[selected]) @@ -996,7 +1028,7 @@ showLive.addEventListener('change', paint); onlyNow.addEventListener('change', paint); - var proxiesLive = null; + var proxiesLive = null, providersLive = null; return { show: function(cfg) { m = model(cfg); @@ -1010,20 +1042,16 @@ paint(); return m; }, - // proxies: GET /proxies .proxies; connections: GET /connections .connections - live: function(proxies, connections) { + // GET /proxies .proxies, /connections .connections, /providers/proxies .providers; + // null keeps the last proxies / providers + live: function(proxies, connections, providers) { if (!m) return; if (proxies) proxiesLive = proxies; - L = live(m, proxiesLive, connections, L); - // which subscription the current choice of a group comes from - L.nodeOfNow = {}; - Object.keys(L.now).forEach(function(g) { - var p = proxiesLive[L.now[g]]; - if (p && p['provider-name']) - L.nodeOfNow[g] = 'v:' + p['provider-name']; - }); + if (providers) + providersLive = providers; + L = live(m, proxiesLive, connections, L, providersLive); paint(); }, fit: fit, diff --git a/luci/mihomo-kit-graph.js b/luci/mihomo-kit-graph.js index 3639e8b..885891f 100644 --- a/luci/mihomo-kit-graph.js +++ b/luci/mihomo-kit-graph.js @@ -28,7 +28,8 @@ return view.extend({ return Promise.all([ loadScript('servers.js', 'mkServers'), loadScript('graph.js', 'mkGraph'), callGraph(''), callStatus() ]); }, - // /proxies every 10 s, /connections every 3 s; only for the running profile and a visible tab + // /proxies and /providers/proxies every 9 s, /connections every 3 s; only for the running + // profile and a visible tab poll: function() { var tick = 0; var loop = L.bind(function() { @@ -36,11 +37,12 @@ return view.extend({ return; if (document.hidden || !this.liveOn) return void (this.timer = window.setTimeout(loop, 3000)); - var want = tick++ % 3 == 0 ? callApi('/proxies') : Promise.resolve(null); - Promise.all([ want, callApi('/connections') ]).then(L.bind(function(r) { - if (r[0] && r[0].error || r[1].error) - throw new Error((r[0] && r[0].error) || r[1].error); - this.graph.live(r[0] && r[0].proxies, r[1].connections || []); + var full = tick++ % 3 == 0; + Promise.all([ full ? callApi('/proxies') : null, callApi('/connections'), full ? callApi('/providers/proxies') : null ]).then(L.bind(function(r) { + var err = r.filter(function(x) { return x && x.error; })[0]; + if (err) + throw new Error(err.error); + this.graph.live(r[0] && r[0].proxies, r[1].connections || [], r[2] && r[2].providers); dom.content(this.state, ''); }, this)).catch(L.bind(function(e) { dom.content(this.state, E('em', 'живое состояние недоступно: ' + (e.message || e))); diff --git a/tools/graph.html b/tools/graph.html index 1236a71..70b3376 100644 --- a/tools/graph.html +++ b/tools/graph.html @@ -91,7 +91,7 @@ read(e.dataTransfer.files[0]); }); - // live: /proxies every 10 s, /connections every 2 s + // live: /proxies and /providers/proxies every 10 s, /connections every 2 s var api = function(path) { var base = $('api').value.trim().replace(/\/+$/, ''), sec = $('secret').value; return fetch(base + path, { headers: sec ? { Authorization: 'Bearer ' + sec } : {} }).then(function(r) { @@ -108,9 +108,9 @@ return ($('apiState').textContent = 'сначала конфиг'); var tick = 0; var loop = function() { - var want = tick++ % 5 == 0 ? api('/proxies') : Promise.resolve(null); - Promise.all([ want, api('/connections') ]).then(function(r) { - g.live(r[0] && r[0].proxies, r[1].connections || []); + var full = tick++ % 5 == 0; + Promise.all([ full ? api('/proxies') : null, api('/connections'), full ? api('/providers/proxies') : null ]).then(function(r) { + g.live(r[0] && r[0].proxies, r[1].connections || [], r[2] && r[2].providers); $('apiState').textContent = 'подключено'; }).catch(function(e) { $('apiState').textContent = 'ошибка: ' + e.message; diff --git a/tools/test-graph.js b/tools/test-graph.js index 0451e85..247a12f 100644 --- a/tools/test-graph.js +++ b/tools/test-graph.js @@ -46,18 +46,26 @@ for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"))) { { const cfg = S.yamlLoad(fs.readFileSync(path.join(dir, "router-csqtt.yaml"), "utf8")); const m = G.model(cfg); - const proxies = { - MAIN: { now: "FOREIGN" }, FOREIGN: { now: "nl-1" }, UPLINK: { now: "CSQTT" }, - "nl-1": { "provider-name": "example", alive: true, history: [{ delay: 42 }] }, + // /proxies: groups and the config's proxies; the subscriptions' nodes only in /providers/proxies + const proxies = { MAIN: { now: "FOREIGN" }, FOREIGN: { now: "nl-1" }, UPLINK: { now: "CSQTT" }, CSQTT: { history: [] } }; + const providers = { + example: { proxies: [{ name: "nl-1", alive: true, history: [{ delay: 42 }] }, { name: "de-1", alive: false }] }, + example2: { proxies: [{ name: "nl-1", alive: true }] }, + default: { proxies: [{ name: "MAIN" }] }, }; - const conns = [{ id: "c1", rule: "Match", rulePayload: "", chains: ["nl-1", "FOREIGN", "MAIN"], upload: 10, download: 20 }]; - const L = G.live(m, proxies, conns); + const conns = [ + { id: "c1", rule: "Match", rulePayload: "", chains: ["nl-1", "FOREIGN", "MAIN"], upload: 10, download: 20 }, + { id: "c2", rule: "", rulePayload: "", chains: ["DIRECT"] }, + ]; + const L = G.live(m, proxies, conns, null, providers); const match = m.ruleIndex["match|"]; const want = [match, "g:MAIN", "g:FOREIGN", "v:example", "g:UPLINK", "p:CSQTT"]; const got = Object.keys(L.nodes); check("live", want.every((id) => L.nodes[id] && L.nodes[id].n == 1), "path " + JSON.stringify(got) + ", want " + JSON.stringify(want)); check("live", Object.keys(L.edges).length == want.length - 1, "edges on the path: " + Object.keys(L.edges).length); - check("live", L.provider["v:example"] && L.provider["v:example"].alive == 1, "alive nodes of example"); + check("live", L.provider["v:example"] && L.provider["v:example"].alive == 1 && L.provider["v:example"].n == 2, "alive nodes of example"); + check("live", L.nowProv["g:FOREIGN"] == "v:example", "FOREIGN's choice comes from example: " + L.nowProv["g:FOREIGN"]); + check("live", L.unmatched == 1 && L.unmatchedRules["без правила"] == 1, "unmatched: " + JSON.stringify(L.unmatchedRules)); check("live", L.delay["g:FOREIGN"] == 42, "delay of FOREIGN's choice"); if (!fail) console.log("ok graph live");