refactor: remove duplication

This commit is contained in:
FUFSoB committed 2026-09-18 21:39:18 +05:00
1 parent f7036f6075
commit 8a4ba2db6a
109 files changed
+2206 -3078

No files matched your search

+7 -80
View File
@@ -4,47 +4,16 @@
}:
{
clashApi,
selection,
# NAME -> value, exported into proxy-ctl and both front ends. The module builds it
# (modules/proxy-suite/service/control.nix); proxy_ctl.py reads every name with env().
env,
guiRefreshInterval ? 3,
# These four are also passed as derivations: the checks read the files' contents through
# passthru.proxySuiteCheck, which toString in env would lose.
subscriptionTagsFile,
subscriptionCacheDir,
perAppRoutingEnabled,
perAppRoutingProxychainsEnabled,
perAppRoutingTunEnabled,
perAppRoutingTproxyEnabled,
perAppRoutingZapretEnabled,
perAppRoutingProfilesFile,
proxychainsConfigFile,
proxychainsQuietArg,
routeModeStateFile,
defaultRouteMode,
amneziaWgProfileNamesFile,
inboundsEnabled,
inboundsLinksFile,
inboundsStatsFile,
inboundsXray,
inboundsApi,
inboundsSubscriptionsFile,
inboundsSubscriptionsBaseUrl,
zapretAutoEnabled,
zapretStateDir,
zapretCutoffEnabled,
outboundInventoryFile,
runtimeOutboundsDir,
runtimeSubscriptionsDir,
userControlGroup,
localProxyUrl,
autoProxyEnabled,
autoProxyStateDir,
torControlSocket ? "",
singBox,
stateDir ? "/var/lib/proxy-suite",
runtimeDir ? "/run",
serviceManager ? "systemd",
privileged ? "1",
# proxy-suitectl, when serviceManager is "supervisor".
supervisorCtl ? "",
guiRefreshInterval ? 3,
}:
let
@@ -52,49 +21,7 @@ let
unwrapped = pkgs.writeScriptBin "proxy-ctl" (
"#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_ctl.py
);
wrapperEnv = {
CLASH_API = clashApi;
SELECTION = selection;
SUB_TAGS_FILE = toString subscriptionTagsFile;
SUB_CACHE_DIR = subscriptionCacheDir;
PER_APP_ROUTING_ENABLED = perAppRoutingEnabled;
PER_APP_ROUTING_PROXYCHAINS_ENABLED = perAppRoutingProxychainsEnabled;
PER_APP_ROUTING_TUN_ENABLED = perAppRoutingTunEnabled;
PER_APP_ROUTING_TPROXY_ENABLED = perAppRoutingTproxyEnabled;
PER_APP_ROUTING_ZAPRET_ENABLED = perAppRoutingZapretEnabled;
PER_APP_ROUTING_PROFILES_FILE = toString perAppRoutingProfilesFile;
PROXYCHAINS_CONFIG = toString proxychainsConfigFile;
PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg;
ROUTE_MODE_STATE_FILE = routeModeStateFile;
DEFAULT_ROUTE_MODE = defaultRouteMode;
AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile;
INBOUNDS_ENABLED = inboundsEnabled;
INBOUNDS_LINKS_FILE = inboundsLinksFile;
INBOUNDS_STATS_FILE = inboundsStatsFile;
INBOUNDS_XRAY = inboundsXray;
INBOUNDS_API = inboundsApi;
INBOUNDS_SUBS_FILE = inboundsSubscriptionsFile;
INBOUNDS_SUB_BASE_URL = inboundsSubscriptionsBaseUrl;
ZAPRET_AUTO_ENABLED = zapretAutoEnabled;
ZAPRET_STATE_DIR = zapretStateDir;
ZAPRET_CUTOFF_ENABLED = zapretCutoffEnabled;
OUTBOUND_INVENTORY_FILE = outboundInventoryFile;
RUNTIME_OUTBOUNDS_DIR = runtimeOutboundsDir;
RUNTIME_SUBS_DIR = runtimeSubscriptionsDir;
USER_CONTROL_GROUP = userControlGroup;
LOCAL_PROXY_URL = localProxyUrl;
AUTOPROXY_ENABLED = autoProxyEnabled;
AUTOPROXY_STATE_DIR = autoProxyStateDir;
TOR_CONTROL_SOCKET = torControlSocket;
SING_BOX = singBox;
STATE_DIR = stateDir;
RUNTIME_DIR = runtimeDir;
SERVICE_MANAGER = serviceManager;
PRIVILEGED = privileged;
}
// lib.optionalAttrs (supervisorCtl != "") {
SUPERVISOR_CTL = supervisorCtl;
};
wrapperEnv = env;
envFlags = lib.concatStringsSep " " (
lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv
);
+22 -27
View File
@@ -162,6 +162,21 @@ def read_json(path):
return json.load(f)
def require_enabled(variable, feature):
"""Refuses when the module did not build this feature in."""
if env(variable) != "1":
die(f"{feature} is not enabled in this configuration.")
def read_json_or(path, fallback):
"""The JSON at path, or fallback when it is missing, unreadable or not JSON."""
try:
value = read_json(path)
except (OSError, ValueError):
return fallback
return value if isinstance(value, type(fallback)) else fallback
def read_text(path):
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()
@@ -396,10 +411,7 @@ def _emit(text, qr):
def _json_list(path):
try:
return [_s(x) for x in read_json(path)]
except (OSError, ValueError, TypeError):
return []
return [_s(x) for x in read_json_or(path, [])]
def _sub_tags():
@@ -948,14 +960,7 @@ def _outbound_inventory():
Empty until the proxy has started once.
"""
path = env("OUTBOUND_INVENTORY_FILE")
if not readable(path):
return {}
try:
inventory = read_json(path)
except (OSError, ValueError):
return {}
return inventory if isinstance(inventory, dict) else {}
return read_json_or(env("OUTBOUND_INVENTORY_FILE"), {})
def _outbound_tags():
@@ -2032,10 +2037,7 @@ def cmd_proxy_probe(*args):
def _backend_tags():
"""User outbound tag -> the backend's tag, which probe exits and their reputation are keyed by."""
try:
return read_json(_runtime_file("outbound-test.json")).get("outbounds") or {}
except (OSError, ValueError, AttributeError):
return {}
return read_json_or(_runtime_file("outbound-test.json"), {}).get("outbounds") or {}
def _backend_tag(tag, backend=None):
@@ -2061,8 +2063,7 @@ def _autoproxy_dir():
def _require_autoproxy():
if env("AUTOPROXY_ENABLED") != "1":
die("proxy.autoProxy is not enabled in this configuration.")
require_enabled("AUTOPROXY_ENABLED", "proxy.autoProxy")
def _autoproxy_unreadable(path):
@@ -2089,11 +2090,7 @@ def _require_autoproxy_readable(path):
def _autoproxy_state(path):
try:
state = read_json(os.path.join(path, "state.json"))
except (OSError, ValueError):
return {}
return state if isinstance(state, dict) else {}
return read_json_or(os.path.join(path, "state.json"), {})
def cmd_proxy_auto(verb="list", *args):
@@ -2729,8 +2726,7 @@ def _per_app_profiles():
def _ensure_app_routing():
if env("PER_APP_ROUTING_ENABLED") != "1":
die("perAppRouting is not enabled in this configuration.")
require_enabled("PER_APP_ROUTING_ENABLED", "perAppRouting")
def _check_no_global_proxy(route):
@@ -3081,8 +3077,7 @@ def _inbound_subscriptions(*args):
def cmd_inbounds(verb="list", *args):
if env("INBOUNDS_ENABLED") != "1":
die("inbounds is not enabled in this configuration.")
require_enabled("INBOUNDS_ENABLED", "inbounds")
if verb == "list":
state = svc_state("proxy-suite-inbounds")
row = " {:<24} {:<16} {:<14} {:<8} {}"
+48 -38
View File
@@ -188,38 +188,45 @@ class Unit:
self.done.notify_all()
class Timer:
class Activator:
"""A .timer or .path unit: it is active or not, and it starts one service."""
section = ""
suffix = ""
def __init__(self, name, definition):
self.name = name
self.definition = definition
self.active = False
@property
def config(self):
return self.definition.get(self.section) or {}
def target(self):
return self.config.get("Unit") or self.name.replace(self.suffix, ".service")
class Timer(Activator):
section = "Timer"
suffix = ".timer"
def __init__(self, name, definition):
super().__init__(name, definition)
self.activated = None
self.fired = set()
self.last = None
self.jitter = 0.0
@property
def config(self):
return self.definition.get("Timer") or {}
def target(self):
return (self.definition.get("Timer") or {}).get("Unit") or self.name.replace(".timer", ".service")
class PathWatch(Activator):
section = "Path"
suffix = ".path"
class PathWatch:
def __init__(self, name, definition):
self.name = name
self.definition = definition
self.active = False
super().__init__(name, definition)
self.seen = {}
@property
def config(self):
return self.definition.get("Path") or {}
def target(self):
return self.config.get("Unit") or self.name.replace(".path", ".service")
def signature(path):
try:
@@ -570,24 +577,34 @@ class Supervisor:
# timers and paths
def start_timer(self, name):
name = full_name(name, "timer")
def _activator(self, registry, kind, cls, name):
"""The unit's Timer/PathWatch, made or replaced when its definition changed."""
name = full_name(name, kind)
definition = self.definition(name)
if definition is None:
return 5
return None
current = registry.get(name)
if current is None or current.definition is not definition:
current = registry[name] = cls(name, definition)
return current
def start_timer(self, name):
with self.guard:
timer = self.timers.get(name)
if timer is None or timer.definition is not definition:
timer = self.timers[name] = Timer(name, definition)
timer = self._activator(self.timers, "timer", Timer, name)
if timer is None:
return 5
if not timer.active:
timer.active, timer.activated, timer.fired = True, time.time(), set()
timer.jitter = self.jitter(timer)
return 0
def stop_timer(self, name):
timer = self.timers.get(full_name(name, "timer"))
if timer:
timer.active = False
return self._stop_activator(self.timers, "timer", name)
def _stop_activator(self, registry, kind, name):
unit = registry.get(full_name(name, kind))
if unit:
unit.active = False
return 0
@staticmethod
@@ -611,24 +628,17 @@ class Supervisor:
return at + timer.jitter, {base for base, when in candidates if when <= at}
def start_path(self, name):
name = full_name(name, "path")
definition = self.definition(name)
if definition is None:
return 5
with self.guard:
watch = self.paths.get(name)
if watch is None or watch.definition is not definition:
watch = self.paths[name] = PathWatch(name, definition)
watch = self._activator(self.paths, "path", PathWatch, name)
if watch is None:
return 5
if not watch.active:
watch.active = True
watch.seen = {p: signature(p) for key in ("PathChanged", "PathModified") for p in as_list(watch.config.get(key))}
return 0
def stop_path(self, name):
watch = self.paths.get(full_name(name, "path"))
if watch:
watch.active = False
return 0
return self._stop_activator(self.paths, "path", name)
def in_background(self, fn, *args):
threading.Thread(target=fn, args=args, daemon=True).start()
+31 -1
View File
@@ -81,6 +81,10 @@ class SupervisorTest(unittest.TestCase):
"Unit": {"Description": "timer job"},
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo tick >> {out}/ticks")},
},
"proxy-suite-watched": {
"Unit": {"Description": "path job"},
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo changed >> {out}/watched")},
},
"proxy-suite-pin@": {
"Unit": {"Description": "template"},
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo '%I' >> {out}/pins")},
@@ -93,7 +97,13 @@ class SupervisorTest(unittest.TestCase):
"Install": {"WantedBy": ["timers.target"]},
},
},
"paths": {},
"paths": {
"proxy-suite-watched": {
"Unit": {"Description": "watch a file"},
"Path": {"PathChanged": [os.path.join(self.tmp, "trigger")]},
"Install": {"WantedBy": ["paths.target"]},
},
},
"tmpfiles": [f"d {self.run_dir} 0700 - - -"],
}
with open(self.manifest + ".tmp", "w") as f:
@@ -168,5 +178,25 @@ class SupervisorTest(unittest.TestCase):
self.assertEqual(self.read("once"), ["ran"])
def test_path_unit_starts_its_service_when_the_file_changes(self):
trigger = os.path.join(self.tmp, "trigger")
# boot brings up the .path unit with the rest of paths.target.
self.assertEqual(self.ctl("boot")[0], 0)
# A .path unit is active itself, and quiet until the file it watches appears.
self.assertEqual(self.ctl("is-active", "--quiet", "proxy-suite-watched.path")[0], 0)
self.assertEqual(self.read("watched"), [])
with open(trigger, "w") as f:
f.write("one")
wait_for(lambda: self.read("watched") == ["changed"])
# Stopped, further changes are ignored.
self.assertEqual(self.ctl("stop", "proxy-suite-watched.path")[0], 0)
with open(trigger, "w") as f:
f.write("two")
time.sleep(1)
self.assertEqual(self.read("watched"), ["changed"])
if __name__ == "__main__":
unittest.main()