diff --git a/.env.example b/.env.example
index 4a5687fe..f90f4316 100644
--- a/.env.example
+++ b/.env.example
@@ -18,6 +18,8 @@ API_KEY = xxxxxxxx-yyyy-zzzz-mmmm-aaaaaaaaaaa
### developer options
# DEBUG = false
# GENERATED_CONFIG_PATH = /var/lib/pg-node/generated
+# SPEED_CAP_FILE = /var/lib/pg-node/speedcaps/speed_caps.json
+# SPEED_CAP_LEASE_SECONDS = 600
# LOG_BUFFER_SIZE = 10000
# STARTUP_LOG_TAIL_SIZE = 200
# STATS_UPDATE_INTERVAL_SECONDS = 10
diff --git a/.github/upstream-waivers.txt b/.github/upstream-waivers.txt
index 88463962..66cc76af 100644
--- a/.github/upstream-waivers.txt
+++ b/.github/upstream-waivers.txt
@@ -11,35 +11,35 @@ ca24af0b58f59a25870422369e36f1b31882e5d7 rejected: StartOrAttach treats a same-c
c194114eb1971d2e252fa1d117d655122c356d35 superseded: branch-only prototype of chunked user sync on upstream branch chunck; upstream squash-merged chunked sync as 4f8568bb17eb (#23), which the fork has branch:chunck
af0846ebb7103fc1a9cc332176e5736d7b89fd74 not-applicable: diagnostic logging on upstream's debug branch, never merged into upstream main or dev branch:debug
8047fad98ec7e9955a405a97bf90a2411d8d6678 not-applicable: diagnostic logging on upstream's debug branch, never merged into upstream main or dev branch:debug
-8542f271c4c38b424bc6b53a1b982184e13104e4 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-90c50a15ef9e794ec485a44a4beb87ba023530ea rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-419732c34cebe8fbc2ec859de6af50f40a61e9e8 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-9f9eac22de5485c6f260ce7c152927243dad78af rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-a87168d50322180782eb90128d17ae351608131d rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-77c62fd662b78e90ebc1b4778608e00cc1821c67 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-630df120d2ac2ca75a6788975f33421bfe962dac rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-0eae051c8f8c78096924057f28308f5f654a003b rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-ef4322942478036594a492a590b587f77297936b rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-cd183a4fb25aa531a724df8d34c2a553baa140aa rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-a66a322f7c545c8f9a78c9d503812d420b813479 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-fa79e3b565d6d482aca2a3f44ed2cd4275905b44 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-098d8287649967b8891960af125ff69706015864 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-2c4fce8d923ed9f4177ab518e60ea082a3f49832 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-4eb26fbd00387c88a4bcaf5c1d9e9e8dc4604b62 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9, so a port would still have to renumber upstream's enum value; revisit if upstream merges it branch:pr-61
-fbb0110881cb03804dded5b7778b78dbb67da72d rejected: upstream merge of origin/dev into feat/mtproto-telemt on the open PR #61 branch pr-61, whose conflict resolution carries changes of its own; PR #61 adds a telemt MTProto backend as BackendType MTPROTO = 2, which collides with the fork's SING_BOX = 2; the fork removed its own MTProto backend on 2026-11-10 and reserved MTPROTO = 4 and Proxy mtproto = 9; revisit if upstream merges it branch:pr-61
+8542f271c4c38b424bc6b53a1b982184e13104e4 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+90c50a15ef9e794ec485a44a4beb87ba023530ea rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+419732c34cebe8fbc2ec859de6af50f40a61e9e8 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+9f9eac22de5485c6f260ce7c152927243dad78af rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+a87168d50322180782eb90128d17ae351608131d rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+77c62fd662b78e90ebc1b4778608e00cc1821c67 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+630df120d2ac2ca75a6788975f33421bfe962dac rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+0eae051c8f8c78096924057f28308f5f654a003b rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+ef4322942478036594a492a590b587f77297936b rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+cd183a4fb25aa531a724df8d34c2a553baa140aa rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+a66a322f7c545c8f9a78c9d503812d420b813479 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+fa79e3b565d6d482aca2a3f44ed2cd4275905b44 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+098d8287649967b8891960af125ff69706015864 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+2c4fce8d923ed9f4177ab518e60ea082a3f49832 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+4eb26fbd00387c88a4bcaf5c1d9e9e8dc4604b62 rejected: upstream PR #61 (branch pr-61, open, not merged) adds a telemt MTProto backend, the Telegram proxy; the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so it is not ported; on the wire it would also take BackendType MTPROTO = 2, which the fork keeps reserved by number and by name since it removed SING_BOX, while the fork's own MTPROTO = 4 and Proxy mtproto = 9 stay reserved; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
+fbb0110881cb03804dded5b7778b78dbb67da72d rejected: upstream merge of origin/dev into feat/mtproto-telemt on the open, not merged PR #61 branch pr-61, whose conflict resolution carries changes of its own; PR #61 adds a telemt MTProto backend, the Telegram proxy, and the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out; on the wire it would also take BackendType MTPROTO = 2, reserved by number and by name in the fork since it removed SING_BOX; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61
7be885ff5410ac7fdb92fa21cf7901a416be5f05 superseded: upstream #86 makes xray Core.Started() take c.mu; the fork closed the same race lock-free in cc27180 (Started reads an atomic coreState snapshot, liveness from waitDone), because c.mu in Started puts every REST/gRPC request behind Stop's kill and 5 s wait (docs/upstream-parity.md); upstream's TestCoreStarted tests and their -race CI step are carried in backend/xray/core_started_test.go
d359a8f7c478044c0fb80afcda207c6d122affd5 not-applicable: upstream #117 only makes StartOrAttach restart an unhealthy backend instead of treating a same-config Start as a heartbeat; the fork does not carry StartOrAttach (see ca24af0b, rejected) and every fork Start runs ReplaceBackend (controller/rpc/base.go), so an unhealthy backend is always restarted
-47857d43fe777f30f9ecc5f2ffe4ca0b037507cb not-applicable: upstream v0.5.5 release commit, whose only change sets controller.NodeVersion to 0.5.5; the fork versions its node on its own line (NodeVersion 0.6.27, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.5 change is tracked here commit by commit
+47857d43fe777f30f9ecc5f2ffe4ca0b037507cb not-applicable: upstream v0.5.5 release commit, whose only change sets controller.NodeVersion to 0.5.5; the fork versions its node on its own line (NodeVersion 0.6.29, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.5 change is tracked here commit by commit
88d5e75db62190d8566caf826536c801465c1482 superseded: upstream #96 (released in node v0.5.6, 675bdaa) is ported from the node v0.5.7 (739eab94) end state by the fork commit "feat(xray): masque inbound on proto field 12": message Masque { string pass = 1; } byte-identical, MasqueAccount/NewMasqueAccount (empty pass skips the user), the masque inbound cases in config.go, user.go and config_clone.go, and the masque_test.go and api/masque_test.go tests; the Proxy field is masque = 12, not 7, because the fork Proxy already uses 7 for Hysteria2 and 8 to 11 for OpenVPN, the reserved MTProto slot, TUIC and L2TP (common/masque_wire_test.go pins the wire tag 0x62); built on xray-core 676eaf66f8f0
243b818307790393d21b41154c99b0d052e89a59 superseded: pre-squash commit (feat: add Masque proxy support) of upstream PR #96 on branch masque, squash-merged as 88d5e75 (released in node v0.5.6, 675bdaa), which the fork ports from the node v0.5.7 end state in its commit feat(xray): masque inbound on proto field 12, with masque = 12 instead of 7 (see the 88d5e75 row) branch:masque
f0877ce629e84aae6099e9bf5c6f47837dff78a8 superseded: pre-squash commit (feat(xray): upgrade to v26.9.30 prerelease and use native MASQUE accounts) of upstream PR #96 on branch masque, squash-merged as 88d5e75; the node agent compiles against its go.mod pin xray-core 676eaf66f8f0 (the v26.11.9 release tag commit), which carries the native MASQUE accounts, while the image's xray binary is held on v26.3.27 (d2758a023cd7), which has no proxy/masque, and ports the #96 end state in feat(xray): masque inbound on proto field 12 (see the 88d5e75 row) branch:masque
b7442879ef0f67b692474e0e668d65f29df8de49 superseded: merge of dev into branch masque (parents f0877ce and 3a3d5c5) inside upstream PR #96, squash-merged as 88d5e75; it brings no content beyond dev and the masque commits, which are tracked on their own rows and through 88d5e75 branch:masque
-675bdaa24a3a67847f2094e518f1ae4d8460aa01 not-applicable: upstream v0.5.6 release commit, whose only change sets controller.NodeVersion to 0.5.6; the fork versions its node on its own line (NodeVersion 0.6.27, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.6 change is tracked here commit by commit
-739eab94a9343d9f0035baf7162796844109f4c4 not-applicable: upstream v0.5.7 release commit, whose only change sets controller.NodeVersion to 0.5.7; the fork versions its node on its own line (NodeVersion 0.6.27, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.7 change is tracked here commit by commit
+675bdaa24a3a67847f2094e518f1ae4d8460aa01 not-applicable: upstream v0.5.6 release commit, whose only change sets controller.NodeVersion to 0.5.6; the fork versions its node on its own line (NodeVersion 0.6.29, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.6 change is tracked here commit by commit
+739eab94a9343d9f0035baf7162796844109f4c4 not-applicable: upstream v0.5.7 release commit, whose only change sets controller.NodeVersion to 0.5.7; the fork versions its node on its own line (NodeVersion 0.6.29, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.7 change is tracked here commit by commit
ebb0d02944bdf4f7166819d31466a224f0daf7e2 superseded: upstream commit of 2026-11-02, released in node v0.5.7 (739eab9, 2026-11-03), for the Ubuntu 26.04 AppArmor wg profile that makes wg set ... private-key fail with fopen: Permission denied on a key file under /tmp in the WireGuard E2E tests; the fork fixed the same failure on 2026-10-29 in b8679894 (on main), which writes the E2E client key with os.CreateTemp under /etc/wireguard, the one key path that profile allows, and with it TestIntegrationE2ESyncUser, TestIntegrationE2ESyncUsers and TestIntegrationE2EUpdateUsers pass on ubuntu-latest (wireguard-integration job 123832855477 on b8679894, no Permission denied in its log); upstream's key-file half is the same change, its chmod 0600 is already the os.CreateTemp mode, and its fallback to the default temp dir would hit the same denial; its other half, unloading the wg and wg-quick AppArmor profiles with apparmor_parser -R and aa-disable from TestMain and from the install_wg Makefile target, is not taken: it weakens the host's AppArmor confinement from a test binary and a package installer, and the fork's fix needs none of it
36dc7a4a78a075d20ed6c82297c8097fd2a6462f not-applicable: removes the .gitlab-ci.yml that upstream #64 (e03754d) added for the contributor's own GitLab pipeline; the fork ported #64 on 2026-11-10 in c755202a without that file, and no commit on main has ever added a .gitlab-ci.yml (git log origin/main -- .gitlab-ci.yml is empty on 2026-11-11), so there is nothing to delete
-689f2665e2157c93d1ee65cb6426d4684a53056a pending: dev-only: upstream #120 adds a telemt MTProto backend (60 files, common/service.proto included) on upstream dev only, in no tag on 2026-11-07 (newest tag v0.5.7, 739eab9); held under the release-only rule and ported, adapted or rejected once a release contains it. It collides with the fork on the wire: upstream sets BackendType MTPROTO = 2 and Proxy mtproto = 8, where the fork has SING_BOX = 2 and open_vpn = 8. The fork removed its own MTProto backend on 2026-11-10 and left MTPROTO = 4 and Proxy mtproto = 9 reserved, so the numbers upstream wants are still taken until:2026-11-30
-9ccd2638c7feb65e62c5350fba38b94809554b50 pending: dev-only: upstream #124 makes the node logger skip a "none" log path, passes "none" access and error logs through to Xray, and stops access entries and Info or Debug lines from counting as startup failures; on upstream dev only, in no tag on 2026-11-07 (newest tag v0.5.7, 739eab9); held under the release-only rule. The fork's logger openLogFile and backend/xray isStartupFailureLog are identical to upstream v0.5.7, before #124 (diffed on 2026-11-07; the failures themselves are not reproduced in the fork) until:2026-11-30
+689f2665e2157c93d1ee65cb6426d4684a53056a pending: dev-only: upstream #120 adds a telemt MTProto backend, the Telegram proxy, in no upstream tag yet (newest tag v0.5.7, 739eab9, checked 2026-12-02); the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so the backend itself is never ported, and on the wire it would also take BackendType 2 and Proxy 8, which the fork keeps reserved and uses for open_vpn; the same commit adds a generic retry-later sync error (backend/errors.go RetryLaterError, answered as HTTP 503 by controller/rest/sync_errors.go and as gRPC Unavailable by controller/rpc/sync_errors.go), which is ported or refused on its own once a release contains it until:2026-12-31
+9ccd2638c7feb65e62c5350fba38b94809554b50 pending: dev-only: upstream #124 makes the node logger skip a "none" log path, passes "none" access and error logs through to Xray, and stops access entries and Info or Debug lines from counting as startup failures; on upstream dev only, in no tag on 2026-11-07 (newest tag v0.5.7, 739eab9); held under the release-only rule. The fork's logger openLogFile and backend/xray isStartupFailureLog are identical to upstream v0.5.7, before #124 (diffed on 2026-11-07; the failures themselves are not reproduced in the fork) until:2026-12-31
a1bf968be975adefa9247d7b3093613cee82f028 not-applicable: fixes the unencrypted-outbound validator that d7fa207 added after the pin; the pinned v26.3.27 has no such validator
7a5721c50d43d06d0c02f5bbd9715f8f2fd39eb8 superseded: pre-squash commit of PR #6741, merged into main as a1bf968be975 (the d7fa207 validator, absent from the pin) branch:account-enc
598bde74122f5f0207c7c6a56ccb74fbbbe33fca superseded: the Router API data race itself is fixed in the shipped 26.3.27 binary by the fork patch patches/xray-router-race.patch (FORK DEVIATION, docs/upstream-parity.md: rules and balancers published as one immutable table through an atomic pointer, lock-free route picks and balancer lookups, writers serialized by the router mutex, a failed ReloadRules publishes nothing, webhooks closed after the mutex is released; -race tests TestRuleAndBalancerUpdatesRaceWithRoutePicking and TestConcurrentRuleWritersLoseNoUpdateWhileRoutesArePicked, stall tests from F-r2B-2); the rest of upstream's refactor does not apply to the pin and is not carried (the inline webhook sweep, removal of OverrideBalancer), because the fork deliberately holds the xray binary on the 26.3.27 line for this rollout because 26.11.9 refuses production plaintext-VLESS chain links (upstream d7fa2076 #6303, first in the v26.7.11 pre-release, no override); the 26.11.9 line is tracked and returns in a later image once chain links are encrypted
@@ -107,50 +107,7 @@ a4a3dff5b20c2faae567b742c172c7b95e75c083 rejected: Xray release v26.10.31 (final
7da5dae6502b787fc6d903863e9a6c5043d107a2 rejected: Mux client race between Dispatch and SessionManager.Close (#6871), first in the v26.10.21 final release; the 26.3.27 binary does not have the fix and no patch in patches/ touches common/mux; the fork deliberately holds the xray binary on the 26.3.27 line for this rollout because 26.11.9 refuses production plaintext-VLESS chain links (upstream d7fa2076 #6303, first in the v26.7.11 pre-release, no override); the 26.11.9 line is tracked and returns in a later image once chain links are encrypted
862e59a2f2f847e66f5667fa92d26f5a2155618c pending: unreleased XTLS/Xray-core #7482 on main (2026-11-25), in no tag on 2026-11-28 (newest tag v26.11.9); held under the release-only rule and decided again once an Xray release contains it. It consolidates the TUN inbound files, deletes TUN tests and renames proxy/tun/wfp_leak.go to wfp_block.go, matched on the word leak; it touches only proxy/tun and infra/conf/tun_test.go, the held pin d2758a023cd7 has neither wfp_leak.go nor tun_windows_outbound.go in proxy/tun, the node image runs Linux and backend/xray never emits a tun inbound, so the expected verdict is not-applicable until:2026-12-12
dfad7776ee00bab4231e00edff12e428b68ff661 pending: unreleased XTLS/Xray-core commit on main (2026-11-24), in no tag on 2026-11-28 (newest tag v26.11.9); held under the release-only rule and decided again once an Xray release contains it. It adds an Exceptions list to SECURITY.md (crash, panic and leak reports belong in public issues), matched on the word security; it changes no code and nothing the build or the node reads, so the expected verdict is not-applicable until:2026-12-12
-6a7f11fca3fade0783ea615b37f9fcbf15a01460 not-applicable: the sing-box side of this commit is a go.mod bump only; the fix itself bounds an index in skipJSONString in sagernet/sing common/json/internal/contextjson/comment.go, and the pinned dependency sing v0.8.14 has neither that file nor any skipJSONString function, so the out-of-bounds slice cannot exist in the tree the node builds; v0.8.14 strips comments with a byte-at-a-time CommentFilter that does no index arithmetic and no slicing; checked 2026-11-10 by grep over the pinned module
-bea01fe80ab9f46c931789c7cb77fad0553341ca pending: the fix lives in sagernet/sing protocol/http, bounding the request body the handshake discards; the pinned sing v0.8.14 still has handleHTTPConnection without it, and sing-box protocol/http, protocol/mixed and protocol/socks are all compiled into the node binary under SINGBOX_TAGS, so only the panel-supplied config keeps it out of reach: the node configures no http or mixed inbound and backend/singbox passes any other inbound through untouched. That is a configuration argument, not a build-level impossibility, so it is held instead of being called not-applicable; it closes with the sing-box 1.14 move, or sooner by making backend/singbox refuse http and mixed inbounds until:2026-12-10
-18b0317018bdc823ecd9c424b247a19e631e852d pending: the pre-fix code demonstrably still ships; transport/v2raygrpclite/conn.go and transport/v2rayhttp/conn.go both still branch on a nil reader and close without the select guard, at the pinned v1.13.21 and in the Free-Guy-IR sing-box build f92b2cdb67bc, and both packages are compiled in under SINGBOX_TAGS; only the panel-supplied config keeps it out of reach, because a Hysteria2 inbound uses no v2ray http or grpc transport. Held instead of being called not-applicable, for the same reason as bea01fe8; it closes with the sing-box 1.14 move or by porting the fix onto the 1.13 tree until:2026-12-10
-474aa5b5d918da6b6be19b3276a180b8215cb8f9 pending: the sing-box side of this commit is a bbolt bump only (to 500ee1e84832, in v1.14.2), which reports corrupted databases from Open and Check instead of crashing; the Free-Guy-IR build f92b2cdb67bc uses bbolt ea5cb2fe9f0a without it. bbolt runs only for experimental.cache_file; backend/singbox does not set it but passes a panel-supplied experimental block through untouched, and on 2026-11-29 a node-rendered config with cache_file enabled made that build create and open cache.db. Only a cache.db that is corrupt on disk reaches the fixed code, not network input (found by reading the code, not reproduced). This replaces a not-applicable row that said no database is ever opened; it is a configuration argument, so it is held with the sing-box 1.14 move until:2026-12-10
-f90999708232e6dfc10bceeac7c08c19e597c454 not-applicable: the 1.14 flow-verdict routing architecture this fix belongs to postdates the pin; adapter.JudgeFlow, adapter.PreMatchResult, PreMatchBypass, tun.FlowVerdict and tun.Port exist neither at the pinned v1.13.21 nor in the Free-Guy-IR sing-box build, whose Router.PreMatch takes a different signature, and pre-match is the TUN path, which the node configures no inbound for; checked 2026-11-10 by grep over both trees. This replaces a pending row that recorded no applicability analysis
-288411b0b9044c11a00a8ab478000e3ec1133101 not-applicable: the crash needs a nil InterfaceMonitor, which the node build cannot produce; the unguarded InterfaceMonitor().MyInterfaces() call is on the node's own path, in protocol/direct/outbound.go at the pin, reached unconditionally from Start, but sing-tun v0.8.15 NewNetworkUpdateMonitor returns an error only under runtime.GOOS == android and otherwise always returns a monitor, so route/network.go always assigns nm.interfaceMonitor and InterfaceMonitor() can never be nil on linux, while a failing default-interface monitor errors out of NewNetworkManager instead of leaving a nil one; dns/transport/dhcp is not compiled at all because with_dhcp is absent from SINGBOX_TAGS; checked 2026-11-10. This reason replaces an earlier one that cited interface-bound rules and DHCP DNS and omitted the direct outbound, which is the path that actually makes the call
-cfddedb3dab8c3e326d8b11f92608cc3ba21d514 not-applicable: daemon start or reload race in the client-app daemon; the node runs the plain sing-box binary
-1e2846a1a5348826b7df564060cdeeca9ded9968 not-applicable: WireGuard endpoint feature that races all resolved addresses, matched on the word race; the node runs no sing-box WireGuard endpoint
-93a4bbacbec908e2501bfb568a5f3af4117a9cf0 not-applicable: executable security check for the openconnect and tor outbounds of the newer lines; the node configures neither
-cdbfceafd1119d02960ac963e7bc81ca464e85b8 not-applicable: fixes the DNS race rule of the newer lines, which 1.13 does not have
-b2f1f630d95e2a2fc548f7677a4434e8816e1d34 not-applicable: security check message in the client-app daemon; the node runs the plain sing-box binary
-9a96e636430bddf4f14bc9e5d8246c1f544b1bb3 not-applicable: SetGroupExpand race in the client-app daemon; the node runs the plain sing-box binary
-fa743743e1307936f0b71b6546991d198f778cfd not-applicable: macOS bridge kernel panic; the node runs on Linux
-0e7f176a163aa26f32b451f87fd4276dad178fd2 not-applicable: goroutine leak in the networkquality CLI tool, which the node never runs
-03412b12d05756fd6f87d4ea9d01a6a906804276 not-applicable: OOM and crash reports for the client-app daemon, matched on the word crash; the node runs the plain sing-box binary
-0b8995879f29a9b98ee027bc17b75e101445b238 pending: first release of the sing-box 1.14 line, which the fork has not moved to; quic-go 0.61 and sing-quic 0.7 rework the congestion control the fork's Hysteria2 upload fix depends on. It is not a legal target on its own either, because its go.mod requires sing-quic v0.7.0-beta.4, a pre-release, and the fork takes a third-party component only from a final release. The 1.14 move is owned as one project, and of the five 1.14 releases only v1.14.1 keeps both sing-box and sing-quic on real releases until:2026-12-10
-1ac1a339cb1223e9c70eae14c44411c75033c02d pending: the one release-rule-clean target for the sing-box 1.14 move, being the only 1.14 release whose go.mod requires a real sing-quic release, v0.7.0; it also carries the quic-go 0.61 line, which bounds the HTTP/3 trailer decode that the pinned sagernet/quic-go v0.59.0-sing-box-mod.4 still leaves unbounded, the subject of GHSA-vvgj-x9jq-8cj9. It cannot be taken today: the fork's sing-quic socket-buffer work does not apply to the 0.7 tree, sing-quic 0.7.0 deletes congestion_bbr1 and congestion_bbr2 and changes NewBrutalSender's signature, and upstream 0.7.x sizes the UDP buffers itself at 8 MiB without the kernel-grant check the fork added at 16 MiB, so Hysteria2 upload on Iranian consumer lines has to be re-measured before any rollout until:2026-12-10
-af6e64c3b69e6132ebaee0e1a3d24e93903f6709 pending: sing-box 1.14 line, held with the 1.14 move; it is also not a legal target under the release-only rule, because its go.mod requires sing-quic v0.7.1-0.20260924092235-6a3a24d65b99, an unreleased commit. Its four security-looking commits are settled on their own rows: 474aa5b5, 18b03170, bea01fe8 and 6a7f11fc until:2026-12-10
-7054cac5124465ffdb145870d7c01885566711b1 pending: sing-box 1.14 line, held with the 1.14 move; it is also not a legal target under the release-only rule, because its go.mod requires sing-quic v0.7.2-0.20261002084117-75c3ac4fa12b, an unreleased commit until:2026-12-10
-42cae14c63d1b8645d787f3f93515820c94f01e7 not-applicable: sing-box 1.14 Apple TLS engine fix; the two files it changes, common/tls/apple_client_platform.go and common/tls/apple_client_platform_darwin.m, do not exist at the pinned v1.13.21 (628cb31ffa79), and the Objective-C half needs CGO on darwin while the node builds sing-box with CGO_ENABLED=0 for linux (Dockerfile singbox-builder); checked 2026-11-10 by listing the v1.13.21 tree. This replaces a pending row that deferred it to the sing-box 1.14 move, which treated a permanently inapplicable item as owed work
-c005f35300ce76427dc285481ec5695f5b179cd2 pending: newest sing-box 1.14 release, held with the 1.14 move; it is also not a legal target under the release-only rule, because its go.mod requires sing-quic v0.7.2-0.20261020082049-7e0a5869a5f4, an unreleased commit until:2026-12-10
-060f54a9a57cf5b6212f3cba2a4101776f15f1f7 not-applicable: sing-box 1.14 bump of sagernet/cronet-go for the naive outbound (in v1.14.5: a GC write barrier crash, IPv6-only resolution, eMudhra intermediates blocked); the commit changes only .github/CRONET_GO_VERSION, go.mod and go.sum, the naive outbound is built only with the with_naive_outbound tag, which SINGBOX_TAGS lacks, and go list -deps of ./cmd/sing-box at the Free-Guy-IR build f92b2cdb67bc with SINGBOX_TAGS for linux/amd64 lists no cronet package; checked 2026-11-28
-b3548ad89d35ca5d6e161dc0a5c18885cdba493d pending: sing-box tproxy inbound socket leak (in v1.14.5); the Free-Guy-IR build f92b2cdb67bc ships protocol/redirect/tproxy.go byte-identical to v1.13.21, whose tproxyPacketWriter drops its cached UDP socket after a failed write without closing it, and protocol/redirect is compiled in; only the panel-supplied config keeps it out of reach, because backend/singbox manages no tproxy inbound and passes other inbounds through untouched. Held with the sing-box 1.14 move, or a port onto the 1.13 tree until:2026-12-10
-ef408a1e10bdfb1237c967e9dd3593600f3d2d52 pending: vless and trojan outbound crash when the outbound has a tls block with enabled false (in v1.14.5); the same code ships in the Free-Guy-IR build f92b2cdb67bc: tls.NewClientWithOptions returns a nil config for a disabled block, the outbound still builds tls.NewDialer over it, and the first dial runs the TLS handshake on that nil config. Outbounds come only from the panel-supplied config, which backend/singbox passes through untouched, so only that config keeps it out of reach. Held with the sing-box 1.14 move, or a port onto the 1.13 tree until:2026-12-10
-e012b572121ccbf8d0db7ea97968af39e21764af superseded: sing-box 1.14 h2mux client deadlock with the Go 1.27 HTTP/2 wrapper (in v1.14.5); the commit only moves golang.org/x/crypto to v0.55.0, x/mod to v0.38.0, x/net to v0.58.0, x/text to v0.41.0 and x/tools to v0.48.0, and the Free-Guy-IR build f92b2cdb67bc already requires x/crypto v0.57.0, x/mod v0.41.0, x/net v0.60.0, x/text v0.42.0 and x/tools v0.49.0, above every one of them
-fde8bf9249556ed03d5f855977a2719b937bf982 pending: sing-box 1.14 bump of sagernet/bbolt to 2ab7bd6d2bff (in v1.14.5), which releases the writer lock when a rollback panics while it reloads the freelist; the pre-fix rollback is in the bbolt ea5cb2fe9f0a of the Free-Guy-IR build f92b2cdb67bc. bbolt runs only for experimental.cache_file; backend/singbox does not set it but passes a panel-supplied experimental block through untouched, and on 2026-11-29 a node-rendered config with cache_file enabled made that build create and open cache.db. The panic needs the freelist reload from that file to fail, so only a cache.db that is damaged on disk reaches it, not network input (found by reading the code, not reproduced). A configuration argument, so held with the sing-box 1.14 move until:2026-12-10
-298d6b7e3652d77199fc4bf5c6a85904e88b7927 not-applicable: sing-box DHCP DNS transport fix (in v1.14.5); dns/transport/dhcp is compiled only with the with_dhcp tag, which SINGBOX_TAGS lacks, and go list -deps of ./cmd/sing-box at the Free-Guy-IR build f92b2cdb67bc with SINGBOX_TAGS for linux/amd64 lists no dhcp package; checked 2026-11-28
-ef3c5a4f0a4dc096005822c84c8d377f37e27b98 not-applicable: sing-box 1.14 listener fix (in v1.14.5) for the interface-follow rebind race and for EMSGSIZE errors in the UDP write-back; the Free-Guy-IR build f92b2cdb67bc has no followBindInterface or interfaceCallbacks in common/listener, its loopUDPOut writes one packet at a time and goes on after any write error, and the sagernet/sing half only adds network.ErrPacketTooBig to generalize an EMSGSIZE skip in copy loops that sing v0.8.14 does not have at all
-c95deb2ee86d62673c3c6644c446704342d6990d pending: sing-box rule-set startup ordering and close races (in v1.14.5); the close-race half changes RuleSetItem.Close, which the Free-Guy-IR build f92b2cdb67bc does not have, but the ordering half applies: that build also links rule-sets into rules only in the router PostStart, after the inbounds start accepting in StartStateStart, so a rule_set rule matches nothing for a connection routed in between (found by reading the code, not reproduced). Only rule_set rules in the panel-supplied route config reach it. Held with the sing-box 1.14 move, or a port onto the 1.13 tree until:2026-12-10
-3b4ea5cc83497a0b82c184c985fbe481c98d8091 not-applicable: sing-box fix in common/certificate/store_darwin.go (in v1.14.5), a CGO file for darwin; the Free-Guy-IR build f92b2cdb67bc has no store_darwin.go in common/certificate, and the node builds sing-box for linux with CGO_ENABLED=0
-f0fbf236f83e78881bbb6b0ac23bd2075c601450 pending: sing-box data race between rule-set updates and matching (in v1.14.5); the race exists in the Free-Guy-IR build f92b2cdb67bc too: RemoteRuleSet.loadBytes and LocalRuleSet.reloadRules replace s.rules under s.access while matchStatesWithBase reads s.rules without it (found by reading the code, not reproduced). It needs a remote rule-set that updates or a watched local one in the panel-supplied route config, and the fix does not apply as is, because the 1.13 tree has no ruleSetContent. Held with the sing-box 1.14 move, or an adapted port onto the 1.13 tree until:2026-12-10
-9e27f3413b085834c19a1432688aa3db6c6c28fa not-applicable: sing-box 1.14 fix for unbounded ICMP sockets in the direct outbound (in v1.14.5); what it changes, the outbound's own ping.NewPort with no timeout and no limit, does not exist in the Free-Guy-IR build f92b2cdb67bc: there the direct outbound gets ICMP only from tun stacks, whose sing-tun v0.8.15 NewDirectRouteMapping keeps at most 1024 flows, expires them after the ICMP timeout and closes what it evicts, and sing-tun v0.8.15 has no ping.NewPort
-97f996fac099058eb73dd44c17ada745fffc2eaa not-applicable: sing-box 1.14 bump of sagernet/sing-snell for the Snell protocol (in v1.14.5); the Free-Guy-IR build f92b2cdb67bc has no protocol/snell and does not require sing-snell
-f6b7c85ca2152814a8d8ce460a9e40a8cdc403ec pending: sing-box bump of sagernet/sing for the UDP-over-TCP payload leak (in v1.14.5); sing v0.8.14, which the Free-Guy-IR build f92b2cdb67bc uses, has the pre-fix uot Conn.WritePacket, whose branch for a connection without a vectorised writer copies the payload into the header buffer and never releases the payload buffer (found by reading the code, not reproduced). Every UDP-over-TCP path of that build ends in that WritePacket: the server-side router of the vless, vmess, tuic, shadowsocks, anytls, mixed, naive, http and socks inbounds, and the client side of the shadowsocks, socks, anytls and tuic outbounds; vless, vmess, tuic and shadowsocks are inbound types backend/singbox manages. No tag of sagernet/sing contains the fix 88ca72637655 on 2026-11-29, so a port means carrying sing itself. Held with the sing-box 1.14 move until:2026-12-10
-bb9fdd5cf158c61c30606970a4af11d4154d91fc pending: sing-box fix for the deprecated Router.RouteConnection and RoutePacketConnection wrappers (in v1.14.5); the Free-Guy-IR build f92b2cdb67bc ships the pre-fix route/route.go, and its shadowsocks inbound (inbound.go, inbound_multi.go, inbound_relay.go) still routes through them: when routePacketConnection returns an error before it hands the connection on (a reject rule, a missing outbound, an outbound without UDP), RoutePacketConnection closes the connection and then waits on a channel that only onClose closes, so the goroutine of that UDP session stays blocked until sing-box stops (found by reading the code, not reproduced). shadowsocks is an inbound type backend/singbox manages, so this is the first item to port if a sing-box node with a shadowsocks inbound is turned on before the 1.14 move. Held with the sing-box 1.14 move, or a port onto the 1.13 tree until:2026-12-10
-f1a71152bad4d7bdf80d88011cc1a852c89d76d4 pending: sing-box bump of sagernet/sing for the race between Read and Close in bufio.CachedConn (in v1.14.5); common/bufio/cache.go of sing v0.8.14, which the Free-Guy-IR build f92b2cdb67bc uses, is byte-identical to the file before the fix dcc5d99d7554: Read uses the cached buffer and Close releases it with no lock between them, so a Close racing a Read can hand the buffer back to the pool while the Read still copies from it (found by reading the code, not reproduced). In that build a CachedConn is made by the trojan inbound only on its fallback path, for a connection whose key matched no user (transport/trojan/service.go), and for mux streams with buffered bytes (transport/trojan/mux.go); by the tuic inbound for streams with buffered request bytes (third_party/sing-quic/tuic/service.go); and by the router only for buffers a sniff rule action read, which the hijack-dns branch also wraps (route/route.go). A hysteria2 inbound reaches it only through such a sniff rule. No tag of sagernet/sing contains dcc5d99d7554 on 2026-11-29, so a port means carrying sing itself. Held with the sing-box 1.14 move until:2026-12-10
-a6844a780ba173e189a018d0ac62df67cd50b8e9 pending: sing-box v1.14.5 (2026-11-27), 1.14 line, held with the 1.14 move; it is also not a legal target under the release-only rule, because its go.mod requires sing-quic v0.7.2-0.20261126024618-6fa4bb84d0bd, an unreleased commit (the newest sing-quic release is v0.7.1). Its 15 security-looking commits are settled on their own rows. Of the rest, b384461e (shadowsocks connections attributed to other users after user updates) is already covered in the Free-Guy-IR build, whose shadowsocks users carry an inbounduser.Identity with the name instead of an index into a replaced slice; the Hysteria2 and QUIC changes 44e418a3, ff43da27, a5f1d8bb, 53440b35 and e4573eb1 only move sing-quic to 0.7.2 pseudo-versions and sagernet/quic-go to v0.61.0-sing-box-mod builds, which ride on the same move; and 9766191e changes only the client packet conns of sing-shadowsocks2, which only the shadowsocks outbound uses until:2026-12-10
-a713aee3058f97f3facc98e85244a3e73c82dca1 pending: sing-box v1.14.6 (2026-11-27), held with the 1.14 move for the same two reasons as v1.14.5: the 1.14 line, and a go.mod that requires the same unreleased sing-quic commit v0.7.2-0.20261126024618-6fa4bb84d0bd. Over v1.14.5 it adds 5c03f548, which bounds the HTTP request header of the http and mixed inbounds: both are compiled into the Free-Guy-IR build, but backend/singbox manages neither and only panel-supplied config can add one, the ground of bea01fe8; the rest is a badtls record type fix on the kTLS path, oomprofile, tfo-go v2.4.2 and toolchain updates until:2026-12-10
-36c518d82febfc36a2ce65ab5557ab14948e9afa pending: sing-box v1.14.7 (2026-12-01), held with the 1.14 move for the same two reasons as v1.14.5 and v1.14.6: the 1.14 line, and a go.mod that requires sing-quic v0.7.2-0.20261130061349-ffca1ff8aeb0, an unreleased commit (the newest sing-quic release is still v0.7.1 in the drift run of 2026-12-01). On 2026-12-01 the owner also set sing-box aside, and the one sing-box core on the production panel serves three nodes that are all disabled, with no node running sing-box as an extra core, so the pin stays on v1.13.21. Its release notes say only "Fixes and improvements"; none of its 23 commits after v1.14.6 matches the drift check's security patterns, and it still requires github.com/anytls/sing-anytls v0.0.11, so it does not carry the AnyTLS fix of 24a6808c until:2026-12-10
-24a6808cb102fd8955fcda332660a3aaf866f842 pending: sing-box 1.15 AnyTLS fix, in the pre-release tag v1.15.0-alpha.16 and on testing only, and in no final release: v1.14.7, stable and oldstable do not contain it (GitHub compare on 2026-12-01). The commit only moves github.com/sagernet/sing-anytls to 3d7db6ab4eb1, whose session.go writeFrame now sets the control frame write deadline after it takes the write lock instead of before. The Free-Guy-IR build f92b2cdb67bc, like v1.13.21 and v1.14.7, uses another module, github.com/anytls/sing-anytls v0.0.11, so the commit cannot apply there; but its session/session.go writeControlFrame has the same kind of race: it sets the 5 second write deadline on the shared connection before writeConn takes connLock and clears it after the lock is released, so the deadline can hit a concurrent data write or be cleared under another control frame write (found by reading the code, not reproduced). The anytls inbound and outbound are compiled into that build, but backend/singbox manages no anytls inbound. Held because the owner set sing-box aside on 2026-12-01 and the three production nodes on the one sing-box core are all disabled; a port onto v0.0.11 is owed before a sing-box node with an anytls inbound is turned on until:2026-12-10
-GHSA-r5hm-mp3j-285g not-applicable: SOCKS inbound authentication bug fixed in sing-box 1.4.5 and 1.5.0-rc.5 in 2023; the pinned v1.13.21 is long past the fix
-4ab2eceaac81e073f53b22ec72ff56aaea89a3d1 pending: the sing-quic pin is not independently movable; the fork's sing-box requires github.com/sagernet/sing-quic v0.6.5 only as a label and replaces it with the in-tree third_party/sing-quic, so a move means re-vendoring a tree that already carries the fork's own Hysteria2 fixes, and v0.7.x cannot build inside the 1.13 module graph at all, which was measured on 2026-11-10 by requiring v0.7.1 in a copy of v1.13.21 and watching sing-tun v0.8.15 fail to compile. v0.7.0 does change the Hysteria2 server, so it is real work, and it rides on the sing-box 1.14 move until:2026-12-10
d2722ef5c80241704572e9f2b45d2123f8b7838c not-applicable: mtg PR #549 (merged upstream 9seconds/mtg master as 753d051), validate the fronting domain TLS certificate in the `mtg doctor` self-diagnostic; touches only internal/cli/doctor.go and its test. The node links the mtg library packages (mtglib, network/v2, antireplay, ipblocklist, mtglib/obfuscation) and never builds or runs the `mtg doctor` CLI, so the fronting-domain certificate probe is unreachable at the node's runtime. Matches the drift keywords expired/untrusted, hence this explicit waiver
-8601a428f4db7fc011b3656080bf4c428ca62417 pending: a later release on the sing-quic 0.7 line, so it cannot be taken before v0.7.0, which is held with the sing-box 1.14 move; its own two commits are client-side, adding SetKeepIdleConnections and CloseIdleConnections to the hysteria, hysteria2 and tuic clients and fixing port hopping in hysteria/hop.go, and the node runs the Hysteria2 server, but that describes its delta and is not a reason it could be taken on its own until:2026-12-10
00a27e407da4db5c73c4dc0dfde967d1c8d650ee superseded: upstream 9seconds/mtg commit of 2026-11-03 09:47 UTC on branch fix/shutdown-connection-race (PR #588), in no tag or release; in mtglib/proxy.go ServeConn its shutdown AfterFunc closes only the original client connection instead of calling ctx.Close(), because upstream's streamContext.Close reads ctx.clientConn and ctx.telegramConn without a lock while ServeConn's setup replaces them; the fork fixed the same race on 2026-09-29 in Free-Guy-IR/mtg 6e378787be50 (with its race test e3e9542730f6), an ancestor of the node's pin 1563871b36dd (Free-Guy-IR/mtg main, one commit after 7f8c04762e3b): the fork's streamContext.Close closes the never-reassigned acceptedConn and reads the telegram connection under telegramMu, so the AfterFunc's ctx.Close() in the fork's serveConn does not race the handshake; re-checked when upstream merges the branch branch:fix/shutdown-connection-race
aa1c3ebe3081e6fa92566b875d3f6e41c2e54038 pending: dev-only: upstream #136 moves golang.org/x/sys from 0.49.0 to 0.50.0 on upstream dev only, in no tag on 2026-11-28 (newest tag v0.5.7, 739eab9); held under the release-only rule and ported once a release contains it; the fork's go.mod requires x/sys v0.49.0 (docs/upstream-parity.md, State on 2026-11-28) until:2026-12-27
aba2d8108e1ea566e4e35014f908e412df492767 pending: dev-only: upstream #138 adds TLS_ENABLED, which lets the node serve REST and gRPC without TLS on a loopback, RFC1918 or IPv6 unique-local NODE_HOST behind an external TLS terminator; on upstream dev only, in no tag on 2026-11-28 (newest tag v0.5.7, 739eab9); held under the release-only rule and ported, adapted or rejected once a release contains it (docs/upstream-parity.md, State on 2026-11-28) until:2026-12-27
diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml
index d6624482..f9fa45fc 100644
--- a/.github/workflows/run-tests.yml
+++ b/.github/workflows/run-tests.yml
@@ -51,34 +51,6 @@ jobs:
- name: Replay the image build's Xray patch guards
run: make test_xray_guards XRAY_GUARD_SRC="$RUNNER_TEMP/xray-guard-src"
- - name: Build the pinned sing-box the image ships
- run: make build_singbox SINGBOX_SRC="$RUNNER_TEMP/sing-box-src" SINGBOX_OUTPUT="$RUNNER_TEMP/sing-box"
-
- - name: Run the live sing-box tests against the pinned build
- env:
- REQUIRED_TESTS: >-
- TestLiveSmoke_SingBoxProcessStartsAndReportsStats
- TestAnEmptyHysteria2PasswordIsNeverAccepted
- TestSharedHysteria2PasswordBillsTheSameUserEveryTime
- TestASingBoxRestartKeepsTheUnreadTraffic
- TestAUserSyncWhoseHotReloadFailsRestartsAndKeepsTheUnreadTraffic
- TestTrafficCountedWhileASingBoxRestartWaitsForItsLockIsBilled
- TestASingBoxFullSyncThatAddsAUserKeepsTheCoreAndTheUnreadTraffic
- TestAUserAddedToARunningSingBoxIsBilled
- TestTheRunningCoreHoldsItsClashSecretPrivately
- run: |
- set -o pipefail
- log="$RUNNER_TEMP/singbox-live.log"
- read -r -a required <<< "${REQUIRED_TESTS}"
- pattern="^($(IFS='|'; echo "${required[*]}"))\$"
- SINGBOX_SMOKE_BINARY="$RUNNER_TEMP/sing-box" XRAY_EXECUTABLE_PATH=/usr/local/bin/xray CGO_ENABLED=1 go test -race -count=1 -timeout 10m -v -run "${pattern}" ./backend/singbox/ 2>&1 | tee "$log"
- for name in "${required[@]}"; do
- if ! grep -Eq "^--- PASS: ${name} \(" "$log"; then
- echo "::error title=Required sing-box test did not pass::${name}"
- exit 1
- fi
- done
-
- name: install wg
run: make install_wg
@@ -116,8 +88,7 @@ jobs:
- name: Run the controller and backend tests under the race detector
run: |
- TEST_INTEGRATION=true CGO_ENABLED=1 SINGBOX_EXECUTABLE_PATH="$RUNNER_TEMP/sing-box" \
- go test -race -timeout 20m -v -p 1 ./controller/...
+ TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./controller/...
TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./backend/...
- name: Check Xray process status races
diff --git a/.gitignore b/.gitignore
index d22925fb..5b413ee5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,4 +37,3 @@ certs/
generated/
pasarguard-node*
/main
-sing-box-src/
diff --git a/Dockerfile b/Dockerfile
index 3dfc8c75..0b57c2b8 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -15,41 +15,6 @@ RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} make NAME=main build
-# --- sing-box (Hysteria2) builder ---
-# Built from source rather than using the official prebuilt sing-box release binary:
-# official releases are not compiled with the "with_v2ray_api" tag, which this node's
-# backend/singbox stats client (v2ray-api gRPC, see backend/singbox and config.go's
-# SINGBOX_EXECUTABLE_PATH) requires to report per-user traffic. Version and tag set are
-# pinned to match what was built and traffic-tested (incl. Salamander-obfuscated
-# Hysteria2 against real QUIC-blocking ISPs) for this fork.
-FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine@sha256:0a5f7fe796599ff487605987432e7619ae45beeb2fba4c2ce0b907879932aebf AS singbox-builder
-
-ARG TARGETOS
-ARG TARGETARCH
-ARG SINGBOX_VERSION=v1.13.21
-ARG SINGBOX_TAGS=with_quic,with_utls,with_clash_api,with_v2ray_api,http2legacy
-# Our fork of sing-box v1.13.14: adds a clash_api PUT /hysteria2/users endpoint so
-# Hysteria2 user changes apply live, without restarting the core (no dropped sessions).
-ARG SINGBOX_REPO=https://github.com/Free-Guy-IR/sing-box.git
-ARG SINGBOX_BRANCH=main
-ARG SINGBOX_COMMIT=f92b2cdb67bcb5e14b3b404f6fc5e43286c2688d
-
-RUN apk update && apk add --no-cache git
-
-COPY scripts/singbox_http2_guard.sh /singbox_http2_guard.sh
-
-WORKDIR /singbox-src
-RUN git init -q . \
- && git remote add origin ${SINGBOX_REPO} \
- && git fetch -q --depth 1 origin ${SINGBOX_COMMIT} \
- && git checkout -q FETCH_HEAD \
- && test "$(git rev-parse HEAD)" = "${SINGBOX_COMMIT}"
-RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} sh /singbox_http2_guard.sh "${SINGBOX_TAGS}"
-RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \
- -tags "${SINGBOX_TAGS}" \
- -ldflags "-X 'github.com/sagernet/sing-box/constant.Version=${SINGBOX_VERSION}' -s -w -buildid=" \
- -o /out/sing-box ./cmd/sing-box
-
# --- xray builder ---
# Built from source rather than using the prebuilt release binary installed by
# make install_xray: Xray's commander starts its gRPC server with no options, so it
@@ -58,8 +23,8 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \
# that server the same 64 MiB this node already allows elsewhere. The build applies the
# patch and then greps for the result, so a patch that stops applying fails the build
# instead of silently shipping an unpatched core. The source is pinned to a commit and
-# the checkout is asserted against it, the same way the sing-box stage does, because a
-# git tag can be moved and a tag alone would not tell us we built what we reviewed.
+# the checkout is asserted against it, because a git tag can be moved and a tag alone
+# would not tell us we built what we reviewed.
FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine@sha256:0a5f7fe796599ff487605987432e7619ae45beeb2fba4c2ce0b907879932aebf AS xray-builder
ARG TARGETOS
@@ -79,6 +44,7 @@ COPY patches/xray-gorilla-websocket-mask-key.patch /patches/xray-gorilla-websock
COPY patches/xray-grpc-1.83.2.patch /patches/xray-grpc-1.83.2.patch
COPY patches/xray-http-100-continue.patch /patches/xray-http-100-continue.patch
COPY patches/xray-listener-mptcp-off.patch /patches/xray-listener-mptcp-off.patch
+COPY patches/xray-per-user-speed-cap.patch /patches/xray-per-user-speed-cap.patch
COPY patches/xray-pinned-ca-servername.patch /patches/xray-pinned-ca-servername.patch
COPY patches/xray-quic-sniff.patch /patches/xray-quic-sniff.patch
COPY patches/xray-router-race.patch /patches/xray-router-race.patch
@@ -168,6 +134,17 @@ RUN git init -q . \
&& grep -qF "lc.SetMultipathTCP(sockopt.TcpMptcp)" transport/internet/system_listener.go \
&& ! grep -qF "lc.SetMultipathTCP(true)" transport/internet/system_listener.go \
&& grep -qF "func TestATCPListenerIsPlainTCPUnlessItsSocketSettingsAskForMPTCP" transport/internet/system_listener_mptcp_test.go \
+ && git apply --verbose /patches/xray-per-user-speed-cap.patch \
+ && grep -qF "func (op *SetUserSpeedsOperation) ApplyInbound(ctx context.Context, _ inbound.Handler) error {" app/proxyman/speedcap/operation.go \
+ && grep -qF "message SetUserSpeedsOperation {" app/proxyman/speedcap/config.proto \
+ && grep -qF "repeated string inbound_tags = 5;" app/proxyman/speedcap/config.proto \
+ && grep -qF "FileEnv = \"XRAY_SPEED_CAP_FILE\"" app/proxyman/speedcap/registry.go \
+ && grep -qF "outboundLink.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Downlink, outboundLink.Writer)" app/dispatcher/default.go \
+ && grep -qF "inboundLink.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Uplink, inboundLink.Writer)" app/dispatcher/default.go \
+ && grep -qF "link.Reader = speedcap.NewReader(ctx, user.Email, sessionInbound.Tag, link.Reader)" app/dispatcher/default.go \
+ && grep -qF "link.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Downlink, link.Writer)" app/dispatcher/default.go \
+ && grep -qF "var splice = inbound.CanSpliceCopy == 1 && !speedcap.CappedUser(inbound.User, inbound.Tag)" proxy/proxy.go \
+ && grep -qF "w, capped, err := spliceUntilCapped(tc, readerConn, inbound)" proxy/proxy.go \
&& git apply --verbose /patches/xray-pinned-ca-servername.patch \
&& grep -qF 'return errors.New("Pinning CA needs a valid ServerName")' transport/internet/tls/config.go \
&& grep -qF "config := tlsConfig.GetTLSConfig(tls.WithDestination(dest))" transport/internet/grpc/dial.go \
@@ -356,7 +333,6 @@ COPY --from=builder /src/main /app/main
COPY --from=xray-builder /out/xray /usr/local/bin/xray
COPY --from=geo-assets /geo/geoip.dat /usr/local/share/xray/geoip.dat
COPY --from=geo-assets /geo/geosite.dat /usr/local/share/xray/geosite.dat
-COPY --from=singbox-builder /out/sing-box /usr/local/bin/sing-box
COPY --from=filter-assets /assets/pgfilter.dat /usr/local/share/xray/pgfilter.dat
COPY --from=filter-assets /assets/pgfilter_index.json /usr/local/share/xray/pgfilter_index.json
diff --git a/Makefile b/Makefile
index bedf0c0e..3ee73b02 100644
--- a/Makefile
+++ b/Makefile
@@ -50,7 +50,7 @@ ifeq ($(shell echo "$(GOARCH)" | grep -Eq "(mips|mipsle)" && echo true),true)
ADDITION = GOMIPS=softfloat go build -o $(NAME)_softfloat -trimpath -ldflags "$(LDFLAGS)" -v $(MAIN)
endif
-.PHONY: clean build build_xray build_singbox test_singbox_http2_guard test_xray_guards test_xray_patches test test-race-wireguard test-integration test-integration-full test-integration-wireguard test-drift \
+.PHONY: clean build build_xray test_xray_guards test_xray_patches test test-race-wireguard test-integration test-integration-full test-integration-wireguard test-drift \
install_geofiles check_geofiles update_geofiles_pin
build:
@@ -239,28 +239,6 @@ build_xray:
cd "$(XRAY_SRC)" && echo "xray $(XRAY_COMMIT) needs go $$(sed -n 's/^go //p' go.mod); building with $$(GOTOOLCHAIN=local go version)"
cd "$(XRAY_SRC)" && GOTOOLCHAIN=local CGO_ENABLED=0 go build -trimpath -ldflags "$(XRAY_LDFLAGS)" -o "$(XRAY_OUTPUT)" ./main
-SINGBOX_REPO ?= $(shell sed -n 's/^ARG SINGBOX_REPO=//p' Dockerfile)
-SINGBOX_COMMIT ?= $(shell sed -n 's/^ARG SINGBOX_COMMIT=//p' Dockerfile)
-SINGBOX_VERSION ?= $(shell sed -n 's/^ARG SINGBOX_VERSION=//p' Dockerfile)
-SINGBOX_TAGS ?= $(shell sed -n 's/^ARG SINGBOX_TAGS=//p' Dockerfile)
-SINGBOX_SRC ?= $(CURDIR)/sing-box-src
-SINGBOX_OUTPUT ?= $(SINGBOX_SRC)/sing-box
-
-build_singbox: test_singbox_http2_guard
- test -n "$(SINGBOX_REPO)" && test -n "$(SINGBOX_COMMIT)" && test -n "$(SINGBOX_VERSION)" && test -n "$(SINGBOX_TAGS)" && test -n "$(SINGBOX_SRC)"
- rm -rf "$(SINGBOX_SRC)"
- git init -q "$(SINGBOX_SRC)"
- git -C "$(SINGBOX_SRC)" remote add origin $(SINGBOX_REPO)
- git -C "$(SINGBOX_SRC)" fetch -q --depth 1 origin $(SINGBOX_COMMIT)
- git -C "$(SINGBOX_SRC)" checkout -q FETCH_HEAD
- test "$$(git -C "$(SINGBOX_SRC)" rev-parse HEAD)" = "$(SINGBOX_COMMIT)"
- cd "$(SINGBOX_SRC)" && GOTOOLCHAIN=local CGO_ENABLED=0 sh $(CURDIR)/scripts/singbox_http2_guard.sh "$(SINGBOX_TAGS)"
- cd "$(SINGBOX_SRC)" && GOTOOLCHAIN=local CGO_ENABLED=0 go build -trimpath -tags "$(SINGBOX_TAGS)" -ldflags "-X 'github.com/sagernet/sing-box/constant.Version=$(SINGBOX_VERSION)' -s -w -buildid=" -o "$(SINGBOX_OUTPUT)" ./cmd/sing-box
- "$(SINGBOX_OUTPUT)" version
-
-test_singbox_http2_guard:
- bash scripts/test_singbox_http2_guard.sh
-
XRAY_GUARD_SRC ?= $(CURDIR)/xray-guard-src
XRAY_FREEDOM_GEOIP_DAT ?= $(wildcard $(GEOFILES_DIR)/geoip.dat)
@@ -308,6 +286,9 @@ test_xray_patches:
cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -run 'TestTheSystemDialerRunsTheConnectCheckBeforeEveryTCPConnect|TestTheConnectCheckSeesTheAddressAResolvedNameConnectsTo|TestEveryRacedConnectAndEveryResolvedRetargetIsChecked|TestTheSystemDialerChecksTheResolvedUDPDestination|TestACheckedPacketConnDropsOnlyTheRefusedDatagrams|TestOnlyTheDefaultSystemDialerAppliesConnectChecks|TestAnOutboundAppliesTheConnectCheckOnlyWhenEverySocketGoesThroughTheDefaultSystemDialer' ./transport/internet/ ./app/proxyman/outbound/
cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -run 'TestEarlyDataConnAddressesBeforeFirstWrite' ./transport/internet/websocket/
cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=3 -timeout 300s -run 'TestCloseWithPacketInFlightDoesNotPanic|TestProcessAfterCloseDoesNotPanic|TestProcessWhileClosingDoesNotRaceOrPanic|TestAClosedHandlerNeverBuildsANewTunnel|TestProcessTCPWhileClosingDoesNotRaceOrPanic|TestADialAfterCloseUsesTheTunnelProcessTookUnderTheLock|TestClosingABindTwiceDoesNotPanic' ./proxy/wireguard/ ./proxy/wireguard/gvisortun/
+ cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -timeout 600s ./app/proxyman/speedcap/...
+ cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -run 'TestWrapLinkCapsTheUserAndKeepsTheStatsWriterOutermost' ./app/dispatcher/
+ cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -timeout 900s -run 'TestSpeedCap' ./testing/scenarios/
install_wg: update_os
ifeq ($(UNAME_S),Linux)
diff --git a/README.md b/README.md
index 8ff0329c..f28048cb 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@
-> Note: This is the [Free-Guy-IR](https://github.com/Free-Guy-IR) fork of the original [PasarGuard node](https://github.com/Free-Guy-IR/node), extended with sing-box (Hysteria2), OpenVPN, and L2TP/IPsec backend support.
+> Note: This is the [Free-Guy-IR](https://github.com/Free-Guy-IR) fork of the original [PasarGuard node](https://github.com/Free-Guy-IR/node), extended with OpenVPN and L2TP/IPsec backend support.
# One-Click Installation (Recommended)
The easiest way to install PasarGuard Node is using our automated installation script:
@@ -41,7 +41,7 @@ node-eu-1 edit-env
You can run any other subcommand for that same node with the same prefix (`node-eu-1 ...`).
-> ⚠️ **Important:** Never reuse ports between nodes. The connection port and every core's inbound/instance ports (Xray, sing-box, OpenVPN, ...) attached to each node must be completely unique per node.
+> ⚠️ **Important:** Never reuse ports between nodes. The connection port and every core's inbound/instance ports (Xray, OpenVPN, ...) attached to each node must be completely unique per node.
# Moving a Node to Another Panel
diff --git a/backend/openvpn/config.go b/backend/openvpn/config.go
index c155287a..bb87b9e3 100644
--- a/backend/openvpn/config.go
+++ b/backend/openvpn/config.go
@@ -19,11 +19,6 @@ type PKI struct {
TLSCryptKey string `json:"tls_crypt_key"`
}
-// InstanceConfig describes one OpenVPN server process ("instance"): one
-// listening proto/port/tun-device combination. This is the OpenVPN analogue
-// of a sing-box "inbound" or an xray inbound - user.go matches against
-// InstanceConfig.Tag exactly the way singbox/xray match a user's Inbounds
-// against an inbound tag.
type InstanceConfig struct {
Tag string `json:"tag"`
Protocol string `json:"protocol"`
@@ -87,11 +82,6 @@ const (
defaultVerb = 3
)
-// NewConfig parses and validates raw OpenVPN backend config JSON (see the
-// package doc comment in openvpn.go for the exact shape). Mirrors
-// singbox.NewConfig's validation style: clear, specific error messages and
-// fail fast on anything that would otherwise start a broken or ambiguous set
-// of OpenVPN processes.
func NewConfig(raw string) (*Config, error) {
var cfg Config
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
diff --git a/backend/openvpn/core_unix.go b/backend/openvpn/core_unix.go
index 1b76fd13..c778c512 100644
--- a/backend/openvpn/core_unix.go
+++ b/backend/openvpn/core_unix.go
@@ -7,9 +7,6 @@ import (
"syscall"
)
-// setProcAttributes sets Unix-specific process attributes for proper process
-// group management (used by Stop()'s SIGTERM/SIGKILL escalation and by
-// killProcessTree). Mirrors backend/singbox/core_unix.go.
func setProcAttributes(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
diff --git a/backend/openvpn/log.go b/backend/openvpn/log.go
index 62879f58..2cbc1205 100644
--- a/backend/openvpn/log.go
+++ b/backend/openvpn/log.go
@@ -11,10 +11,6 @@ import (
// logRing is a small fixed-size circular buffer of recent log lines, used to
// give context (e.g. in an error returned to the caller) when startup fails.
-// Mirrors backend/singbox/log.go's logRing exactly (kept as an independent
-// copy rather than a shared import - this repo does not share internal
-// helper packages between backend implementations; xray and singbox each
-// carry their own near-identical process/log helpers too).
type logRing struct {
mu sync.Mutex
lines []string
@@ -125,9 +121,6 @@ func (p *instanceProcess) recordLog(line string) {
}
}
-// isStartupFailureLog is a best-effort heuristic for detecting fatal openvpn
-// startup errors from its log output, analogous to backend/singbox/log.go's
-// isStartupFailureLog and backend/xray/startup_diagnostics.go's.
func isStartupFailureLog(line string) bool {
lower := strings.ToLower(line)
diff --git a/backend/openvpn/management.go b/backend/openvpn/management.go
index 72b4ace7..ee4d47ab 100644
--- a/backend/openvpn/management.go
+++ b/backend/openvpn/management.go
@@ -14,33 +14,6 @@ import (
"time"
)
-// ManagementClient talks OpenVPN's line-based management-interface protocol
-// over one instance's Unix domain socket (see render.go's "management
-// unix" / "management-client-auth" directives). It is the only piece
-// of this package with no precedent elsewhere in this codebase - every other
-// backend's equivalent (xray's HandlerService, sing-box's v2ray_api) is a
-// typed gRPC API; OpenVPN's management interface is a bare line-oriented text
-// protocol multiplexing three kinds of traffic on one connection:
-//
-// 1. synchronous command/response ("status 2" -> multi-line reply ending in
-// a line that is just "END", or a single "SUCCESS: ..."/"ERROR: ..."
-// line);
-// 2. asynchronous, unprompted "real-time" notifications, always prefixed
-// with ">" (">CLIENT:CONNECT,...", ">BYTECOUNT_CLI:...", etc.) that can
-// arrive interleaved with a command's response at any time; and
-// 3. commands we issue in reaction to a real-time notification
-// ("client-auth"/"client-deny" in response to ">CLIENT:CONNECT") that we
-// must NOT wait for a reply to, since the only goroutine that could ever
-// read that reply is the one currently blocked sending the command - see
-// writeLine vs sendCommand below.
-//
-// A single background goroutine (readLoop/consume) is the sole reader of the
-// connection for its whole lifetime; it reconnects (with backoff, up to a
-// bounded number of attempts) if the connection drops before Close is
-// called, so a transient management-socket hiccup doesn't require the whole
-// openvpn process to be restarted (process.go handles the process actually
-// dying separately, by tearing this client down and building a fresh one on
-// the next Start - see instanceProcess.Restart).
type ManagementClient struct {
tag string
socketPath string
diff --git a/backend/openvpn/openvpn.go b/backend/openvpn/openvpn.go
index 69fe6fd4..ceb0b3e4 100644
--- a/backend/openvpn/openvpn.go
+++ b/backend/openvpn/openvpn.go
@@ -1,21 +1,3 @@
-// Package openvpn implements backend.Backend on top of N OpenVPN server
-// subprocesses ("instances", see config.go), one per configured
-// tag/proto/port combination - this backend's analogue of a sing-box/xray
-// "inbound". See process.go's instanceProcess for the single-subprocess
-// lifecycle (mirrors backend/singbox/core.go's Core, generalized to N-of
-// instead of one) and management.go for the single biggest structural
-// difference from every other backend in this repo: user membership is
-// authenticated live over each instance's management-interface Unix socket
-// against an in-memory map, instead of being baked into a config file - see
-// user.go's doc comment for why this means SyncUser/SyncUsers/UpdateUsers/
-// UpdateUsersAndRestart never need to restart a subprocess here, unlike
-// sing-box where every one of them currently does.
-//
-// PKI (CA cert, server cert, server key, tls-crypt key) is generated by the
-// panel and arrives pre-rendered as PEM text in Backend.config's "pki" object
-// (see config.go's Config.PKI) - this package only ever consumes it as opaque
-// text to inline into a rendered server config (render.go); it never
-// generates or touches key material itself.
package openvpn
import (
@@ -278,11 +260,6 @@ func (b *Backend) Shutdown() {
log.Println("openvpn shutdown complete")
}
-// superviseInstances periodically restarts any instance that isn't running
-// (e.g. after a crash), with per-instance exponential backoff so a
-// persistently broken instance doesn't get restart-stormed - mirrors the
-// spirit of sing-box's checkHealth (backend/singbox/jobs.go), adapted for N
-// independently-supervised instances instead of one.
func (b *Backend) superviseInstances(ctx context.Context) {
const (
checkInterval = 3 * time.Second
diff --git a/backend/openvpn/process.go b/backend/openvpn/process.go
index aedceabf..f4f6b265 100644
--- a/backend/openvpn/process.go
+++ b/backend/openvpn/process.go
@@ -16,12 +16,6 @@ import (
"github.com/pasarguard/node/pkg/stats"
)
-// instanceProcess owns the full lifecycle of exactly one OpenVPN server
-// subprocess: config rendering, spawn, management-socket client, NAT rule,
-// log capture, crash/restart bookkeeping, and graceful stop. It is the
-// per-instance analogue of backend/singbox/core.go's Core, generalized to run
-// N of them concurrently - one per configured instance (see Backend in
-// openvpn.go).
type instanceProcess struct {
tag string
inst *InstanceConfig
@@ -100,10 +94,6 @@ func (p *instanceProcess) writeConfigFile() error {
if err := os.MkdirAll(p.configDir, 0o700); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
- // 0600: unlike sing-box's generated config (backend/singbox/core.go's
- // writeConfigFile, 0644), this file embeds the server's PEM-encoded
- // private key inline (see render.go) and must not be world/group
- // readable.
return os.WriteFile(p.configFilePath(), []byte(text), 0o600)
}
@@ -343,12 +333,6 @@ func (p *instanceProcess) handleProcessExit(cmd *exec.Cmd, err error) {
p.recordLog(message)
}
-// Stop gracefully stops the process: SIGTERM (OpenVPN's clean-shutdown
-// signal - it notifies connected clients and exits, unlike sing-box's Stop()
-// in backend/singbox/core.go, which calls Process.Kill() (SIGKILL) directly;
-// worth the extra step here since a hard-killed openvpn server leaves
-// clients without a clean disconnect signal), wait with a timeout, then
-// escalate to killProcessTree's SIGTERM+SIGKILL+process-group fallback.
func (p *instanceProcess) Stop() {
p.stop(false)
}
@@ -469,7 +453,6 @@ func (p *instanceProcess) Restart() error {
// cleanupOrphanedProcesses finds and kills openvpn processes for this
// specific instance (matched by executable path + --config path, see
// process_unix.go) that are zombies or parented by this node process.
-// Mirrors backend/singbox/core.go's Core.cleanupOrphanedProcesses.
func (p *instanceProcess) cleanupOrphanedProcesses() error {
processes, err := findOpenVPNProcesses(p.executablePath, p.configFilePath())
if err != nil {
diff --git a/backend/openvpn/process_unix.go b/backend/openvpn/process_unix.go
index a87abfb4..500ec683 100644
--- a/backend/openvpn/process_unix.go
+++ b/backend/openvpn/process_unix.go
@@ -23,16 +23,6 @@ type ProcessInfo struct {
IsZombie bool
}
-// findOpenVPNProcesses finds running openvpn processes matching
-// executablePath whose command line references configPath as their
-// "--config" argument.
-//
-// Unlike backend/singbox's findSingBoxProcesses (which only ever has to find
-// at most one sing-box process for the whole backend), this backend runs one
-// openvpn process per configured instance, so matching by executable path
-// alone would risk attributing (and potentially killing) a sibling
-// instance's healthy process during cleanup. Matching the config path out of
-// /proc//cmdline disambiguates between instances.
func findOpenVPNProcesses(executablePath, configPath string) ([]ProcessInfo, error) {
absExe, err := filepath.Abs(executablePath)
if err != nil {
@@ -146,12 +136,6 @@ func findOpenVPNProcessesFromProc(absExe, absConfig string) ([]ProcessInfo, erro
return processes, nil
}
-// killProcessTree, getProcessGroupID, verifyProcessDead, isProcessRunning,
-// and pathsMatch mirror backend/singbox/process_unix.go (generic
-// process-management helpers with no openvpn-specific logic - this repo does
-// not share such helpers between backend packages, see log.go's doc
-// comment).
-
func killProcessTree(pid int) error {
proc, err := os.FindProcess(pid)
if err != nil {
diff --git a/backend/openvpn/smoke_test.go b/backend/openvpn/smoke_test.go
index fcf18256..4362930d 100644
--- a/backend/openvpn/smoke_test.go
+++ b/backend/openvpn/smoke_test.go
@@ -25,11 +25,6 @@ import (
"github.com/pasarguard/node/config"
)
-// discoverOpenVPNBinary looks for a real openvpn binary to run the live
-// smoke test against. It skips the test rather than failing when none is
-// found, mirroring backend/singbox/smoke_test.go's discoverSingBoxBinary -
-// this needs a real subprocess, a real tun device, and root, and has no
-// business running in an ordinary CI environment.
func discoverOpenVPNBinary(t *testing.T) string {
t.Helper()
diff --git a/backend/openvpn/stats.go b/backend/openvpn/stats.go
index c9b3e918..1438da6c 100644
--- a/backend/openvpn/stats.go
+++ b/backend/openvpn/stats.go
@@ -211,13 +211,6 @@ func (b *Backend) GetStats(ctx context.Context, request *common.StatRequest) (*c
}
}
-// GetSysStats reports the controlling node process's own Go runtime stats.
-// OpenVPN's management interface exposes no analogue of xray/sing-box's
-// in-process runtime-stats API (there is no "report your own memory/GC
-// stats" command in the management protocol) - the same situation WireGuard
-// is in (see backend/wireguard/stats.go's GetSysStats), so - like WireGuard -
-// this reports the node process's own stats as the best available proxy for
-// backend health/resource usage.
func (b *Backend) GetSysStats(ctx context.Context) (*common.BackendStatsResponse, error) {
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
@@ -240,13 +233,6 @@ func (b *Backend) GetSysStats(ctx context.Context) (*common.BackendStatsResponse
}, nil
}
-// GetUserOnlineStats reports how many concurrent sessions email has open
-// across all instances right now, read live off each instance's
-// ManagementClient. Unlike sing-box's GetUserOnlineStats
-// (backend/singbox/stats.go), which always reports 0 because sing-box's
-// v2ray_api has no online concept to query, OpenVPN's management interface
-// gives a real answer via CLIENT:ESTABLISHED/DISCONNECT tracking (see
-// management.go).
func (b *Backend) GetUserOnlineStats(ctx context.Context, email string) (*common.OnlineStatResponse, error) {
b.mu.RLock()
instances := make([]*instanceProcess, 0, len(b.instances))
@@ -302,14 +288,6 @@ func (b *Backend) GetUserOnlineIpListStats(ctx context.Context, email string) (*
return &common.StatsOnlineIpListResponse{Name: email, Ips: ips}, nil
}
-// GetOutboundsLatency is a stub for the same reason sing-box's is
-// (backend/singbox/stats.go): OpenVPN, like a single Hysteria2 inbound, has
-// no "outbound" concept at all to probe - a server instance either accepts
-// tunneled traffic or it doesn't, there's nothing analogous to xray's
-// multi-outbound egress selection to measure latency against. Returns an
-// empty, non-error response so callers relying on the Backend interface
-// degrade gracefully instead of failing hard; a real implementation is out
-// of scope.
func (b *Backend) GetOutboundsLatency(ctx context.Context, request *common.LatencyRequest) (*common.LatencyResponse, error) {
return &common.LatencyResponse{Latencies: []*common.Latency{}}, nil
}
diff --git a/backend/openvpn/user.go b/backend/openvpn/user.go
index 9866b596..8092923e 100644
--- a/backend/openvpn/user.go
+++ b/backend/openvpn/user.go
@@ -7,20 +7,6 @@ import (
"github.com/pasarguard/node/common"
)
-// User sync for OpenVPN is fundamentally different from every other backend
-// in this repo: xray hot-upserts via its HandlerService gRPC API, sing-box
-// has no hot-upsert API at all and must rewrite-config-and-restart for every
-// sync (see backend/singbox/user.go), and WireGuard reconfigures its kernel
-// interface in place. OpenVPN sits apart from all three: users are
-// authenticated per-connection over each instance's management-interface
-// Unix socket (see management.go) against an in-memory username->credential
-// map this file maintains - there is no config file entry to rewrite and
-// therefore no restart required for ANY of SyncUser/SyncUsers/UpdateUsers/
-// UpdateUsersAndRestart. This is this backend's headline advantage: user
-// churn is instant and disruption-free for every other already-connected
-// user, unlike sing-box where every single-user sync currently causes a
-// brief connection drop for the whole node.
-
// authEntry is what an instance's authStore keeps per OpenVPN username: the
// password to validate against, and the user's canonical email. The latter
// is what every stats/online-tracking method in this package (and the
@@ -186,14 +172,6 @@ func (s *authStore) authenticate(username, password string) (string, uint32, boo
return entry.email, entry.maxConcurrent, true
}
-// openVPNCredential extracts the (username, password) pair an OpenVpnUser
-// proxy carries. A user with no OpenVpnUser proxy configured (ok == false)
-// can never be added to or removed from an instance's authStore by
-// username, since there is no username to key by - the panel is expected to
-// keep sending the OpenVpnUser credential block even when revoking access,
-// only shrinking Inbounds to signal the revocation (mirrors the same
-// requirement singbox's SyncUser/updateUsers place on Hysteria2 users - see
-// backend/singbox/user.go and its tests).
func openVPNCredential(user *common.User) (username, password string, maxConcurrent uint32, ok bool) {
proxy := user.GetProxies().GetOpenVpn()
if proxy == nil {
@@ -235,12 +213,6 @@ func (b *Backend) syncAllUsers(users []*common.User) {
}
}
-// updateUsers incrementally upserts/removes the given users against every
-// instance's authStore: a user is authorized on an instance's tag if it
-// carries an OpenVPN credential and lists that tag in Inbounds, otherwise it
-// is removed from that instance if present. Mirrors singbox's
-// Config.updateUsers incremental-merge semantics (see
-// backend/singbox/user.go).
func (b *Backend) updateUsers(users []*common.User) {
touched := make(map[string]struct{}, len(b.instances))
@@ -300,11 +272,6 @@ func (b *Backend) UpdateUsers(_ context.Context, users []*common.User) error {
return nil
}
-// UpdateUsersAndRestart behaves identically to UpdateUsers on this backend:
-// there is no config-rewrite-plus-restart path to take at all here (see the
-// doc comment above) - kept as a distinct method rather than an alias to
-// preserve the Backend interface's call sites, mirroring sing-box's identical
-// rationale for its own UpdateUsersAndRestart (backend/singbox/user.go).
func (b *Backend) UpdateUsersAndRestart(ctx context.Context, users []*common.User) error {
return b.UpdateUsers(ctx, users)
}
diff --git a/backend/singbox/api/base.go b/backend/singbox/api/base.go
deleted file mode 100644
index 5948276c..00000000
--- a/backend/singbox/api/base.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Package api is a thin gRPC client for sing-box's experimental.v2ray_api
-// StatsService. See proto/stats.proto for why this is a hand-written minimal
-// client rather than a dependency on xtls/xray-core's stats client.
-package api
-
-import (
- "context"
- "fmt"
- "net"
- "time"
-
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials/insecure"
-)
-
-const maxGRPCMessageSize = 64 * 1024 * 1024 // 64MB
-
-// Client wraps a gRPC connection to a running sing-box process's
-// experimental.v2ray_api port. Mirrors backend/xray/api.XrayHandler's dial
-// pattern.
-type Client struct {
- StatsServiceClient statscmd.StatsServiceClient
- GrpcClient *grpc.ClientConn
-}
-
-func NewClient(apiPort int) (*Client, error) {
- c := &Client{}
- target := fmt.Sprintf("127.0.0.1:%v", apiPort)
- dialer := &net.Dialer{
- Timeout: 5 * time.Second,
- LocalAddr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1")},
- }
-
- var err error
- c.GrpcClient, err = grpc.NewClient(
- target,
- grpc.WithTransportCredentials(insecure.NewCredentials()),
- grpc.WithDefaultCallOptions(
- grpc.MaxCallRecvMsgSize(maxGRPCMessageSize),
- grpc.MaxCallSendMsgSize(maxGRPCMessageSize),
- ),
- grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
- conn, dialErr := dialer.DialContext(ctx, "tcp4", addr)
- if dialErr == nil {
- return conn, nil
- }
-
- var fallback net.Dialer
- return fallback.DialContext(ctx, "tcp", addr)
- }),
- )
- if err != nil {
- return nil, err
- }
-
- c.StatsServiceClient = statscmd.NewStatsServiceClient(c.GrpcClient)
-
- return c, nil
-}
-
-func (c *Client) Close() {
- if c.GrpcClient != nil {
- _ = c.GrpcClient.Close()
- }
-}
diff --git a/backend/singbox/api/close_test.go b/backend/singbox/api/close_test.go
deleted file mode 100644
index 445aa939..00000000
--- a/backend/singbox/api/close_test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package api
-
-import (
- "context"
- "sync"
- "testing"
- "time"
-)
-
-func callWithoutPanic(t *testing.T, name string, call func() error) error {
- t.Helper()
-
- var err error
- func() {
- defer func() {
- if r := recover(); r != nil {
- t.Fatalf("%s on a closed client panicked: %v", name, r)
- }
- }()
- err = call()
- }()
- return err
-}
-
-func TestAStatsCallOnAClosedClientFailsInsteadOfPanicking(t *testing.T) {
- _, port := startFakeStatsServer(t)
- client, err := NewClient(port)
- if err != nil {
- t.Fatal(err)
- }
- client.Close()
-
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
-
- if err := callWithoutPanic(t, "GetSysStats", func() error {
- _, err := client.GetSysStats(ctx)
- return err
- }); err == nil {
- t.Fatal("GetSysStats on a closed client must fail")
- }
- if err := callWithoutPanic(t, "QueryStats", func() error {
- _, err := client.QueryStats(ctx, "user>>>", false)
- return err
- }); err == nil {
- t.Fatal("QueryStats on a closed client must fail")
- }
- if err := callWithoutPanic(t, "DrainInboundCounters", func() error {
- _, err := client.DrainInboundCounters(ctx)
- return err
- }); err == nil {
- t.Fatal("DrainInboundCounters on a closed client must fail")
- }
-}
-
-func TestClosingTheClientDoesNotRaceAStatsCallInFlight(t *testing.T) {
- _, port := startFakeStatsServer(t)
-
- for range 50 {
- client, err := NewClient(port)
- if err != nil {
- t.Fatal(err)
- }
-
- started := make(chan struct{})
- var wg sync.WaitGroup
- wg.Add(1)
- go func() {
- defer wg.Done()
- defer func() {
- if r := recover(); r != nil {
- t.Errorf("a stats call racing Close panicked: %v", r)
- }
- }()
- close(started)
- for range 20 {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
- _, _ = client.GetSysStats(ctx)
- cancel()
- }
- }()
-
- <-started
- client.Close()
- wg.Wait()
- }
-}
diff --git a/backend/singbox/api/proto/stats.pb.go b/backend/singbox/api/proto/stats.pb.go
deleted file mode 100644
index 4b62bd00..00000000
--- a/backend/singbox/api/proto/stats.pb.go
+++ /dev/null
@@ -1,556 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// versions:
-// protoc-gen-go v1.36.11
-// protoc v3.12.4
-// source: backend/singbox/api/proto/stats.proto
-
-// This is a minimal, hand-written re-declaration of the gRPC surface sing-box's
-// experimental.v2ray_api StatsService actually implements - NOT xray-core's
-// newer "xray.app.stats.command.StatsService". sing-box registers the legacy
-// v2ray/v2fly service name and shape (see
-// experimental/v2rayapi/stats.go/.proto in the sing-box source, tag v1.13.14):
-// `StatsService_ServiceDesc.ServiceName = "v2ray.core.app.stats.command.StatsService"`.
-// A client built against xtls/xray-core's app/stats/command package fails
-// against sing-box with "Unimplemented desc = unknown service
-// xray.app.stats.command.StatsService" - do not switch this back to that
-// package. Field numbers/types below are copied 1:1 from sing-box's real
-// experimental/v2rayapi/stats.proto so this stays wire-compatible; only the
-// unimplemented GetStatsList RPC (present in an earlier exploration proto, but
-// never actually registered by sing-box's server) has been dropped.
-
-package proto
-
-import (
- protoreflect "google.golang.org/protobuf/reflect/protoreflect"
- protoimpl "google.golang.org/protobuf/runtime/protoimpl"
- reflect "reflect"
- sync "sync"
- unsafe "unsafe"
-)
-
-const (
- // Verify that this generated code is sufficiently up-to-date.
- _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
- // Verify that runtime/protoimpl is sufficiently up-to-date.
- _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
-)
-
-type GetStatsRequest struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- Reset_ bool `protobuf:"varint,2,opt,name=reset,proto3" json:"reset,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *GetStatsRequest) Reset() {
- *x = GetStatsRequest{}
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[0]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *GetStatsRequest) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*GetStatsRequest) ProtoMessage() {}
-
-func (x *GetStatsRequest) ProtoReflect() protoreflect.Message {
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[0]
- if x != nil {
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- if ms.LoadMessageInfo() == nil {
- ms.StoreMessageInfo(mi)
- }
- return ms
- }
- return mi.MessageOf(x)
-}
-
-// Deprecated: Use GetStatsRequest.ProtoReflect.Descriptor instead.
-func (*GetStatsRequest) Descriptor() ([]byte, []int) {
- return file_backend_singbox_api_proto_stats_proto_rawDescGZIP(), []int{0}
-}
-
-func (x *GetStatsRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *GetStatsRequest) GetReset_() bool {
- if x != nil {
- return x.Reset_
- }
- return false
-}
-
-type Stat struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- Value int64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *Stat) Reset() {
- *x = Stat{}
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[1]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *Stat) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*Stat) ProtoMessage() {}
-
-func (x *Stat) ProtoReflect() protoreflect.Message {
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[1]
- if x != nil {
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- if ms.LoadMessageInfo() == nil {
- ms.StoreMessageInfo(mi)
- }
- return ms
- }
- return mi.MessageOf(x)
-}
-
-// Deprecated: Use Stat.ProtoReflect.Descriptor instead.
-func (*Stat) Descriptor() ([]byte, []int) {
- return file_backend_singbox_api_proto_stats_proto_rawDescGZIP(), []int{1}
-}
-
-func (x *Stat) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *Stat) GetValue() int64 {
- if x != nil {
- return x.Value
- }
- return 0
-}
-
-type GetStatsResponse struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- Stat *Stat `protobuf:"bytes,1,opt,name=stat,proto3" json:"stat,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *GetStatsResponse) Reset() {
- *x = GetStatsResponse{}
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[2]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *GetStatsResponse) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*GetStatsResponse) ProtoMessage() {}
-
-func (x *GetStatsResponse) ProtoReflect() protoreflect.Message {
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[2]
- if x != nil {
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- if ms.LoadMessageInfo() == nil {
- ms.StoreMessageInfo(mi)
- }
- return ms
- }
- return mi.MessageOf(x)
-}
-
-// Deprecated: Use GetStatsResponse.ProtoReflect.Descriptor instead.
-func (*GetStatsResponse) Descriptor() ([]byte, []int) {
- return file_backend_singbox_api_proto_stats_proto_rawDescGZIP(), []int{2}
-}
-
-func (x *GetStatsResponse) GetStat() *Stat {
- if x != nil {
- return x.Stat
- }
- return nil
-}
-
-// IMPORTANT: sing-box's QueryStats handler filters using `patterns` (field 3,
-// repeated) and `regexp` (field 4) - it never reads the older singular
-// `pattern` (field 1), even though that field is still accepted on the wire.
-// Sending only `pattern` silently returns ALL counters, unfiltered. Always
-// populate `patterns` from client code (see api/stats.go's QueryStats helper).
-type QueryStatsRequest struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- Pattern string `protobuf:"bytes,1,opt,name=pattern,proto3" json:"pattern,omitempty"`
- Reset_ bool `protobuf:"varint,2,opt,name=reset,proto3" json:"reset,omitempty"`
- Patterns []string `protobuf:"bytes,3,rep,name=patterns,proto3" json:"patterns,omitempty"`
- Regexp bool `protobuf:"varint,4,opt,name=regexp,proto3" json:"regexp,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *QueryStatsRequest) Reset() {
- *x = QueryStatsRequest{}
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[3]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *QueryStatsRequest) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*QueryStatsRequest) ProtoMessage() {}
-
-func (x *QueryStatsRequest) ProtoReflect() protoreflect.Message {
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[3]
- if x != nil {
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- if ms.LoadMessageInfo() == nil {
- ms.StoreMessageInfo(mi)
- }
- return ms
- }
- return mi.MessageOf(x)
-}
-
-// Deprecated: Use QueryStatsRequest.ProtoReflect.Descriptor instead.
-func (*QueryStatsRequest) Descriptor() ([]byte, []int) {
- return file_backend_singbox_api_proto_stats_proto_rawDescGZIP(), []int{3}
-}
-
-func (x *QueryStatsRequest) GetPattern() string {
- if x != nil {
- return x.Pattern
- }
- return ""
-}
-
-func (x *QueryStatsRequest) GetReset_() bool {
- if x != nil {
- return x.Reset_
- }
- return false
-}
-
-func (x *QueryStatsRequest) GetPatterns() []string {
- if x != nil {
- return x.Patterns
- }
- return nil
-}
-
-func (x *QueryStatsRequest) GetRegexp() bool {
- if x != nil {
- return x.Regexp
- }
- return false
-}
-
-type QueryStatsResponse struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- Stat []*Stat `protobuf:"bytes,1,rep,name=stat,proto3" json:"stat,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *QueryStatsResponse) Reset() {
- *x = QueryStatsResponse{}
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[4]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *QueryStatsResponse) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*QueryStatsResponse) ProtoMessage() {}
-
-func (x *QueryStatsResponse) ProtoReflect() protoreflect.Message {
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[4]
- if x != nil {
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- if ms.LoadMessageInfo() == nil {
- ms.StoreMessageInfo(mi)
- }
- return ms
- }
- return mi.MessageOf(x)
-}
-
-// Deprecated: Use QueryStatsResponse.ProtoReflect.Descriptor instead.
-func (*QueryStatsResponse) Descriptor() ([]byte, []int) {
- return file_backend_singbox_api_proto_stats_proto_rawDescGZIP(), []int{4}
-}
-
-func (x *QueryStatsResponse) GetStat() []*Stat {
- if x != nil {
- return x.Stat
- }
- return nil
-}
-
-type SysStatsRequest struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *SysStatsRequest) Reset() {
- *x = SysStatsRequest{}
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[5]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *SysStatsRequest) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*SysStatsRequest) ProtoMessage() {}
-
-func (x *SysStatsRequest) ProtoReflect() protoreflect.Message {
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[5]
- if x != nil {
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- if ms.LoadMessageInfo() == nil {
- ms.StoreMessageInfo(mi)
- }
- return ms
- }
- return mi.MessageOf(x)
-}
-
-// Deprecated: Use SysStatsRequest.ProtoReflect.Descriptor instead.
-func (*SysStatsRequest) Descriptor() ([]byte, []int) {
- return file_backend_singbox_api_proto_stats_proto_rawDescGZIP(), []int{5}
-}
-
-type SysStatsResponse struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- NumGoroutine uint32 `protobuf:"varint,1,opt,name=NumGoroutine,proto3" json:"NumGoroutine,omitempty"`
- NumGC uint32 `protobuf:"varint,2,opt,name=NumGC,proto3" json:"NumGC,omitempty"`
- Alloc uint64 `protobuf:"varint,3,opt,name=Alloc,proto3" json:"Alloc,omitempty"`
- TotalAlloc uint64 `protobuf:"varint,4,opt,name=TotalAlloc,proto3" json:"TotalAlloc,omitempty"`
- Sys uint64 `protobuf:"varint,5,opt,name=Sys,proto3" json:"Sys,omitempty"`
- Mallocs uint64 `protobuf:"varint,6,opt,name=Mallocs,proto3" json:"Mallocs,omitempty"`
- Frees uint64 `protobuf:"varint,7,opt,name=Frees,proto3" json:"Frees,omitempty"`
- LiveObjects uint64 `protobuf:"varint,8,opt,name=LiveObjects,proto3" json:"LiveObjects,omitempty"`
- PauseTotalNs uint64 `protobuf:"varint,9,opt,name=PauseTotalNs,proto3" json:"PauseTotalNs,omitempty"`
- Uptime uint32 `protobuf:"varint,10,opt,name=Uptime,proto3" json:"Uptime,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *SysStatsResponse) Reset() {
- *x = SysStatsResponse{}
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[6]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *SysStatsResponse) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*SysStatsResponse) ProtoMessage() {}
-
-func (x *SysStatsResponse) ProtoReflect() protoreflect.Message {
- mi := &file_backend_singbox_api_proto_stats_proto_msgTypes[6]
- if x != nil {
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- if ms.LoadMessageInfo() == nil {
- ms.StoreMessageInfo(mi)
- }
- return ms
- }
- return mi.MessageOf(x)
-}
-
-// Deprecated: Use SysStatsResponse.ProtoReflect.Descriptor instead.
-func (*SysStatsResponse) Descriptor() ([]byte, []int) {
- return file_backend_singbox_api_proto_stats_proto_rawDescGZIP(), []int{6}
-}
-
-func (x *SysStatsResponse) GetNumGoroutine() uint32 {
- if x != nil {
- return x.NumGoroutine
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetNumGC() uint32 {
- if x != nil {
- return x.NumGC
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetAlloc() uint64 {
- if x != nil {
- return x.Alloc
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetTotalAlloc() uint64 {
- if x != nil {
- return x.TotalAlloc
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetSys() uint64 {
- if x != nil {
- return x.Sys
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetMallocs() uint64 {
- if x != nil {
- return x.Mallocs
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetFrees() uint64 {
- if x != nil {
- return x.Frees
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetLiveObjects() uint64 {
- if x != nil {
- return x.LiveObjects
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetPauseTotalNs() uint64 {
- if x != nil {
- return x.PauseTotalNs
- }
- return 0
-}
-
-func (x *SysStatsResponse) GetUptime() uint32 {
- if x != nil {
- return x.Uptime
- }
- return 0
-}
-
-var File_backend_singbox_api_proto_stats_proto protoreflect.FileDescriptor
-
-const file_backend_singbox_api_proto_stats_proto_rawDesc = "" +
- "\n" +
- "%backend/singbox/api/proto/stats.proto\x12\x1cv2ray.core.app.stats.command\";\n" +
- "\x0fGetStatsRequest\x12\x12\n" +
- "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" +
- "\x05reset\x18\x02 \x01(\bR\x05reset\"0\n" +
- "\x04Stat\x12\x12\n" +
- "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" +
- "\x05value\x18\x02 \x01(\x03R\x05value\"J\n" +
- "\x10GetStatsResponse\x126\n" +
- "\x04stat\x18\x01 \x01(\v2\".v2ray.core.app.stats.command.StatR\x04stat\"w\n" +
- "\x11QueryStatsRequest\x12\x18\n" +
- "\apattern\x18\x01 \x01(\tR\apattern\x12\x14\n" +
- "\x05reset\x18\x02 \x01(\bR\x05reset\x12\x1a\n" +
- "\bpatterns\x18\x03 \x03(\tR\bpatterns\x12\x16\n" +
- "\x06regexp\x18\x04 \x01(\bR\x06regexp\"L\n" +
- "\x12QueryStatsResponse\x126\n" +
- "\x04stat\x18\x01 \x03(\v2\".v2ray.core.app.stats.command.StatR\x04stat\"\x11\n" +
- "\x0fSysStatsRequest\"\xa2\x02\n" +
- "\x10SysStatsResponse\x12\"\n" +
- "\fNumGoroutine\x18\x01 \x01(\rR\fNumGoroutine\x12\x14\n" +
- "\x05NumGC\x18\x02 \x01(\rR\x05NumGC\x12\x14\n" +
- "\x05Alloc\x18\x03 \x01(\x04R\x05Alloc\x12\x1e\n" +
- "\n" +
- "TotalAlloc\x18\x04 \x01(\x04R\n" +
- "TotalAlloc\x12\x10\n" +
- "\x03Sys\x18\x05 \x01(\x04R\x03Sys\x12\x18\n" +
- "\aMallocs\x18\x06 \x01(\x04R\aMallocs\x12\x14\n" +
- "\x05Frees\x18\a \x01(\x04R\x05Frees\x12 \n" +
- "\vLiveObjects\x18\b \x01(\x04R\vLiveObjects\x12\"\n" +
- "\fPauseTotalNs\x18\t \x01(\x04R\fPauseTotalNs\x12\x16\n" +
- "\x06Uptime\x18\n" +
- " \x01(\rR\x06Uptime2\xde\x02\n" +
- "\fStatsService\x12k\n" +
- "\bGetStats\x12-.v2ray.core.app.stats.command.GetStatsRequest\x1a..v2ray.core.app.stats.command.GetStatsResponse\"\x00\x12q\n" +
- "\n" +
- "QueryStats\x12/.v2ray.core.app.stats.command.QueryStatsRequest\x1a0.v2ray.core.app.stats.command.QueryStatsResponse\"\x00\x12n\n" +
- "\vGetSysStats\x12-.v2ray.core.app.stats.command.SysStatsRequest\x1a..v2ray.core.app.stats.command.SysStatsResponse\"\x00B6Z4github.com/pasarguard/node/backend/singbox/api/protob\x06proto3"
-
-var (
- file_backend_singbox_api_proto_stats_proto_rawDescOnce sync.Once
- file_backend_singbox_api_proto_stats_proto_rawDescData []byte
-)
-
-func file_backend_singbox_api_proto_stats_proto_rawDescGZIP() []byte {
- file_backend_singbox_api_proto_stats_proto_rawDescOnce.Do(func() {
- file_backend_singbox_api_proto_stats_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_backend_singbox_api_proto_stats_proto_rawDesc), len(file_backend_singbox_api_proto_stats_proto_rawDesc)))
- })
- return file_backend_singbox_api_proto_stats_proto_rawDescData
-}
-
-var file_backend_singbox_api_proto_stats_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
-var file_backend_singbox_api_proto_stats_proto_goTypes = []any{
- (*GetStatsRequest)(nil), // 0: v2ray.core.app.stats.command.GetStatsRequest
- (*Stat)(nil), // 1: v2ray.core.app.stats.command.Stat
- (*GetStatsResponse)(nil), // 2: v2ray.core.app.stats.command.GetStatsResponse
- (*QueryStatsRequest)(nil), // 3: v2ray.core.app.stats.command.QueryStatsRequest
- (*QueryStatsResponse)(nil), // 4: v2ray.core.app.stats.command.QueryStatsResponse
- (*SysStatsRequest)(nil), // 5: v2ray.core.app.stats.command.SysStatsRequest
- (*SysStatsResponse)(nil), // 6: v2ray.core.app.stats.command.SysStatsResponse
-}
-var file_backend_singbox_api_proto_stats_proto_depIdxs = []int32{
- 1, // 0: v2ray.core.app.stats.command.GetStatsResponse.stat:type_name -> v2ray.core.app.stats.command.Stat
- 1, // 1: v2ray.core.app.stats.command.QueryStatsResponse.stat:type_name -> v2ray.core.app.stats.command.Stat
- 0, // 2: v2ray.core.app.stats.command.StatsService.GetStats:input_type -> v2ray.core.app.stats.command.GetStatsRequest
- 3, // 3: v2ray.core.app.stats.command.StatsService.QueryStats:input_type -> v2ray.core.app.stats.command.QueryStatsRequest
- 5, // 4: v2ray.core.app.stats.command.StatsService.GetSysStats:input_type -> v2ray.core.app.stats.command.SysStatsRequest
- 2, // 5: v2ray.core.app.stats.command.StatsService.GetStats:output_type -> v2ray.core.app.stats.command.GetStatsResponse
- 4, // 6: v2ray.core.app.stats.command.StatsService.QueryStats:output_type -> v2ray.core.app.stats.command.QueryStatsResponse
- 6, // 7: v2ray.core.app.stats.command.StatsService.GetSysStats:output_type -> v2ray.core.app.stats.command.SysStatsResponse
- 5, // [5:8] is the sub-list for method output_type
- 2, // [2:5] is the sub-list for method input_type
- 2, // [2:2] is the sub-list for extension type_name
- 2, // [2:2] is the sub-list for extension extendee
- 0, // [0:2] is the sub-list for field type_name
-}
-
-func init() { file_backend_singbox_api_proto_stats_proto_init() }
-func file_backend_singbox_api_proto_stats_proto_init() {
- if File_backend_singbox_api_proto_stats_proto != nil {
- return
- }
- type x struct{}
- out := protoimpl.TypeBuilder{
- File: protoimpl.DescBuilder{
- GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
- RawDescriptor: unsafe.Slice(unsafe.StringData(file_backend_singbox_api_proto_stats_proto_rawDesc), len(file_backend_singbox_api_proto_stats_proto_rawDesc)),
- NumEnums: 0,
- NumMessages: 7,
- NumExtensions: 0,
- NumServices: 1,
- },
- GoTypes: file_backend_singbox_api_proto_stats_proto_goTypes,
- DependencyIndexes: file_backend_singbox_api_proto_stats_proto_depIdxs,
- MessageInfos: file_backend_singbox_api_proto_stats_proto_msgTypes,
- }.Build()
- File_backend_singbox_api_proto_stats_proto = out.File
- file_backend_singbox_api_proto_stats_proto_goTypes = nil
- file_backend_singbox_api_proto_stats_proto_depIdxs = nil
-}
diff --git a/backend/singbox/api/proto/stats.proto b/backend/singbox/api/proto/stats.proto
deleted file mode 100644
index 1fe5bf3e..00000000
--- a/backend/singbox/api/proto/stats.proto
+++ /dev/null
@@ -1,69 +0,0 @@
-syntax = "proto3";
-
-// This is a minimal, hand-written re-declaration of the gRPC surface sing-box's
-// experimental.v2ray_api StatsService actually implements - NOT xray-core's
-// newer "xray.app.stats.command.StatsService". sing-box registers the legacy
-// v2ray/v2fly service name and shape (see
-// experimental/v2rayapi/stats.go/.proto in the sing-box source, tag v1.13.14):
-// `StatsService_ServiceDesc.ServiceName = "v2ray.core.app.stats.command.StatsService"`.
-// A client built against xtls/xray-core's app/stats/command package fails
-// against sing-box with "Unimplemented desc = unknown service
-// xray.app.stats.command.StatsService" - do not switch this back to that
-// package. Field numbers/types below are copied 1:1 from sing-box's real
-// experimental/v2rayapi/stats.proto so this stays wire-compatible; only the
-// unimplemented GetStatsList RPC (present in an earlier exploration proto, but
-// never actually registered by sing-box's server) has been dropped.
-package v2ray.core.app.stats.command;
-
-option go_package = "github.com/pasarguard/node/backend/singbox/api/proto";
-
-message GetStatsRequest {
- string name = 1;
- bool reset = 2;
-}
-
-message Stat {
- string name = 1;
- int64 value = 2;
-}
-
-message GetStatsResponse {
- Stat stat = 1;
-}
-
-// IMPORTANT: sing-box's QueryStats handler filters using `patterns` (field 3,
-// repeated) and `regexp` (field 4) - it never reads the older singular
-// `pattern` (field 1), even though that field is still accepted on the wire.
-// Sending only `pattern` silently returns ALL counters, unfiltered. Always
-// populate `patterns` from client code (see api/stats.go's QueryStats helper).
-message QueryStatsRequest {
- string pattern = 1;
- bool reset = 2;
- repeated string patterns = 3;
- bool regexp = 4;
-}
-
-message QueryStatsResponse {
- repeated Stat stat = 1;
-}
-
-message SysStatsRequest {}
-
-message SysStatsResponse {
- uint32 NumGoroutine = 1;
- uint32 NumGC = 2;
- uint64 Alloc = 3;
- uint64 TotalAlloc = 4;
- uint64 Sys = 5;
- uint64 Mallocs = 6;
- uint64 Frees = 7;
- uint64 LiveObjects = 8;
- uint64 PauseTotalNs = 9;
- uint32 Uptime = 10;
-}
-
-service StatsService {
- rpc GetStats(GetStatsRequest) returns (GetStatsResponse) {}
- rpc QueryStats(QueryStatsRequest) returns (QueryStatsResponse) {}
- rpc GetSysStats(SysStatsRequest) returns (SysStatsResponse) {}
-}
diff --git a/backend/singbox/api/proto/stats_grpc.pb.go b/backend/singbox/api/proto/stats_grpc.pb.go
deleted file mode 100644
index cc761389..00000000
--- a/backend/singbox/api/proto/stats_grpc.pb.go
+++ /dev/null
@@ -1,211 +0,0 @@
-// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
-// versions:
-// - protoc-gen-go-grpc v1.6.2
-// - protoc v3.12.4
-// source: backend/singbox/api/proto/stats.proto
-
-// This is a minimal, hand-written re-declaration of the gRPC surface sing-box's
-// experimental.v2ray_api StatsService actually implements - NOT xray-core's
-// newer "xray.app.stats.command.StatsService". sing-box registers the legacy
-// v2ray/v2fly service name and shape (see
-// experimental/v2rayapi/stats.go/.proto in the sing-box source, tag v1.13.14):
-// `StatsService_ServiceDesc.ServiceName = "v2ray.core.app.stats.command.StatsService"`.
-// A client built against xtls/xray-core's app/stats/command package fails
-// against sing-box with "Unimplemented desc = unknown service
-// xray.app.stats.command.StatsService" - do not switch this back to that
-// package. Field numbers/types below are copied 1:1 from sing-box's real
-// experimental/v2rayapi/stats.proto so this stays wire-compatible; only the
-// unimplemented GetStatsList RPC (present in an earlier exploration proto, but
-// never actually registered by sing-box's server) has been dropped.
-
-package proto
-
-import (
- context "context"
- grpc "google.golang.org/grpc"
- codes "google.golang.org/grpc/codes"
- status "google.golang.org/grpc/status"
-)
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the grpc package it is being compiled against.
-// Requires gRPC-Go v1.64.0 or later.
-const _ = grpc.SupportPackageIsVersion9
-
-const (
- StatsService_GetStats_FullMethodName = "/v2ray.core.app.stats.command.StatsService/GetStats"
- StatsService_QueryStats_FullMethodName = "/v2ray.core.app.stats.command.StatsService/QueryStats"
- StatsService_GetSysStats_FullMethodName = "/v2ray.core.app.stats.command.StatsService/GetSysStats"
-)
-
-// StatsServiceClient is the client API for StatsService service.
-//
-// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
-type StatsServiceClient interface {
- GetStats(ctx context.Context, in *GetStatsRequest, opts ...grpc.CallOption) (*GetStatsResponse, error)
- QueryStats(ctx context.Context, in *QueryStatsRequest, opts ...grpc.CallOption) (*QueryStatsResponse, error)
- GetSysStats(ctx context.Context, in *SysStatsRequest, opts ...grpc.CallOption) (*SysStatsResponse, error)
-}
-
-type statsServiceClient struct {
- cc grpc.ClientConnInterface
-}
-
-func NewStatsServiceClient(cc grpc.ClientConnInterface) StatsServiceClient {
- return &statsServiceClient{cc}
-}
-
-func (c *statsServiceClient) GetStats(ctx context.Context, in *GetStatsRequest, opts ...grpc.CallOption) (*GetStatsResponse, error) {
- cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
- out := new(GetStatsResponse)
- err := c.cc.Invoke(ctx, StatsService_GetStats_FullMethodName, in, out, cOpts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *statsServiceClient) QueryStats(ctx context.Context, in *QueryStatsRequest, opts ...grpc.CallOption) (*QueryStatsResponse, error) {
- cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
- out := new(QueryStatsResponse)
- err := c.cc.Invoke(ctx, StatsService_QueryStats_FullMethodName, in, out, cOpts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *statsServiceClient) GetSysStats(ctx context.Context, in *SysStatsRequest, opts ...grpc.CallOption) (*SysStatsResponse, error) {
- cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
- out := new(SysStatsResponse)
- err := c.cc.Invoke(ctx, StatsService_GetSysStats_FullMethodName, in, out, cOpts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// StatsServiceServer is the server API for StatsService service.
-// All implementations must embed UnimplementedStatsServiceServer
-// for forward compatibility.
-type StatsServiceServer interface {
- GetStats(context.Context, *GetStatsRequest) (*GetStatsResponse, error)
- QueryStats(context.Context, *QueryStatsRequest) (*QueryStatsResponse, error)
- GetSysStats(context.Context, *SysStatsRequest) (*SysStatsResponse, error)
- mustEmbedUnimplementedStatsServiceServer()
-}
-
-// UnimplementedStatsServiceServer must be embedded to have
-// forward compatible implementations.
-//
-// NOTE: this should be embedded by value instead of pointer to avoid a nil
-// pointer dereference when methods are called.
-type UnimplementedStatsServiceServer struct{}
-
-func (UnimplementedStatsServiceServer) GetStats(context.Context, *GetStatsRequest) (*GetStatsResponse, error) {
- return nil, status.Error(codes.Unimplemented, "method GetStats not implemented")
-}
-func (UnimplementedStatsServiceServer) QueryStats(context.Context, *QueryStatsRequest) (*QueryStatsResponse, error) {
- return nil, status.Error(codes.Unimplemented, "method QueryStats not implemented")
-}
-func (UnimplementedStatsServiceServer) GetSysStats(context.Context, *SysStatsRequest) (*SysStatsResponse, error) {
- return nil, status.Error(codes.Unimplemented, "method GetSysStats not implemented")
-}
-func (UnimplementedStatsServiceServer) mustEmbedUnimplementedStatsServiceServer() {}
-func (UnimplementedStatsServiceServer) testEmbeddedByValue() {}
-
-// UnsafeStatsServiceServer may be embedded to opt out of forward compatibility for this service.
-// Use of this interface is not recommended, as added methods to StatsServiceServer will
-// result in compilation errors.
-type UnsafeStatsServiceServer interface {
- mustEmbedUnimplementedStatsServiceServer()
-}
-
-func RegisterStatsServiceServer(s grpc.ServiceRegistrar, srv StatsServiceServer) {
- // If the following call panics, it indicates UnimplementedStatsServiceServer was
- // embedded by pointer and is nil. This will cause panics if an
- // unimplemented method is ever invoked, so we test this at initialization
- // time to prevent it from happening at runtime later due to I/O.
- if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
- t.testEmbeddedByValue()
- }
- s.RegisterService(&StatsService_ServiceDesc, srv)
-}
-
-func _StatsService_GetStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(GetStatsRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(StatsServiceServer).GetStats(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: StatsService_GetStats_FullMethodName,
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(StatsServiceServer).GetStats(ctx, req.(*GetStatsRequest))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-func _StatsService_QueryStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(QueryStatsRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(StatsServiceServer).QueryStats(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: StatsService_QueryStats_FullMethodName,
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(StatsServiceServer).QueryStats(ctx, req.(*QueryStatsRequest))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-func _StatsService_GetSysStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(SysStatsRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(StatsServiceServer).GetSysStats(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: StatsService_GetSysStats_FullMethodName,
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(StatsServiceServer).GetSysStats(ctx, req.(*SysStatsRequest))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-// StatsService_ServiceDesc is the grpc.ServiceDesc for StatsService service.
-// It's only intended for direct use with grpc.RegisterService,
-// and not to be introspected or modified (even as a copy)
-var StatsService_ServiceDesc = grpc.ServiceDesc{
- ServiceName: "v2ray.core.app.stats.command.StatsService",
- HandlerType: (*StatsServiceServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "GetStats",
- Handler: _StatsService_GetStats_Handler,
- },
- {
- MethodName: "QueryStats",
- Handler: _StatsService_QueryStats_Handler,
- },
- {
- MethodName: "GetSysStats",
- Handler: _StatsService_GetSysStats_Handler,
- },
- },
- Streams: []grpc.StreamDesc{},
- Metadata: "backend/singbox/api/proto/stats.proto",
-}
diff --git a/backend/singbox/api/stats.go b/backend/singbox/api/stats.go
deleted file mode 100644
index 3c2a8cee..00000000
--- a/backend/singbox/api/stats.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package api
-
-import (
- "context"
- "errors"
- "fmt"
- "strings"
-
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
-)
-
-func (c *Client) GetSysStats(ctx context.Context) (*common.BackendStatsResponse, error) {
- resp, err := c.StatsServiceClient.GetSysStats(ctx, &statscmd.SysStatsRequest{})
- if err != nil {
- code := codes.Unknown
- if st, ok := status.FromError(err); ok {
- code = st.Code()
- }
- return nil, status.Errorf(code, "failed to get sys stats: %v", err)
- }
-
- return &common.BackendStatsResponse{
- NumGoroutine: resp.GetNumGoroutine(),
- NumGc: resp.GetNumGC(),
- Alloc: resp.GetAlloc(),
- TotalAlloc: resp.GetTotalAlloc(),
- Sys: resp.GetSys(),
- Mallocs: resp.GetMallocs(),
- Frees: resp.GetFrees(),
- LiveObjects: resp.GetLiveObjects(),
- PauseTotalNs: resp.GetPauseTotalNs(),
- Uptime: resp.GetUptime(),
- }, nil
-}
-
-// QueryStats queries sing-box's v2ray_api StatsService. It always populates the
-// modern "patterns" (repeated substring match) field rather than the legacy
-// singular "pattern" field - see proto/stats.proto's doc comment: sing-box's
-// server-side handler only ever reads request.Patterns, so sending just
-// Pattern would silently disable filtering and return every counter.
-func (c *Client) QueryStats(ctx context.Context, pattern string, reset bool) (*statscmd.QueryStatsResponse, error) {
- req := &statscmd.QueryStatsRequest{Reset_: reset}
- if pattern != "" {
- req.Patterns = []string{pattern}
- }
-
- resp, err := c.StatsServiceClient.QueryStats(ctx, req)
- if err != nil {
- return nil, err
- }
-
- return resp, nil
-}
-
-func (c *Client) GetUsersStats(ctx context.Context, reset bool) (*common.StatResponse, error) {
- resp, err := c.QueryStats(ctx, "user>>>", reset)
- if err != nil {
- return nil, err
- }
- return buildStatResponse(resp.GetStat()), nil
-}
-
-func (c *Client) GetInboundsStats(ctx context.Context, reset bool) (*common.StatResponse, error) {
- resp, err := c.QueryStats(ctx, "inbound>>>", reset)
- if err != nil {
- return nil, err
- }
- return buildStatResponse(resp.GetStat()), nil
-}
-
-func (c *Client) DrainInboundCounters(ctx context.Context) ([]*statscmd.Stat, error) {
- resp, err := c.QueryStats(ctx, "inbound>>>", true)
- if err != nil {
- return nil, err
- }
- return resp.GetStat(), nil
-}
-
-func (c *Client) GetOutboundsStats(ctx context.Context, reset bool) (*common.StatResponse, error) {
- resp, err := c.QueryStats(ctx, "outbound>>>", reset)
- if err != nil {
- return nil, err
- }
- return buildStatResponse(resp.GetStat()), nil
-}
-
-func (c *Client) GetUserStats(ctx context.Context, email string, reset bool) (*common.StatResponse, error) {
- if email == "" {
- return nil, errors.New("email required")
- }
- resp, err := c.QueryStats(ctx, fmt.Sprintf("user>>>%s>>>", email), reset)
- if err != nil {
- return nil, err
- }
- return buildStatResponse(resp.GetStat()), nil
-}
-
-func (c *Client) GetInboundStats(ctx context.Context, tag string, reset bool) (*common.StatResponse, error) {
- if tag == "" {
- return nil, errors.New("tag required")
- }
- resp, err := c.QueryStats(ctx, fmt.Sprintf("inbound>>>%s>>>", tag), reset)
- if err != nil {
- return nil, err
- }
- return buildStatResponse(resp.GetStat()), nil
-}
-
-func (c *Client) GetOutboundStats(ctx context.Context, tag string, reset bool) (*common.StatResponse, error) {
- if tag == "" {
- return nil, errors.New("tag required")
- }
- resp, err := c.QueryStats(ctx, fmt.Sprintf("outbound>>>%s>>>", tag), reset)
- if err != nil {
- return nil, err
- }
- return buildStatResponse(resp.GetStat()), nil
-}
-
-func BuildStatResponse(stats []*statscmd.Stat) *common.StatResponse {
- return buildStatResponse(stats)
-}
-
-func buildStatResponse(stats []*statscmd.Stat) *common.StatResponse {
- resp := &common.StatResponse{}
- for _, stat := range stats {
- name, link, statType, ok := parseStatName(stat.GetName())
- if !ok {
- continue
- }
-
- resp.Stats = append(resp.Stats, &common.Stat{
- Name: name,
- Type: statType,
- Link: link,
- Value: stat.GetValue(),
- })
- }
- return resp
-}
-
-// parseStatName mirrors backend/xray/api/stats.go's parseStatName: sing-box's
-// v2ray_api registers counters using the exact same "kind>>>name>>>type>>>link"
-// naming convention as xray-core.
-func parseStatName(raw string) (name, link, statType string, ok bool) {
- parts := strings.Split(raw, ">>>")
- if len(parts) < 4 {
- return "", "", "", false
- }
- if parts[1] == "" || parts[2] == "" || parts[3] == "" {
- return "", "", "", false
- }
- return parts[1], parts[2], parts[3], true
-}
diff --git a/backend/singbox/api/stats_test.go b/backend/singbox/api/stats_test.go
deleted file mode 100644
index de066f8e..00000000
--- a/backend/singbox/api/stats_test.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package api
-
-import (
- "context"
- "net"
- "strings"
- "testing"
-
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "google.golang.org/grpc"
-)
-
-// fakeStatsServer mimics the real sing-box behavior found in
-// experimental/v2rayapi/stats.go: QueryStats only ever inspects
-// request.Patterns, never the deprecated singular request.Pattern field. This
-// is what makes the test below meaningful - a client that populated only
-// Pattern (as the original spike proto only allowed) would get every counter
-// back unfiltered here, not just the matching one.
-type fakeStatsServer struct {
- statscmd.UnimplementedStatsServiceServer
- lastRequest *statscmd.QueryStatsRequest
-}
-
-var allFakeStats = []*statscmd.Stat{
- {Name: "user>>>alice@example.com>>>traffic>>>uplink", Value: 111},
- {Name: "user>>>bob@example.com>>>traffic>>>uplink", Value: 222},
-}
-
-func (f *fakeStatsServer) QueryStats(_ context.Context, req *statscmd.QueryStatsRequest) (*statscmd.QueryStatsResponse, error) {
- f.lastRequest = req
-
- if len(req.GetPatterns()) == 0 {
- return &statscmd.QueryStatsResponse{Stat: allFakeStats}, nil
- }
-
- var out []*statscmd.Stat
- for _, stat := range allFakeStats {
- for _, pattern := range req.GetPatterns() {
- if strings.Contains(stat.GetName(), pattern) {
- out = append(out, stat)
- break
- }
- }
- }
- return &statscmd.QueryStatsResponse{Stat: out}, nil
-}
-
-func startFakeStatsServer(t *testing.T) (*fakeStatsServer, int) {
- t.Helper()
-
- lis, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("failed to listen: %v", err)
- }
-
- srv := grpc.NewServer()
- fake := &fakeStatsServer{}
- statscmd.RegisterStatsServiceServer(srv, fake)
-
- go func() {
- _ = srv.Serve(lis)
- }()
- t.Cleanup(srv.Stop)
-
- return fake, lis.Addr().(*net.TCPAddr).Port
-}
-
-func TestQueryStats_PopulatesPatternsFieldNotDeprecatedPattern(t *testing.T) {
- fake, port := startFakeStatsServer(t)
-
- client, err := NewClient(port)
- if err != nil {
- t.Fatalf("NewClient() error = %v", err)
- }
- defer client.Close()
-
- resp, err := client.QueryStats(context.Background(), "alice@example.com", false)
- if err != nil {
- t.Fatalf("QueryStats() error = %v", err)
- }
-
- if fake.lastRequest == nil {
- t.Fatal("fake server never received a request")
- }
- if got := fake.lastRequest.GetPatterns(); len(got) != 1 || got[0] != "alice@example.com" {
- t.Fatalf("expected server to receive Patterns=[alice@example.com], got %+v", got)
- }
-
- stats := resp.GetStat()
- if len(stats) != 1 || stats[0].GetName() != "user>>>alice@example.com>>>traffic>>>uplink" {
- t.Fatalf("expected exactly alice's stat back (proving server-side filtering via Patterns worked), got %+v", stats)
- }
-}
-
-func TestQueryStats_EmptyPatternReturnsEverything(t *testing.T) {
- _, port := startFakeStatsServer(t)
-
- client, err := NewClient(port)
- if err != nil {
- t.Fatalf("NewClient() error = %v", err)
- }
- defer client.Close()
-
- resp, err := client.QueryStats(context.Background(), "", false)
- if err != nil {
- t.Fatalf("QueryStats() error = %v", err)
- }
- if len(resp.GetStat()) != len(allFakeStats) {
- t.Fatalf("expected all %d stats back for an empty pattern, got %d", len(allFakeStats), len(resp.GetStat()))
- }
-}
-
-func TestGetSysStats_MapsAllFields(t *testing.T) {
- lis, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("failed to listen: %v", err)
- }
- srv := grpc.NewServer()
- statscmd.RegisterStatsServiceServer(srv, &sysStatsFakeServer{})
- go func() { _ = srv.Serve(lis) }()
- t.Cleanup(srv.Stop)
-
- client, err := NewClient(lis.Addr().(*net.TCPAddr).Port)
- if err != nil {
- t.Fatalf("NewClient() error = %v", err)
- }
- defer client.Close()
-
- stats, err := client.GetSysStats(context.Background())
- if err != nil {
- t.Fatalf("GetSysStats() error = %v", err)
- }
-
- if stats.GetNumGoroutine() != 7 || stats.GetUptime() != 42 || stats.GetAlloc() != 1024 {
- t.Fatalf("unexpected mapped sys stats: %+v", stats)
- }
-}
-
-type sysStatsFakeServer struct {
- statscmd.UnimplementedStatsServiceServer
-}
-
-func (sysStatsFakeServer) GetSysStats(context.Context, *statscmd.SysStatsRequest) (*statscmd.SysStatsResponse, error) {
- return &statscmd.SysStatsResponse{
- NumGoroutine: 7,
- Uptime: 42,
- Alloc: 1024,
- }, nil
-}
diff --git a/backend/singbox/carrier_test.go b/backend/singbox/carrier_test.go
deleted file mode 100644
index 0da27bd9..00000000
--- a/backend/singbox/carrier_test.go
+++ /dev/null
@@ -1,183 +0,0 @@
-//go:build !windows
-
-package singbox
-
-import (
- "context"
- "errors"
- "net"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "testing"
- "time"
-
- "google.golang.org/grpc"
-
- "github.com/pasarguard/node/backend/singbox/api"
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
-)
-
-type heldSingBoxStats struct {
- statscmd.UnimplementedStatsServiceServer
- mu sync.Mutex
- counters map[string]int64
- hold chan struct{}
- holding chan struct{}
-}
-
-func (s *heldSingBoxStats) GetSysStats(context.Context, *statscmd.SysStatsRequest) (*statscmd.SysStatsResponse, error) {
- return &statscmd.SysStatsResponse{Uptime: 1}, nil
-}
-
-func (s *heldSingBoxStats) QueryStats(_ context.Context, req *statscmd.QueryStatsRequest) (*statscmd.QueryStatsResponse, error) {
- s.mu.Lock()
- resp := &statscmd.QueryStatsResponse{}
- for name, value := range s.counters {
- if !ledgerMatches(name, req.GetPatterns()) {
- continue
- }
- resp.Stat = append(resp.Stat, &statscmd.Stat{Name: name, Value: value})
- if req.GetReset_() {
- s.counters[name] = 0
- }
- }
- hold, holding := s.hold, s.holding
- s.hold, s.holding = nil, nil
- s.mu.Unlock()
- if hold != nil {
- close(holding)
- <-hold
- }
- return resp, nil
-}
-
-func (s *heldSingBoxStats) add(name string, value int64) {
- s.mu.Lock()
- defer s.mu.Unlock()
- s.counters[name] += value
-}
-
-func (s *heldSingBoxStats) holdNextQuery() (<-chan struct{}, func()) {
- s.mu.Lock()
- defer s.mu.Unlock()
- hold, holding := make(chan struct{}), make(chan struct{})
- s.hold, s.holding = hold, holding
- return holding, sync.OnceFunc(func() { close(hold) })
-}
-
-func newHeldSingBox(t *testing.T, stats *heldSingBoxStats) *SingBox {
- t.Helper()
- dir := t.TempDir()
- exe := filepath.Join(dir, "sing-box-carrier-model")
- script := "#!/bin/sh\ncase \"$1\" in version) echo \"sing-box version 1.0.0-carrier-model\"; exit 0;; esac\nexec sleep 300\n"
- if err := os.WriteFile(exe, []byte(script), 0o755); err != nil {
- t.Fatal(err)
- }
-
- listener, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatal(err)
- }
- server := grpc.NewServer()
- statscmd.RegisterStatsServiceServer(server, stats)
- go func() { _ = server.Serve(listener) }()
- t.Cleanup(server.Stop)
- client, err := api.NewClient(listener.Addr().(*net.TCPAddr).Port)
- if err != nil {
- t.Fatal(err)
- }
-
- cfg, err := NewConfig(`{"log":{"level":"error"},"inbounds":[{"type":"vless","tag":"vless-in","listen":"127.0.0.1","listen_port":1,"users":[]}],"outbounds":[{"type":"direct"}]}`)
- if err != nil {
- t.Fatal(err)
- }
- core, err := NewCore(exe, filepath.Join(dir, "config"), 64, 64)
- if err != nil {
- t.Fatal(err)
- }
- if err := os.MkdirAll(filepath.Join(dir, "config"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := core.Start(cfg); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(core.Stop)
- return &SingBox{config: cfg, cfg: &config.Config{StartupLogTailSize: 64}, core: core, client: client, cancelFunc: func() {}}
-}
-
-func TestUnreadCountersTakenFromOneSingBoxAreBilledOnceByTheNext(t *testing.T) {
- old, oldCore := newLedgerSingBox(t)
- oldCore.add("user>>>1.alice>>>traffic>>>downlink", 1000)
- oldCore.add(ledgerHy2Down, 700)
- expectLedger(t, "outbounds read on the old backend", mustLedgerRead(t, old, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 700})
- oldCore.add(ledgerHy2Down, 50)
- old.keepUnreadCounters(context.Background())
-
- carried := old.TakeUnreadCounters()
- if again := old.TakeUnreadCounters(); len(again) != 0 {
- t.Fatalf("the old backend still holds %v after it handed its counters over", again)
- }
- next, _ := newLedgerSingBox(t)
- next.AdoptUnreadCounters(carried)
-
- expectLedger(t, "users", billedUsers(t, next, common.StatType_UsersStat, "", true), map[string]int64{"1.alice/downlink": 1000})
- expectLedger(t, "users read again", billedUsers(t, next, common.StatType_UsersStat, "", true), map[string]int64{})
- expectLedger(t, "outbounds", mustLedgerRead(t, next, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 50})
- expectLedger(t, "inbounds", mustLedgerRead(t, next, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 750})
- expectLedger(t, "inbounds read again", mustLedgerRead(t, next, common.StatType_Inbounds, "", true), map[string]int64{})
-}
-
-func TestASingBoxShutdownWaitsForARestartDrainInFlightAndHandsItsCountersOver(t *testing.T) {
- const alice = "user>>>1.alice>>>traffic>>>downlink"
- stats := &heldSingBoxStats{counters: map[string]int64{}}
- sb := newHeldSingBox(t, stats)
- stats.add(alice, 1000)
- holding, release := stats.holdNextQuery()
- defer release()
-
- restarted := make(chan error, 1)
- go func() { restarted <- sb.restartCoreWithConfig(sb.config) }()
- select {
- case <-holding:
- case <-time.After(10 * time.Second):
- t.Fatal("the restart never drained the core")
- }
-
- shutDown := make(chan struct{})
- go func() {
- sb.Shutdown()
- close(shutDown)
- }()
- var handed map[string]int64
- taken := false
- select {
- case <-shutDown:
- handed, taken = sb.TakeUnreadCounters(), true
- case <-time.After(300 * time.Millisecond):
- }
- release()
- select {
- case <-shutDown:
- case <-time.After(10 * time.Second):
- t.Fatal("the shutdown never finished")
- }
- if !taken {
- handed = sb.TakeUnreadCounters()
- }
- if err := <-restarted; err != nil && !errors.Is(err, errShutDown) {
- t.Fatalf("the restart that raced the shutdown: %v", err)
- }
- users := map[string]int64{}
- for name, value := range handed {
- if strings.HasPrefix(name, userCounterPrefix) {
- users[name] = value
- }
- }
- if len(users) != 1 || users[alice] != 1000 {
- t.Fatalf("the shutdown handed over %v, want the 1000 bytes the restart drain had in flight", handed)
- }
-}
diff --git a/backend/singbox/clash_port_test.go b/backend/singbox/clash_port_test.go
deleted file mode 100644
index b0cc9e89..00000000
--- a/backend/singbox/clash_port_test.go
+++ /dev/null
@@ -1,60 +0,0 @@
-package singbox
-
-import (
- "encoding/json"
- "testing"
-)
-
-func TestTheClashAPIListensOnThePortItWasGiven(t *testing.T) {
- cfg, err := NewConfig(`{"inbounds": [{"type": "vless", "tag": "vless-in", "listen": "127.0.0.1", "listen_port": 1, "users": []}], "outbounds": [{"type": "direct"}]}`)
- if err != nil {
- t.Fatal(err)
- }
- if err := cfg.ApplyAPI(18090, 25000); err != nil {
- t.Fatal(err)
- }
- data, err := cfg.ToBytes()
- if err != nil {
- t.Fatal(err)
- }
- var root struct {
- Experimental struct {
- V2RayAPI struct {
- Listen string `json:"listen"`
- } `json:"v2ray_api"`
- ClashAPI struct {
- ExternalController string `json:"external_controller"`
- } `json:"clash_api"`
- } `json:"experimental"`
- }
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- if got := root.Experimental.V2RayAPI.Listen; got != "127.0.0.1:18090" {
- t.Errorf("v2ray_api listens on %q, want 127.0.0.1:18090", got)
- }
- if got := root.Experimental.ClashAPI.ExternalController; got != "127.0.0.1:25000" {
- t.Errorf("clash_api listens on %q, want 127.0.0.1:25000", got)
- }
- if got := cfg.ClashPort(); got != 25000 {
- t.Errorf("ClashPort() = %d, want 25000", got)
- }
- clone, err := cfg.Clone()
- if err != nil {
- t.Fatal(err)
- }
- if got := clone.ClashPort(); got != 25000 {
- t.Errorf("the clone's ClashPort() = %d, want 25000", got)
- }
-}
-
-func TestTheClashPortNeverSharesTheStatsAPIPort(t *testing.T) {
- if got := clashPortBesides(18090, 25000); got != 25000 {
- t.Errorf("clashPortBesides(18090, 25000) = %d, want 25000", got)
- }
- for range 20 {
- if got := clashPortBesides(18090, 18090); got == 18090 || got <= 0 || got > 65535 {
- t.Fatalf("clashPortBesides(18090, 18090) = %d, want another valid port", got)
- }
- }
-}
diff --git a/backend/singbox/clash_secret_test.go b/backend/singbox/clash_secret_test.go
deleted file mode 100644
index 3b0a00e8..00000000
--- a/backend/singbox/clash_secret_test.go
+++ /dev/null
@@ -1,324 +0,0 @@
-package singbox
-
-import (
- "bufio"
- "bytes"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io"
- "net"
- "net/http"
- "net/http/httptest"
- "os"
- "reflect"
- "strconv"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/google/uuid"
-
- "github.com/pasarguard/node/common"
-)
-
-const guardTestConfig = `{"inbounds": [` +
- `{"type": "vless", "tag": "b-in", "listen": "127.0.0.1", "listen_port": 1, "users": []},` +
- `{"type": "hysteria2", "tag": "a-in", "listen": "127.0.0.1", "listen_port": 2, "users": []},` +
- `{"type": "direct", "tag": "plain-in", "listen": "127.0.0.1", "listen_port": 3}],` +
- `"outbounds": [{"type": "direct", "tag": "direct"}],` +
- `"route": {"rules": [{"network": ["tcp", "udp"], "action": "route", "outbound": "direct"}], "final": "direct"}}`
-
-func appliedConfig(t *testing.T, raw string) *Config {
- t.Helper()
- cfg, err := NewConfig(raw)
- if err != nil {
- t.Fatal(err)
- }
- if err := cfg.ApplyAPI(18090, 25000); err != nil {
- t.Fatal(err)
- }
- return cfg
-}
-
-func TestEachStartGetsAStrongClashSecretThatOnlyTheCoreConfigShows(t *testing.T) {
- cfg := appliedConfig(t, guardTestConfig)
- secret := cfg.clashAPISecret()
- if raw, err := hex.DecodeString(secret); err != nil || len(raw) != 32 {
- t.Fatalf("the clash secret %d characters long is not 32 random bytes in hex", len(secret))
- }
- if other := appliedConfig(t, guardTestConfig).clashAPISecret(); other == secret {
- t.Fatal("two starts got the same clash secret")
- }
-
- shown, err := cfg.ToBytes()
- if err != nil {
- t.Fatal(err)
- }
- if bytes.Contains(shown, []byte(secret)) {
- t.Fatal("ToBytes shows the clash secret")
- }
- if !bytes.Contains(shown, []byte(`"secret": "`+maskedClashSecret+`"`)) {
- t.Fatal("ToBytes does not show the clash secret as masked")
- }
- core, err := cfg.coreBytes()
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Contains(core, []byte(`"secret": "`+secret+`"`)) {
- t.Fatal("the config handed to the core does not carry the clash secret")
- }
- tree, err := json.Marshal(cfg.root)
- if err != nil {
- t.Fatal(err)
- }
- if bytes.Contains(tree, []byte(secret)) {
- t.Fatal("the config tree keeps the clash secret after the core config was rendered")
- }
-
- clone, err := cfg.Clone()
- if err != nil {
- t.Fatal(err)
- }
- if clone.clashAPISecret() != secret {
- t.Fatal("the clone lost the clash secret")
- }
- cloneShown, err := clone.ToBytes()
- if err != nil {
- t.Fatal(err)
- }
- if bytes.Contains(cloneShown, []byte(secret)) {
- t.Fatal("the clone's ToBytes shows the clash secret")
- }
- cloneCore, err := clone.coreBytes()
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Contains(cloneCore, []byte(`"secret": "`+secret+`"`)) {
- t.Fatal("the clone's core config does not carry the clash secret")
- }
-}
-
-func renderedRoute(t *testing.T, data []byte) map[string]any {
- t.Helper()
- var root struct {
- Route map[string]any `json:"route"`
- }
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- return root.Route
-}
-
-func guardRulesFor(exempt ...any) []any {
- if len(exempt) == 0 {
- return []any{
- map[string]any{"action": "resolve"},
- map[string]any{"ip_cidr": loopbackGuardCIDRs, "action": "reject"},
- }
- }
- return []any{
- map[string]any{"inbound": exempt, "invert": true, "action": "resolve"},
- map[string]any{"type": "logical", "mode": "and", "rules": []any{
- map[string]any{"inbound": exempt, "invert": true},
- map[string]any{"ip_cidr": loopbackGuardCIDRs},
- }, "action": "reject"},
- }
-}
-
-func TestTheLoopbackGuardComesFirstForEveryUserInbound(t *testing.T) {
- cfg := appliedConfig(t, guardTestConfig)
- want := append(guardRulesFor("plain-in"), map[string]any{"network": []any{"tcp", "udp"}, "action": "route", "outbound": "direct"})
- for _, cidr := range []string{"127.0.0.0/8", "::1/128", "0.0.0.0/8", "::/128"} {
- found := false
- for _, guarded := range loopbackGuardCIDRs {
- found = found || guarded == cidr
- }
- if !found {
- t.Fatalf("the loopback guard does not reject %s", cidr)
- }
- }
-
- shown, err := cfg.ToBytes()
- if err != nil {
- t.Fatal(err)
- }
- core, err := cfg.coreBytes()
- if err != nil {
- t.Fatal(err)
- }
- clone, err := cfg.Clone()
- if err != nil {
- t.Fatal(err)
- }
- cloneCore, err := clone.coreBytes()
- if err != nil {
- t.Fatal(err)
- }
- for what, data := range map[string][]byte{"ToBytes": shown, "the core config": core, "the clone's core config": cloneCore} {
- route := renderedRoute(t, data)
- if got := route["rules"]; !reflect.DeepEqual(got, want) {
- t.Errorf("%s routes with %v, want %v", what, got, want)
- }
- if route["final"] != "direct" {
- t.Errorf("%s lost the panel's final outbound: %v", what, route["final"])
- }
- }
-}
-
-func TestTheLoopbackGuardSparesOnlyFixedAndTransparentInbounds(t *testing.T) {
- for _, tc := range []struct {
- what string
- inbounds string
- want []any
- }{
- {
- what: "proxy inbounds the node does not manage and an unknown type",
- inbounds: `{"type": "mixed", "tag": "mixed-in", "listen_port": 1}, {"type": "socks", "tag": "socks-in", "listen_port": 2},` +
- `{"type": "http", "tag": "http-in", "listen_port": 3}, {"type": "naive", "tag": "naive-in", "listen_port": 4},` +
- `{"type": "future-proxy", "tag": "future-in", "listen_port": 5}, {"type": "vless", "tag": "vless-in", "listen_port": 6, "users": []}`,
- want: guardRulesFor(),
- },
- {
- what: "fixed and transparent inbounds next to a proxy",
- inbounds: `{"type": "tun", "tag": "tun-in"}, {"type": "redirect", "tag": "redirect-in", "listen_port": 1},` +
- `{"type": "tproxy", "tag": "tproxy-in", "listen_port": 2}, {"type": "direct", "tag": "direct-in", "listen_port": 3},` +
- `{"type": "mixed", "tag": "mixed-in", "listen_port": 4}`,
- want: guardRulesFor("direct-in", "redirect-in", "tproxy-in", "tun-in"),
- },
- {
- what: "a direct inbound without a tag next to a proxy",
- inbounds: `{"type": "direct", "listen_port": 1}, {"type": "mixed", "tag": "mixed-in", "listen_port": 2}`,
- want: guardRulesFor(),
- },
- {
- what: "only fixed and transparent inbounds",
- inbounds: `{"type": "direct", "tag": "direct-in", "listen_port": 1}, {"type": "tun", "tag": "tun-in"}`,
- want: nil,
- },
- } {
- cfg, err := NewConfig(`{"inbounds": [` + tc.inbounds + `], "outbounds": [{"type": "direct"}]}`)
- if err != nil {
- t.Fatalf("%s: %v", tc.what, err)
- }
- shown, err := cfg.ToBytes()
- if err != nil {
- t.Fatalf("%s: %v", tc.what, err)
- }
- route := renderedRoute(t, shown)
- var got any
- if route != nil {
- got = route["rules"]
- }
- if tc.want == nil {
- if route != nil {
- t.Errorf("%s got a route %v, want none", tc.what, route)
- }
- continue
- }
- if !reflect.DeepEqual(got, tc.want) {
- t.Errorf("%s routes with %v, want %v", tc.what, got, tc.want)
- }
- }
-}
-
-func TestTheHotReloadSendsTheSecretAndKeepsItOutOfErrors(t *testing.T) {
- var mu sync.Mutex
- var seen []string
- status := http.StatusUnauthorized
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- seen = append(seen, r.Header.Get("Authorization"))
- code := status
- mu.Unlock()
- w.WriteHeader(code)
- _, _ = fmt.Fprintf(w, "echo %s", r.Header.Get("Authorization"))
- }))
- t.Cleanup(server.Close)
-
- cfg := appliedConfig(t, guardTestConfig)
- cfg.mu.Lock()
- cfg.clashPort = server.Listener.Addr().(*net.TCPAddr).Port
- cfg.mu.Unlock()
- cfg.syncUsers([]*common.User{vlessSingBoxUser("1.alice", uuid.New())})
- secret := cfg.clashAPISecret()
- sb := &SingBox{config: cfg}
-
- err := sb.hotReloadUsers(cfg)
- if err == nil {
- t.Fatal("a hot-reload refused with 401 returned no error")
- }
- if strings.Contains(err.Error(), secret) {
- t.Fatal("the hot-reload error shows the clash secret")
- }
- mu.Lock()
- status = http.StatusOK
- mu.Unlock()
- if err := sb.hotReloadUsers(cfg); err != nil {
- t.Fatalf("a hot-reload the clash API accepts: %v", err)
- }
- mu.Lock()
- defer mu.Unlock()
- if len(seen) == 0 {
- t.Fatal("the hot-reload never reached the clash API")
- }
- for _, header := range seen {
- if header != "Bearer "+secret {
- t.Fatalf("the hot-reload sent the Authorization header %d characters long, want the Bearer secret", len(header))
- }
- }
-}
-
-func clashStatus(t *testing.T, port int, authorization string) int {
- t.Helper()
- conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), 3*time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer conn.Close()
- _, _ = fmt.Fprintf(conn, "GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n%s\r\n", authorization)
- _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
- resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
- if err != nil {
- t.Fatal(err)
- }
- _, _ = io.Copy(io.Discard, resp.Body)
- _ = resp.Body.Close()
- return resp.StatusCode
-}
-
-func TestTheRunningCoreHoldsItsClashSecretPrivately(t *testing.T) {
- sb, _ := startVlessSingBox(t, vlessSingBoxUser("1.alice", uuid.New()))
- secret := sb.config.clashAPISecret()
-
- path := sb.core.configFilePath()
- info, err := os.Stat(path)
- if err != nil {
- t.Fatal(err)
- }
- if perm := info.Mode().Perm(); perm&0o077 != 0 {
- t.Errorf("the core config holding the clash secret is readable beyond its owner: %v", perm)
- }
- raw, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Contains(raw, []byte(secret)) {
- t.Error("the core config does not carry the clash secret")
- }
- if logs := strings.Join(sb.core.StartupLogTail(200), "\n"); strings.Contains(logs, secret) {
- t.Error("the core logs show the clash secret")
- }
-
- port := sb.config.ClashPort()
- if got := clashStatus(t, port, ""); got != http.StatusUnauthorized {
- t.Errorf("the clash API answered a request without the secret with %d, want 401", got)
- }
- if got := clashStatus(t, port, "Authorization: Bearer "+strings.Repeat("0", len(secret))+"\r\n"); got != http.StatusUnauthorized {
- t.Errorf("the clash API answered a wrong secret with %d, want 401", got)
- }
- if got := clashStatus(t, port, "Authorization: Bearer "+secret+"\r\n"); got != http.StatusOK {
- t.Errorf("the clash API answered the node's own secret with %d, want 200", got)
- }
-}
diff --git a/backend/singbox/coalesce_test.go b/backend/singbox/coalesce_test.go
deleted file mode 100644
index aed66c0b..00000000
--- a/backend/singbox/coalesce_test.go
+++ /dev/null
@@ -1,352 +0,0 @@
-//go:build linux
-
-package singbox
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
-)
-
-// TestLiveSmoke_ConcurrentSyncUserCoalescesIntoOneRestart is the regression
-// test for the production incident this fix addresses: every SyncUser call
-// used to trigger its own full sing-box restart, so a busy panel calling
-// SyncUser every few minutes (new signups, subscription refreshes, etc.) was
-// disconnecting every other connected user for a few seconds each time -
-// confirmed live via production logs showing restarts seconds apart, each
-// immediately preceded by exactly one SyncUser call.
-//
-// This measures wall-clock time rather than counting restarts directly
-// (there is no exported restart counter, and adding one purely for a test
-// would be its own small risk) - it establishes a single-call baseline, then
-// fires N calls concurrently and asserts the batch completes in close to
-// that same baseline rather than N times it, which is only possible if the
-// N calls were coalesced into one restart instead of N sequential ones.
-func TestLiveSmoke_ConcurrentSyncUserCoalescesIntoOneRestart(t *testing.T) {
- bin := discoverSingBoxBinary(t)
-
- dir := t.TempDir()
- certPath, keyPath := writeSelfSignedCert(t, dir)
-
- hyPort := freeUDPPort(t)
- apiPort, clashPort := singBoxAPIPorts(t)
-
- raw := fmt.Sprintf(`{
- "log": {"level": "debug"},
- "inbounds": [{
- "type": "hysteria2",
- "tag": "hy2-in",
- "listen": "::",
- "listen_port": %d,
- "users": [],
- "tls": {"enabled": true, "certificate_path": %q, "key_path": %q}
- }],
- "outbounds": [{"type": "direct"}]
- }`, hyPort, certPath, keyPath)
-
- sbConfig, err := NewConfig(raw)
- if err != nil {
- t.Fatalf("NewConfig() error = %v", err)
- }
-
- cfg := &config.Config{
- SingBoxExecutablePath: bin,
- GeneratedConfigPath: dir,
- LogBufferSize: 1000,
- StartupLogTailSize: 200,
- }
-
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
- defer cancel()
-
- sb, err := New(ctx, sbConfig, nil, apiPort, clashPort, cfg)
- if err != nil {
- t.Fatalf("New() error = %v", err)
- }
- defer sb.Shutdown()
-
- syncCtx, syncCancel := context.WithTimeout(context.Background(), 15*time.Second)
- defer syncCancel()
-
- // Baseline: one isolated SyncUser call, letting its debounce window
- // elapse on its own (nothing else queued behind it).
- baselineUser := &common.User{
- Email: "baseline@example.com",
- Inbounds: []string{"hy2-in"},
- Proxies: &common.Proxy{Hysteria2: &common.Hysteria2{Password: "baselinepass"}},
- }
- baselineStart := time.Now()
- if err := sb.SyncUser(syncCtx, baselineUser); err != nil {
- t.Fatalf("baseline SyncUser() error = %v", err)
- }
- baseline := time.Since(baselineStart)
- t.Logf("baseline single SyncUser duration: %v", baseline)
-
- // Let things settle before firing the concurrent batch, so this batch's
- // debounce window starts cleanly rather than possibly still overlapping
- // the baseline's.
- time.Sleep(200 * time.Millisecond)
-
- const concurrentCalls = 5
- var wg sync.WaitGroup
- errs := make([]error, concurrentCalls)
-
- batchStart := time.Now()
- for i := 0; i < concurrentCalls; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- u := &common.User{
- Email: fmt.Sprintf("concurrent%d@example.com", i),
- Inbounds: []string{"hy2-in"},
- Proxies: &common.Proxy{Hysteria2: &common.Hysteria2{Password: fmt.Sprintf("pass%d", i)}},
- }
- errs[i] = sb.SyncUser(syncCtx, u)
- }(i)
- }
- wg.Wait()
- batchDuration := time.Since(batchStart)
-
- for i, err := range errs {
- if err != nil {
- t.Errorf("concurrent SyncUser[%d]() error = %v", i, err)
- }
- }
-
- t.Logf("%d concurrent SyncUser calls total duration: %v (baseline was %v)", concurrentCalls, batchDuration, baseline)
-
- // If each call restarted sing-box separately, batchDuration would be on
- // the order of concurrentCalls*baseline. Coalesced into one restart, it
- // should stay close to a single baseline plus the debounce wait. 2.5x is
- // a safe margin: comfortably above normal variance, comfortably below
- // what N separate sequential restarts would produce.
- if maxAllowed := baseline * 5 / 2; batchDuration > maxAllowed {
- t.Errorf("concurrent batch took %v, want <= %v (%.1fx baseline) - restarts were not coalesced",
- batchDuration, maxAllowed, float64(batchDuration)/float64(baseline))
- }
-
- // All five users from the batch must actually be present in the final
- // config - coalescing must not drop any caller's change.
- generatedBytes, err := os.ReadFile(filepath.Join(dir, "singbox.json"))
- if err != nil {
- t.Fatalf("read generated config: %v", err)
- }
- generated := string(generatedBytes)
- for i := 0; i < concurrentCalls; i++ {
- email := fmt.Sprintf("concurrent%d@example.com", i)
- if !strings.Contains(generated, email) {
- t.Errorf("expected generated config to contain batched user %q; got:\n%s", email, generated)
- }
- }
- if !strings.Contains(generated, "baseline@example.com") {
- t.Errorf("expected generated config to still contain earlier-synced baseline user; got:\n%s", generated)
- }
-}
-
-// TestQueueUser_TightSequentialCallsCoalesceIntoOneRestart is the regression
-// test for the real production call pattern this fix targets: the panel's
-// node bridge sends every pending user for a node over ONE client-streaming
-// SyncUser RPC, and controller/rpc's handler only reads the next message
-// once the previous one's backend call has returned - so a debounce window
-// built on a *blocking* SyncUser can never actually see more than one
-// message at a time, no matter how large the window is (confirmed
-// empirically against a real panel: 8 users synced back-to-back on one
-// stream still produced 7 restarts with the blocking version of this fix).
-//
-// QueueUser exists so that receive loop can dispatch a message and
-// immediately go back to reading the next one instead of blocking. This
-// test simulates that loop directly - tight sequential calls, no
-// goroutines, no delay, exactly how controller/rpc's SyncUser drains an
-// already-buffered stream - and asserts the batch still ends up with every
-// user and still costs exactly one restart's wait, not N of them.
-func TestQueueUser_TightSequentialCallsCoalesceIntoOneRestart(t *testing.T) {
- bin := discoverSingBoxBinary(t)
-
- dir := t.TempDir()
- certPath, keyPath := writeSelfSignedCert(t, dir)
-
- hyPort := freeUDPPort(t)
- apiPort, clashPort := singBoxAPIPorts(t)
-
- raw := fmt.Sprintf(`{
- "log": {"level": "debug"},
- "inbounds": [{
- "type": "hysteria2",
- "tag": "hy2-in",
- "listen": "::",
- "listen_port": %d,
- "users": [],
- "tls": {"enabled": true, "certificate_path": %q, "key_path": %q}
- }],
- "outbounds": [{"type": "direct"}]
- }`, hyPort, certPath, keyPath)
-
- sbConfig, err := NewConfig(raw)
- if err != nil {
- t.Fatalf("NewConfig() error = %v", err)
- }
-
- cfg := &config.Config{
- SingBoxExecutablePath: bin,
- GeneratedConfigPath: dir,
- LogBufferSize: 1000,
- StartupLogTailSize: 200,
- }
-
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
- defer cancel()
-
- sb, err := New(ctx, sbConfig, nil, apiPort, clashPort, cfg)
- if err != nil {
- t.Fatalf("New() error = %v", err)
- }
- defer sb.Shutdown()
-
- syncCtx, syncCancel := context.WithTimeout(context.Background(), 15*time.Second)
- defer syncCancel()
-
- const n = 6
- var b *singBoxPendingBatch
- for i := 0; i < n; i++ {
- u := &common.User{
- Email: fmt.Sprintf("queued%d@example.com", i),
- Inbounds: []string{"hy2-in"},
- Proxies: &common.Proxy{Hysteria2: &common.Hysteria2{Password: fmt.Sprintf("qpass%d", i)}},
- }
- if err := sb.QueueUser(syncCtx, u); err != nil {
- t.Fatalf("QueueUser[%d]() error = %v", i, err)
- }
- if i == 0 {
- sb.batchMu.Lock()
- b = sb.batch
- sb.batchMu.Unlock()
- if b == nil {
- t.Fatal("expected a pending batch to exist right after the first QueueUser call")
- }
- }
- }
-
- select {
- case <-b.done:
- case <-time.After(15 * time.Second):
- t.Fatal("batch did not flush within 15s - QueueUser calls did not coalesce as expected")
- }
- if b.err != nil {
- t.Fatalf("batch flush error = %v", b.err)
- }
-
- generatedBytes, err := os.ReadFile(filepath.Join(dir, "singbox.json"))
- if err != nil {
- t.Fatalf("read generated config: %v", err)
- }
- generated := string(generatedBytes)
- for i := 0; i < n; i++ {
- email := fmt.Sprintf("queued%d@example.com", i)
- if !strings.Contains(generated, email) {
- t.Errorf("expected generated config to contain queued user %q; got:\n%s", email, generated)
- }
- }
-}
-
-// TestSyncUser_UnchangedUserSetSkipsRestart is the regression test for the
-// Hysteria2 "won't connect" incident: the panel syncs users constantly, but
-// most syncs are traffic/online updates that leave every hysteria2 inbound's
-// user set unchanged. Restarting on those dropped every Hysteria2 (QUIC)
-// session for no reason. The fix skips the restart when the user set is
-// identical - proven here by the generated config file's mtime, which the
-// restart rewrites and a skipped sync leaves untouched.
-func TestSyncUser_UnchangedUserSetSkipsRestart(t *testing.T) {
- bin := discoverSingBoxBinary(t)
- dir := t.TempDir()
- certPath, keyPath := writeSelfSignedCert(t, dir)
- hyPort := freeUDPPort(t)
- apiPort, clashPort := singBoxAPIPorts(t)
-
- raw := fmt.Sprintf(`{
- "log": {"level": "debug"},
- "inbounds": [{
- "type": "hysteria2",
- "tag": "hy2-in",
- "listen": "::",
- "listen_port": %d,
- "users": [],
- "tls": {"enabled": true, "certificate_path": %q, "key_path": %q}
- }],
- "outbounds": [{"type": "direct"}]
- }`, hyPort, certPath, keyPath)
-
- sbConfig, err := NewConfig(raw)
- if err != nil {
- t.Fatalf("NewConfig() error = %v", err)
- }
- cfg := &config.Config{
- SingBoxExecutablePath: bin,
- GeneratedConfigPath: dir,
- LogBufferSize: 1000,
- StartupLogTailSize: 200,
- }
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- sb, err := New(ctx, sbConfig, nil, apiPort, clashPort, cfg)
- if err != nil {
- t.Fatalf("New() error = %v", err)
- }
- defer sb.Shutdown()
-
- cfgPath := filepath.Join(dir, "singbox.json")
- user := &common.User{
- Email: "steady@example.com",
- Inbounds: []string{"hy2-in"},
- Proxies: &common.Proxy{Hysteria2: &common.Hysteria2{Password: "steadypass"}},
- }
-
- // First sync installs the user and restarts (writes the config file).
- if err := sb.SyncUser(ctx, user); err != nil {
- t.Fatalf("first SyncUser() error = %v", err)
- }
- st1, err := os.Stat(cfgPath)
- if err != nil {
- t.Fatalf("stat after first sync: %v", err)
- }
-
- // Syncing the identical user again changes no hysteria2 user set, so it
- // must NOT restart - the config file's mtime must be unchanged.
- time.Sleep(300 * time.Millisecond)
- if err := sb.SyncUser(ctx, user); err != nil {
- t.Fatalf("no-op SyncUser() error = %v", err)
- }
- st2, err := os.Stat(cfgPath)
- if err != nil {
- t.Fatalf("stat after no-op sync: %v", err)
- }
- if !st2.ModTime().Equal(st1.ModTime()) {
- t.Errorf("no-op sync restarted the core (config mtime changed %v -> %v); the identical user set should skip the restart",
- st1.ModTime(), st2.ModTime())
- }
-
- // A genuine change (a new user) must still restart - mtime advances.
- other := &common.User{
- Email: "newcomer@example.com",
- Inbounds: []string{"hy2-in"},
- Proxies: &common.Proxy{Hysteria2: &common.Hysteria2{Password: "newpass"}},
- }
- time.Sleep(300 * time.Millisecond)
- if err := sb.SyncUser(ctx, other); err != nil {
- t.Fatalf("changing SyncUser() error = %v", err)
- }
- st3, err := os.Stat(cfgPath)
- if err != nil {
- t.Fatalf("stat after changing sync: %v", err)
- }
- if st3.ModTime().Equal(st2.ModTime()) {
- t.Errorf("adding a new hysteria2 user did not restart the core (config mtime unchanged) - a real change must apply")
- }
-}
diff --git a/backend/singbox/config.go b/backend/singbox/config.go
deleted file mode 100644
index cdc1705a..00000000
--- a/backend/singbox/config.go
+++ /dev/null
@@ -1,535 +0,0 @@
-package singbox
-
-import (
- "crypto/rand"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "sort"
- "strings"
- "sync"
-)
-
-// Config wraps a sing-box JSON configuration tree.
-//
-// Scope note: this Config understands sing-box inbounds of the proxy types
-// listed in supportedInboundTypes ("hysteria2", "vless", "vmess", "trojan",
-// "shadowsocks", "tuic"). For each such inbound it manages the per-user credential
-// array ("users"). Any other inbound/outbound or top-level key (log, dns,
-// route, outbounds, endpoints, ...) supplied in the raw config is passed
-// through untouched via the generic `root` map. Unlike xray's backend, this is
-// not a full generic multi-protocol resolver: it only injects the per-user
-// account objects each supported inbound type needs, keyed by inbound tag.
-//
-// Concurrency note: a single sync.Mutex (not xray's per-inbound RWMutex) guards
-// the whole tree. This config is only touched around restarts/syncs (not a
-// per-request hot path), so the simpler single-lock model is sufficient and
-// easier to reason about.
-type Config struct {
- mu sync.Mutex
- root map[string]any
- inbounds map[string]*protoInbound // tag -> inbound (any supported proxy type)
- apiPort int // 0 until ApplyAPI is called
- clashPort int // local clash_api controller port, for live user hot-reload; 0 until ApplyAPI
-
- clashSecret string
-}
-
-const maskedClashSecret = "redacted"
-
-var loopbackGuardCIDRs = []any{
- "127.0.0.0/8", "0.0.0.0/8", "169.254.0.0/16",
- "::1/128", "::/128", "fe80::/10",
- "::ffff:127.0.0.0/104", "::ffff:0.0.0.0/104", "::ffff:169.254.0.0/112",
-}
-
-func newClashSecret() (string, error) {
- raw := make([]byte, 32)
- if _, err := rand.Read(raw); err != nil {
- return "", err
- }
- return hex.EncodeToString(raw), nil
-}
-
-// supportedInboundTypes is the set of sing-box inbound "type" values whose
-// per-user "users" array this Config indexes and injects credentials into.
-var supportedInboundTypes = map[string]bool{
- "hysteria2": true,
- "vless": true,
- "vmess": true,
- "trojan": true,
- "shadowsocks": true,
- "tuic": true,
-}
-
-// protoInbound holds one indexed supported inbound. typ is the sing-box inbound
-// "type" (one of supportedInboundTypes) and decides the JSON shape each user in
-// the "users" array is serialized to (see userEntry.toUserJSON). obj is a live
-// reference into root["inbounds"][i], mutated in place. users is the source of
-// truth for this inbound's "users" array, keyed by email/name.
-type protoInbound struct {
- tag string
- typ string
- obj map[string]any
- users map[string]userEntry
-}
-
-// userEntry is the union of the per-protocol fields a sing-box user object can
-// carry. Which fields are populated (and serialized) depends on the owning
-// inbound's typ: password for hysteria2/trojan/shadowsocks, uuid (+optional
-// flow) for vless, uuid for vmess, uuid+password for tuic. The json tags describe the flat {name,
-// password} shape and are used by tests that decode a generated config back;
-// production serialization goes through toUserJSON so each type emits exactly
-// the fields sing-box expects.
-type userEntry struct {
- Name string `json:"name"`
- Password string `json:"password,omitempty"`
- UUID string `json:"uuid,omitempty"`
- Flow string `json:"flow,omitempty"`
-}
-
-// toUserJSON renders this entry into the exact sing-box user object shape for
-// the given inbound type:
-// - vless: {name, uuid, flow?} (flow omitted when empty)
-// - vmess: {name, uuid, alterId} (alterId always 0)
-// - tuic: {name, uuid, password}
-// - trojan/ss: {name, password}
-// - hysteria2: {name, password}
-//
-// The same shapes are used both for the config file's "users" array and for the
-// clash_api hot-reload request body.
-func (u userEntry) toUserJSON(typ string) map[string]any {
- switch typ {
- case "vless":
- m := map[string]any{"name": u.Name, "uuid": u.UUID}
- if u.Flow != "" {
- m["flow"] = u.Flow
- }
- return m
- case "vmess":
- return map[string]any{"name": u.Name, "uuid": u.UUID, "alterId": 0}
- case "tuic":
- return map[string]any{"name": u.Name, "uuid": u.UUID, "password": u.Password}
- default: // hysteria2, trojan, shadowsocks
- return map[string]any{"name": u.Name, "password": u.Password}
- }
-}
-
-// userEntryFromJSON parses a user object already present in an admin-supplied
-// inbound template back into a userEntry, reading the fields relevant to typ.
-// Returns false for objects without a usable "name".
-func userEntryFromJSON(typ string, um map[string]any) (userEntry, bool) {
- name, _ := um["name"].(string)
- if name == "" {
- return userEntry{}, false
- }
- e := userEntry{Name: name}
- switch typ {
- case "vless":
- e.UUID, _ = um["uuid"].(string)
- e.Flow, _ = um["flow"].(string)
- case "vmess":
- e.UUID, _ = um["uuid"].(string)
- case "tuic":
- e.UUID, _ = um["uuid"].(string)
- e.Password, _ = um["password"].(string)
- default: // hysteria2, trojan, shadowsocks
- e.Password, _ = um["password"].(string)
- }
- return e, true
-}
-
-// sameUsers reports whether every indexed inbound in c holds exactly the same
-// user set as the matching inbound in other. When it does, restarting the core
-// would drop every live session only to reinstall the identical set of
-// credentials - disruption for no change - so the caller can skip the restart.
-// Compares the credential-bearing fields per type (via full userEntry equality);
-// traffic counters and other churn are intentionally ignored.
-func (c *Config) sameUsers(other *Config) bool {
- c.mu.Lock()
- defer c.mu.Unlock()
- other.mu.Lock()
- defer other.mu.Unlock()
-
- if len(c.inbounds) != len(other.inbounds) {
- return false
- }
- for tag, in := range c.inbounds {
- oin, ok := other.inbounds[tag]
- if !ok || len(in.users) != len(oin.users) {
- return false
- }
- for name, u := range in.users {
- ou, ok := oin.users[name]
- if !ok || ou != u {
- return false
- }
- }
- }
- return true
-}
-
-// sortedUserObjects returns this inbound's users as sing-box user objects
-// (shaped per this inbound's type), ordered by name for stable output.
-func (in *protoInbound) sortedUserObjects() []any {
- names := make([]string, 0, len(in.users))
- for name := range in.users {
- names = append(names, name)
- }
- sort.Strings(names)
-
- out := make([]any, 0, len(names))
- for _, name := range names {
- out = append(out, in.users[name].toUserJSON(in.typ))
- }
- return out
-}
-
-// NewConfig parses a raw sing-box JSON config and indexes every supported
-// inbound found in it by tag, so users can later be synced in.
-func NewConfig(raw string) (*Config, error) {
- var root map[string]any
- if err := json.Unmarshal([]byte(raw), &root); err != nil {
- return nil, fmt.Errorf("parse sing-box config: %w", err)
- }
-
- cfg := &Config{
- root: root,
- inbounds: make(map[string]*protoInbound),
- }
-
- if err := cfg.indexInbounds(); err != nil {
- return nil, err
- }
-
- return cfg, nil
-}
-
-func (c *Config) indexInbounds() error {
- inboundsRaw, ok := c.root["inbounds"]
- if !ok {
- // No inbounds at all is unusual for a node config but not fatal at parse
- // time - surfaces naturally later (no supported inbound to sync users into).
- return nil
- }
-
- inboundList, ok := inboundsRaw.([]any)
- if !ok {
- return fmt.Errorf("sing-box config: \"inbounds\" must be an array")
- }
-
- for idx, raw := range inboundList {
- obj, ok := raw.(map[string]any)
- if !ok {
- continue
- }
-
- typ, _ := obj["type"].(string)
- if !supportedInboundTypes[typ] {
- continue
- }
-
- tag, _ := obj["tag"].(string)
- tag = strings.TrimSpace(tag)
- if tag == "" {
- return fmt.Errorf("sing-box config: %s inbound at index %d is missing a \"tag\"", typ, idx)
- }
- if _, dup := c.inbounds[tag]; dup {
- return fmt.Errorf("sing-box config: duplicate inbound tag %q", tag)
- }
-
- entry := &protoInbound{
- tag: tag,
- typ: typ,
- obj: obj,
- users: make(map[string]userEntry),
- }
-
- // Seed from any users already present in the admin-supplied template, in
- // case it wasn't empty (defensive - normally the panel sends an empty list
- // and relies on us to inject users).
- if existing, ok := obj["users"].([]any); ok {
- for _, raw := range existing {
- um, ok := raw.(map[string]any)
- if !ok {
- continue
- }
- if ue, ok := userEntryFromJSON(typ, um); ok && (typ != "hysteria2" || ue.Password != "") {
- entry.users[ue.Name] = ue
- }
- }
- }
-
- c.inbounds[tag] = entry
- }
-
- return nil
-}
-
-// ApplyAPI records the local v2ray_api stats port and injects/refreshes the
-// "experimental.v2ray_api" block. It mirrors xray's Config.ApplyAPI entry point:
-// called once up front after parsing, before the first Start().
-func (c *Config) ApplyAPI(apiPort, clashPort int) error {
- secret, err := newClashSecret()
- if err != nil {
- return err
- }
-
- c.mu.Lock()
- defer c.mu.Unlock()
-
- c.apiPort = apiPort
- c.clashPort = clashPort
- c.clashSecret = secret
- return c.refreshAPILocked(false)
-}
-
-// refreshAPILocked (re)writes the experimental.v2ray_api block so that its
-// "stats.users" list always reflects every user email currently known across all
-// indexed inbounds. This matters because sing-box's v2ray_api only creates a
-// per-user counter for names present in "stats.users" *at process start* - unlike
-// xray there is no live "add user" API call, so this must be current every time
-// we are about to (re)start the process. Called from ApplyAPI and from ToBytes.
-func (c *Config) refreshAPILocked(revealSecret bool) error {
- if c.apiPort == 0 {
- return nil
- }
-
- experimental, _ := c.root["experimental"].(map[string]any)
- if experimental == nil {
- experimental = make(map[string]any)
- }
-
- experimental["v2ray_api"] = map[string]any{
- "listen": fmt.Sprintf("127.0.0.1:%d", c.apiPort),
- "stats": map[string]any{
- "enabled": true,
- // Without this, sing-box's v2ray_api.StatsService builds its
- // inbounds map from an empty options.Inbounds list (see
- // NewStatsService in sing-box's experimental/v2rayapi/stats.go),
- // so RoutedConnection's countInbound check is always false and
- // no per-inbound counter is ever created - GetInboundsStats/
- // GetInboundStats (backend/singbox/api/stats.go) would then
- // always return empty regardless of how much real traffic
- // flows. Listing every indexed inbound tag here is what makes
- // those two RPCs (which backend/singbox/stats.go's GetStats now
- // delegates Outbound/Outbounds to, since this backend's
- // minimal direct-outbound config has no traffic-bearing
- // "outbound" of its own to track) return real, non-zero data.
- "inbounds": c.allInboundTagsLocked(),
- "users": c.allUserEmailsLocked(),
- },
- }
- if c.clashPort != 0 {
- clashAPI := map[string]any{
- "external_controller": fmt.Sprintf("127.0.0.1:%d", c.clashPort),
- }
- switch {
- case c.clashSecret == "":
- case revealSecret:
- clashAPI["secret"] = c.clashSecret
- default:
- clashAPI["secret"] = maskedClashSecret
- }
- experimental["clash_api"] = clashAPI
- }
- c.root["experimental"] = experimental
-
- return nil
-}
-
-// ClashPort is the loopback port of the clash_api controller that hosts the
-// live user-update endpoint. 0 until ApplyAPI has run.
-func (c *Config) ClashPort() int {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.clashPort
-}
-
-func (c *Config) clashAPISecret() string {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.clashSecret
-}
-
-var unguardedInboundTypes = map[string]bool{
- "direct": true,
- "tun": true,
- "redirect": true,
- "tproxy": true,
-}
-
-func (c *Config) guardedRouteLocked() map[string]any {
- inbounds, _ := c.root["inbounds"].([]any)
- var exempt []string
- guarded := 0
- for _, raw := range inbounds {
- inbound, _ := raw.(map[string]any)
- kind, _ := inbound["type"].(string)
- tag, _ := inbound["tag"].(string)
- if unguardedInboundTypes[kind] && tag != "" {
- exempt = append(exempt, tag)
- continue
- }
- guarded++
- }
- if guarded == 0 {
- return nil
- }
-
- resolve := map[string]any{"action": "resolve"}
- reject := map[string]any{"ip_cidr": loopbackGuardCIDRs, "action": "reject"}
- if len(exempt) > 0 {
- sort.Strings(exempt)
- tags := make([]any, 0, len(exempt))
- for _, tag := range exempt {
- tags = append(tags, tag)
- }
- resolve = map[string]any{"inbound": tags, "invert": true, "action": "resolve"}
- reject = map[string]any{
- "type": "logical",
- "mode": "and",
- "rules": []any{
- map[string]any{"inbound": tags, "invert": true},
- map[string]any{"ip_cidr": loopbackGuardCIDRs},
- },
- "action": "reject",
- }
- }
-
- route := make(map[string]any)
- if panel, ok := c.root["route"].(map[string]any); ok {
- for key, value := range panel {
- route[key] = value
- }
- }
- rules := []any{resolve, reject}
- if panelRules, ok := route["rules"].([]any); ok {
- rules = append(rules, panelRules...)
- }
- route["rules"] = rules
- return route
-}
-
-// inboundUserSet is one indexed inbound's protocol type plus its current user
-// set, already rendered into the sing-box user object shape for that type.
-// Used to push a live user update to the running core instead of restarting it.
-type inboundUserSet struct {
- Type string
- Users []any
-}
-
-// UserSets returns, per indexed inbound tag, its type and current user set
-// (rendered as sing-box user objects). Used to push a live user update to the
-// running core via the clash_api hot-reload endpoint instead of restarting it.
-func (c *Config) UserSets() map[string]inboundUserSet {
- c.mu.Lock()
- defer c.mu.Unlock()
- out := make(map[string]inboundUserSet, len(c.inbounds))
- for tag, in := range c.inbounds {
- out[tag] = inboundUserSet{Type: in.typ, Users: in.sortedUserObjects()}
- }
- return out
-}
-
-func (c *Config) allInboundTagsLocked() []string {
- tags := make([]string, 0, len(c.inbounds))
- for tag := range c.inbounds {
- tags = append(tags, tag)
- }
- sort.Strings(tags)
- return tags
-}
-
-func (c *Config) allUserEmailsLocked() []string {
- seen := make(map[string]struct{})
- for _, inbound := range c.inbounds {
- for email := range inbound.users {
- seen[email] = struct{}{}
- }
- }
-
- emails := make([]string, 0, len(seen))
- for email := range seen {
- emails = append(emails, email)
- }
- sort.Strings(emails)
- return emails
-}
-
-func (c *Config) ToBytes() ([]byte, error) {
- return c.render(false)
-}
-
-func (c *Config) coreBytes() ([]byte, error) {
- return c.render(true)
-}
-
-func (c *Config) render(revealSecret bool) ([]byte, error) {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- for _, inbound := range c.inbounds {
- inbound.obj["users"] = inbound.sortedUserObjects()
- }
- if err := c.refreshAPILocked(revealSecret); err != nil {
- return nil, err
- }
- if revealSecret {
- defer func() { _ = c.refreshAPILocked(false) }()
- }
-
- root := make(map[string]any, len(c.root)+1)
- for key, value := range c.root {
- root[key] = value
- }
- if route := c.guardedRouteLocked(); route != nil {
- root["route"] = route
- }
- return json.MarshalIndent(root, "", " ")
-}
-
-// Clone returns an independent deep copy of the config (including the current
-// in-memory user state), obtained by round-tripping through JSON and
-// re-indexing - mirrors xray's Config.Clone, reused by the
-// apply-candidate-then-restart-with-rollback pattern in user.go.
-func (c *Config) Clone() (*Config, error) {
- if c == nil {
- return nil, fmt.Errorf("sing-box config is nil")
- }
-
- c.mu.Lock()
- defer c.mu.Unlock()
-
- for _, inbound := range c.inbounds {
- inbound.obj["users"] = inbound.sortedUserObjects()
- }
- if err := c.refreshAPILocked(false); err != nil {
- return nil, err
- }
-
- data, err := json.Marshal(c.root)
- if err != nil {
- return nil, fmt.Errorf("marshal sing-box config clone: %w", err)
- }
-
- cloned, err := NewConfig(string(data))
- if err != nil {
- return nil, fmt.Errorf("unmarshal sing-box config clone: %w", err)
- }
- cloned.apiPort = c.apiPort
- cloned.clashPort = c.clashPort
- cloned.clashSecret = c.clashSecret
-
- return cloned, nil
-}
-
-// HasInbounds reports whether the config indexed at least one supported inbound
-// (hysteria2/vless/vmess/trojan/shadowsocks/tuic). Useful for fast-failing at startup
-// with a clear error instead of silently starting a sing-box process that can
-// never carry traffic for any user.
-func (c *Config) HasInbounds() bool {
- c.mu.Lock()
- defer c.mu.Unlock()
- return len(c.inbounds) > 0
-}
diff --git a/backend/singbox/config_test.go b/backend/singbox/config_test.go
deleted file mode 100644
index 9ea5489e..00000000
--- a/backend/singbox/config_test.go
+++ /dev/null
@@ -1,433 +0,0 @@
-package singbox
-
-import (
- "encoding/json"
- "testing"
-
- "github.com/pasarguard/node/common"
-)
-
-const testRawConfig = `{
- "log": {"level": "debug"},
- "inbounds": [{
- "type": "hysteria2",
- "tag": "hy2-in",
- "listen": "::",
- "listen_port": 8443,
- "users": [],
- "tls": {"enabled": true, "certificate_path": "/certs/cert.pem", "key_path": "/certs/key.pem"}
- }, {
- "type": "hysteria2",
- "tag": "hy2-in-2",
- "listen": "::",
- "listen_port": 8444,
- "users": []
- }],
- "outbounds": [{"type": "direct"}]
-}`
-
-func hy2User(email, password string, inbounds ...string) *common.User {
- return &common.User{
- Email: email,
- Inbounds: inbounds,
- Proxies: &common.Proxy{
- Hysteria2: &common.Hysteria2{Password: password},
- },
- }
-}
-
-func mustParseConfig(t *testing.T, raw string) *Config {
- t.Helper()
- cfg, err := NewConfig(raw)
- if err != nil {
- t.Fatalf("NewConfig() error = %v", err)
- }
- return cfg
-}
-
-// decodedConfig unmarshal helpers to inspect ToBytes() output.
-
-type decodedInbound struct {
- Tag string `json:"tag"`
- Type string `json:"type"`
- Users []userEntry `json:"users"`
-}
-
-type decodedV2RayAPI struct {
- Listen string `json:"listen"`
- Stats struct {
- Enabled bool `json:"enabled"`
- Users []string `json:"users"`
- } `json:"stats"`
-}
-
-type decodedRoot struct {
- Inbounds []decodedInbound `json:"inbounds"`
- Experimental struct {
- V2RayAPI decodedV2RayAPI `json:"v2ray_api"`
- } `json:"experimental"`
-}
-
-func decode(t *testing.T, data []byte) decodedRoot {
- t.Helper()
- var out decodedRoot
- if err := json.Unmarshal(data, &out); err != nil {
- t.Fatalf("failed to unmarshal generated config: %v\n%s", err, string(data))
- }
- return out
-}
-
-func inboundByTag(root decodedRoot, tag string) *decodedInbound {
- for i := range root.Inbounds {
- if root.Inbounds[i].Tag == tag {
- return &root.Inbounds[i]
- }
- }
- return nil
-}
-
-func TestNewConfig_IndexesHysteria2Inbounds(t *testing.T) {
- cfg := mustParseConfig(t, testRawConfig)
-
- if !cfg.HasInbounds() {
- t.Fatal("expected config to report supported inbounds present")
- }
- if len(cfg.inbounds) != 2 {
- t.Fatalf("expected 2 hysteria2 inbounds indexed, got %d", len(cfg.inbounds))
- }
- if _, ok := cfg.inbounds["hy2-in"]; !ok {
- t.Error("expected hy2-in to be indexed")
- }
- if _, ok := cfg.inbounds["hy2-in-2"]; !ok {
- t.Error("expected hy2-in-2 to be indexed")
- }
-}
-
-func TestNewConfig_MissingTagErrors(t *testing.T) {
- raw := `{"inbounds": [{"type": "hysteria2", "listen": "::", "users": []}]}`
- if _, err := NewConfig(raw); err == nil {
- t.Fatal("expected an error for a hysteria2 inbound missing a tag")
- }
-}
-
-func TestNewConfig_UnsupportedInboundsIgnored(t *testing.T) {
- // wireguard is a real sing-box inbound type that this backend does not
- // manage per-user credentials for, so it must be passed through untouched
- // and never indexed.
- raw := `{"inbounds": [{"type": "wireguard", "tag": "wg-in"}]}`
- cfg := mustParseConfig(t, raw)
- if cfg.HasInbounds() {
- t.Fatal("expected no supported inbounds to be indexed for a wireguard-only config")
- }
-}
-
-func TestNewConfig_IndexesAllSupportedTypes(t *testing.T) {
- raw := `{"inbounds": [
- {"type": "vless", "tag": "vless-in", "users": []},
- {"type": "vmess", "tag": "vmess-in", "users": []},
- {"type": "trojan", "tag": "trojan-in", "users": []},
- {"type": "shadowsocks", "tag": "ss-in", "method": "chacha20-ietf-poly1305", "users": []},
- {"type": "hysteria2", "tag": "hy2-in", "users": []},
- {"type": "wireguard", "tag": "wg-in"}
- ]}`
- cfg := mustParseConfig(t, raw)
- wantTypes := map[string]string{
- "vless-in": "vless",
- "vmess-in": "vmess",
- "trojan-in": "trojan",
- "ss-in": "shadowsocks",
- "hy2-in": "hysteria2",
- }
- if len(cfg.inbounds) != len(wantTypes) {
- t.Fatalf("expected %d supported inbounds indexed, got %d", len(wantTypes), len(cfg.inbounds))
- }
- for tag, wantType := range wantTypes {
- in, ok := cfg.inbounds[tag]
- if !ok {
- t.Errorf("expected %q to be indexed", tag)
- continue
- }
- if in.typ != wantType {
- t.Errorf("inbound %q: expected type %q, got %q", tag, wantType, in.typ)
- }
- }
- if _, ok := cfg.inbounds["wg-in"]; ok {
- t.Error("wireguard inbound must not be indexed")
- }
-}
-
-// TestSyncUsers_MultiProtocol proves each inbound type serializes the exact
-// per-protocol user object shape sing-box expects, and that a user is only
-// added to an inbound it both lists in Inbounds and carries a matching proxy
-// for.
-func TestSyncUsers_MultiProtocol(t *testing.T) {
- raw := `{"inbounds": [
- {"type": "vless", "tag": "vless-in", "users": []},
- {"type": "vmess", "tag": "vmess-in", "users": []},
- {"type": "trojan", "tag": "trojan-in", "users": []},
- {"type": "shadowsocks", "tag": "ss-in", "method": "chacha20-ietf-poly1305", "users": []},
- {"type": "hysteria2", "tag": "hy2-in", "users": []}
- ], "outbounds": [{"type": "direct"}]}`
- cfg := mustParseConfig(t, raw)
-
- user := &common.User{
- Email: "multi@example.com",
- Inbounds: []string{"vless-in", "vmess-in", "trojan-in", "ss-in", "hy2-in"},
- Proxies: &common.Proxy{
- Vless: &common.Vless{Id: "vless-uuid", Flow: "xtls-rprx-vision"},
- Vmess: &common.Vmess{Id: "vmess-uuid"},
- Trojan: &common.Trojan{Password: "trojan-pass"},
- Shadowsocks: &common.Shadowsocks{Password: "ss-pass", Method: "chacha20-ietf-poly1305"},
- Hysteria2: &common.Hysteria2{Password: "hy2-pass"},
- },
- }
- // A vless-only user that lists the trojan inbound must NOT land on it
- // (no trojan proxy), but must land on the vless inbound.
- vlessOnly := &common.User{
- Email: "vlessonly@example.com",
- Inbounds: []string{"vless-in", "trojan-in"},
- Proxies: &common.Proxy{Vless: &common.Vless{Id: "vo-uuid"}},
- }
-
- cfg.syncUsers([]*common.User{user, vlessOnly})
-
- if err := cfg.ApplyAPI(18090, 18091); err != nil {
- t.Fatalf("ApplyAPI() error = %v", err)
- }
- data, err := cfg.ToBytes()
- if err != nil {
- t.Fatalf("ToBytes() error = %v", err)
- }
-
- var root struct {
- Inbounds []struct {
- Tag string `json:"tag"`
- Users []map[string]any `json:"users"`
- } `json:"inbounds"`
- }
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatalf("unmarshal generated config: %v\n%s", err, string(data))
- }
- byTag := make(map[string][]map[string]any)
- for _, in := range root.Inbounds {
- byTag[in.Tag] = in.Users
- }
-
- // vless: {name, uuid, flow} for the full user; {name, uuid} (no flow) for
- // the vless-only user whose flow is empty.
- vless := byTag["vless-in"]
- if len(vless) != 2 {
- t.Fatalf("expected 2 users on vless-in, got %d (%+v)", len(vless), vless)
- }
- // sorted by name: multi@ then vlessonly@
- if vless[0]["name"] != "multi@example.com" || vless[0]["uuid"] != "vless-uuid" || vless[0]["flow"] != "xtls-rprx-vision" {
- t.Errorf("unexpected vless user[0]: %+v", vless[0])
- }
- if _, hasPassword := vless[0]["password"]; hasPassword {
- t.Errorf("vless user must not carry a password field: %+v", vless[0])
- }
- if vless[1]["name"] != "vlessonly@example.com" || vless[1]["uuid"] != "vo-uuid" {
- t.Errorf("unexpected vless user[1]: %+v", vless[1])
- }
- if _, hasFlow := vless[1]["flow"]; hasFlow {
- t.Errorf("vless user with empty flow must omit the flow field: %+v", vless[1])
- }
-
- // vmess: {name, uuid, alterId:0}
- vmess := byTag["vmess-in"]
- if len(vmess) != 1 {
- t.Fatalf("expected 1 user on vmess-in, got %d (%+v)", len(vmess), vmess)
- }
- if vmess[0]["name"] != "multi@example.com" || vmess[0]["uuid"] != "vmess-uuid" {
- t.Errorf("unexpected vmess user: %+v", vmess[0])
- }
- if alterId, ok := vmess[0]["alterId"]; !ok || alterId.(float64) != 0 {
- t.Errorf("vmess user must carry alterId:0, got %+v", vmess[0])
- }
-
- // trojan: {name, password} - only the full user (vlessOnly has no trojan proxy).
- trojan := byTag["trojan-in"]
- if len(trojan) != 1 || trojan[0]["name"] != "multi@example.com" || trojan[0]["password"] != "trojan-pass" {
- t.Fatalf("expected only multi@ with trojan-pass on trojan-in, got %+v", trojan)
- }
-
- // shadowsocks: {name, password}
- ss := byTag["ss-in"]
- if len(ss) != 1 || ss[0]["name"] != "multi@example.com" || ss[0]["password"] != "ss-pass" {
- t.Fatalf("expected only multi@ with ss-pass on ss-in, got %+v", ss)
- }
-
- // hysteria2: {name, password}
- hy2 := byTag["hy2-in"]
- if len(hy2) != 1 || hy2[0]["name"] != "multi@example.com" || hy2[0]["password"] != "hy2-pass" {
- t.Fatalf("expected only multi@ with hy2-pass on hy2-in, got %+v", hy2)
- }
-}
-
-func TestSyncUsers_FullReplace(t *testing.T) {
- cfg := mustParseConfig(t, testRawConfig)
-
- alice := hy2User("alice@example.com", "alicepass", "hy2-in")
- bob := hy2User("bob@example.com", "bobpass", "hy2-in", "hy2-in-2")
- // carol has no hysteria2 proxy configured; should never show up anywhere.
- carol := &common.User{Email: "carol@example.com", Inbounds: []string{"hy2-in"}}
-
- cfg.syncUsers([]*common.User{alice, bob, carol})
-
- if err := cfg.ApplyAPI(18080, 18081); err != nil {
- t.Fatalf("ApplyAPI() error = %v", err)
- }
-
- data, err := cfg.ToBytes()
- if err != nil {
- t.Fatalf("ToBytes() error = %v", err)
- }
- root := decode(t, data)
-
- hy2in := inboundByTag(root, "hy2-in")
- if hy2in == nil {
- t.Fatal("hy2-in inbound missing from generated config")
- }
- if len(hy2in.Users) != 2 {
- t.Fatalf("expected 2 users on hy2-in, got %d (%+v)", len(hy2in.Users), hy2in.Users)
- }
- // sortedUsers() sorts by email, so alice then bob.
- if hy2in.Users[0].Name != "alice@example.com" || hy2in.Users[0].Password != "alicepass" {
- t.Errorf("unexpected first user on hy2-in: %+v", hy2in.Users[0])
- }
- if hy2in.Users[1].Name != "bob@example.com" || hy2in.Users[1].Password != "bobpass" {
- t.Errorf("unexpected second user on hy2-in: %+v", hy2in.Users[1])
- }
-
- hy2in2 := inboundByTag(root, "hy2-in-2")
- if hy2in2 == nil {
- t.Fatal("hy2-in-2 inbound missing from generated config")
- }
- if len(hy2in2.Users) != 1 || hy2in2.Users[0].Name != "bob@example.com" {
- t.Fatalf("expected only bob on hy2-in-2, got %+v", hy2in2.Users)
- }
-
- // experimental.v2ray_api.stats.users must list every synced user up front
- // (per-user stats counters only get created for names present at process
- // start - see config.go's refreshAPILocked doc comment).
- if !root.Experimental.V2RayAPI.Stats.Enabled {
- t.Error("expected v2ray_api stats to be enabled")
- }
- if root.Experimental.V2RayAPI.Listen != "127.0.0.1:18080" {
- t.Errorf("unexpected v2ray_api listen address: %q", root.Experimental.V2RayAPI.Listen)
- }
- wantUsers := map[string]bool{"alice@example.com": true, "bob@example.com": true}
- if len(root.Experimental.V2RayAPI.Stats.Users) != len(wantUsers) {
- t.Fatalf("expected %d stats users, got %v", len(wantUsers), root.Experimental.V2RayAPI.Stats.Users)
- }
- for _, u := range root.Experimental.V2RayAPI.Stats.Users {
- if !wantUsers[u] {
- t.Errorf("unexpected stats user %q", u)
- }
- }
-}
-
-func TestUpdateUsers_IncrementalMergeAndRemoval(t *testing.T) {
- cfg := mustParseConfig(t, testRawConfig)
-
- alice := hy2User("alice@example.com", "alicepass", "hy2-in")
- bob := hy2User("bob@example.com", "bobpass", "hy2-in")
- cfg.syncUsers([]*common.User{alice, bob})
-
- // Now update just alice's password, and remove bob (by no longer listing the
- // inbound tag - simulating a user losing access to hy2-in).
- aliceUpdated := hy2User("alice@example.com", "newpass", "hy2-in")
- bobRemoved := &common.User{Email: "bob@example.com", Proxies: &common.Proxy{Hysteria2: &common.Hysteria2{Password: "bobpass"}}} // no Inbounds -> inactive everywhere
-
- cfg.updateUsers([]*common.User{aliceUpdated, bobRemoved})
-
- inbound := cfg.inbounds["hy2-in"]
- if len(inbound.users) != 1 {
- t.Fatalf("expected 1 user left on hy2-in after update, got %d (%+v)", len(inbound.users), inbound.users)
- }
- got, ok := inbound.users["alice@example.com"]
- if !ok {
- t.Fatal("expected alice to remain on hy2-in")
- }
- if got.Password != "newpass" {
- t.Errorf("expected alice's password to be updated to 'newpass', got %q", got.Password)
- }
- if _, stillThere := inbound.users["bob@example.com"]; stillThere {
- t.Error("expected bob to be removed from hy2-in")
- }
-}
-
-func TestUpsertUser_SingleUserAddAndRemove(t *testing.T) {
- cfg := mustParseConfig(t, testRawConfig)
-
- alice := hy2User("alice@example.com", "alicepass", "hy2-in")
- cfg.upsertUser(alice)
-
- if _, ok := cfg.inbounds["hy2-in"].users["alice@example.com"]; !ok {
- t.Fatal("expected alice to be added to hy2-in via upsertUser")
- }
-
- // Now "remove" alice by syncing a version of her with no matching inbound.
- aliceGone := &common.User{Email: "alice@example.com", Proxies: &common.Proxy{Hysteria2: &common.Hysteria2{Password: "alicepass"}}}
- cfg.upsertUser(aliceGone)
-
- if _, ok := cfg.inbounds["hy2-in"].users["alice@example.com"]; ok {
- t.Fatal("expected alice to be removed from hy2-in via upsertUser")
- }
-}
-
-func TestClone_IsIndependent(t *testing.T) {
- cfg := mustParseConfig(t, testRawConfig)
- cfg.syncUsers([]*common.User{hy2User("alice@example.com", "alicepass", "hy2-in")})
- if err := cfg.ApplyAPI(18080, 18081); err != nil {
- t.Fatalf("ApplyAPI() error = %v", err)
- }
-
- clone, err := cfg.Clone()
- if err != nil {
- t.Fatalf("Clone() error = %v", err)
- }
-
- // Mutate the clone; the original must not observe the change.
- clone.syncUsers([]*common.User{hy2User("bob@example.com", "bobpass", "hy2-in")})
-
- if _, ok := cfg.inbounds["hy2-in"].users["alice@example.com"]; !ok {
- t.Error("mutating the clone affected the original config's user set")
- }
- if _, ok := cfg.inbounds["hy2-in"].users["bob@example.com"]; ok {
- t.Error("mutating the clone leaked bob into the original config")
- }
- if _, ok := clone.inbounds["hy2-in"].users["bob@example.com"]; !ok {
- t.Error("expected bob to be present on the clone after syncing it")
- }
-
- // apiPort must have carried over to the clone.
- data, err := clone.ToBytes()
- if err != nil {
- t.Fatalf("clone.ToBytes() error = %v", err)
- }
- root := decode(t, data)
- if root.Experimental.V2RayAPI.Listen != "127.0.0.1:18080" {
- t.Errorf("expected clone to retain apiPort in v2ray_api.listen, got %q", root.Experimental.V2RayAPI.Listen)
- }
-}
-
-func TestToBytes_PreservesUnrelatedTopLevelKeys(t *testing.T) {
- cfg := mustParseConfig(t, testRawConfig)
- data, err := cfg.ToBytes()
- if err != nil {
- t.Fatalf("ToBytes() error = %v", err)
- }
-
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatalf("failed to unmarshal: %v", err)
- }
-
- if _, ok := root["log"]; !ok {
- t.Error("expected pass-through \"log\" key to survive ToBytes()")
- }
- if _, ok := root["outbounds"]; !ok {
- t.Error("expected pass-through \"outbounds\" key to survive ToBytes()")
- }
-}
diff --git a/backend/singbox/core.go b/backend/singbox/core.go
deleted file mode 100644
index d6c76e0d..00000000
--- a/backend/singbox/core.go
+++ /dev/null
@@ -1,433 +0,0 @@
-package singbox
-
-import (
- "context"
- "errors"
- "fmt"
- "github.com/pasarguard/node/backend"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "regexp"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-)
-
-// Core manages the sing-box subprocess lifecycle: spawn, log capture, health
-// bookkeeping, stop/restart, and orphan cleanup. Mirrors backend/xray/core.go,
-// trimmed to what sing-box needs - notably there is no stdin config mode (see
-// package doc comment), so configPath is always a directory we write
-// "singbox.json" into and launch with "sing-box run -c ", and there is no
-// xray-style access/error file logger split (all stdout/stderr is captured into
-// a single ring buffer + channel).
-type Core struct {
- executablePath string
- configDir string
- version string
- process *exec.Cmd
- processPID int
- restarting bool
- stopping bool
- waitDone chan struct{}
- logsChan chan string
- logs *logRing
- startupLogSize int
- startupFailure string
- cancelFunc context.CancelFunc
- mu sync.Mutex
- state atomic.Pointer[coreState]
- processStart uint64
- startupFailureM sync.RWMutex
-}
-
-func NewCore(executablePath, configDir string, logBufferSize, startupLogTailSize int) (*Core, error) {
- if logBufferSize <= 0 {
- logBufferSize = 1
- }
- if startupLogTailSize <= 0 {
- startupLogTailSize = 200
- }
-
- c := &Core{
- executablePath: executablePath,
- configDir: configDir,
- logsChan: make(chan string, logBufferSize),
- logs: newLogRing(startupLogTailSize),
- startupLogSize: startupLogTailSize,
- }
-
- c.version = c.refreshVersion()
-
- return c, nil
-}
-
-func (c *Core) configFilePath() string {
- return filepath.Join(c.configDir, "singbox.json")
-}
-
-func (c *Core) stageConfigFile(config []byte) (string, error) {
- if err := os.MkdirAll(c.configDir, 0755); err != nil {
- return "", fmt.Errorf("failed to create config directory: %w", err)
- }
- tmp, err := os.CreateTemp(c.configDir, "singbox-*.json")
- if err != nil {
- return "", fmt.Errorf("failed to create temporary config file: %w", err)
- }
- name := tmp.Name()
- if _, err := tmp.Write(config); err != nil {
- tmp.Close()
- os.Remove(name)
- return "", fmt.Errorf("failed to write temporary config file: %w", err)
- }
- if err := tmp.Sync(); err != nil {
- tmp.Close()
- os.Remove(name)
- return "", fmt.Errorf("failed to flush temporary config file: %w", err)
- }
- if err := tmp.Close(); err != nil {
- os.Remove(name)
- return "", fmt.Errorf("failed to close temporary config file: %w", err)
- }
- if err := os.Chmod(name, 0600); err != nil {
- os.Remove(name)
- return "", fmt.Errorf("failed to set config file mode: %w", err)
- }
- return name, nil
-}
-
-func (c *Core) commitConfigFileLocked(staged string) error {
- return os.Rename(staged, c.configFilePath())
-}
-
-func (c *Core) writeConfigFile(config []byte) error {
- staged, err := c.stageConfigFile(config)
- if err != nil {
- return err
- }
- if err := c.commitConfigFileLocked(staged); err != nil {
- os.Remove(staged)
- return err
- }
- return nil
-}
-
-var versionProbeTimeout = 10 * time.Second
-
-// refreshVersion best-effort parses `sing-box version` output. Unlike xray's
-// equivalent, a parse failure here is NOT treated as fatal: a source build
-// without version ldflags set (as used by this integration's build recipe)
-// prints "sing-box version unknown", which is a legitimate, working binary -
-// failing NewCore over a cosmetic string would be wrong.
-func (c *Core) refreshVersion() string {
- ctx, cancel := context.WithTimeout(context.Background(), versionProbeTimeout)
- defer cancel()
-
- cmd := exec.CommandContext(ctx, c.executablePath, "version")
- backend.ConfigureProbe(cmd)
-
- out, err := cmd.Output()
- if err != nil {
- return "unknown"
- }
-
- r := regexp.MustCompile(`sing-box version (\S+)`)
- if m := r.FindStringSubmatch(string(out)); len(m) > 1 {
- return m[1]
- }
-
- line, _, _ := strings.Cut(string(out), "\n")
- return strings.TrimSpace(line)
-}
-
-func (c *Core) Version() string {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.version
-}
-
-type coreState struct {
- cmd *exec.Cmd
- waitDone <-chan struct{}
-}
-
-func startedFromState(s *coreState) bool {
- if s == nil || s.cmd == nil || s.cmd.Process == nil {
- return false
- }
- if s.waitDone == nil {
- return true
- }
- select {
- case <-s.waitDone:
- return false
- default:
- return true
- }
-}
-
-func (c *Core) publishStateLocked() {
- if c.process == nil || c.process.Process == nil {
- c.state.Store(nil)
- return
- }
- c.state.Store(&coreState{cmd: c.process, waitDone: c.waitDone})
-}
-
-func (c *Core) Started() bool {
- return startedFromState(c.state.Load())
-}
-
-func (c *Core) Stopping() bool {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.stopping
-}
-
-func (c *Core) Start(sbConfig *Config) error {
- bytesConfig, err := sbConfig.coreBytes()
- if err != nil {
- return err
- }
-
- staged, err := c.stageConfigFile(bytesConfig)
- if err != nil {
- return err
- }
- defer os.Remove(staged)
-
- c.mu.Lock()
- defer c.mu.Unlock()
-
- if c.Started() {
- return errors.New("sing-box is started already")
- }
-
- c.logs.reset()
- c.setStartupFailure("")
-
- // Clean up any orphaned sing-box processes before starting a new one.
- if err := c.cleanupOrphanedProcesses(); err != nil {
- log.Printf("warning: failed to cleanup orphaned sing-box processes: %v", err)
- }
-
- if c.process != nil && c.process.Process != nil {
- pid := c.process.Process.Pid
- startTime := c.processStart
- _ = c.process.Process.Kill()
- if canKillByPid(pid, startTime) {
- _ = killProcessTree(pid)
- }
- c.process = nil
- c.processPID = 0
- c.processStart = 0
- c.publishStateLocked()
- }
-
- if err := c.commitConfigFileLocked(staged); err != nil {
- return err
- }
-
- cmd := exec.Command(c.executablePath, "run", "-c", c.configFilePath())
- setProcAttributes(cmd)
-
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- return err
- }
- stderr, err := cmd.StderrPipe()
- if err != nil {
- return err
- }
-
- if err = cmd.Start(); err != nil {
- return err
- }
-
- c.process = cmd
- c.processPID = cmd.Process.Pid
- c.processStart, _ = processStartTime(cmd.Process.Pid)
- c.stopping = false
- c.waitDone = make(chan struct{})
- c.publishStateLocked()
-
- waitDone := c.waitDone
- go func() {
- waitErr := cmd.Wait()
- close(waitDone)
- c.handleProcessExit(cmd, waitErr)
- }()
-
- ctxCore, cancel := context.WithCancel(context.Background())
- c.cancelFunc = cancel
-
- go c.captureProcessLogs(ctxCore, stdout)
- go c.captureProcessLogs(ctxCore, stderr)
-
- return nil
-}
-
-func (c *Core) handleProcessExit(cmd *exec.Cmd, err error) {
- c.mu.Lock()
- expected := c.stopping || c.process != cmd
- c.mu.Unlock()
-
- if expected {
- return
- }
-
- message := "sing-box process exited unexpectedly"
- if err != nil {
- message = fmt.Sprintf("%s: %v", message, err)
- if strings.Contains(strings.ToLower(err.Error()), "signal: killed") {
- message += " (process was killed externally; check container/system OOM and memory limits)"
- }
- }
-
- log.Println(message)
- c.recordLog(message)
-}
-
-func (c *Core) Stop() {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- started := c.Started()
- if !started && c.process == nil && c.cancelFunc == nil {
- return
- }
-
- if started {
- pid := c.process.Process.Pid
- c.processPID = pid
- startTime := c.processStart
- waitDone := c.waitDone
- c.stopping = true
-
- _ = c.process.Process.Kill()
-
- select {
- case <-waitDone:
- case <-time.After(5 * time.Second):
- log.Printf("sing-box process %d did not terminate within timeout, force killing", pid)
- if canKillByPid(pid, startTime) {
- _ = killProcessTree(pid)
- }
- }
-
- if err := verifyProcessDead(pid, startTime); err != nil {
- log.Printf("warning: sing-box process %d may still be running: %v", pid, err)
- if canKillByPid(pid, startTime) {
- _ = killProcessTree(pid)
- }
- }
- }
-
- c.process = nil
- c.processPID = 0
- c.processStart = 0
- c.publishStateLocked()
- c.stopping = false
- c.waitDone = nil
-
- if c.cancelFunc != nil {
- c.cancelFunc()
- c.cancelFunc = nil
- }
-
- log.Println("sing-box core stopped")
-}
-
-func (c *Core) Restart(sbConfig *Config) error {
- c.mu.Lock()
- if c.restarting {
- c.mu.Unlock()
- return errors.New("sing-box is already restarting")
- }
- c.restarting = true
- c.mu.Unlock()
-
- defer func() {
- c.mu.Lock()
- c.restarting = false
- c.mu.Unlock()
- }()
-
- log.Println("restarting sing-box core...")
- c.Stop()
- if err := c.Start(sbConfig); err != nil {
- return err
- }
- return nil
-}
-
-func (c *Core) Restarting() bool {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.restarting
-}
-
-func (c *Core) Logs() <-chan string {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.logsChan
-}
-
-// ProcessInfo holds information about a process.
-type ProcessInfo struct {
- PID int
- PPID int
- IsZombie bool
-}
-
-// cleanupOrphanedProcesses finds and kills sing-box processes that are zombies
-// or parented by this node process. Mirrors xray's Core.cleanupOrphanedProcesses.
-func (c *Core) cleanupOrphanedProcesses() error {
- processes, err := findSingBoxProcesses(c.executablePath)
- if err != nil {
- return fmt.Errorf("failed to find sing-box processes: %w", err)
- }
-
- currentPID := 0
- if c.process != nil && c.process.Process != nil {
- currentPID = c.process.Process.Pid
- }
-
- nodePID := os.Getpid()
-
- killedCount := 0
- for _, procInfo := range processes {
- if procInfo.PID == currentPID {
- continue
- }
-
- kill := false
- reason := ""
- if procInfo.IsZombie && (procInfo.PPID == 0 || procInfo.PPID == 1) {
- kill = true
- reason = "zombie sing-box process without parent"
- } else if procInfo.PPID == nodePID {
- kill = true
- reason = fmt.Sprintf("orphaned sing-box process with node as parent (PPID: %d)", procInfo.PPID)
- }
-
- if !kill {
- continue
- }
-
- log.Printf("%s %d (PPID: %d), killing it", reason, procInfo.PID, procInfo.PPID)
- if err := killProcessTree(procInfo.PID); err != nil {
- log.Printf("warning: failed to kill orphaned process %d: %v", procInfo.PID, err)
- } else {
- killedCount++
- }
- }
-
- if killedCount > 0 {
- log.Printf("cleaned up %d orphaned sing-box process(es)", killedCount)
- }
-
- return nil
-}
diff --git a/backend/singbox/core_concurrency_test.go b/backend/singbox/core_concurrency_test.go
deleted file mode 100644
index 57ead732..00000000
--- a/backend/singbox/core_concurrency_test.go
+++ /dev/null
@@ -1,449 +0,0 @@
-//go:build linux
-
-package singbox
-
-import (
- "fmt"
- "github.com/pasarguard/node/backend"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "sync"
- "syscall"
- "testing"
- "time"
-)
-
-func stubScript(body string) string {
- return fmt.Sprintf("#!/bin/sh\ncase \"$1\" in version) echo \"sing-box version 1.0.0-stub\"; exit 0;; esac\n%s\n", body)
-}
-
-func stubCoreWith(t *testing.T, body string) *Core {
- t.Helper()
- dir := t.TempDir()
- exe := filepath.Join(dir, "stub-sing-box")
- if err := os.WriteFile(exe, []byte(stubScript(body)), 0o755); err != nil {
- t.Fatalf("write stub binary: %v", err)
- }
- core, err := NewCore(exe, dir, 16, 16)
- if err != nil {
- t.Fatalf("NewCore: %v", err)
- }
- return core
-}
-
-func stubConfig(t *testing.T) *Config {
- t.Helper()
- cfg, err := NewConfig(`{"log":{"level":"error"},"inbounds":[],"outbounds":[{"type":"direct"}]}`)
- if err != nil {
- t.Fatalf("NewConfig: %v", err)
- }
- return cfg
-}
-
-func TestCore_StubBinaryAnswersVersionProbe(t *testing.T) {
- core := stubCoreWith(t, "exec sleep 30")
- if core.Version() != "1.0.0-stub" {
- t.Fatalf("stub binary must answer the version probe, got %q", core.Version())
- }
-}
-
-func TestCore_ConcurrentStartStopStartedIsRaceFree(t *testing.T) {
- core := stubCoreWith(t, "exec sleep 30")
- cfg := stubConfig(t)
- t.Cleanup(core.Stop)
-
- done := make(chan struct{})
- var wg sync.WaitGroup
-
- for i := 0; i < 4; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for {
- select {
- case <-done:
- return
- default:
- _ = core.Started()
- _ = core.Stopping()
- _ = core.Version()
- time.Sleep(time.Millisecond)
- }
- }
- }()
- }
-
- wg.Add(1)
- go func() {
- defer wg.Done()
- for {
- select {
- case <-done:
- return
- default:
- _ = core.Start(cfg)
- time.Sleep(5 * time.Millisecond)
- }
- }
- }()
-
- wg.Add(1)
- go func() {
- defer wg.Done()
- for {
- select {
- case <-done:
- return
- default:
- core.Stop()
- time.Sleep(7 * time.Millisecond)
- }
- }
- }()
-
- time.Sleep(800 * time.Millisecond)
- close(done)
- wg.Wait()
-}
-
-func TestCore_StartedFlipsFalseOnceTheProcessExits(t *testing.T) {
- core := stubCoreWith(t, "exit 0")
- t.Cleanup(core.Stop)
-
- if err := core.Start(stubConfig(t)); err != nil {
- t.Fatalf("Start: %v", err)
- }
-
- deadline := time.Now().Add(5 * time.Second)
- for core.Started() {
- if time.Now().After(deadline) {
- t.Fatal("Started() still reports true long after the process exited")
- }
- time.Sleep(10 * time.Millisecond)
- }
-}
-
-func TestCore_VersionProbeCannotHangForever(t *testing.T) {
- original := versionProbeTimeout
- versionProbeTimeout = 250 * time.Millisecond
- t.Cleanup(func() { versionProbeTimeout = original })
-
- dir := t.TempDir()
- exe := filepath.Join(dir, "stub-sing-box")
- if err := os.WriteFile(exe, []byte("#!/bin/sh\nexec sleep 600\n"), 0o755); err != nil {
- t.Fatalf("write stub binary: %v", err)
- }
-
- done := make(chan struct{})
- go func() {
- defer close(done)
- if _, err := NewCore(exe, dir, 16, 16); err != nil {
- t.Errorf("NewCore: %v", err)
- }
- }()
-
- select {
- case <-done:
- case <-time.After(versionProbeTimeout + 5*time.Second):
- t.Fatalf("NewCore blocked past the %s version-probe timeout on a hanging binary", versionProbeTimeout)
- }
-}
-
-func TestCore_StartedDoesNotBlockWhileTheCoreLockIsHeld(t *testing.T) {
- core := stubCoreWith(t, "exec sleep 30")
- t.Cleanup(core.Stop)
-
- if err := core.Start(stubConfig(t)); err != nil {
- t.Fatalf("Start: %v", err)
- }
-
- core.mu.Lock()
- answered := make(chan bool, 1)
- go func() { answered <- core.Started() }()
-
- select {
- case got := <-answered:
- core.mu.Unlock()
- if !got {
- t.Fatal("Started() must still see the running process while another goroutine holds the core lock")
- }
- case <-time.After(3 * time.Second):
- core.mu.Unlock()
- t.Fatal("Started() blocked on the core lock; the request hot path is no longer lock-free")
- }
-}
-
-func TestCore_StartedGoesFalseWhileTheCoreLockIsHeldDuringStop(t *testing.T) {
- core := stubCoreWith(t, "exec sleep 30")
- cfg := stubConfig(t)
-
- if err := core.Start(cfg); err != nil {
- t.Fatalf("Start: %v", err)
- }
- if !core.Started() {
- t.Fatal("Started() must be true right after a successful Start")
- }
-
- stopped := make(chan struct{})
- go func() {
- core.Stop()
- close(stopped)
- }()
-
- deadline := time.Now().Add(10 * time.Second)
- for core.Started() {
- if time.Now().After(deadline) {
- t.Fatal("Started() never went false while Stop() was running")
- }
- time.Sleep(2 * time.Millisecond)
- }
-
- select {
- case <-stopped:
- case <-time.After(10 * time.Second):
- t.Fatal("Stop() did not return")
- }
-}
-
-func TestWrapperStartedAnswersWhileShutdownHoldsTheWrapperLock(t *testing.T) {
- sb := &SingBox{core: stubCoreWith(t, "exec sleep 30")}
- t.Cleanup(sb.core.Stop)
-
- if err := sb.core.Start(stubConfig(t)); err != nil {
- t.Fatalf("Start: %v", err)
- }
-
- sb.mu.Lock()
- answered := make(chan bool, 1)
- go func() { answered <- sb.Started() }()
-
- select {
- case got := <-answered:
- sb.mu.Unlock()
- if !got {
- t.Fatal("the wrapper must report the running core while the wrapper lock is held")
- }
- case <-time.After(3 * time.Second):
- sb.mu.Unlock()
- t.Fatal("SingBox.Started() blocked on the wrapper lock; Shutdown would stall every request again")
- }
-}
-
-func TestVerifyProcessDeadIgnoresARecycledPid(t *testing.T) {
- self := os.Getpid()
-
- actual, ok := processStartTime(self)
- if !ok {
- t.Skip("cannot read the start time of this process")
- }
-
- if err := verifyProcessDead(self, actual); err == nil {
- t.Fatal("a live process with a matching start time must be reported as alive")
- }
-
- if err := verifyProcessDead(self, actual+1); err != nil {
- t.Fatalf("a live pid whose start time does not match is a different process and must count as dead, got %v", err)
- }
-
- if err := verifyProcessDead(self, 0); err == nil {
- t.Fatal("a zero start time must fall back to the old pid-only behaviour")
- }
-}
-
-func TestProcessStartTimeIsStableAndPerProcess(t *testing.T) {
- self := os.Getpid()
- a, ok := processStartTime(self)
- if !ok {
- t.Skip("cannot read the start time of this process")
- }
- b, _ := processStartTime(self)
- if a != b {
- t.Fatalf("start time must not change between reads: %d then %d", a, b)
- }
- if _, ok := processStartTime(1 << 30); ok {
- t.Fatal("a pid that cannot exist must not yield a start time")
- }
-}
-
-func TestCanKillByPidRequiresProvenIdentity(t *testing.T) {
- self := os.Getpid()
- actual, ok := processStartTime(self)
- if !ok {
- t.Skip("cannot read the start time of this process")
- }
-
- if !canKillByPid(self, actual) {
- t.Fatal("a pid whose start time matches is ours and must be killable")
- }
- if canKillByPid(self, actual+1) {
- t.Fatal("a recycled pid must never be killed by pid")
- }
- if canKillByPid(self, 0) {
- t.Fatal("an unknown start time must fail closed, not fall back to killing by pid")
- }
- if canKillByPid(1<<30, actual) {
- t.Fatal("a pid that cannot exist must not be killable")
- }
-}
-
-func TestStagedConfigIsOnlyCommittedByTheStartThatStagedIt(t *testing.T) {
- core := stubCoreWith(t, "exec sleep 30")
-
- first, err := core.stageConfigFile([]byte(`{"first":true}`))
- if err != nil {
- t.Fatalf("stage first: %v", err)
- }
- second, err := core.stageConfigFile([]byte(`{"second":true}`))
- if err != nil {
- t.Fatalf("stage second: %v", err)
- }
- if first == second {
- t.Fatal("two concurrent stages must not share a temporary file")
- }
-
- if err := core.commitConfigFileLocked(second); err != nil {
- t.Fatalf("commit second: %v", err)
- }
- got, err := os.ReadFile(core.configFilePath())
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- if string(got) != `{"second":true}` {
- t.Fatalf("the committed config must be the one that was committed, got %s", got)
- }
-
- if err := core.commitConfigFileLocked(first); err != nil {
- t.Fatalf("commit first: %v", err)
- }
- got, err = os.ReadFile(core.configFilePath())
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- if string(got) != `{"first":true}` {
- t.Fatalf("each commit must replace the file wholesale, got %s", got)
- }
-}
-
-func TestConcurrentStartsLaunchWithTheWinnersConfig(t *testing.T) {
- core := stubCoreWith(t, "exec sleep 30")
- t.Cleanup(core.Stop)
-
- first, err := NewConfig(`{"log":{"level":"error"},"inbounds":[],"outbounds":[{"type":"direct"}]}`)
- if err != nil {
- t.Fatalf("NewConfig first: %v", err)
- }
- second, err := NewConfig(`{"log":{"level":"warn"},"inbounds":[],"outbounds":[{"type":"block"}]}`)
- if err != nil {
- t.Fatalf("NewConfig second: %v", err)
- }
-
- type attempt struct {
- cfg *Config
- err error
- }
- results := make([]attempt, 2)
- var wg sync.WaitGroup
- for i, cfg := range []*Config{first, second} {
- wg.Add(1)
- go func(i int, cfg *Config) {
- defer wg.Done()
- results[i] = attempt{cfg: cfg, err: core.Start(cfg)}
- }(i, cfg)
- }
- wg.Wait()
-
- winners := 0
- var winner *Config
- for _, r := range results {
- if r.err == nil {
- winners++
- winner = r.cfg
- }
- }
- if winners != 1 {
- t.Fatalf("exactly one concurrent Start must succeed, got %d", winners)
- }
-
- want, err := winner.ToBytes()
- if err != nil {
- t.Fatalf("winner ToBytes: %v", err)
- }
- got, err := os.ReadFile(core.configFilePath())
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- if string(got) != string(want) {
- t.Fatalf("the running process must have launched with the config of the Start that won:\n on disk: %s\n winner : %s", got, want)
- }
-
- leftovers, _ := filepath.Glob(filepath.Join(core.configDir, "singbox-*.json"))
- if len(leftovers) != 0 {
- t.Fatalf("staged temp files must not be left behind, found %v", leftovers)
- }
-}
-
-func reapMarkerChild(t *testing.T, marker string) {
- t.Helper()
- t.Cleanup(func() {
- raw, err := os.ReadFile(marker)
- if err != nil {
- return
- }
- if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 1 {
- _ = syscall.Kill(pid, syscall.SIGKILL)
- }
- })
-}
-
-func TestVersionProbeReturnsBoundedAndReapsAForkedChild(t *testing.T) {
- original := versionProbeTimeout
- versionProbeTimeout = 500 * time.Millisecond
- t.Cleanup(func() { versionProbeTimeout = original })
-
- dir := t.TempDir()
- exe := filepath.Join(dir, "stub-sing-box")
- marker := filepath.Join(dir, "grandchild.pid")
- script := "#!/bin/sh\nsleep 600 &\necho $! > " + marker + "\nwait\n"
- if err := os.WriteFile(exe, []byte(script), 0o755); err != nil {
- t.Fatalf("write stub binary: %v", err)
- }
- reapMarkerChild(t, marker)
-
- done := make(chan struct{})
- start := time.Now()
- go func() {
- defer close(done)
- if _, err := NewCore(exe, dir, 16, 16); err != nil {
- t.Errorf("NewCore: %v", err)
- }
- }()
-
- select {
- case <-done:
- t.Logf("NewCore returned after %s", time.Since(start))
- case <-time.After(versionProbeTimeout + backend.ProbeWaitDelay + 5*time.Second):
- t.Fatal("NewCore blocked past the probe timeout while a forked child held stdout")
- }
-
- raw, err := os.ReadFile(marker)
- if err != nil {
- t.Skip("the stub never recorded a grandchild pid")
- }
- pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
- if err != nil {
- t.Skipf("unreadable grandchild pid %q", raw)
- }
-
- deadline := time.Now().Add(5 * time.Second)
- for {
- if !isProcessRunning(pid) {
- return
- }
- if time.Now().After(deadline) {
- t.Fatalf("cancelling the probe context must kill the whole process group; grandchild %d still runs", pid)
- }
- time.Sleep(50 * time.Millisecond)
- }
-}
diff --git a/backend/singbox/core_unix.go b/backend/singbox/core_unix.go
deleted file mode 100644
index ed638860..00000000
--- a/backend/singbox/core_unix.go
+++ /dev/null
@@ -1,17 +0,0 @@
-//go:build !windows
-
-package singbox
-
-import (
- "os/exec"
- "syscall"
-)
-
-// setProcAttributes sets Unix-specific process attributes for proper process
-// management. Mirrors backend/xray/core_unix.go.
-func setProcAttributes(cmd *exec.Cmd) {
- cmd.SysProcAttr = &syscall.SysProcAttr{
- Setpgid: true,
- Pgid: 0,
- }
-}
diff --git a/backend/singbox/hysteria2_credential_session_test.go b/backend/singbox/hysteria2_credential_session_test.go
deleted file mode 100644
index 7e699707..00000000
--- a/backend/singbox/hysteria2_credential_session_test.go
+++ /dev/null
@@ -1,384 +0,0 @@
-package singbox
-
-import (
- "bytes"
- "context"
- "crypto/ecdsa"
- "crypto/elliptic"
- "crypto/rand"
- "crypto/sha256"
- "crypto/x509"
- "crypto/x509/pkix"
- "encoding/hex"
- "encoding/json"
- "encoding/pem"
- "fmt"
- "maps"
- "math/big"
- "net"
- "os"
- "os/exec"
- "path/filepath"
- "slices"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
-)
-
-const (
- credentialTag = "hy2-credential"
- credentialWarmup = 256 * 1024
- credentialRefusal = 2 * time.Second
- credentialFlushSleep = singBoxSyncDebounceWindow + 2*time.Second
-)
-
-func credentialSingBoxBinary(t *testing.T) string {
- t.Helper()
-
- for _, candidate := range []string{os.Getenv("SINGBOX_SMOKE_BINARY"), "/usr/local/bin/sing-box"} {
- if candidate == "" {
- continue
- }
- if _, err := os.Stat(candidate); err == nil {
- return candidate
- }
- }
- t.Skip("no sing-box binary found; set SINGBOX_SMOKE_BINARY")
- return ""
-}
-
-func credentialPort(t *testing.T, network string) int {
- t.Helper()
-
- if network == "udp" {
- conn, err := net.ListenPacket("udp", "127.0.0.1:0")
- if err != nil {
- t.Fatal(err)
- }
- defer conn.Close()
- return conn.LocalAddr().(*net.UDPAddr).Port
- }
- listener, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatal(err)
- }
- defer listener.Close()
- return listener.Addr().(*net.TCPAddr).Port
-}
-
-func hysteria2ClientBinary(t *testing.T) string {
- t.Helper()
-
- for _, candidate := range []string{os.Getenv("XRAY_EXECUTABLE_PATH"), "/usr/local/bin/xray"} {
- if candidate == "" {
- continue
- }
- if _, err := os.Stat(candidate); err == nil {
- return candidate
- }
- }
- t.Skip("no xray binary to act as the hysteria2 client; set XRAY_EXECUTABLE_PATH")
- return ""
-}
-
-func pinnedHysteria2Cert(t *testing.T) (string, string, string) {
- t.Helper()
-
- key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
- if err != nil {
- t.Fatal(err)
- }
- template := &x509.Certificate{
- SerialNumber: big.NewInt(time.Now().UnixNano()),
- Subject: pkix.Name{CommonName: "localhost"},
- DNSNames: []string{"localhost"},
- NotBefore: time.Now().Add(-time.Hour),
- NotAfter: time.Now().Add(24 * time.Hour),
- KeyUsage: x509.KeyUsageDigitalSignature,
- ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
- }
- der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
- if err != nil {
- t.Fatal(err)
- }
- keyDER, err := x509.MarshalECPrivateKey(key)
- if err != nil {
- t.Fatal(err)
- }
- dir := t.TempDir()
- certFile := filepath.Join(dir, "cert.pem")
- keyFile := filepath.Join(dir, "key.pem")
- if err := os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil {
- t.Fatal(err)
- }
- sum := sha256.Sum256(der)
- return certFile, keyFile, hex.EncodeToString(sum[:])
-}
-
-func startByteTarget(t *testing.T) int {
- t.Helper()
-
- listener, err := net.Listen("tcp4", net.JoinHostPort(userTrafficHost(t), "0"))
- if err != nil {
- t.Fatal(err)
- }
- go func() {
- for {
- conn, err := listener.Accept()
- if err != nil {
- return
- }
- go func() {
- defer conn.Close()
- chunk := bytes.Repeat([]byte{'x'}, 16*1024)
- ticker := time.NewTicker(5 * time.Millisecond)
- defer ticker.Stop()
- for range ticker.C {
- if _, err := conn.Write(chunk); err != nil {
- return
- }
- }
- }()
- }
- }()
- t.Cleanup(func() { _ = listener.Close() })
- return listener.Addr().(*net.TCPAddr).Port
-}
-
-type hysteria2Node struct {
- sb *SingBox
- port int
- pin string
- target int
- dir string
- xray string
-}
-
-func startHysteria2Node(t *testing.T, users []*common.User) *hysteria2Node {
- t.Helper()
-
- bin := credentialSingBoxBinary(t)
- xrayBinary := hysteria2ClientBinary(t)
- certFile, keyFile, pin := pinnedHysteria2Cert(t)
- port := credentialPort(t, "udp")
- raw := fmt.Sprintf(`{
- "log": {"level": "warn"},
- "inbounds": [{
- "type": "hysteria2",
- "tag": %q,
- "listen": "127.0.0.1",
- "listen_port": %d,
- "users": [],
- "tls": {"enabled": true, "alpn": ["h3"], "certificate_path": %q, "key_path": %q}
- }],
- "outbounds": [{"type": "direct"}]
- }`, credentialTag, port, certFile, keyFile)
- sbConfig, err := NewConfig(raw)
- if err != nil {
- t.Fatal(err)
- }
- dir := t.TempDir()
- cfg := &config.Config{
- SingBoxExecutablePath: bin,
- GeneratedConfigPath: dir,
- LogBufferSize: 1000,
- StartupLogTailSize: 200,
- }
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- statsPort, clashPort := singBoxAPIPorts(t)
- sb, err := New(ctx, sbConfig, users, statsPort, clashPort, cfg)
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(sb.Shutdown)
- return &hysteria2Node{sb: sb, port: port, pin: pin, target: startByteTarget(t), dir: dir, xray: xrayBinary}
-}
-
-func (n *hysteria2Node) client(t *testing.T, password string) int {
- t.Helper()
-
- clientPort := credentialPort(t, "tcp")
- clientConfig := map[string]any{
- "log": map[string]any{"loglevel": "warning"},
- "inbounds": []any{map[string]any{
- "tag": "in",
- "listen": "127.0.0.1",
- "port": clientPort,
- "protocol": "dokodemo-door",
- "settings": map[string]any{"address": userTrafficHost(t), "port": n.target, "network": "tcp"},
- }},
- "outbounds": []any{map[string]any{
- "tag": "out",
- "protocol": "hysteria",
- "settings": map[string]any{"version": 2, "address": "127.0.0.1", "port": n.port},
- "streamSettings": map[string]any{
- "network": "hysteria",
- "hysteriaSettings": map[string]any{"version": 2, "auth": password},
- "security": "tls",
- "tlsSettings": map[string]any{
- "serverName": "localhost",
- "alpn": []string{"h3"},
- "pinnedPeerCertSha256": n.pin,
- },
- },
- }},
- }
- raw, err := json.Marshal(clientConfig)
- if err != nil {
- t.Fatal(err)
- }
- dir := t.TempDir()
- configFile := filepath.Join(dir, "client.json")
- if err := os.WriteFile(configFile, raw, 0o600); err != nil {
- t.Fatal(err)
- }
- cmd := exec.Command(n.xray, "run", "-c", configFile)
- if err := cmd.Start(); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() {
- _ = cmd.Process.Kill()
- _ = cmd.Wait()
- })
-
- deadline := time.Now().Add(10 * time.Second)
- for time.Now().Before(deadline) {
- conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", clientPort), 200*time.Millisecond)
- if err == nil {
- _ = conn.Close()
- return clientPort
- }
- time.Sleep(50 * time.Millisecond)
- }
- t.Fatalf("client inbound %d never listened", clientPort)
- return 0
-}
-
-func transferred(t *testing.T, clientPort int, want int64, window time.Duration) int64 {
- t.Helper()
-
- conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", clientPort), 5*time.Second)
- if err != nil {
- t.Fatal(err)
- }
- var received atomic.Int64
- ended := make(chan struct{})
- go func() {
- buffer := make([]byte, 64*1024)
- for {
- n, err := conn.Read(buffer)
- received.Add(int64(n))
- if err != nil {
- close(ended)
- return
- }
- }
- }()
- deadline := time.Now().Add(window)
- for time.Now().Before(deadline) && received.Load() < want {
- select {
- case <-ended:
- deadline = time.Now()
- case <-time.After(20 * time.Millisecond):
- }
- }
- _ = conn.Close()
- <-ended
- return received.Load()
-}
-
-func (n *hysteria2Node) drainTraffic(t *testing.T) map[string]int64 {
- t.Helper()
-
- resp, err := n.sb.GetStats(context.Background(), &common.StatRequest{Type: common.StatType_UsersStat, Reset_: true})
- if err != nil {
- t.Fatal(err)
- }
- traffic := make(map[string]int64)
- for _, stat := range resp.GetStats() {
- if stat.GetValue() > 0 {
- traffic[stat.GetName()] += stat.GetValue()
- }
- }
- return traffic
-}
-
-func (n *hysteria2Node) generatedUsers(t *testing.T) []string {
- t.Helper()
-
- raw, err := os.ReadFile(filepath.Join(n.dir, "singbox.json"))
- if err != nil {
- t.Fatal(err)
- }
- inbound := inboundByTag(decode(t, raw), credentialTag)
- if inbound == nil {
- t.Fatalf("the generated config has no %s inbound", credentialTag)
- }
- names := make([]string, 0, len(inbound.Users))
- for _, user := range inbound.Users {
- names = append(names, user.Name)
- }
- return names
-}
-
-func TestAnEmptyHysteria2PasswordIsNeverAccepted(t *testing.T) {
- const bobSecret = "bob-own-hy2-key"
- node := startHysteria2Node(t, []*common.User{hy2User("1", "", credentialTag), hy2User("2", bobSecret, credentialTag)})
-
- if listed := node.generatedUsers(t); !slices.Equal(listed, []string{"2"}) {
- t.Fatalf("the config handed to sing-box lists %v on the hysteria2 inbound, want only the user with a password", listed)
- }
-
- node.drainTraffic(t)
- if moved := transferred(t, node.client(t, ""), credentialWarmup, credentialRefusal); moved != 0 {
- t.Fatalf("a client with an empty hysteria2 password moved %d bytes (%v)", moved, node.drainTraffic(t))
- }
- if moved := transferred(t, node.client(t, bobSecret), credentialWarmup, 15*time.Second); moved < credentialWarmup {
- t.Fatalf("the user with a password moved only %d bytes", moved)
- }
-
- if err := node.sb.SyncUser(context.Background(), hy2User("2", "", credentialTag)); err != nil {
- t.Fatalf("emptying the password failed the sync: %v", err)
- }
- time.Sleep(credentialFlushSleep)
- if moved := transferred(t, node.client(t, bobSecret), credentialWarmup, credentialRefusal); moved != 0 {
- t.Fatalf("the user whose password became empty still connected with the old password and moved %d bytes", moved)
- }
- if moved := transferred(t, node.client(t, ""), credentialWarmup, credentialRefusal); moved != 0 {
- t.Fatalf("a client with an empty hysteria2 password moved %d bytes after a user's password became empty", moved)
- }
-}
-
-func TestSharedHysteria2PasswordBillsTheSameUserEveryTime(t *testing.T) {
- const shared = "0123456789abcdefSHARED"
- users := []*common.User{hy2User("10", shared, credentialTag), hy2User("9", shared, credentialTag)}
- node := startHysteria2Node(t, users)
-
- for round := range 3 {
- if round > 0 {
- if err := node.sb.SyncUsers(context.Background(), users); err != nil {
- t.Fatalf("round %d: resync: %v", round, err)
- }
- }
- if listed := node.generatedUsers(t); !slices.Equal(listed, []string{"10", "9"}) {
- t.Fatalf("round %d: the config handed to sing-box lists %v, want them in name order", round, listed)
- }
- node.drainTraffic(t)
- if moved := transferred(t, node.client(t, shared), credentialWarmup, 15*time.Second); moved < credentialWarmup {
- t.Fatalf("round %d: the shared-password client moved only %d bytes", round, moved)
- }
- time.Sleep(1500 * time.Millisecond)
- traffic := node.drainTraffic(t)
- if billed := slices.Sorted(maps.Keys(traffic)); !slices.Equal(billed, []string{"9"}) {
- t.Fatalf("round %d: the shared-password client was billed to %v (%v), want the last user in name order every time", round, billed, traffic)
- }
- t.Logf("round %d: the shared-password client was billed to %v", round, traffic)
- }
-}
diff --git a/backend/singbox/hysteria2_empty_password_test.go b/backend/singbox/hysteria2_empty_password_test.go
deleted file mode 100644
index bdf924ea..00000000
--- a/backend/singbox/hysteria2_empty_password_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package singbox
-
-import (
- "slices"
- "testing"
-
- "github.com/pasarguard/node/common"
-)
-
-const emptyPasswordRawConfig = `{"inbounds": [
- {"type": "hysteria2", "tag": "hy2-in", "users": [{"name": "template-empty", "password": ""}, {"name": "template-set", "password": "template-secret"}]},
- {"type": "vless", "tag": "vless-in", "users": []}
-], "outbounds": [{"type": "direct"}]}`
-
-func hy2AndVlessUser(email, pw string) *common.User {
- return &common.User{
- Email: email,
- Inbounds: []string{"hy2-in", "vless-in"},
- Proxies: &common.Proxy{
- Hysteria2: &common.Hysteria2{Password: pw},
- Vless: &common.Vless{Id: "0b6f2a4e-6a54-4a51-9a3a-6f1e2b1f7c11"},
- },
- }
-}
-
-func generatedNames(t *testing.T, cfg *Config) (map[string][]string, []string) {
- t.Helper()
-
- if err := cfg.ApplyAPI(18090, 18091); err != nil {
- t.Fatal(err)
- }
- data, err := cfg.ToBytes()
- if err != nil {
- t.Fatal(err)
- }
- root := decode(t, data)
- names := make(map[string][]string, len(root.Inbounds))
- for _, inbound := range root.Inbounds {
- for _, user := range inbound.Users {
- names[inbound.Tag] = append(names[inbound.Tag], user.Name)
- }
- }
- return names, root.Experimental.V2RayAPI.Stats.Users
-}
-
-func TestAnEmptyHysteria2PasswordIsNeverInstalled(t *testing.T) {
- apply := map[string]func(*Config, []*common.User){
- "syncUsers": (*Config).syncUsers,
- "updateUsers": (*Config).updateUsers,
- "upsertUser": func(cfg *Config, users []*common.User) {
- for _, user := range users {
- cfg.upsertUser(user)
- }
- },
- }
- for name, sync := range apply {
- t.Run(name, func(t *testing.T) {
- cfg := mustParseConfig(t, emptyPasswordRawConfig)
- sync(cfg, []*common.User{hy2AndVlessUser("1", ""), hy2AndVlessUser("2", "own-password")})
-
- names, _ := generatedNames(t, cfg)
- if got := names["hy2-in"]; slices.Contains(got, "1") || !slices.Contains(got, "2") {
- t.Fatalf("hy2-in lists %v, want the user with an empty password left off", got)
- }
- if got := names["vless-in"]; !slices.Equal(got, []string{"1", "2"}) {
- t.Fatalf("an empty hysteria2 password also dropped the user from vless-in: %v", got)
- }
- })
- }
-}
-
-func TestATemplateUserWithAnEmptyHysteria2PasswordIsDropped(t *testing.T) {
- cfg := mustParseConfig(t, emptyPasswordRawConfig)
-
- names, _ := generatedNames(t, cfg)
- if got := names["hy2-in"]; !slices.Equal(got, []string{"template-set"}) {
- t.Fatalf("hy2-in lists %v from the template, want the user with an empty password dropped", got)
- }
-}
-
-func TestAUserWhoseHysteria2PasswordBecomesEmptyIsRemoved(t *testing.T) {
- cfg := mustParseConfig(t, emptyPasswordRawConfig)
- cfg.syncUsers([]*common.User{hy2AndVlessUser("1", "own-password")})
-
- names, _ := generatedNames(t, cfg)
- if got := names["hy2-in"]; !slices.Equal(got, []string{"1"}) {
- t.Fatalf("hy2-in lists %v before the password became empty", got)
- }
-
- cfg.upsertUser(hy2AndVlessUser("1", ""))
- names, _ = generatedNames(t, cfg)
- if got := names["hy2-in"]; len(got) != 0 {
- t.Fatalf("hy2-in still lists %v after the user's password became empty", got)
- }
- if got := names["vless-in"]; !slices.Equal(got, []string{"1"}) {
- t.Fatalf("the user left vless-in when only the hysteria2 password became empty: %v", got)
- }
-}
diff --git a/backend/singbox/inbound_ledger.go b/backend/singbox/inbound_ledger.go
deleted file mode 100644
index b6319cb5..00000000
--- a/backend/singbox/inbound_ledger.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package singbox
-
-import (
- "context"
- "errors"
- "sort"
- "strings"
- "sync"
-
- "github.com/pasarguard/node/backend/singbox/api"
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
-)
-
-type ledgerConsumer int
-
-const (
- consumerOutbounds ledgerConsumer = iota
- consumerInbounds
-)
-
-const inboundCounterPrefix = "inbound>>>"
-
-var (
- errLedgerNoClient = errors.New("sing-box stats client is not available")
- errLedgerTagRequired = errors.New("tag required")
-)
-
-type inboundLedger struct {
- mu sync.Mutex
- pending [2]map[string]int64
-}
-
-func (l *inboundLedger) collectTag(ctx context.Context, client *api.Client, consumer ledgerConsumer, tag string, reset bool) (*common.StatResponse, error) {
- if tag == "" {
- return nil, errLedgerTagRequired
- }
- return l.collect(ctx, client, consumer, tag, reset)
-}
-
-func (l *inboundLedger) collect(ctx context.Context, client *api.Client, consumer ledgerConsumer, tag string, reset bool) (*common.StatResponse, error) {
- if client == nil || client.StatsServiceClient == nil {
- return nil, errLedgerNoClient
- }
-
- drained, err := client.DrainInboundCounters(ctx)
- if err != nil {
- return nil, err
- }
-
- l.mu.Lock()
- defer l.mu.Unlock()
-
- l.credit(drained)
-
- prefix := inboundCounterPrefix
- if tag != "" {
- prefix += tag + ">>>"
- }
-
- balance := l.pending[consumer]
- names := make([]string, 0, len(balance))
- for name, value := range balance {
- if value != 0 && strings.HasPrefix(name, prefix) {
- names = append(names, name)
- }
- }
- sort.Strings(names)
-
- collected := make([]*statscmd.Stat, 0, len(names))
- for _, name := range names {
- collected = append(collected, &statscmd.Stat{Name: name, Value: balance[name]})
- }
-
- if reset {
- for _, name := range names {
- delete(balance, name)
- }
- }
-
- return api.BuildStatResponse(collected), nil
-}
-
-func (l *inboundLedger) keep(ctx context.Context, client *api.Client) error {
- if client == nil || client.StatsServiceClient == nil {
- return errLedgerNoClient
- }
-
- drained, err := client.DrainInboundCounters(ctx)
- if err != nil {
- return err
- }
-
- l.mu.Lock()
- defer l.mu.Unlock()
- l.credit(drained)
- return nil
-}
-
-func (l *inboundLedger) take() [2]map[string]int64 {
- l.mu.Lock()
- defer l.mu.Unlock()
- taken := l.pending
- l.pending = [2]map[string]int64{}
- return taken
-}
-
-func (l *inboundLedger) adopt(balances [2]map[string]int64) {
- l.mu.Lock()
- defer l.mu.Unlock()
- for consumer, balance := range balances {
- for name, value := range balance {
- if value == 0 {
- continue
- }
- if l.pending[consumer] == nil {
- l.pending[consumer] = make(map[string]int64)
- }
- l.pending[consumer][name] += value
- }
- }
-}
-
-func (l *inboundLedger) credit(drained []*statscmd.Stat) {
- for i := range l.pending {
- if l.pending[i] == nil {
- l.pending[i] = make(map[string]int64)
- }
- }
-
- for _, stat := range drained {
- name, value := stat.GetName(), stat.GetValue()
- if value == 0 || !strings.HasPrefix(name, inboundCounterPrefix) {
- continue
- }
- for _, balance := range l.pending {
- balance[name] += value
- }
- }
-}
diff --git a/backend/singbox/inbound_ledger_lock_test.go b/backend/singbox/inbound_ledger_lock_test.go
deleted file mode 100644
index 6c730b17..00000000
--- a/backend/singbox/inbound_ledger_lock_test.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package singbox
-
-import (
- "context"
- "net"
- "sync"
- "sync/atomic"
- "testing"
- "time"
-
- "google.golang.org/grpc"
-
- "github.com/pasarguard/node/backend/singbox/api"
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
-)
-
-type blockingLedgerCore struct {
- *ledgerFakeCore
- arrived chan struct{}
- release chan struct{}
-}
-
-func (b *blockingLedgerCore) QueryStats(ctx context.Context, req *statscmd.QueryStatsRequest) (*statscmd.QueryStatsResponse, error) {
- b.arrived <- struct{}{}
- select {
- case <-b.release:
- case <-ctx.Done():
- return nil, ctx.Err()
- }
- return b.ledgerFakeCore.QueryStats(ctx, req)
-}
-
-func newBlockingLedgerSingBox(t *testing.T) (*SingBox, *blockingLedgerCore) {
- t.Helper()
-
- lis, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("listen: %v", err)
- }
- core := &blockingLedgerCore{
- ledgerFakeCore: &ledgerFakeCore{counters: make(map[string]*atomic.Int64)},
- arrived: make(chan struct{}, 8),
- release: make(chan struct{}),
- }
- srv := grpc.NewServer()
- statscmd.RegisterStatsServiceServer(srv, core)
- go func() { _ = srv.Serve(lis) }()
- t.Cleanup(srv.Stop)
-
- client, err := api.NewClient(lis.Addr().(*net.TCPAddr).Port)
- if err != nil {
- t.Fatalf("NewClient: %v", err)
- }
- t.Cleanup(client.Close)
-
- return &SingBox{client: client}, core
-}
-
-func TestLedgerDrainsDoNotWaitBehindTheLedgerLock(t *testing.T) {
- sb, core := newBlockingLedgerSingBox(t)
- core.add(ledgerHy2Down, 1000)
-
- var released sync.Once
- release := func() { released.Do(func() { close(core.release) }) }
- t.Cleanup(release)
-
- type result struct {
- stats map[string]int64
- err error
- }
- outbounds := make(chan result, 1)
- inbounds := make(chan result, 1)
- go func() {
- stats, err := ledgerRead(sb, common.StatType_Outbounds, "", true)
- outbounds <- result{stats, err}
- }()
- go func() {
- stats, err := ledgerRead(sb, common.StatType_Inbounds, "", true)
- inbounds <- result{stats, err}
- }()
-
- reached := 0
- for reached < 2 {
- select {
- case <-core.arrived:
- reached++
- continue
- case <-time.After(3 * time.Second):
- }
- break
- }
- release()
-
- outFirst, inFirst := <-outbounds, <-inbounds
- if reached < 2 {
- t.Fatalf("only %d of 2 concurrent drains reached the core; the second waited behind the ledger lock", reached)
- }
- if outFirst.err != nil || inFirst.err != nil {
- t.Fatalf("reads failed: outbounds %v, inbounds %v", outFirst.err, inFirst.err)
- }
-
- outTotal := sumLedger(outFirst.stats) + sumLedger(mustLedgerReadAfterRelease(t, sb, common.StatType_Outbounds, core))
- inTotal := sumLedger(inFirst.stats) + sumLedger(mustLedgerReadAfterRelease(t, sb, common.StatType_Inbounds, core))
- if outTotal != 1000 || inTotal != 1000 {
- t.Fatalf("each series must report the 1000 bytes exactly once, got outbounds %d, inbounds %d", outTotal, inTotal)
- }
-}
-
-func mustLedgerReadAfterRelease(t *testing.T, sb *SingBox, statType common.StatType, core *blockingLedgerCore) map[string]int64 {
- t.Helper()
- done := make(chan ledgerReadResult, 1)
- go func() {
- stats, err := ledgerRead(sb, statType, "", true)
- done <- ledgerReadResult{stats, err}
- }()
- select {
- case <-core.arrived:
- case <-time.After(3 * time.Second):
- t.Fatalf("follow-up %s read never reached the core", statType)
- }
- got := <-done
- if got.err != nil {
- t.Fatalf("follow-up GetStats(%s, reset=true): %v", statType, got.err)
- }
- return got.stats
-}
-
-type ledgerReadResult struct {
- stats map[string]int64
- err error
-}
-
-func sumLedger(stats map[string]int64) int64 {
- var total int64
- for _, value := range stats {
- total += value
- }
- return total
-}
diff --git a/backend/singbox/jobs.go b/backend/singbox/jobs.go
deleted file mode 100644
index 2f178f79..00000000
--- a/backend/singbox/jobs.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package singbox
-
-import (
- "context"
- "errors"
- "fmt"
- "log"
- "strings"
- "time"
-)
-
-func (s *SingBox) startupLogTailSize() int {
- if s.cfg != nil && s.cfg.StartupLogTailSize > 0 {
- return s.cfg.StartupLogTailSize
- }
- return 200
-}
-
-func (s *SingBox) extractStartupError() error {
- failure := s.core.LatestStartupFailure()
- if failure == "" {
- return nil
- }
- return fmt.Errorf("failed to start sing-box: %s", failure)
-}
-
-func (s *SingBox) startupErrorWithTail(reason string) error {
- failure := s.core.LatestStartupFailure()
- if failure != "" {
- return fmt.Errorf("failed to start sing-box: %s", failure)
- }
-
- tail := s.core.StartupLogTail(s.startupLogTailSize())
- if len(tail) == 0 {
- return errors.New(reason)
- }
-
- return fmt.Errorf("%s; no fatal sing-box startup log was detected. Recent sing-box logs:\n%s", reason, strings.Join(tail, "\n"))
-}
-
-// checkStatus polls GetSysStats (a live round-trip through the v2ray_api
-// StatsService) until it succeeds or a fatal startup error is observed in the
-// captured logs, mirroring xray's Xray.checkXrayStatus.
-func (s *SingBox) checkStatus(baseCtx context.Context) error {
- apiTicker := time.NewTicker(1 * time.Second)
- defer apiTicker.Stop()
- errorTicker := time.NewTicker(2 * time.Second)
- defer errorTicker.Stop()
-
- for {
- select {
- case <-baseCtx.Done():
- return errors.New("context cancelled")
-
- case <-errorTicker.C:
- if err := s.extractStartupError(); err != nil {
- return err
- }
-
- case <-apiTicker.C:
- ctx, cancel := context.WithTimeout(baseCtx, 1*time.Second)
- _, err := s.GetSysStats(ctx)
- cancel()
-
- if err == nil {
- return nil
- }
-
- if err := s.extractStartupError(); err != nil {
- return err
- }
-
- if !s.core.Started() {
- reason := "sing-box process stopped before API became ready"
- if s.core.Stopping() {
- reason = "sing-box startup was interrupted by a stop/restart request before API became ready"
- }
- return s.startupErrorWithTail(reason)
- }
- }
- }
-}
-
-// checkHealth periodically verifies the v2ray_api is still responsive and
-// restarts sing-box after repeated consecutive failures, mirroring xray's
-// Xray.checkXrayHealth.
-func (s *SingBox) checkHealth(baseCtx context.Context) {
- consecutiveFailures := 0
- maxFailures := 10
- checkInterval := 2 * time.Second
-
- restart := func(reason string) {
- log.Println(reason)
- if tail := s.core.StartupLogTail(10); len(tail) > 0 {
- log.Printf("last %d sing-box log lines before restart:\n%s", len(tail), strings.Join(tail, "\n"))
- }
- if err := s.Restart(); err != nil {
- log.Println(err.Error())
- } else {
- log.Println("sing-box restarted")
- consecutiveFailures = 0
- }
- }
-
- for {
- select {
- case <-baseCtx.Done():
- return
- default:
- if s.core.Restarting() {
- consecutiveFailures = 0
- time.Sleep(checkInterval)
- continue
- }
-
- ctx, cancel := context.WithTimeout(baseCtx, 3*time.Second)
- _, err := s.GetSysStats(ctx)
- cancel()
-
- if err != nil {
- if errors.Is(err, context.Canceled) {
- return
- }
-
- consecutiveFailures++
- log.Printf("sing-box health check failure %d/%d: %v", consecutiveFailures, maxFailures, err)
-
- if !s.core.Started() {
- restart("sing-box process is not running, restarting...")
- } else if consecutiveFailures >= maxFailures {
- restart(fmt.Sprintf("sing-box health check failed %d times, restarting...", consecutiveFailures))
- }
- } else {
- consecutiveFailures = 0
- }
- }
- time.Sleep(checkInterval)
- }
-}
diff --git a/backend/singbox/log.go b/backend/singbox/log.go
deleted file mode 100644
index 9073a50c..00000000
--- a/backend/singbox/log.go
+++ /dev/null
@@ -1,159 +0,0 @@
-package singbox
-
-import (
- "bufio"
- "context"
- "io"
- "strings"
- "sync"
-)
-
-// logRing is a small fixed-size circular buffer of recent log lines, used to
-// give context (e.g. in an error returned to the caller) when startup fails or
-// health checks trip a restart. This replaces xray's separate
-// startup-phase/runtime-phase log ring pair (startup_diagnostics.go) with a
-// single always-on ring - sing-box's v1 scope doesn't need the phase-switching
-// complexity xray uses to avoid overhead during steady-state runtime.
-type logRing struct {
- mu sync.Mutex
- lines []string
- next int
- full bool
-}
-
-func newLogRing(size int) *logRing {
- if size <= 0 {
- size = 1
- }
- return &logRing{lines: make([]string, size)}
-}
-
-func (r *logRing) reset() {
- r.mu.Lock()
- defer r.mu.Unlock()
- r.next = 0
- r.full = false
- for i := range r.lines {
- r.lines[i] = ""
- }
-}
-
-func (r *logRing) add(line string) {
- r.mu.Lock()
- defer r.mu.Unlock()
- if len(r.lines) == 0 {
- return
- }
- r.lines[r.next] = line
- r.next = (r.next + 1) % len(r.lines)
- if r.next == 0 {
- r.full = true
- }
-}
-
-func (r *logRing) tail(n int) []string {
- r.mu.Lock()
- defer r.mu.Unlock()
-
- count := r.next
- if r.full {
- count = len(r.lines)
- }
- if count == 0 {
- return nil
- }
- if n <= 0 || n > count {
- n = count
- }
-
- oldest := 0
- if r.full {
- oldest = r.next
- }
-
- start := count - n
- out := make([]string, 0, n)
- for i := 0; i < n; i++ {
- idx := (oldest + start + i) % len(r.lines)
- out = append(out, r.lines[idx])
- }
- return out
-}
-
-func (c *Core) setStartupFailure(msg string) {
- c.startupFailureM.Lock()
- defer c.startupFailureM.Unlock()
- c.startupFailure = msg
-}
-
-func (c *Core) LatestStartupFailure() string {
- c.startupFailureM.RLock()
- defer c.startupFailureM.RUnlock()
- return c.startupFailure
-}
-
-func (c *Core) StartupLogTail(n int) []string {
- return c.logs.tail(n)
-}
-
-func (c *Core) captureProcessLogs(ctx context.Context, pipe io.Reader) {
- scanner := bufio.NewScanner(pipe)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- select {
- case <-ctx.Done():
- return
- default:
- c.recordLog(scanner.Text())
- }
- }
-}
-
-func (c *Core) recordLog(line string) {
- c.logs.add(line)
-
- // Non-blocking send: skip if channel is full to prevent deadlock/blocking the
- // sing-box process's stdout/stderr pipe.
- select {
- case c.logsChan <- line:
- default:
- }
-
- if isStartupFailureLog(line) {
- c.setStartupFailure(line)
- }
-}
-
-// isStartupFailureLog is a best-effort heuristic for detecting fatal sing-box
-// startup errors from its log output, analogous to xray's
-// startup_diagnostics.go isStartupFailureLog. Calibrated against real output
-// captured on the dev box: sing-box prefixes fatal lines with "FATAL[" (caught
-// by the "fatal" substring check below), e.g.
-//
-// FATAL[0000] decode config at ...: inbounds[0].listen_port: json: cannot unmarshal number 99999 into Go struct field ...
-// FATAL[0000] start service: start inbound/hysteria2[hy2-in]: listen udp 0.0.0.0:18443: bind: address already in use
-func isStartupFailureLog(line string) bool {
- lower := strings.ToLower(line)
-
- keywords := [...]string{
- "fatal",
- "panic",
- "failed to start",
- "start service",
- "permission denied",
- "no such file or directory",
- "cannot find",
- "failed to open",
- "failed to load",
- "failed to listen",
- "address already in use",
- }
-
- for _, keyword := range keywords {
- if strings.Contains(lower, keyword) {
- return true
- }
- }
-
- return false
-}
diff --git a/backend/singbox/process_unix.go b/backend/singbox/process_unix.go
deleted file mode 100644
index 558014ca..00000000
--- a/backend/singbox/process_unix.go
+++ /dev/null
@@ -1,303 +0,0 @@
-//go:build !windows
-
-package singbox
-
-import (
- "bytes"
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
- "syscall"
- "time"
-)
-
-// findSingBoxProcesses finds all running sing-box processes by executable
-// path, returning PID/PPID/zombie state. Mirrors
-// backend/xray/process_unix.go's findXrayProcesses (this node only targets
-// Linux, so the /proc path below is the one actually exercised; the ps
-// fallback is kept for parity with xray's implementation).
-func findSingBoxProcesses(executablePath string) ([]ProcessInfo, error) {
- absPath, err := filepath.Abs(executablePath)
- if err != nil {
- return nil, err
- }
-
- if runtime.GOOS == "linux" {
- if procs, perr := findSingBoxProcessesFromProc(absPath); perr == nil {
- return procs, nil
- }
- }
-
- cmd := exec.Command("ps", "-eo", "pid,ppid,state,command")
- output, err := cmd.Output()
- if err != nil {
- return nil, fmt.Errorf("failed to list processes: %w", err)
- }
-
- var processes []ProcessInfo
- lines := strings.Split(string(output), "\n")
- executableName := filepath.Base(absPath)
-
- for _, line := range lines {
- line = strings.TrimSpace(line)
- if line == "" || strings.HasPrefix(line, "PID") {
- continue
- }
-
- fields := strings.Fields(line)
- if len(fields) < 4 {
- continue
- }
-
- pidStr := fields[0]
- ppidStr := fields[1]
- state := fields[2]
- cmdPath := fields[3]
-
- pid, err := strconv.Atoi(pidStr)
- if err != nil {
- continue
- }
- ppid, err := strconv.Atoi(ppidStr)
- if err != nil {
- continue
- }
-
- match := false
- if procPath, err := getProcessPath(pid); err == nil {
- match = pathsMatch(procPath, absPath)
- }
- if !match {
- match = pathsMatch(cmdPath, absPath) || filepath.Base(cmdPath) == executableName
- }
- if !match {
- continue
- }
-
- isZombie := state == "Z" || state == "z"
-
- processes = append(processes, ProcessInfo{
- PID: pid,
- PPID: ppid,
- IsZombie: isZombie,
- })
- }
-
- return processes, nil
-}
-
-// findSingBoxProcessesFromProc scans /proc directly (Linux-only).
-func findSingBoxProcessesFromProc(absPath string) ([]ProcessInfo, error) {
- entries, err := os.ReadDir("/proc")
- if err != nil {
- return nil, err
- }
-
- var processes []ProcessInfo
- for _, entry := range entries {
- if !entry.IsDir() {
- continue
- }
- pid, err := strconv.Atoi(entry.Name())
- if err != nil || pid <= 0 {
- continue
- }
-
- exePath, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid))
- if err != nil {
- continue
- }
- if !pathsMatch(exePath, absPath) {
- continue
- }
-
- statPath := fmt.Sprintf("/proc/%d/stat", pid)
- data, err := os.ReadFile(statPath)
- if err != nil {
- continue
- }
- fields := strings.Fields(string(data))
- if len(fields) < 4 {
- continue
- }
- state := fields[2]
- ppid, err := strconv.Atoi(fields[3])
- if err != nil {
- continue
- }
-
- processes = append(processes, ProcessInfo{
- PID: pid,
- PPID: ppid,
- IsZombie: state == "Z" || state == "z",
- })
- }
-
- return processes, nil
-}
-
-func getProcessPath(pid int) (string, error) {
- procPath := fmt.Sprintf("/proc/%d/exe", pid)
- path, err := os.Readlink(procPath)
- if err == nil {
- return path, nil
- }
-
- psOutput, psErr := exec.Command("ps", "-p", strconv.Itoa(pid), "-o", "command=").Output()
- if psErr != nil {
- return "", fmt.Errorf("failed to read process path: %w (ps fallback error: %v)", err, psErr)
- }
-
- cmdline := strings.TrimSpace(string(psOutput))
- if cmdline == "" {
- return "", fmt.Errorf("failed to read process path: empty command for pid %d", pid)
- }
-
- fields := strings.Fields(cmdline)
- if len(fields) == 0 {
- return "", fmt.Errorf("failed to read process path: empty command for pid %d", pid)
- }
-
- return fields[0], nil
-}
-
-// killProcessTree kills a process and all its children on Unix.
-func killProcessTree(pid int) error {
- proc, err := os.FindProcess(pid)
- if err != nil {
- return fmt.Errorf("failed to find process %d: %w", pid, err)
- }
-
- _ = proc.Signal(syscall.SIGTERM)
-
- pgid, err := getProcessGroupID(pid)
- if err == nil && pgid != 0 {
- _ = syscall.Kill(-pgid, syscall.SIGTERM)
- _ = syscall.Kill(-pgid, syscall.SIGKILL)
- }
-
- _ = proc.Signal(syscall.SIGKILL)
-
- for i := 0; i < 10; i++ {
- if !isProcessRunning(pid) {
- return nil
- }
- time.Sleep(100 * time.Millisecond)
- }
-
- return fmt.Errorf("process %d is still running after kill attempt", pid)
-}
-
-func getProcessGroupID(pid int) (int, error) {
- statPath := fmt.Sprintf("/proc/%d/stat", pid)
- data, err := os.ReadFile(statPath)
- if err != nil {
- return 0, err
- }
-
- fields := strings.Fields(string(data))
- if len(fields) < 5 {
- return 0, fmt.Errorf("invalid stat format")
- }
-
- pgid, err := strconv.Atoi(fields[4])
- if err != nil {
- return 0, err
- }
-
- return pgid, nil
-}
-
-func verifyProcessDead(pid int, startTime uint64) error {
- if !isProcessRunning(pid) {
- return nil
- }
- if !sameProcess(pid, startTime) {
- return nil
- }
- return fmt.Errorf("process %d is still running", pid)
-}
-
-func isProcessRunning(pid int) bool {
- proc, err := os.FindProcess(pid)
- if err != nil {
- return false
- }
- err = proc.Signal(syscall.Signal(0))
- return err == nil
-}
-
-// pathsMatch compares two executable paths, resolving symlinks and
-// absolutizing both.
-func pathsMatch(candidate, target string) bool {
- if candidate == "" || target == "" {
- return false
- }
-
- candidateAbs, err := filepath.Abs(candidate)
- if err != nil {
- return false
- }
- targetAbs, err := filepath.Abs(target)
- if err != nil {
- return false
- }
-
- if candidateAbs == targetAbs {
- return true
- }
-
- candidateReal, errA := filepath.EvalSymlinks(candidateAbs)
- targetReal, errB := filepath.EvalSymlinks(targetAbs)
- if errA == nil && errB == nil && candidateReal == targetReal {
- return true
- }
-
- return false
-}
-
-func processStartTime(pid int) (uint64, bool) {
- raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
- if err != nil {
- return 0, false
- }
- close := bytes.LastIndexByte(raw, ')')
- if close < 0 || close+2 >= len(raw) {
- return 0, false
- }
- fields := strings.Fields(string(raw[close+2:]))
- if len(fields) < 20 {
- return 0, false
- }
- start, err := strconv.ParseUint(fields[19], 10, 64)
- if err != nil {
- return 0, false
- }
- return start, true
-}
-
-func sameProcess(pid int, startTime uint64) bool {
- if startTime == 0 {
- return true
- }
- current, ok := processStartTime(pid)
- if !ok {
- return false
- }
- return current == startTime
-}
-
-func canKillByPid(pid int, startTime uint64) bool {
- if startTime == 0 {
- return false
- }
- current, ok := processStartTime(pid)
- if !ok {
- return false
- }
- return current == startTime
-}
diff --git a/backend/singbox/removal_without_credentials_nodeverify_test.go b/backend/singbox/removal_without_credentials_nodeverify_test.go
deleted file mode 100644
index 1a331d1d..00000000
--- a/backend/singbox/removal_without_credentials_nodeverify_test.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package singbox
-
-import (
- "encoding/hex"
- "testing"
-
- "google.golang.org/protobuf/proto"
-
- "github.com/pasarguard/node/common"
-)
-
-const nvSingboxConfig = `{
- "log": {"level": "warn"},
- "inbounds": [
- {"type": "hysteria2", "tag": "hy2-in", "listen": "::", "listen_port": 8443, "users": []},
- {"type": "vless", "tag": "vless-in", "users": []},
- {"type": "vmess", "tag": "vmess-in", "users": []},
- {"type": "trojan", "tag": "trojan-in", "users": []},
- {"type": "shadowsocks", "tag": "ss-in", "method": "aes-128-gcm", "users": []},
- {"type": "tuic", "tag": "tuic-in", "users": []}
- ],
- "outbounds": [{"type": "direct"}]
-}`
-
-func nvSingboxPanelRemoval(t *testing.T) *common.User {
- t.Helper()
- raw, err := hex.DecodeString("0a0234321200")
- if err != nil {
- t.Fatal(err)
- }
- user := &common.User{}
- if err := proto.Unmarshal(raw, user); err != nil {
- t.Fatal(err)
- }
- if user.GetEmail() != "42" || user.GetProxies().GetHysteria2() != nil || len(user.GetInbounds()) != 0 {
- t.Fatalf("decoded removal is not the panel shape: %v", user)
- }
- return user
-}
-
-func nvSingboxMember(email string) *common.User {
- return &common.User{
- Email: email,
- Inbounds: []string{"hy2-in", "vless-in", "vmess-in", "trojan-in", "ss-in", "tuic-in"},
- Proxies: &common.Proxy{
- Hysteria2: &common.Hysteria2{Password: "hy2-" + email},
- Vless: &common.Vless{Id: "0b6f2a4e-6a54-4a51-9a3a-6f1e2b1f7c11"},
- Vmess: &common.Vmess{Id: "6f1c6c5e-3f59-4a0e-9d8a-2b4f1c9d7e10"},
- Trojan: &common.Trojan{Password: "trojan-" + email},
- Shadowsocks: &common.Shadowsocks{Password: "ss-" + email, Method: "aes-128-gcm"},
- Tuic: &common.Tuic{Uuid: "7d0f2a4e-6a54-4a51-9a3a-6f1e2b1f7c12", Password: "tuic-" + email},
- },
- }
-}
-
-func TestNodeVerifySingboxPanelRemovalWithoutCredentialsRevokesEveryInbound(t *testing.T) {
- for name, apply := range map[string]func(*Config, *common.User){
- "upsertUser": func(c *Config, u *common.User) { c.upsertUser(u) },
- "updateUsers": func(c *Config, u *common.User) { c.updateUsers([]*common.User{u}) },
- } {
- t.Run(name, func(t *testing.T) {
- cfg := mustParseConfig(t, nvSingboxConfig)
- cfg.syncUsers([]*common.User{nvSingboxMember("42"), nvSingboxMember("43")})
- for tag, inbound := range cfg.inbounds {
- if _, ok := inbound.users["42"]; !ok {
- t.Fatalf("precondition: user 42 must be on %s", tag)
- }
- }
- apply(cfg, nvSingboxPanelRemoval(t))
- for tag, inbound := range cfg.inbounds {
- if _, ok := inbound.users["42"]; ok {
- t.Fatalf("user 42 still on %s after the panel removed it", tag)
- }
- if _, ok := inbound.users["43"]; !ok {
- t.Fatalf("removing user 42 dropped user 43 from %s", tag)
- }
- }
- })
- }
-}
diff --git a/backend/singbox/restart_carry_test.go b/backend/singbox/restart_carry_test.go
deleted file mode 100644
index d17ba63e..00000000
--- a/backend/singbox/restart_carry_test.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package singbox
-
-import (
- "context"
- "sync"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/pasarguard/node/common"
-)
-
-func billedUsers(t *testing.T, sb *SingBox, statType common.StatType, name string, reset bool) map[string]int64 {
- t.Helper()
- out := map[string]int64{}
- for key, value := range mustLedgerRead(t, sb, statType, name, reset) {
- if value != 0 {
- out[key] = value
- }
- }
- return out
-}
-
-func TestCountersKeptBeforeARestartAreBilledOnceAfterIt(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add("user>>>1.alice>>>traffic>>>downlink", 1000)
- fake.add("user>>>2.bob>>>traffic>>>uplink", 300)
- fake.add(ledgerHy2Down, 700)
-
- sb.keepUnreadCounters(context.Background())
- fake.restart()
- fake.add("user>>>1.alice>>>traffic>>>downlink", 50)
-
- expectLedger(t, "alice read without a reset", billedUsers(t, sb, common.StatType_UserStat, "1.alice", false), map[string]int64{"1.alice/downlink": 1050})
- expectLedger(t, "users", billedUsers(t, sb, common.StatType_UsersStat, "", true), map[string]int64{"1.alice/downlink": 1050, "2.bob/uplink": 300})
- expectLedger(t, "users read again", billedUsers(t, sb, common.StatType_UsersStat, "", true), map[string]int64{})
- expectLedger(t, "outbounds", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 700})
- expectLedger(t, "inbounds", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 700})
-}
-
-func TestAResetReadBetweenTheDrainAndTheRestartBillsEachByteOnce(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add("user>>>1.alice>>>traffic>>>downlink", 1000)
- fake.add(ledgerHy2Down, 700)
-
- sb.keepUnreadCounters(context.Background())
- fake.add("user>>>1.alice>>>traffic>>>downlink", 30)
-
- expectLedger(t, "users read between the drain and the restart", billedUsers(t, sb, common.StatType_UsersStat, "", true), map[string]int64{"1.alice/downlink": 1030})
- expectLedger(t, "inbounds read between the drain and the restart", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 700})
- fake.restart()
- expectLedger(t, "users after the restart", billedUsers(t, sb, common.StatType_UsersStat, "", true), map[string]int64{})
- expectLedger(t, "inbounds after the restart", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{})
- expectLedger(t, "outbounds after the restart", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 700})
-}
-
-func TestAUserReadTakesOnlyThatUsersKeptCounters(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add("user>>>1.alice>>>traffic>>>downlink", 1000)
- fake.add("user>>>11.alicia>>>traffic>>>downlink", 400)
-
- sb.keepUnreadCounters(context.Background())
- fake.restart()
-
- expectLedger(t, "alice", billedUsers(t, sb, common.StatType_UserStat, "1.alice", true), map[string]int64{"1.alice/downlink": 1000})
- expectLedger(t, "users after alice was read", billedUsers(t, sb, common.StatType_UsersStat, "", true), map[string]int64{"11.alicia/downlink": 400})
- if _, err := sb.GetStats(context.Background(), &common.StatRequest{Type: common.StatType_UserStat}); err == nil {
- t.Fatal("a user read without a name returned no error")
- }
-}
-
-func TestAFailedRestartDrainKeepsTheCountersOnTheCore(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add("user>>>1.alice>>>traffic>>>downlink", 1000)
- fake.add(ledgerHy2Down, 700)
-
- fake.failNext()
- fake.failNext()
- sb.keepUnreadCounters(context.Background())
-
- expectLedger(t, "users", billedUsers(t, sb, common.StatType_UsersStat, "", true), map[string]int64{"1.alice/downlink": 1000})
- expectLedger(t, "inbounds", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 700})
-}
-
-func TestRestartDrainsRacingResetReadsBillEveryUserByteOnce(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- const counter = "user>>>1.alice>>>traffic>>>downlink"
- const writers, readers, drains = 8, 6, 60
-
- var billed atomic.Int64
- stopReading := make(chan struct{})
- errs := make(chan error, readers)
- var reading sync.WaitGroup
- for range readers {
- reading.Add(1)
- go func() {
- defer reading.Done()
- for {
- select {
- case <-stopReading:
- return
- default:
- }
- got, err := ledgerRead(sb, common.StatType_UsersStat, "", true)
- if err != nil {
- errs <- err
- return
- }
- billed.Add(got["1.alice/downlink"])
- }
- }()
- }
-
- var written atomic.Int64
- stopWriting := make(chan struct{})
- var writing sync.WaitGroup
- for i := range writers {
- writing.Add(1)
- go func() {
- defer writing.Done()
- for j := 0; ; j++ {
- select {
- case <-stopWriting:
- return
- default:
- }
- fake.add(counter, int64(i+1))
- written.Add(int64(i + 1))
- if j%20 == 0 {
- time.Sleep(100 * time.Microsecond)
- }
- }
- }()
- }
- for range drains {
- sb.keepUnreadCounters(context.Background())
- }
- close(stopWriting)
- writing.Wait()
- close(stopReading)
- reading.Wait()
- close(errs)
- for err := range errs {
- t.Fatalf("a racing reset read failed: %v", err)
- }
- billed.Add(mustLedgerRead(t, sb, common.StatType_UsersStat, "", true)["1.alice/downlink"])
-
- if got, want := billed.Load(), written.Load(); got != want {
- t.Fatalf("racing reset reads and %d restart drains billed %d bytes, want %d", drains, got, want)
- }
- t.Logf("%d restart drains raced the reset reads over %d written bytes", drains, written.Load())
-}
diff --git a/backend/singbox/restart_counters_test.go b/backend/singbox/restart_counters_test.go
deleted file mode 100644
index fa142884..00000000
--- a/backend/singbox/restart_counters_test.go
+++ /dev/null
@@ -1,372 +0,0 @@
-package singbox
-
-import (
- "context"
- "encoding/binary"
- "fmt"
- "io"
- "net"
- "os"
- "strconv"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/google/uuid"
-
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
-)
-
-func singBoxUnderTest(t *testing.T) string {
- t.Helper()
- binary := os.Getenv("SINGBOX_SMOKE_BINARY")
- if binary == "" {
- t.Skip("SINGBOX_SMOKE_BINARY names no sing-box binary")
- }
- return binary
-}
-
-func singBoxPID(sb *SingBox) int {
- state := sb.core.state.Load()
- if state == nil || state.cmd == nil || state.cmd.Process == nil {
- return 0
- }
- return state.cmd.Process.Pid
-}
-
-func sizedTarget(t *testing.T, size int) *net.TCPAddr {
- t.Helper()
- listener, err := net.Listen("tcp4", net.JoinHostPort(userTrafficHost(t), "0"))
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { _ = listener.Close() })
- go func() {
- chunk := make([]byte, 32*1024)
- for {
- conn, err := listener.Accept()
- if err != nil {
- return
- }
- go func() {
- defer conn.Close()
- for left := size; left > 0; {
- n, err := conn.Write(chunk[:min(left, len(chunk))])
- left -= n
- if err != nil {
- return
- }
- }
- }()
- }
- }()
- return listener.Addr().(*net.TCPAddr)
-}
-
-func vlessDownload(t *testing.T, port int, id uuid.UUID, size int) int64 {
- t.Helper()
- target := sizedTarget(t, size)
- conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), 3*time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer conn.Close()
- request := []byte{0}
- request = append(request, id[:]...)
- request = append(request, 0, 1)
- request = binary.BigEndian.AppendUint16(request, uint16(target.Port))
- request = append(request, 1)
- request = append(request, target.IP.To4()...)
- if _, err := conn.Write(request); err != nil {
- t.Fatal(err)
- }
- _ = conn.SetReadDeadline(time.Now().Add(30 * time.Second))
- received, err := io.Copy(io.Discard, conn)
- if err != nil || received < int64(size) {
- t.Fatalf("a %d byte download through sing-box received %d bytes (err %v)", size, received, err)
- }
- return int64(size)
-}
-
-func singBoxUserBytes(t *testing.T, sb *SingBox, email string, reset bool) int64 {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- resp, err := sb.GetStats(ctx, &common.StatRequest{Type: common.StatType_UsersStat, Reset_: reset})
- if err != nil {
- t.Fatalf("GetStats(UsersStat, reset=%v): %v", reset, err)
- }
- var total int64
- for _, stat := range resp.GetStats() {
- if stat.GetName() == email {
- total += stat.GetValue()
- }
- }
- return total
-}
-
-func waitForSingBoxUserBytes(t *testing.T, sb *SingBox, email string, want int64) int64 {
- t.Helper()
- deadline := time.Now().Add(5 * time.Second)
- for {
- got := singBoxUserBytes(t, sb, email, false)
- if got >= want || time.Now().After(deadline) {
- return got
- }
- time.Sleep(50 * time.Millisecond)
- }
-}
-
-func vlessSingBoxUser(email string, id uuid.UUID) *common.User {
- return &common.User{Email: email, Inbounds: []string{"vless-in"}, Proxies: &common.Proxy{Vless: &common.Vless{Id: id.String()}}}
-}
-
-func startVlessSingBox(t *testing.T, users ...*common.User) (*SingBox, int) {
- t.Helper()
- bin := singBoxUnderTest(t)
- port := loopbackPortsBelowTheEphemeralRange(t, 1)
- sbConfig, err := NewConfig(fmt.Sprintf(`{
- "log": {"level": "warn"},
- "inbounds": [{"type": "vless", "tag": "vless-in", "listen": "127.0.0.1", "listen_port": %d, "users": []}],
- "outbounds": [{"type": "direct"}]
- }`, port))
- if err != nil {
- t.Fatal(err)
- }
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- statsPort, clashPort := singBoxAPIPorts(t)
- sb, err := New(ctx, sbConfig, users, statsPort, clashPort, &config.Config{
- SingBoxExecutablePath: bin,
- GeneratedConfigPath: t.TempDir(),
- LogBufferSize: 1000,
- StartupLogTailSize: 200,
- })
- if err != nil {
- t.Fatalf("New: %v", err)
- }
- t.Cleanup(sb.Shutdown)
- t.Logf("sing-box under test: %s", sb.Version())
- return sb, port
-}
-
-func rawSingBoxCounters(t *testing.T, sb *SingBox) map[string]int64 {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- resp, err := sb.client.QueryStats(ctx, "", false)
- if err != nil {
- t.Fatalf("QueryStats on the running core: %v", err)
- }
- out := map[string]int64{}
- for _, stat := range resp.GetStat() {
- if stat.GetValue() != 0 {
- out[stat.GetName()] = stat.GetValue()
- }
- }
- return out
-}
-
-func billedSingBoxCounters(t *testing.T, sb *SingBox, statType common.StatType) map[string]int64 {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- resp, err := sb.GetStats(ctx, &common.StatRequest{Type: statType, Reset_: true})
- if err != nil {
- t.Fatalf("GetStats(%s, reset): %v", statType, err)
- }
- out := map[string]int64{}
- for _, stat := range resp.GetStats() {
- if stat.GetValue() != 0 {
- out[stat.GetName()+">>>"+stat.GetLink()+">>>"+stat.GetType()] += stat.GetValue()
- }
- }
- return out
-}
-
-func withPrefix(counters map[string]int64, prefix string) map[string]int64 {
- out := map[string]int64{}
- for name, value := range counters {
- if rest, ok := strings.CutPrefix(name, prefix); ok {
- out[rest] = value
- }
- }
- return out
-}
-
-func expectSingBoxCounters(t *testing.T, what string, got, want map[string]int64) {
- t.Helper()
- if fmt.Sprint(got) != fmt.Sprint(want) {
- t.Errorf("%s: got %v, want %v", what, got, want)
- }
-}
-
-func waitForSingBoxAPI(t *testing.T, sb *SingBox) {
- t.Helper()
- deadline := time.Now().Add(15 * time.Second)
- for {
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- _, err := sb.GetSysStats(ctx)
- cancel()
- if err == nil {
- return
- }
- if time.Now().After(deadline) {
- t.Fatalf("the restarted core never answered: %v", err)
- }
- time.Sleep(100 * time.Millisecond)
- }
-}
-
-func expectUnreadTrafficBilledOnce(t *testing.T, sb *SingBox, before map[string]int64) {
- t.Helper()
- users := withPrefix(before, "user>>>")
- inbounds := withPrefix(before, "inbound>>>")
- if len(users) == 0 || len(inbounds) == 0 {
- t.Fatalf("the core held no user or inbound traffic before the restart: %v", before)
- }
- expectSingBoxCounters(t, "users billed after the restart", billedSingBoxCounters(t, sb, common.StatType_UsersStat), users)
- expectSingBoxCounters(t, "inbounds billed after the restart", billedSingBoxCounters(t, sb, common.StatType_Inbounds), inbounds)
- expectSingBoxCounters(t, "outbounds billed after the restart", billedSingBoxCounters(t, sb, common.StatType_Outbounds), inbounds)
- expectSingBoxCounters(t, "users billed again", billedSingBoxCounters(t, sb, common.StatType_UsersStat), map[string]int64{})
- expectSingBoxCounters(t, "inbounds billed again", billedSingBoxCounters(t, sb, common.StatType_Inbounds), map[string]int64{})
-}
-
-func TestASingBoxFullSyncThatAddsAUserKeepsTheCoreAndTheUnreadTraffic(t *testing.T) {
- aliceID, carolID := uuid.New(), uuid.New()
- alice := vlessSingBoxUser("1.alice", aliceID)
- sb, port := startVlessSingBox(t, alice)
-
- moved := vlessDownload(t, port, aliceID, 24<<20)
- before := waitForSingBoxUserBytes(t, sb, "1.alice", moved)
- pid := singBoxPID(sb)
-
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
- if err := sb.SyncUsers(ctx, []*common.User{alice, vlessSingBoxUser("3.carol", carolID)}); err != nil {
- t.Fatalf("a full sync that adds carol: %v", err)
- }
- restarted := singBoxPID(sb) != pid
- after := singBoxUserBytes(t, sb, "1.alice", true)
- t.Logf("1.alice moved %d bytes, %d unread before the full sync; the full sync restarted the core: %v; read after it: %d", moved, before, restarted, after)
- if restarted {
- t.Errorf("a full sync that adds a user restarted sing-box")
- }
- if after < before {
- t.Errorf("a full sync that adds a user lost %d unread bytes of 1.alice", before-after)
- }
-}
-
-func TestAUserAddedToARunningSingBoxIsBilled(t *testing.T) {
- aliceID, carolID := uuid.New(), uuid.New()
- alice := vlessSingBoxUser("1.alice", aliceID)
- sb, port := startVlessSingBox(t, alice)
-
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
- pid := singBoxPID(sb)
- if err := sb.SyncUsers(ctx, []*common.User{alice, vlessSingBoxUser("3.carol", carolID)}); err != nil {
- t.Fatalf("a full sync that adds carol: %v", err)
- }
- moved := vlessDownload(t, port, carolID, 16<<20)
- billed := waitForSingBoxUserBytes(t, sb, "3.carol", moved)
- t.Logf("carol, added while the core ran (restarted %v), moved %d bytes and was billed %d", singBoxPID(sb) != pid, moved, billed)
- if billed < moved {
- t.Errorf("carol, added to a running core, moved %d bytes but %d were counted", moved, billed)
- }
-}
-
-func TestASingBoxRestartKeepsTheUnreadTraffic(t *testing.T) {
- aliceID := uuid.New()
- sb, port := startVlessSingBox(t, vlessSingBoxUser("1.alice", aliceID))
-
- moved := vlessDownload(t, port, aliceID, 24<<20)
- waitForSingBoxUserBytes(t, sb, "1.alice", moved)
- before := rawSingBoxCounters(t, sb)
- pid := singBoxPID(sb)
- started := time.Now()
- if err := sb.Restart(); err != nil {
- t.Fatalf("Restart: %v", err)
- }
- if singBoxPID(sb) == pid {
- t.Fatalf("Restart kept pid %d", pid)
- }
- waitForSingBoxAPI(t, sb)
- t.Logf("1.alice moved %d bytes; the core held %v before the restart, which took %s", moved, before, time.Since(started).Round(time.Millisecond))
- expectUnreadTrafficBilledOnce(t, sb, before)
-}
-
-func TestAUserSyncWhoseHotReloadFailsRestartsAndKeepsTheUnreadTraffic(t *testing.T) {
- aliceID, carolID := uuid.New(), uuid.New()
- alice := vlessSingBoxUser("1.alice", aliceID)
- sb, port := startVlessSingBox(t, alice)
-
- moved := vlessDownload(t, port, aliceID, 24<<20)
- waitForSingBoxUserBytes(t, sb, "1.alice", moved)
- before := rawSingBoxCounters(t, sb)
- pid := singBoxPID(sb)
-
- unreachable := loopbackPortsBelowTheEphemeralRange(t, 1)
- sb.config.mu.Lock()
- sb.config.clashPort = unreachable
- sb.config.mu.Unlock()
-
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
- if err := sb.SyncUsers(ctx, []*common.User{alice, vlessSingBoxUser("3.carol", carolID)}); err != nil {
- t.Fatalf("a full sync that adds carol while the hot-reload endpoint is unreachable: %v", err)
- }
- if singBoxPID(sb) == pid {
- t.Fatalf("the user sync whose hot-reload failed kept pid %d instead of restarting", pid)
- }
- t.Logf("1.alice moved %d bytes; the core held %v before the fallback restart", moved, before)
- expectUnreadTrafficBilledOnce(t, sb, before)
-
- carolMoved := vlessDownload(t, port, carolID, 4<<20)
- if billed := waitForSingBoxUserBytes(t, sb, "3.carol", carolMoved); billed != carolMoved {
- t.Errorf("carol, added by the fallback restart, moved %d bytes and was billed %d", carolMoved, billed)
- }
-}
-
-func TestTrafficCountedWhileASingBoxRestartWaitsForItsLockIsBilled(t *testing.T) {
- aliceID := uuid.New()
- sb, port := startVlessSingBox(t, vlessSingBoxUser("1.alice", aliceID))
-
- first := vlessDownload(t, port, aliceID, 16<<20)
- waitForSingBoxUserBytes(t, sb, "1.alice", first)
- pid := singBoxPID(sb)
- config := sb.activeConfig()
-
- sb.mu.RLock()
- release := sync.OnceFunc(sb.mu.RUnlock)
- defer release()
- restarted := make(chan error, 1)
- go func() { restarted <- sb.restartCoreWithConfig(config) }()
- deadline := time.Now().Add(10 * time.Second)
- for withPrefix(rawSingBoxCounters(t, sb), "user>>>")["1.alice>>>traffic>>>downlink"] != 0 {
- if time.Now().After(deadline) {
- t.Fatal("the restart never drained the core while a reader held the lock")
- }
- time.Sleep(10 * time.Millisecond)
- }
- second := vlessDownload(t, port, aliceID, 8<<20)
- deadline = time.Now().Add(10 * time.Second)
- for withPrefix(rawSingBoxCounters(t, sb), "user>>>")["1.alice>>>traffic>>>downlink"] != second {
- if time.Now().After(deadline) {
- t.Fatal("the core never counted the traffic that followed the drain")
- }
- time.Sleep(10 * time.Millisecond)
- }
-
- release()
- if err := <-restarted; err != nil {
- t.Fatalf("restart: %v", err)
- }
- if singBoxPID(sb) == pid {
- t.Fatalf("the restart kept pid %d", pid)
- }
- waitForSingBoxAPI(t, sb)
- expectSingBoxCounters(t, "users billed after the restart", billedSingBoxCounters(t, sb, common.StatType_UsersStat), map[string]int64{"1.alice>>>traffic>>>downlink": first + second})
-}
diff --git a/backend/singbox/restart_interleave_test.go b/backend/singbox/restart_interleave_test.go
deleted file mode 100644
index f0187a42..00000000
--- a/backend/singbox/restart_interleave_test.go
+++ /dev/null
@@ -1,200 +0,0 @@
-//go:build linux
-
-package singbox
-
-import (
- "context"
- "fmt"
- "math/rand/v2"
- "sync"
- "testing"
- "time"
-
- "github.com/pasarguard/node/common"
-)
-
-type syncRound struct {
- name string
- apply func(context.Context, *SingBox) error
- want func(map[string]*common.User)
-}
-
-func randomSyncRound(rng *rand.Rand, pool []*common.User, committed map[string]*common.User) syncRound {
- switch rng.IntN(4) {
- case 0:
- var subset []*common.User
- for _, user := range pool {
- if rng.IntN(2) == 0 {
- subset = append(subset, user)
- }
- }
- if len(subset) == 0 {
- subset = append(subset, pool[rng.IntN(len(pool))])
- }
- return syncRound{
- name: fmt.Sprintf("full sync of %d users", len(subset)),
- apply: func(ctx context.Context, sb *SingBox) error { return sb.SyncUsers(ctx, subset) },
- want: func(state map[string]*common.User) {
- clear(state)
- for _, user := range subset {
- state[user.GetEmail()] = user
- }
- },
- }
- case 1:
- user := pool[rng.IntN(len(pool))]
- return syncRound{
- name: "single sync adding " + user.GetEmail(),
- apply: func(ctx context.Context, sb *SingBox) error { return sb.SyncUser(ctx, user) },
- want: func(state map[string]*common.User) { state[user.GetEmail()] = user },
- }
- case 2:
- var present []string
- for name := range committed {
- present = append(present, name)
- }
- name := pool[rng.IntN(len(pool))].GetEmail()
- if len(present) > 0 {
- name = present[rng.IntN(len(present))]
- }
- revoked := &common.User{Email: name}
- return syncRound{
- name: "update revoking " + name,
- apply: func(ctx context.Context, sb *SingBox) error { return sb.UpdateUsers(ctx, []*common.User{revoked}) },
- want: func(state map[string]*common.User) { delete(state, name) },
- }
- default:
- first := pool[rng.IntN(len(pool))]
- second := pool[rng.IntN(len(pool))]
- return syncRound{
- name: "queued " + first.GetEmail() + " then single sync " + second.GetEmail(),
- apply: func(ctx context.Context, sb *SingBox) error {
- if err := sb.QueueUser(ctx, first); err != nil {
- return err
- }
- return sb.SyncUser(ctx, second)
- },
- want: func(state map[string]*common.User) {
- state[first.GetEmail()] = first
- state[second.GetEmail()] = second
- },
- }
- }
-}
-
-func usersOf(state map[string]*common.User) []*common.User {
- users := make([]*common.User, 0, len(state))
- for _, user := range state {
- users = append(users, user)
- }
- return users
-}
-
-func fireHealthRestarts(rng *rand.Rand, sb *SingBox, count int, within time.Duration) <-chan error {
- delays := make([]time.Duration, count)
- for i := range delays {
- delays[i] = time.Duration(rng.Int64N(int64(within)))
- }
- errs := make(chan error, count)
- var wg sync.WaitGroup
- for _, delay := range delays {
- wg.Add(1)
- go func() {
- defer wg.Done()
- time.Sleep(delay)
- errs <- sb.Restart()
- }()
- }
- go func() {
- wg.Wait()
- close(errs)
- }()
- return errs
-}
-
-func TestHealthRestartsRacingUserSyncsKeepTheCoreOnTheCommittedUsers(t *testing.T) {
- for _, hotReload := range []bool{false, true} {
- name := "restart fallback"
- if hotReload {
- name = "hot reload"
- }
- t.Run(name, func(t *testing.T) { healthRestartsRacingSyncs(t, hotReload) })
- }
-}
-
-func healthRestartsRacingSyncs(t *testing.T, hotReload bool) {
- seed := uint64(time.Now().UnixNano())
- t.Logf("seed %d", seed)
- rng := rand.New(rand.NewPCG(seed, seed^0x9e3779b97f4a7c15))
-
- pool := make([]*common.User, 0, 6)
- for i := range 6 {
- pool = append(pool, restartModelUser(fmt.Sprintf("%d.user", i)))
- }
- exe := restartModelExecutable(t)
- dir := t.TempDir()
- m := newRestartModel(t, exe, dir, pool[0])
- clash := m.enableHotReload(t)
- clash.fail.Store(!hotReload)
-
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
- defer cancel()
-
- committed := map[string]*common.User{pool[0].GetEmail(): pool[0]}
- for round := range 4 {
- step := randomSyncRound(rng, pool, committed)
- restarts := fireHealthRestarts(rng, m.sb, 3, 3500*time.Millisecond)
- if err := step.apply(ctx, m.sb); err != nil {
- t.Fatalf("round %d (%s) failed: %v", round, step.name, err)
- }
- step.want(committed)
- for err := range restarts {
- if err != nil {
- t.Fatalf("round %d (%s): a health restart failed: %v", round, step.name, err)
- }
- }
-
- want := expectUsers(usersOf(committed)...)
- if got := m.committed(); !sameUserNames(got, want) {
- t.Fatalf("round %d (%s): the backend committed %v, want %v", round, step.name, got, want)
- }
- if got := m.live(t); !sameUserNames(got, want) {
- t.Fatalf("round %d (%s): the running core serves %v while the backend committed %v", round, step.name, got, want)
- }
- if !m.sb.core.Started() {
- t.Fatalf("round %d (%s): the core is not running", round, step.name)
- }
- }
-
- final := randomSyncRound(rng, pool, committed)
- finalDone := make(chan error, 1)
- go func() { finalDone <- final.apply(ctx, m.sb) }()
- restarts := fireHealthRestarts(rng, m.sb, 3, 3500*time.Millisecond)
- time.Sleep(time.Duration(rng.Int64N(int64(3 * time.Second))))
- m.sb.Shutdown()
-
- carol := restartModelUser("9.carol")
- replacement := newRestartModel(t, exe, dir, carol)
- pid := corePID(replacement.sb.core)
-
- select {
- case <-finalDone:
- case <-ctx.Done():
- t.Fatal("the sync racing shutdown never returned")
- }
- for range restarts {
- }
-
- if err := m.sb.Restart(); err == nil {
- t.Error("a restart after shutdown must be refused")
- }
- if m.sb.core.Started() {
- t.Error("the shut-down backend's core is running again")
- }
- if got, want := replacement.launched(t), expectUsers(carol); !sameUserNames(got, want) {
- t.Errorf("the shut-down backend rewrote the replacement core's config to %v, want %v", got, want)
- }
- if !replacement.sb.core.Started() || corePID(replacement.sb.core) != pid {
- t.Error("the replacement core was restarted or stopped by the shut-down backend")
- }
-}
diff --git a/backend/singbox/restart_lifecycle_test.go b/backend/singbox/restart_lifecycle_test.go
deleted file mode 100644
index 0107a7f5..00000000
--- a/backend/singbox/restart_lifecycle_test.go
+++ /dev/null
@@ -1,617 +0,0 @@
-//go:build linux
-
-package singbox
-
-import (
- "context"
- "encoding/json"
- "io"
- "maps"
- "net"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "runtime"
- "slices"
- "sort"
- "strings"
- "sync"
- "sync/atomic"
- "testing"
- "time"
-
- "google.golang.org/grpc"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-
- "github.com/pasarguard/node/backend/singbox/api"
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
-)
-
-const restartModelConfig = `{"log":{"level":"error"},"inbounds":[` +
- `{"type":"hysteria2","tag":"hy2-a","listen":"127.0.0.1","listen_port":1,"users":[]},` +
- `{"type":"hysteria2","tag":"hy2-b","listen":"127.0.0.1","listen_port":2,"users":[]}` +
- `],"outbounds":[{"type":"direct"}]}`
-
-var restartModelTags = []string{"hy2-a", "hy2-b"}
-
-func restartModelUser(name string) *common.User {
- return hy2User(name, "k-"+name, restartModelTags...)
-}
-
-type sysStatsModel struct {
- statscmd.UnimplementedStatsServiceServer
- mu sync.Mutex
- held bool
- entered chan struct{}
-}
-
-func (m *sysStatsModel) GetSysStats(context.Context, *statscmd.SysStatsRequest) (*statscmd.SysStatsResponse, error) {
- m.mu.Lock()
- held := m.held
- entered := m.entered
- m.entered = nil
- m.mu.Unlock()
-
- if entered != nil {
- close(entered)
- }
- if held {
- return nil, status.Error(codes.Unavailable, "the core API is not ready")
- }
- return &statscmd.SysStatsResponse{Uptime: 1}, nil
-}
-
-func (m *sysStatsModel) hold() <-chan struct{} {
- m.mu.Lock()
- defer m.mu.Unlock()
- m.held = true
- m.entered = make(chan struct{})
- return m.entered
-}
-
-func (m *sysStatsModel) release() {
- m.mu.Lock()
- defer m.mu.Unlock()
- m.held = false
-}
-
-type clashUsersModel struct {
- core *Core
- fail atomic.Bool
- mu sync.Mutex
- puts int
- pid int
- byTag map[string][]string
- server *httptest.Server
-}
-
-func (c *clashUsersModel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- tag, ok := strings.CutPrefix(r.URL.Path, "/inbounds/")
- tag, ok2 := strings.CutSuffix(tag, "/users")
- if r.Method != http.MethodPut || !ok || !ok2 {
- http.NotFound(w, r)
- return
- }
- raw, err := io.ReadAll(r.Body)
- if err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- var body struct {
- Users []struct {
- Name string `json:"name"`
- } `json:"users"`
- }
- if err := json.Unmarshal(raw, &body); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
-
- c.mu.Lock()
- c.puts++
- c.mu.Unlock()
-
- if c.fail.Load() {
- http.Error(w, "the hot reload is unavailable", http.StatusServiceUnavailable)
- return
- }
-
- names := make([]string, 0, len(body.Users))
- for _, user := range body.Users {
- names = append(names, user.Name)
- }
- sort.Strings(names)
-
- pid := corePID(c.core)
- c.mu.Lock()
- if c.pid != pid {
- c.byTag = make(map[string][]string)
- c.pid = pid
- }
- c.byTag[tag] = names
- c.mu.Unlock()
- w.WriteHeader(http.StatusOK)
-}
-
-func (c *clashUsersModel) putCount() int {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.puts
-}
-
-func (c *clashUsersModel) reloaded() (map[string][]string, int) {
- c.mu.Lock()
- defer c.mu.Unlock()
- return maps.Clone(c.byTag), c.pid
-}
-
-func corePID(c *Core) int {
- c.mu.Lock()
- defer c.mu.Unlock()
- return c.processPID
-}
-
-func restartModelExecutable(t *testing.T) string {
- t.Helper()
-
- exe := filepath.Join(t.TempDir(), "sing-box-restart-model")
- script := "#!/bin/sh\ncase \"$1\" in version) echo \"sing-box version 1.0.0-restart-model\"; exit 0;; esac\nexec sleep 300\n"
- if err := os.WriteFile(exe, []byte(script), 0o755); err != nil {
- t.Fatal(err)
- }
- return exe
-}
-
-type restartModel struct {
- sb *SingBox
- stats *sysStatsModel
- clash *clashUsersModel
- dir string
- health context.Context
-}
-
-func newRestartModel(t *testing.T, exe, dir string, users ...*common.User) *restartModel {
- t.Helper()
-
- listener, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatal(err)
- }
- stats := &sysStatsModel{}
- server := grpc.NewServer()
- statscmd.RegisterStatsServiceServer(server, stats)
- go func() { _ = server.Serve(listener) }()
- t.Cleanup(server.Stop)
-
- client, err := api.NewClient(listener.Addr().(*net.TCPAddr).Port)
- if err != nil {
- t.Fatal(err)
- }
-
- cfg, err := NewConfig(restartModelConfig)
- if err != nil {
- t.Fatal(err)
- }
- cfg.syncUsers(users)
-
- core, err := NewCore(exe, dir, 64, 64)
- if err != nil {
- t.Fatal(err)
- }
- if err := core.Start(cfg); err != nil {
- t.Fatal(err)
- }
-
- health, stopHealth := context.WithCancel(context.Background())
- t.Cleanup(func() {
- stopHealth()
- core.Stop()
- client.Close()
- })
-
- return &restartModel{
- sb: &SingBox{
- config: cfg,
- cfg: &config.Config{StartupLogTailSize: 64},
- core: core,
- client: client,
- cancelFunc: stopHealth,
- },
- stats: stats,
- dir: dir,
- health: health,
- }
-}
-
-func (m *restartModel) enableHotReload(t *testing.T) *clashUsersModel {
- t.Helper()
-
- clash := &clashUsersModel{core: m.sb.core, byTag: make(map[string][]string)}
- clash.server = httptest.NewServer(clash)
- t.Cleanup(clash.server.Close)
-
- port := clash.server.Listener.Addr().(*net.TCPAddr).Port
- m.sb.mu.RLock()
- cfg := m.sb.config
- m.sb.mu.RUnlock()
- cfg.mu.Lock()
- cfg.clashPort = port
- cfg.mu.Unlock()
-
- m.clash = clash
- return clash
-}
-
-func userNamesOf(cfg *Config) map[string][]string {
- out := make(map[string][]string)
- for tag, set := range cfg.UserSets() {
- names := make([]string, 0, len(set.Users))
- for _, raw := range set.Users {
- if entry, ok := raw.(map[string]any); ok {
- if name, ok := entry["name"].(string); ok {
- names = append(names, name)
- }
- }
- }
- sort.Strings(names)
- out[tag] = names
- }
- return out
-}
-
-func expectUsers(users ...*common.User) map[string][]string {
- names := make([]string, 0, len(users))
- for _, user := range users {
- names = append(names, user.GetEmail())
- }
- sort.Strings(names)
- out := make(map[string][]string, len(restartModelTags))
- for _, tag := range restartModelTags {
- out[tag] = slices.Clone(names)
- }
- return out
-}
-
-func sameUserNames(a, b map[string][]string) bool {
- return maps.EqualFunc(a, b, func(x, y []string) bool { return slices.Equal(x, y) })
-}
-
-func (m *restartModel) committed() map[string][]string {
- m.sb.mu.RLock()
- cfg := m.sb.config
- m.sb.mu.RUnlock()
- return userNamesOf(cfg)
-}
-
-func (m *restartModel) launched(t *testing.T) map[string][]string {
- t.Helper()
-
- raw, err := os.ReadFile(filepath.Join(m.dir, "singbox.json"))
- if err != nil {
- t.Fatal(err)
- }
- var parsed struct {
- Inbounds []struct {
- Tag string `json:"tag"`
- Users []struct {
- Name string `json:"name"`
- } `json:"users"`
- } `json:"inbounds"`
- }
- if err := json.Unmarshal(raw, &parsed); err != nil {
- t.Fatal(err)
- }
- out := make(map[string][]string)
- for _, inbound := range parsed.Inbounds {
- names := make([]string, 0, len(inbound.Users))
- for _, user := range inbound.Users {
- names = append(names, user.Name)
- }
- sort.Strings(names)
- out[inbound.Tag] = names
- }
- return out
-}
-
-func (m *restartModel) live(t *testing.T) map[string][]string {
- t.Helper()
-
- if m.clash != nil {
- if users, pid := m.clash.reloaded(); pid != 0 && pid == corePID(m.sb.core) && len(users) == len(restartModelTags) {
- return users
- }
- }
- return m.launched(t)
-}
-
-func goroutineIn(frames ...string) bool {
- buf := make([]byte, 1<<20)
- for {
- n := runtime.Stack(buf, true)
- if n < len(buf) {
- buf = buf[:n]
- break
- }
- buf = make([]byte, 2*len(buf))
- }
- for stack := range strings.SplitSeq(string(buf), "\n\n") {
- matched := true
- for _, frame := range frames {
- if !strings.Contains(stack, frame) {
- matched = false
- break
- }
- }
- if matched {
- return true
- }
- }
- return false
-}
-
-func waitForGoroutineIn(timeout time.Duration, frames ...string) bool {
- deadline := time.Now().Add(timeout)
- for time.Now().Before(deadline) {
- if goroutineIn(frames...) {
- return true
- }
- time.Sleep(10 * time.Millisecond)
- }
- return false
-}
-
-func TestAHealthRestartDoesNotRaceASyncCommittingItsConfig(t *testing.T) {
- alice := restartModelUser("1.alice")
- m := newRestartModel(t, restartModelExecutable(t), t.TempDir(), alice)
- ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
- defer cancel()
-
- stop := make(chan struct{})
- var wg sync.WaitGroup
- wg.Add(1)
- go func() {
- defer wg.Done()
- for {
- select {
- case <-stop:
- return
- default:
- }
- _ = m.sb.Restart()
- time.Sleep(2 * time.Millisecond)
- }
- }()
-
- for range 2 {
- if err := m.sb.SyncUsers(ctx, []*common.User{alice}); err != nil {
- t.Error(err)
- }
- }
- close(stop)
- wg.Wait()
-}
-
-func TestAHealthRestartDuringAFullSyncRestartsTheCoreWithTheSyncedUsers(t *testing.T) {
- alice := restartModelUser("1.alice")
- bob := restartModelUser("2.bob")
- m := newRestartModel(t, restartModelExecutable(t), t.TempDir(), alice)
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
- defer cancel()
-
- probed := m.stats.hold()
- synced := make(chan error, 1)
- go func() { synced <- m.sb.SyncUsers(ctx, []*common.User{alice, bob}) }()
- select {
- case <-probed:
- case <-time.After(30 * time.Second):
- t.Fatal("the full sync never waited for the restarted core's API")
- }
-
- restarted := make(chan error, 1)
- go func() { restarted <- m.sb.Restart() }()
-
- finished := false
- var restartErr error
- deadline := time.Now().Add(15 * time.Second)
- for !finished && !goroutineIn(".(*SingBox).Restart", "sync.(*Mutex).Lock") {
- select {
- case restartErr = <-restarted:
- finished = true
- case <-time.After(10 * time.Millisecond):
- }
- if time.Now().After(deadline) {
- t.Fatal("the health restart neither waited for the running sync nor finished")
- }
- }
- m.stats.release()
-
- select {
- case err := <-synced:
- if err != nil {
- t.Fatalf("the full sync failed: %v", err)
- }
- case <-time.After(90 * time.Second):
- t.Fatal("the full sync never returned")
- }
- if !finished {
- select {
- case restartErr = <-restarted:
- case <-time.After(60 * time.Second):
- t.Fatal("the health restart never returned")
- }
- }
- if restartErr != nil {
- t.Fatalf("the health restart failed: %v", restartErr)
- }
-
- want := expectUsers(alice, bob)
- if got := m.committed(); !sameUserNames(got, want) {
- t.Fatalf("the sync committed %v, want %v", got, want)
- }
- if got := m.launched(t); !sameUserNames(got, want) {
- t.Fatalf("the core was restarted with %v after the sync committed %v: the health restart replayed the previous user set", got, want)
- }
- if !m.sb.core.Started() {
- t.Fatal("the core must be running after the sync and the health restart")
- }
-}
-
-func TestAHealthRestartThatWaitedForASyncDoesNotReviveTheCoreAfterShutdown(t *testing.T) {
- m := newRestartModel(t, restartModelExecutable(t), t.TempDir(), restartModelUser("1.alice"))
- m.stats.hold()
- m.sb.core.Stop()
-
- m.sb.syncMu.Lock()
- syncHeld := true
- releaseSync := func() {
- if syncHeld {
- syncHeld = false
- m.sb.syncMu.Unlock()
- }
- }
-
- healthStopped := make(chan struct{})
- go func() {
- defer close(healthStopped)
- m.sb.checkHealth(m.health)
- }()
- t.Cleanup(func() {
- m.sb.cancelFunc()
- releaseSync()
- select {
- case <-healthStopped:
- case <-time.After(30 * time.Second):
- t.Error("the health loop never stopped")
- }
- })
-
- if !waitForGoroutineIn(15*time.Second, ".(*SingBox).checkHealth", ".(*SingBox).Restart", "sync.(*Mutex).Lock") {
- t.Fatal("the health restart never waited for the running sync")
- }
-
- m.sb.Shutdown()
- releaseSync()
-
- select {
- case <-healthStopped:
- case <-time.After(30 * time.Second):
- t.Fatal("the health loop never stopped after the node shut down")
- }
- if m.sb.core.Started() {
- t.Fatal("a health restart that waited for a sync restarted the core after the node shut down")
- }
-}
-
-func TestARestartAfterShutdownIsRefusedAndRevivesNothing(t *testing.T) {
- m := newRestartModel(t, restartModelExecutable(t), t.TempDir(), restartModelUser("1.alice"))
-
- m.sb.Shutdown()
- err := m.sb.Restart()
- if m.sb.core.Started() {
- t.Fatal("a restart after shutdown brought the core back")
- }
- if err == nil {
- t.Fatal("a restart after shutdown must be refused")
- }
-}
-
-func TestAFullSyncCutShortByShutdownDoesNotReviveTheCore(t *testing.T) {
- alice := restartModelUser("1.alice")
- bob := restartModelUser("2.bob")
- m := newRestartModel(t, restartModelExecutable(t), t.TempDir(), alice)
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
- defer cancel()
-
- probed := m.stats.hold()
- synced := make(chan error, 1)
- go func() { synced <- m.sb.SyncUsers(ctx, []*common.User{alice, bob}) }()
- select {
- case <-probed:
- case <-time.After(30 * time.Second):
- t.Fatal("the full sync never waited for the restarted core's API")
- }
-
- m.sb.Shutdown()
-
- revived := false
- for done := false; !done; {
- select {
- case err := <-synced:
- done = true
- if err == nil {
- t.Error("a full sync cut short by shutdown reported success")
- }
- case <-time.After(20 * time.Millisecond):
- if m.sb.core.Started() {
- revived = true
- }
- case <-ctx.Done():
- t.Fatal("the full sync never returned after the node shut down")
- }
- }
- if revived || m.sb.core.Started() {
- t.Fatal("a full sync cut short by shutdown restarted the core after the node shut down")
- }
-}
-
-func TestABatchFlushedAfterShutdownLeavesTheReplacementCoreAlone(t *testing.T) {
- for _, hotReload := range []bool{true, false} {
- name := "restart fallback"
- if hotReload {
- name = "hot reload"
- }
- t.Run(name, func(t *testing.T) { batchFlushedAfterShutdown(t, hotReload) })
- }
-}
-
-func batchFlushedAfterShutdown(t *testing.T, hotReload bool) {
- exe := restartModelExecutable(t)
- dir := t.TempDir()
- alice := restartModelUser("1.alice")
- bob := restartModelUser("2.bob")
- carol := restartModelUser("3.carol")
-
- old := newRestartModel(t, exe, dir, alice)
- clash := old.enableHotReload(t)
- clash.fail.Store(!hotReload)
- batch := old.sb.enqueue(func(c *Config) { c.upsertUser(bob) })
- old.sb.Shutdown()
-
- replacement := newRestartModel(t, exe, dir, carol)
- pid := corePID(replacement.sb.core)
-
- revived := false
- deadline := time.After(3 * time.Minute)
- for done := false; !done; {
- select {
- case <-batch.done:
- done = true
- case <-time.After(20 * time.Millisecond):
- if old.sb.core.Started() {
- revived = true
- }
- case <-deadline:
- t.Fatal("the batch queued before shutdown never flushed")
- }
- }
-
- if revived || old.sb.core.Started() {
- t.Error("a batch queued before shutdown restarted the old core after the node shut down")
- }
- if puts := clash.putCount(); puts != 0 {
- t.Errorf("a batch queued before shutdown pushed its user set to the old clash port %d time(s) after the node shut down", puts)
- }
- if batch.err == nil {
- t.Error("a batch that cannot be applied after shutdown must report failure")
- }
- if got, want := replacement.launched(t), expectUsers(carol); !sameUserNames(got, want) {
- t.Errorf("the shut-down backend rewrote the replacement core's config to %v, want %v", got, want)
- }
- if !replacement.sb.core.Started() || corePID(replacement.sb.core) != pid {
- t.Error("the replacement core was restarted or stopped by the shut-down backend")
- }
-}
diff --git a/backend/singbox/restart_shutdown_window_test.go b/backend/singbox/restart_shutdown_window_test.go
deleted file mode 100644
index 09c6598e..00000000
--- a/backend/singbox/restart_shutdown_window_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-//go:build linux
-
-package singbox
-
-import (
- "errors"
- "net"
- "net/http"
- "net/http/httptest"
- "sync"
- "testing"
- "time"
-)
-
-func TestNoHotReloadCallReachesTheCoreAfterShutdownReturns(t *testing.T) {
- alice := restartModelUser("1.alice")
- bob := restartModelUser("2.bob")
- m := newRestartModel(t, restartModelExecutable(t), t.TempDir(), alice)
-
- var mu sync.Mutex
- var arrivals []time.Time
- entered := make(chan struct{}, len(restartModelTags))
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- arrivals = append(arrivals, time.Now())
- mu.Unlock()
- entered <- struct{}{}
- time.Sleep(time.Second)
- w.WriteHeader(http.StatusOK)
- }))
- t.Cleanup(server.Close)
-
- cfg := m.sb.activeConfig()
- cfg.mu.Lock()
- cfg.clashPort = server.Listener.Addr().(*net.TCPAddr).Port
- cfg.mu.Unlock()
-
- batch := m.sb.enqueue(func(c *Config) { c.upsertUser(bob) })
- select {
- case <-entered:
- case <-time.After(20 * time.Second):
- t.Fatal("the batch never reached clash_api")
- }
-
- m.sb.Shutdown()
- returned := time.Now()
-
- select {
- case <-batch.done:
- case <-time.After(60 * time.Second):
- t.Fatal("the batch never finished")
- }
-
- mu.Lock()
- defer mu.Unlock()
- if len(arrivals) < 2 {
- t.Fatalf("the hot reload made %d call(s); the test needs one per inbound to observe the window", len(arrivals))
- }
- for i, at := range arrivals {
- if at.After(returned) {
- t.Fatalf("hot reload call %d of %d reached clash_api %s after Shutdown returned", i+1, len(arrivals), at.Sub(returned).Round(time.Millisecond))
- }
- }
-}
-
-func TestARestartWaitingOnTheWrapperLockIsRefusedWhenShutdownTookItFirst(t *testing.T) {
- m := newRestartModel(t, restartModelExecutable(t), t.TempDir(), restartModelUser("1.alice"))
-
- m.sb.mu.RLock()
- held := true
- release := func() {
- if held {
- held = false
- m.sb.mu.RUnlock()
- }
- }
- t.Cleanup(release)
-
- restarted := make(chan error, 1)
- go func() { restarted <- m.sb.Restart() }()
-
- if !waitForGoroutineIn(15*time.Second, ".(*SingBox).restartCoreWithConfig", "sync.(*RWMutex).Lock") {
- release()
- <-restarted
- t.Fatal("the restart did not wait for the wrapper lock before deciding")
- }
-
- m.sb.shutDown = true
- m.sb.cancelFunc()
- m.sb.core.Stop()
- release()
-
- select {
- case err := <-restarted:
- if !errors.Is(err, errShutDown) {
- t.Fatalf("a restart that waited while the backend shut down returned %v, want errShutDown", err)
- }
- case <-time.After(30 * time.Second):
- t.Fatal("the restart never returned")
- }
- if m.sb.core.Started() {
- t.Fatal("a restart that waited while the backend shut down started the core again")
- }
-}
diff --git a/backend/singbox/singbox.go b/backend/singbox/singbox.go
deleted file mode 100644
index 296b2123..00000000
--- a/backend/singbox/singbox.go
+++ /dev/null
@@ -1,196 +0,0 @@
-// Package singbox implements backend.Backend on top of a sing-box subprocess,
-// scoped to the Hysteria2 protocol for v1 (see config.go's doc comment).
-//
-// It follows the shape of backend/xray as closely as makes sense given two
-// structural differences from xray-core:
-// - sing-box has no stdin config mode; it must be started with "-c ", so
-// the generated config is always written to a file (not just in debug mode
-// like xray).
-// - sing-box's experimental.v2ray_api only exposes a StatsService (no
-// HandlerService equivalent for hot user add/remove), so every user sync
-// operation goes through a full config rewrite + process restart. See
-// user.go's doc comments for the concrete implications.
-package singbox
-
-import (
- "context"
- "errors"
- "log"
- "path/filepath"
- "sync"
- "time"
-
- "github.com/pasarguard/node/backend/singbox/api"
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
- "github.com/pasarguard/node/pkg/netutil"
-)
-
-// SingBox is the sing-box-backed implementation of backend.Backend.
-type SingBox struct {
- config *Config
- cfg *config.Config
- core *Core
- client *api.Client
- apiPort int
- cancelFunc context.CancelFunc
- mu sync.RWMutex
- syncMu sync.Mutex
- drainMu sync.Mutex
- shutDown bool
-
- batchMu sync.Mutex
- batch *singBoxPendingBatch
-
- inbounds inboundLedger
- users userCarry
-}
-
-var errShutDown = errors.New("sing-box has been shut down")
-
-func clashPortBesides(apiPort, clashPort int) int {
- for clashPort == apiPort {
- clashPort = netutil.FindFreePort()
- }
- return clashPort
-}
-
-// New builds and starts a sing-box process from sbConfig, syncs the initial
-// user set into it before the first start, dials its v2ray_api stats port, and
-// waits for it to become healthy. Mirrors xray.New's shape/signature.
-func New(ctx context.Context, sbConfig *Config, users []*common.User, apiPort, clashPort int, cfg *config.Config) (*SingBox, error) {
- executableAbsolutePath, err := filepath.Abs(cfg.SingBoxExecutablePath)
- if err != nil {
- return nil, err
- }
-
- configAbsolutePath, err := filepath.Abs(cfg.GeneratedConfigPath)
- if err != nil {
- return nil, err
- }
-
- sCtx, sCancel := context.WithCancel(context.Background())
-
- sb := &SingBox{
- cancelFunc: sCancel,
- cfg: cfg,
- apiPort: apiPort,
- }
-
- start := time.Now()
-
- if err = sbConfig.ApplyAPI(apiPort, clashPortBesides(apiPort, clashPort)); err != nil {
- sCancel()
- return nil, err
- }
-
- if len(users) > 0 {
- log.Printf("syncing %d users on startup", len(users))
- sbConfig.syncUsers(users)
- } else {
- log.Println("no users provided on startup")
- }
-
- sb.config = sbConfig
-
- log.Println("sing-box config generated in", time.Since(start).Seconds(), "second.")
-
- core, err := NewCore(executableAbsolutePath, configAbsolutePath, cfg.LogBufferSize, cfg.StartupLogTailSize)
- if err != nil {
- sCancel()
- return nil, err
- }
-
- if err = core.Start(sbConfig); err != nil {
- sCancel()
- return nil, err
- }
- sb.core = core
-
- client, err := api.NewClient(apiPort)
- if err != nil {
- sb.Shutdown()
- return nil, err
- }
- sb.client = client
-
- if err = sb.checkStatus(ctx); err != nil {
- sb.Shutdown()
- return nil, err
- }
-
- // Wait a bit for sing-box to fully initialize before starting health checks,
- // mirroring xray's startup grace period.
- go sb.checkHealth(sCtx)
-
- log.Println("sing-box started, Version:", sb.Version())
-
- return sb, nil
-}
-
-func (s *SingBox) SubscribeLogs(context.Context) <-chan string {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.core.Logs()
-}
-
-func (s *SingBox) Version() string {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.core.Version()
-}
-
-func (s *SingBox) Started() bool {
- return s.core.Started()
-}
-
-func (s *SingBox) Restart() error {
- s.syncMu.Lock()
- defer s.syncMu.Unlock()
- return s.restartCoreWithConfig(s.activeConfig())
-}
-
-func (s *SingBox) restartCoreWithConfig(cfg *Config) error {
- answered := s.carryUnreadCounters()
- s.mu.Lock()
- defer s.mu.Unlock()
- if s.shutDown {
- return errShutDown
- }
- if answered {
- s.carryUnreadCounters()
- }
- return s.core.Restart(cfg)
-}
-
-func (s *SingBox) activeConfig() *Config {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.config
-}
-
-func (s *SingBox) setConfig(cfg *Config) {
- s.mu.Lock()
- defer s.mu.Unlock()
- s.config = cfg
-}
-
-func (s *SingBox) Shutdown() {
- s.mu.Lock()
- defer s.mu.Unlock()
- s.shutDown = true
-
- // Cancel context first to stop health checks and other goroutines.
- s.cancelFunc()
-
- s.drainMu.Lock()
- s.drainUnreadCounters()
- if s.core != nil {
- s.core.Stop()
- }
- s.drainMu.Unlock()
-
- if s.client != nil {
- s.client.Close()
- }
-}
diff --git a/backend/singbox/smoke_test.go b/backend/singbox/smoke_test.go
deleted file mode 100644
index e2676e61..00000000
--- a/backend/singbox/smoke_test.go
+++ /dev/null
@@ -1,213 +0,0 @@
-//go:build linux
-
-package singbox
-
-import (
- "context"
- "crypto/rand"
- "crypto/rsa"
- "crypto/x509"
- "crypto/x509/pkix"
- "encoding/pem"
- "fmt"
- "math/big"
- "net"
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time"
-
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
-)
-
-// discoverSingBoxBinary looks for a real sing-box binary (built with the
-// with_v2ray_api build tag per the project's build recipe) to run the live
-// smoke test against. It skips the test rather than failing when none is
-// found, since this test needs a real subprocess and real network ports and
-// has no business running in an ordinary CI environment that doesn't have
-// sing-box built.
-func discoverSingBoxBinary(t *testing.T) string {
- t.Helper()
-
- if p := os.Getenv("SINGBOX_SMOKE_BINARY"); p != "" {
- if _, err := os.Stat(p); err == nil {
- return p
- }
- }
-
- candidates := []string{
- "/root/singbox-spike/sing-box-v2api", // dev-box proof-of-concept build
- "/usr/local/bin/sing-box", // default SingBoxExecutablePath
- }
- for _, c := range candidates {
- if _, err := os.Stat(c); err == nil {
- return c
- }
- }
-
- t.Skip("no sing-box binary found for live smoke test; set SINGBOX_SMOKE_BINARY=/path/to/sing-box to run it")
- return ""
-}
-
-func freeUDPPort(t *testing.T) int {
- t.Helper()
- c, err := net.ListenPacket("udp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("failed to find a free UDP port: %v", err)
- }
- defer c.Close()
- return c.LocalAddr().(*net.UDPAddr).Port
-}
-
-// writeSelfSignedCert generates a throwaway self-signed cert/key pair sing-box
-// can load for its hysteria2 inbound's TLS. No client ever connects in this
-// test, so trust/chain validity doesn't matter - sing-box just needs to be
-// able to read a valid cert+key at startup.
-func writeSelfSignedCert(t *testing.T, dir string) (certPath, keyPath string) {
- t.Helper()
-
- key, err := rsa.GenerateKey(rand.Reader, 2048)
- if err != nil {
- t.Fatalf("generate key: %v", err)
- }
-
- template := x509.Certificate{
- SerialNumber: big.NewInt(1),
- Subject: pkix.Name{CommonName: "localhost"},
- NotBefore: time.Now().Add(-time.Hour),
- NotAfter: time.Now().Add(24 * time.Hour),
- KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
- ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
- DNSNames: []string{"localhost"},
- }
-
- der, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
- if err != nil {
- t.Fatalf("create certificate: %v", err)
- }
-
- certPath = filepath.Join(dir, "smoke-cert.pem")
- keyPath = filepath.Join(dir, "smoke-key.pem")
-
- certOut, err := os.Create(certPath)
- if err != nil {
- t.Fatalf("create cert file: %v", err)
- }
- if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil {
- t.Fatalf("encode cert: %v", err)
- }
- certOut.Close()
-
- keyOut, err := os.Create(keyPath)
- if err != nil {
- t.Fatalf("create key file: %v", err)
- }
- if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}); err != nil {
- t.Fatalf("encode key: %v", err)
- }
- keyOut.Close()
-
- return certPath, keyPath
-}
-
-// TestLiveSmoke_SingBoxProcessStartsAndReportsStats is the strongest evidence
-// in this package that the whole chain works: it spawns a real sing-box
-// binary via New(), with a real generated Hysteria2 config and a real test
-// user injected, then confirms the process reports itself started and that
-// GetSysStats returns live data through the hand-written v2ray_api gRPC
-// client (api/). This proves config generation, process spawn, startup health
-// polling, and the gRPC stats client all work end-to-end against a real
-// sing-box process - not just against mocks.
-//
-// It does NOT exercise real Hysteria2 client traffic (no QUIC client is
-// driven against the inbound), so per-user/per-inbound traffic counters are
-// not validated live here - see api/stats_test.go's
-// TestQueryStats_PopulatesPatternsFieldNotDeprecatedPattern for a targeted,
-// fully-automated regression test of that specific wire-format behavior
-// against a fake server standing in for sing-box.
-func TestLiveSmoke_SingBoxProcessStartsAndReportsStats(t *testing.T) {
- bin := discoverSingBoxBinary(t)
-
- dir := t.TempDir()
- certPath, keyPath := writeSelfSignedCert(t, dir)
-
- hyPort := freeUDPPort(t)
- apiPort, clashPort := singBoxAPIPorts(t)
-
- raw := fmt.Sprintf(`{
- "log": {"level": "debug"},
- "inbounds": [{
- "type": "hysteria2",
- "tag": "hy2-in",
- "listen": "::",
- "listen_port": %d,
- "users": [],
- "tls": {"enabled": true, "certificate_path": %q, "key_path": %q}
- }],
- "outbounds": [{"type": "direct"}]
- }`, hyPort, certPath, keyPath)
-
- sbConfig, err := NewConfig(raw)
- if err != nil {
- t.Fatalf("NewConfig() error = %v", err)
- }
-
- testUser := &common.User{
- Email: "smoketest@example.com",
- Inbounds: []string{"hy2-in"},
- Proxies: &common.Proxy{
- Hysteria2: &common.Hysteria2{Password: "smoketestpass"},
- },
- }
-
- cfg := &config.Config{
- SingBoxExecutablePath: bin,
- GeneratedConfigPath: dir,
- LogBufferSize: 1000,
- StartupLogTailSize: 200,
- }
-
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
- defer cancel()
-
- sb, err := New(ctx, sbConfig, []*common.User{testUser}, apiPort, clashPort, cfg)
- if err != nil {
- t.Fatalf("New() error = %v", err)
- }
- defer sb.Shutdown()
-
- if !sb.Started() {
- t.Fatal("expected sing-box to report Started() == true")
- }
- t.Logf("sing-box version: %q", sb.Version())
-
- statsCtx, statsCancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer statsCancel()
-
- stats, err := sb.GetSysStats(statsCtx)
- if err != nil {
- t.Fatalf("GetSysStats() error = %v", err)
- }
-
- t.Logf("live sys stats: NumGoroutine=%d Uptime=%d Alloc=%d NumGC=%d",
- stats.GetNumGoroutine(), stats.GetUptime(), stats.GetAlloc(), stats.GetNumGc())
-
- if stats.GetNumGoroutine() == 0 {
- t.Error("expected NumGoroutine > 0 from a live sing-box process")
- }
-
- // Also exercise the full common.User email injection was picked up: the
- // generated config file on disk should list our test user under the
- // hysteria2 inbound.
- generated, err := os.ReadFile(filepath.Join(dir, "singbox.json"))
- if err != nil {
- t.Fatalf("read generated config: %v", err)
- }
- for _, needle := range []string{"smoketest@example.com", "smoketestpass", "hy2-in"} {
- if !strings.Contains(string(generated), needle) {
- t.Errorf("expected generated config to contain %q; got:\n%s", needle, string(generated))
- }
- }
-}
diff --git a/backend/singbox/stats.go b/backend/singbox/stats.go
deleted file mode 100644
index af6984dd..00000000
--- a/backend/singbox/stats.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package singbox
-
-import (
- "context"
- "errors"
-
- "github.com/pasarguard/node/common"
-)
-
-func (s *SingBox) GetSysStats(ctx context.Context) (*common.BackendStatsResponse, error) {
- return s.client.GetSysStats(ctx)
-}
-
-func (s *SingBox) GetStats(ctx context.Context, request *common.StatRequest) (*common.StatResponse, error) {
- switch request.GetType() {
-
- // This backend's generated Hysteria2 config has no traffic-bearing
- // outbound to populate sing-box's "outbound>>>" counters (see
- // GetOutboundsLatency below) - the panel's node-level traffic total is
- // sourced from an Outbound/Outbounds query regardless of backend type
- // (app/jobs/record_usages.py get_outbounds_stats), so this answers with
- // the inbound listener's own counters instead, which is where
- // Hysteria2's real byte counts actually land. GetInboundsStats/
- // GetInboundStats query sing-box's independent "inbound>>>" counter
- // namespace (see backend/singbox/api/stats.go's QueryStats), with its
- // own reset cycle separate from "user>>>"'s - safe to reset here
- // without affecting per-user billing accuracy.
- case common.StatType_Outbounds:
- return s.inbounds.collect(ctx, s.client, consumerOutbounds, "", request.GetReset_())
- case common.StatType_Outbound:
- return s.inbounds.collectTag(ctx, s.client, consumerOutbounds, request.GetName(), request.GetReset_())
-
- case common.StatType_Inbounds:
- return s.inbounds.collect(ctx, s.client, consumerInbounds, "", request.GetReset_())
- case common.StatType_Inbound:
- return s.inbounds.collectTag(ctx, s.client, consumerInbounds, request.GetName(), request.GetReset_())
-
- case common.StatType_UsersStat:
- return s.users.read(ctx, s.client, userCounterPrefix, request.GetReset_())
- case common.StatType_UserStat:
- if request.GetName() == "" {
- return nil, errors.New("email required")
- }
- return s.users.read(ctx, s.client, userCounterPrefix+request.GetName()+">>>", request.GetReset_())
-
- default:
- return nil, errors.New("not implemented stat type")
- }
-}
-
-// GetOutboundsLatency is a known v1 limitation: xray's implementation
-// (backend/xray/latency.go) scrapes xray's own HTTP "/debug/vars" observatory
-// endpoint, which has no sing-box equivalent wired into this minimal Hysteria2
-// integration. A single hysteria2 inbound also has no outbounds to probe in the
-// first place (this backend's generated config only ever has a "direct"-style
-// egress). Returns an empty, non-error response so callers relying on the
-// Backend interface degrade gracefully instead of failing hard; a real
-// implementation is out of scope for this pass.
-func (s *SingBox) GetOutboundsLatency(ctx context.Context, request *common.LatencyRequest) (*common.LatencyResponse, error) {
- return &common.LatencyResponse{Latencies: []*common.Latency{}}, nil
-}
-
-// GetUserOnlineStats is a stub: sing-box's v2ray_api StatsService does not
-// track an "online" pseudo-counter the way xray-core does. Confirmed by
-// reading experimental/v2rayapi/stats.go on the dev box - RoutedConnection/
-// RoutedPacketConnection only ever create
-// "user>>>email>>>traffic>>>{uplink,downlink}" counters, there is no
-// "user>>>email>>>online" counter and no GetStatsOnline RPC on the service at
-// all (see api/proto/stats.proto - only GetStats/QueryStats/GetSysStats exist).
-// There is genuinely no data source to answer this from, so rather than
-// inventing a number this always reports 0.
-func (s *SingBox) GetUserOnlineStats(ctx context.Context, email string) (*common.OnlineStatResponse, error) {
- return &common.OnlineStatResponse{Name: email, Value: 0}, nil
-}
-
-// GetUserOnlineIpListStats is a stub for the same reason as
-// GetUserOnlineStats: sing-box's v2ray_api has no GetStatsOnlineIpList RPC or
-// any per-IP tracking to query, so there is nothing to report.
-func (s *SingBox) GetUserOnlineIpListStats(ctx context.Context, email string) (*common.StatsOnlineIpListResponse, error) {
- return &common.StatsOnlineIpListResponse{Name: email, Ips: map[string]int64{}}, nil
-}
diff --git a/backend/singbox/stats_ledger_test.go b/backend/singbox/stats_ledger_test.go
deleted file mode 100644
index 8d2ad720..00000000
--- a/backend/singbox/stats_ledger_test.go
+++ /dev/null
@@ -1,428 +0,0 @@
-package singbox
-
-import (
- "context"
- "errors"
- "fmt"
- "net"
- "sort"
- "strings"
- "sync"
- "sync/atomic"
- "testing"
-
- "google.golang.org/grpc"
-
- "github.com/pasarguard/node/backend/singbox/api"
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
-)
-
-const (
- ledgerHy2Down = "inbound>>>Hysteria2>>>traffic>>>downlink"
- ledgerHy2Up = "inbound>>>Hysteria2>>>traffic>>>uplink"
- ledgerAltDown = "inbound>>>Hysteria2-alt>>>traffic>>>downlink"
- ledgerOldDown = "inbound>>>old>>>traffic>>>downlink"
-)
-
-type ledgerFakeCore struct {
- statscmd.UnimplementedStatsServiceServer
-
- mu sync.Mutex
- counters map[string]*atomic.Int64
- requests []*statscmd.QueryStatsRequest
- failures int
-}
-
-func (f *ledgerFakeCore) add(name string, value int64) {
- f.mu.Lock()
- counter, ok := f.counters[name]
- if !ok {
- counter = new(atomic.Int64)
- f.counters[name] = counter
- }
- f.mu.Unlock()
- counter.Add(value)
-}
-
-func (f *ledgerFakeCore) remove(name string) {
- f.mu.Lock()
- delete(f.counters, name)
- f.mu.Unlock()
-}
-
-func (f *ledgerFakeCore) restart() {
- f.mu.Lock()
- f.counters = make(map[string]*atomic.Int64)
- f.mu.Unlock()
-}
-
-func (f *ledgerFakeCore) failNext() {
- f.mu.Lock()
- f.failures++
- f.mu.Unlock()
-}
-
-func (f *ledgerFakeCore) value(name string) int64 {
- f.mu.Lock()
- defer f.mu.Unlock()
- counter, ok := f.counters[name]
- if !ok {
- return 0
- }
- return counter.Load()
-}
-
-func (f *ledgerFakeCore) lastRequest() *statscmd.QueryStatsRequest {
- f.mu.Lock()
- defer f.mu.Unlock()
- if len(f.requests) == 0 {
- return nil
- }
- return f.requests[len(f.requests)-1]
-}
-
-func (f *ledgerFakeCore) QueryStats(_ context.Context, req *statscmd.QueryStatsRequest) (*statscmd.QueryStatsResponse, error) {
- f.mu.Lock()
- f.requests = append(f.requests, &statscmd.QueryStatsRequest{
- Patterns: append([]string(nil), req.GetPatterns()...),
- Reset_: req.GetReset_(),
- })
- if f.failures > 0 {
- f.failures--
- f.mu.Unlock()
- return nil, errors.New("fake stats service unavailable")
- }
- names := make([]string, 0, len(f.counters))
- counters := make(map[string]*atomic.Int64, len(f.counters))
- for name, counter := range f.counters {
- if !ledgerMatches(name, req.GetPatterns()) {
- continue
- }
- names = append(names, name)
- counters[name] = counter
- }
- f.mu.Unlock()
-
- sort.Strings(names)
- resp := &statscmd.QueryStatsResponse{}
- for _, name := range names {
- var value int64
- if req.GetReset_() {
- value = counters[name].Swap(0)
- } else {
- value = counters[name].Load()
- }
- resp.Stat = append(resp.Stat, &statscmd.Stat{Name: name, Value: value})
- }
- return resp, nil
-}
-
-func ledgerMatches(name string, patterns []string) bool {
- if len(patterns) == 0 {
- return true
- }
- for _, pattern := range patterns {
- if strings.Contains(name, pattern) {
- return true
- }
- }
- return false
-}
-
-func newLedgerSingBox(t *testing.T) (*SingBox, *ledgerFakeCore) {
- t.Helper()
-
- lis, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("listen: %v", err)
- }
- fake := &ledgerFakeCore{counters: make(map[string]*atomic.Int64)}
- srv := grpc.NewServer()
- statscmd.RegisterStatsServiceServer(srv, fake)
- go func() { _ = srv.Serve(lis) }()
- t.Cleanup(srv.Stop)
-
- client, err := api.NewClient(lis.Addr().(*net.TCPAddr).Port)
- if err != nil {
- t.Fatalf("NewClient: %v", err)
- }
- t.Cleanup(client.Close)
-
- return &SingBox{client: client}, fake
-}
-
-func ledgerRead(sb *SingBox, statType common.StatType, name string, reset bool) (map[string]int64, error) {
- resp, err := sb.GetStats(context.Background(), &common.StatRequest{Type: statType, Name: name, Reset_: reset})
- if err != nil {
- return nil, err
- }
- out := make(map[string]int64)
- for _, stat := range resp.GetStats() {
- out[stat.GetName()+"/"+stat.GetType()] += stat.GetValue()
- }
- return out, nil
-}
-
-func mustLedgerRead(t *testing.T, sb *SingBox, statType common.StatType, name string, reset bool) map[string]int64 {
- t.Helper()
- out, err := ledgerRead(sb, statType, name, reset)
- if err != nil {
- t.Fatalf("GetStats(%s, %q, reset=%v): %v", statType, name, reset, err)
- }
- return out
-}
-
-func expectLedger(t *testing.T, label string, got, want map[string]int64) {
- t.Helper()
- if len(got) != len(want) {
- t.Fatalf("%s: got %v, want %v", label, got, want)
- }
- for key, value := range want {
- if got[key] != value {
- t.Fatalf("%s: got %v, want %v", label, got, want)
- }
- }
-}
-
-func TestLedgerOutboundsThenInboundsEachReportAllTraffic(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerHy2Down, 1000)
-
- expectLedger(t, "outbounds", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 1000})
- expectLedger(t, "inbounds", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 1000})
-
- expectLedger(t, "outbounds again", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{})
- expectLedger(t, "inbounds again", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{})
-}
-
-func TestLedgerInboundsThenOutboundsEachReportAllTraffic(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerHy2Down, 1000)
-
- expectLedger(t, "inbounds", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 1000})
- expectLedger(t, "outbounds", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 1000})
-
- expectLedger(t, "inbounds again", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{})
- expectLedger(t, "outbounds again", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{})
-}
-
-func TestLedgerReadWithoutResetKeepsTheBalance(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerHy2Down, 1000)
-
- expectLedger(t, "inbounds without reset", mustLedgerRead(t, sb, common.StatType_Inbounds, "", false), map[string]int64{"Hysteria2/downlink": 1000})
- expectLedger(t, "inbounds with reset", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 1000})
-
- fake.add(ledgerHy2Down, 300)
- expectLedger(t, "inbounds newer traffic", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{"Hysteria2/downlink": 300})
- expectLedger(t, "outbounds all traffic", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 1300})
-}
-
-func TestLedgerSingleInboundAndOutboundByTag(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerHy2Down, 1000)
- fake.add(ledgerHy2Up, 400)
- fake.add(ledgerAltDown, 700)
-
- hy2 := map[string]int64{"Hysteria2/downlink": 1000, "Hysteria2/uplink": 400}
- expectLedger(t, "outbound Hysteria2", mustLedgerRead(t, sb, common.StatType_Outbound, "Hysteria2", true), hy2)
- expectLedger(t, "inbound Hysteria2", mustLedgerRead(t, sb, common.StatType_Inbound, "Hysteria2", true), hy2)
-
- alt := map[string]int64{"Hysteria2-alt/downlink": 700}
- expectLedger(t, "outbounds rest", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), alt)
- expectLedger(t, "inbounds rest", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), alt)
-
- expectLedger(t, "unknown tag", mustLedgerRead(t, sb, common.StatType_Inbound, "missing", true), map[string]int64{})
-}
-
-func TestLedgerSingleReadsStillRequireATag(t *testing.T) {
- sb, _ := newLedgerSingBox(t)
-
- for _, statType := range []common.StatType{common.StatType_Outbound, common.StatType_Inbound} {
- if _, err := ledgerRead(sb, statType, "", true); err == nil {
- t.Fatalf("GetStats(%s) with an empty tag returned no error", statType)
- }
- }
-}
-
-func TestLedgerCoreRestartLosesNothingCollected(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerHy2Down, 1000)
-
- expectLedger(t, "outbounds before restart", mustLedgerRead(t, sb, common.StatType_Outbounds, "", false), map[string]int64{"Hysteria2/downlink": 1000})
-
- fake.restart()
- fake.add(ledgerHy2Down, 500)
-
- want := map[string]int64{"Hysteria2/downlink": 1500}
- expectLedger(t, "outbounds after restart", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), want)
- expectLedger(t, "inbounds after restart", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), want)
-
- expectLedger(t, "outbounds drained", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{})
- expectLedger(t, "inbounds drained", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{})
-}
-
-func TestLedgerConcurrentReadsEachSeeTheExactTotal(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerHy2Down, 1000)
- fake.add(ledgerHy2Up, 1000)
-
- const readers = 50
- const writers = 10
- const writes = 200
-
- var sumMu sync.Mutex
- sums := map[common.StatType]map[string]int64{
- common.StatType_Outbounds: {},
- common.StatType_Inbounds: {},
- }
- record := func(statType common.StatType, got map[string]int64) {
- sumMu.Lock()
- defer sumMu.Unlock()
- for key, value := range got {
- sums[statType][key] += value
- }
- }
-
- errs := make(chan error, 2*readers)
- start := make(chan struct{})
- var wg sync.WaitGroup
- for i := 0; i < readers; i++ {
- for _, statType := range []common.StatType{common.StatType_Outbounds, common.StatType_Inbounds} {
- wg.Add(1)
- go func(statType common.StatType) {
- defer wg.Done()
- <-start
- got, err := ledgerRead(sb, statType, "", true)
- if err != nil {
- errs <- err
- return
- }
- record(statType, got)
- }(statType)
- }
- }
- for i := 0; i < writers; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- <-start
- for j := 0; j < writes; j++ {
- fake.add(ledgerHy2Down, int64(i+1))
- fake.add(ledgerHy2Up, 3)
- }
- }(i)
- }
- close(start)
- wg.Wait()
- close(errs)
- for err := range errs {
- t.Fatalf("concurrent read failed: %v", err)
- }
-
- for _, statType := range []common.StatType{common.StatType_Outbounds, common.StatType_Inbounds} {
- got := mustLedgerRead(t, sb, statType, "", true)
- record(statType, got)
- }
-
- var down int64 = 1000
- for i := 0; i < writers; i++ {
- down += int64(i+1) * writes
- }
- want := map[string]int64{
- "Hysteria2/downlink": down,
- "Hysteria2/uplink": 1000 + 3*writers*writes,
- }
- expectLedger(t, "outbounds series", sums[common.StatType_Outbounds], want)
- expectLedger(t, "inbounds series", sums[common.StatType_Inbounds], want)
-}
-
-func TestLedgerDrainErrorKeepsTheBalance(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerHy2Down, 1000)
-
- fake.failNext()
- if _, err := ledgerRead(sb, common.StatType_Outbounds, "", true); err == nil {
- t.Fatal("a failed drain returned no error")
- }
-
- want := map[string]int64{"Hysteria2/downlink": 1000}
- expectLedger(t, "outbounds after error", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), want)
-
- fake.failNext()
- if _, err := ledgerRead(sb, common.StatType_Inbounds, "", true); err == nil {
- t.Fatal("a failed drain returned no error")
- }
- expectLedger(t, "inbounds after error", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), want)
-}
-
-func TestLedgerUsersStatStillReadsTheCoreCounters(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add("user>>>alice@example.com>>>traffic>>>uplink", 111)
- fake.add("user>>>bob@example.com>>>traffic>>>downlink", 222)
- fake.add(ledgerHy2Down, 1000)
-
- expectLedger(t, "outbounds", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{"Hysteria2/downlink": 1000})
-
- resp, err := sb.GetStats(context.Background(), &common.StatRequest{Type: common.StatType_UsersStat, Reset_: true})
- if err != nil {
- t.Fatalf("UsersStat: %v", err)
- }
- req := fake.lastRequest()
- if req == nil || len(req.GetPatterns()) != 1 || req.GetPatterns()[0] != "user>>>" || !req.GetReset_() {
- t.Fatalf("UsersStat reached the core as %+v, want Patterns=[user>>>] Reset_=true", req)
- }
- got := make([]string, 0, len(resp.GetStats()))
- for _, stat := range resp.GetStats() {
- got = append(got, fmt.Sprintf("%s|%s|%s|%d", stat.GetName(), stat.GetLink(), stat.GetType(), stat.GetValue()))
- }
- sort.Strings(got)
- want := []string{"alice@example.com|traffic|uplink|111", "bob@example.com|traffic|downlink|222"}
- if strings.Join(got, ",") != strings.Join(want, ",") {
- t.Fatalf("UsersStat = %v, want %v", got, want)
- }
- if fake.value("user>>>alice@example.com>>>traffic>>>uplink") != 0 {
- t.Fatal("UsersStat with reset did not reset the core's user counter")
- }
-
- if _, err := sb.GetStats(context.Background(), &common.StatRequest{Type: common.StatType_UserStat, Name: "alice@example.com"}); err != nil {
- t.Fatalf("UserStat: %v", err)
- }
- req = fake.lastRequest()
- if req == nil || len(req.GetPatterns()) != 1 || req.GetPatterns()[0] != "user>>>alice@example.com>>>" || req.GetReset_() {
- t.Fatalf("UserStat reached the core as %+v, want Patterns=[user>>>alice@example.com>>>] Reset_=false", req)
- }
-}
-
-func TestLedgerRemovedInboundIsReportedOnceMore(t *testing.T) {
- sb, fake := newLedgerSingBox(t)
- fake.add(ledgerOldDown, 900)
- fake.add(ledgerHy2Down, 100)
-
- both := map[string]int64{"old/downlink": 900, "Hysteria2/downlink": 100}
- expectLedger(t, "inbounds without reset", mustLedgerRead(t, sb, common.StatType_Inbounds, "", false), both)
-
- fake.remove(ledgerOldDown)
-
- expectLedger(t, "outbounds", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), both)
- expectLedger(t, "inbounds", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), both)
-
- expectLedger(t, "outbounds again", mustLedgerRead(t, sb, common.StatType_Outbounds, "", true), map[string]int64{})
- expectLedger(t, "inbounds again", mustLedgerRead(t, sb, common.StatType_Inbounds, "", true), map[string]int64{})
-}
-
-func TestLedgerWithoutACoreClientReturnsAnError(t *testing.T) {
- defer func() {
- if r := recover(); r != nil {
- t.Fatalf("GetStats without a core client panicked: %v", r)
- }
- }()
-
- sb := &SingBox{}
- for _, statType := range []common.StatType{common.StatType_Outbounds, common.StatType_Inbounds} {
- if _, err := ledgerRead(sb, statType, "", true); err == nil {
- t.Fatalf("GetStats(%s) without a core client returned no error", statType)
- }
- }
-}
diff --git a/backend/singbox/test_ports_test.go b/backend/singbox/test_ports_test.go
deleted file mode 100644
index 2b60b6c5..00000000
--- a/backend/singbox/test_ports_test.go
+++ /dev/null
@@ -1,133 +0,0 @@
-package singbox
-
-import (
- "math/rand/v2"
- "net"
- "os"
- "sort"
- "strconv"
- "strings"
- "sync"
- "testing"
- "time"
-)
-
-const (
- lowestTestPort = 20000
- testPortSpan = 12000
-)
-
-func loopbackPortsBelowTheEphemeralRange(t *testing.T, count int) int {
- t.Helper()
- for range 200 {
- first := lowestTestPort + rand.IntN(testPortSpan-count)
- if loopbackPortsFree(first, count) {
- return first
- }
- }
- t.Fatalf("no %d adjacent free loopback ports in [%d, %d)", count, lowestTestPort, lowestTestPort+testPortSpan)
- return 0
-}
-
-func loopbackPortsFree(first, count int) bool {
- listeners := make([]net.Listener, 0, count)
- defer func() {
- for _, listener := range listeners {
- _ = listener.Close()
- }
- }()
- for port := first; port < first+count; port++ {
- listener, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
- if err != nil {
- return false
- }
- listeners = append(listeners, listener)
- }
- return true
-}
-
-func singBoxAPIPorts(t *testing.T) (int, int) {
- t.Helper()
- first := loopbackPortsBelowTheEphemeralRange(t, 2)
- return first, first + 1
-}
-
-func TestTestPortsStayBelowTheEphemeralRangeAndAreFree(t *testing.T) {
- if raw, err := os.ReadFile("/proc/sys/net/ipv4/ip_local_port_range"); err == nil {
- fields := strings.Fields(string(raw))
- if len(fields) != 2 {
- t.Fatalf("unreadable ephemeral port range %q", raw)
- }
- first, err := strconv.Atoi(fields[0])
- if err != nil {
- t.Fatalf("unreadable ephemeral port range %q: %v", raw, err)
- }
- if lowestTestPort+testPortSpan > first {
- t.Fatalf("the test port band [%d, %d) reaches into this host's ephemeral range %s", lowestTestPort, lowestTestPort+testPortSpan, strings.Join(fields, "-"))
- }
- t.Logf("ephemeral range %s, test port band [%d, %d)", strings.Join(fields, "-"), lowestTestPort, lowestTestPort+testPortSpan)
- }
- for range 50 {
- statsPort, clashPort := singBoxAPIPorts(t)
- for _, port := range []int{statsPort, clashPort} {
- if port < lowestTestPort || port >= lowestTestPort+testPortSpan {
- t.Fatalf("API port %d is outside [%d, %d)", port, lowestTestPort, lowestTestPort+testPortSpan)
- }
- if !loopbackPortsFree(port, 1) {
- t.Fatalf("API port %d is not free", port)
- }
- }
- if statsPort == clashPort {
- t.Fatalf("the stats and clash API ports are both %d", statsPort)
- }
- }
- held, err := net.Listen("tcp4", "127.0.0.1:0")
- if err != nil {
- t.Fatal(err)
- }
- defer held.Close()
- if loopbackPortsFree(held.Addr().(*net.TCPAddr).Port, 1) {
- t.Fatal("a port held by a listener was reported free")
- }
-}
-
-var (
- trafficHostOnce sync.Once
- trafficHost string
-)
-
-func userTrafficHost(t *testing.T) string {
- t.Helper()
- trafficHostOnce.Do(func() {
- addrs, err := net.InterfaceAddrs()
- if err != nil {
- return
- }
- var candidates []string
- for _, addr := range addrs {
- if ipNet, ok := addr.(*net.IPNet); ok {
- if ip := ipNet.IP.To4(); ip != nil && !ip.IsLoopback() && !ip.IsLinkLocalUnicast() && !ip.IsUnspecified() {
- candidates = append(candidates, ip.String())
- }
- }
- }
- sort.Strings(candidates)
- for _, candidate := range candidates {
- listener, err := net.Listen("tcp4", net.JoinHostPort(candidate, "0"))
- if err != nil {
- continue
- }
- conn, err := net.DialTimeout("tcp4", listener.Addr().String(), time.Second)
- _ = listener.Close()
- if err == nil {
- _ = conn.Close()
- trafficHost = candidate
- return
- }
- }
- })
- if trafficHost == "" {
- t.Skip("this host has no reachable non-loopback IPv4 address to place user traffic targets on")
- }
- return trafficHost
-}
diff --git a/backend/singbox/user.go b/backend/singbox/user.go
deleted file mode 100644
index 1748b385..00000000
--- a/backend/singbox/user.go
+++ /dev/null
@@ -1,485 +0,0 @@
-package singbox
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "log"
- "net/http"
- "net/url"
- "strings"
- "time"
-
- "github.com/pasarguard/node/common"
-)
-
-// userEntryForType extracts the sing-box user object a given inbound type needs
-// from a common.User, if that user actually has the matching proxy sub-message
-// configured. The name is always the user's email. Returns false when the user
-// has no email or no proxy of that type.
-//
-// - hysteria2 -> {name, password}
-// - vless -> {name, uuid, flow}
-// - vmess -> {name, uuid}
-// - trojan -> {name, password}
-// - shadowsocks -> {name, password}
-// - tuic -> {name, uuid, password}
-func userEntryForType(user *common.User, typ string) (userEntry, bool) {
- email := user.GetEmail()
- if email == "" {
- return userEntry{}, false
- }
- proxies := user.GetProxies()
- switch typ {
- case "hysteria2":
- p := proxies.GetHysteria2()
- if p.GetPassword() == "" {
- return userEntry{}, false
- }
- return userEntry{Name: email, Password: p.GetPassword()}, true
- case "vless":
- p := proxies.GetVless()
- if p == nil {
- return userEntry{}, false
- }
- return userEntry{Name: email, UUID: p.GetId(), Flow: p.GetFlow()}, true
- case "vmess":
- p := proxies.GetVmess()
- if p == nil {
- return userEntry{}, false
- }
- return userEntry{Name: email, UUID: p.GetId()}, true
- case "trojan":
- p := proxies.GetTrojan()
- if p == nil {
- return userEntry{}, false
- }
- return userEntry{Name: email, Password: p.GetPassword()}, true
- case "shadowsocks":
- p := proxies.GetShadowsocks()
- if p == nil {
- return userEntry{}, false
- }
- return userEntry{Name: email, Password: p.GetPassword()}, true
- case "tuic":
- p := proxies.GetTuic()
- if p == nil {
- return userEntry{}, false
- }
- return userEntry{Name: email, UUID: p.GetUuid(), Password: p.GetPassword()}, true
- default:
- return userEntry{}, false
- }
-}
-
-// syncUsers replaces the full user list of every indexed inbound: a user is
-// kept on an inbound only if it (a) carries the proxy sub-message matching that
-// inbound's type and (b) lists the inbound's tag in its Inbounds. Mirrors xray's
-// Config.syncUsers (full resync).
-func (c *Config) syncUsers(users []*common.User) {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- for _, inbound := range c.inbounds {
- inbound.users = make(map[string]userEntry)
- }
-
- for _, user := range users {
- for _, tag := range user.GetInbounds() {
- inbound, ok := c.inbounds[tag]
- if !ok {
- continue
- }
- entry, ok := userEntryForType(user, inbound.typ)
- if !ok {
- continue
- }
- inbound.users[entry.Name] = entry
- }
- }
-}
-
-// updateUsers upserts/removes only the given users against every indexed
-// inbound, leaving all other already-synced users untouched. A user is
-// added/updated on an inbound's tag if it is active there (has the matching
-// proxy for that inbound's type and lists that tag), otherwise it is removed
-// from that inbound if present. Mirrors xray's Config.updateUsers/
-// buildInboundUpdates incremental-merge semantics.
-func (c *Config) updateUsers(users []*common.User) {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- for _, user := range users {
- email := user.GetEmail()
- if email == "" {
- continue
- }
-
- activeTags := make(map[string]struct{})
- for _, tag := range user.GetInbounds() {
- activeTags[tag] = struct{}{}
- }
-
- for tag, inbound := range c.inbounds {
- if _, isActive := activeTags[tag]; isActive {
- if entry, ok := userEntryForType(user, inbound.typ); ok {
- inbound.users[email] = entry
- continue
- }
- }
- delete(inbound.users, email)
- }
- }
-}
-
-// upsertUser is the single-user form of updateUsers, used by SyncUser.
-func (c *Config) upsertUser(user *common.User) {
- c.updateUsers([]*common.User{user})
-}
-
-// singBoxSyncDebounceWindow is how long enqueueSync waits, after the most
-// recent call to join a batch, before flushing it - it slides forward on
-// every new call that joins an in-flight batch, so a trickle of syncs a
-// couple seconds apart keeps extending the wait instead of each one
-// triggering its own restart.
-//
-// singBoxSyncDebounceMaxWait caps that sliding window so sustained load
-// can't delay a batch indefinitely: once this much time has passed since
-// the batch's first call, it flushes regardless of how recently the last
-// one joined.
-//
-// Both values come from live production log analysis: restart gaps
-// (each one a separate SyncUser call, each disconnecting every Hysteria2
-// user on the node) ranged from ~1s to ~25s apart. A single fixed window
-// can only ever catch bursts tighter than itself - short windows miss
-// most of that spread, long ones needlessly delay genuinely isolated
-// syncs. The sliding window keeps genuinely close-together syncs merged
-// however long the burst runs, while the max-wait cap keeps that bound
-// well clear of the widely-spaced (13s, 25s) gaps that should just apply
-// on their own.
-const (
- singBoxSyncDebounceWindow = 2 * time.Second
- singBoxSyncDebounceMaxWait = 8 * time.Second
-)
-
-// singBoxPendingBatch accumulates config mutators from every SyncUser/
-// SyncUsers/UpdateUsers call that arrives during one debounce window, so
-// they can all be applied with a single restart. done is closed (not sent
-// on) once the batch's restart has completed, waking every caller waiting
-// on it at once; err is only safe to read after that close happens-before
-// relationship. mutators/lastActivity/deadline are only ever read or
-// written while holding the owning SingBox's batchMu.
-type singBoxPendingBatch struct {
- mutators []func(*Config)
- done chan struct{}
- err error
- lastActivity time.Time
- deadline time.Time
-}
-
-// SyncUser applies a single user's membership across all indexed inbounds and
-// applies the resulting config to sing-box.
-//
-// Deviation from xray worth double-checking: xray's SyncUser/UpdateUsers add or
-// remove a user live via the xray HandlerService gRPC API with no core restart.
-// sing-box's experimental.v2ray_api only registers a StatsService (confirmed by
-// reading experimental/v2rayapi/server.go on the dev box - only
-// RegisterStatsServiceServer is called, there is no handler/proxyman-command
-// equivalent). Our custom sing-box fork instead exposes a clash_api
-// /inbounds/{tag}/users endpoint that lets us swap an inbound's user set live;
-// when that endpoint is available every one of SyncUser/SyncUsers/UpdateUsers/
-// UpdateUsersAndRestart applies with no restart. When it is not (older sing-box,
-// api unreachable, or a rejected update) they fall back to rewriting the config
-// file and restarting the process (brief connection drop for all users on this
-// node). enqueueSync (below) coalesces rapid successive calls so that fallback
-// restart, when it happens, happens as infrequently as possible.
-func (s *SingBox) SyncUser(ctx context.Context, user *common.User) error {
- return s.enqueueSync(func(c *Config) { c.upsertUser(user) })
-}
-
-// SyncUsers fully replaces the user list on every indexed inbound and applies
-// the resulting config to sing-box.
-func (s *SingBox) SyncUsers(ctx context.Context, users []*common.User) error {
- return s.enqueueSync(func(c *Config) { c.syncUsers(users) })
-}
-
-// UpdateUsers incrementally merges the given users and applies the resulting
-// config to sing-box.
-//
-// Note: kept as a distinct method (rather than aliasing) to preserve the
-// Backend interface's semantics/call sites; on the fallback path it behaves
-// identically to UpdateUsersAndRestart.
-func (s *SingBox) UpdateUsers(ctx context.Context, users []*common.User) error {
- return s.enqueueSync(func(c *Config) { c.updateUsers(users) })
-}
-
-// UpdateUsersAndRestart behaves identically to UpdateUsers on this backend -
-// see UpdateUsers's doc comment.
-func (s *SingBox) UpdateUsersAndRestart(ctx context.Context, users []*common.User) error {
- return s.UpdateUsers(ctx, users)
-}
-
-// enqueueSync merges concurrent/rapid-succession user-sync requests into a
-// single restart instead of one restart per call. Every caller that lands in
-// the same batch still blocks until that batch's restart is confirmed applied
-// (or failed) and gets that exact result back, preserving the original
-// synchronous contract of SyncUser/SyncUsers/UpdateUsers - only the number of
-// underlying restarts changes, not the caller-visible semantics.
-func (s *SingBox) enqueueSync(mutate func(*Config)) error {
- b := s.enqueue(mutate)
- <-b.done
- return b.err
-}
-
-// QueueUser adds user's membership to the current (or a new) pending batch and
-// returns immediately, without waiting for that batch to flush.
-//
-// Why this exists alongside enqueueSync/SyncUser: the panel's node bridge
-// sends a burst of individually-queued users to this node over ONE
-// client-streaming SyncUser RPC - the controller/rpc layer's loop calls
-// stream.Recv() for the next message only after backend.SyncUser() returns
-// for the current one. If SyncUser blocks until its batch flushes (as
-// enqueueSync does), that receive loop stalls for the same duration, so the
-// next already-in-flight message on the wire is never read in time to join
-// the same batch - every message ends up starting (and waiting out) its own
-// batch, and coalescing never actually happens despite the debounce logic
-// being "correct" in isolation. This was caught by burst-testing against a
-// real panel: 8 users synced back-to-back on one stream still produced 7
-// restarts.
-//
-// QueueUser breaks that stall: the controller/rpc layer calls this instead
-// of SyncUser when the backend supports it (see the nonBlockingUserSyncer
-// interface check in controller/rpc/user.go), so it can immediately go back
-// to stream.Recv() for the next message. Every message already sent by the
-// client lands in the same batch, and the whole stream's worth of users
-// restarts sing-box exactly once.
-//
-// Trade-off: the caller no longer learns whether the eventual restart
-// succeeds (the stream ack now just means "queued", not "applied"). A failed
-// flush is logged from flushBatch instead of returned to a waiter. This is
-// judged acceptable because a failing restart is an infrastructure problem
-// (bad generated config, sing-box binary/env issue) rather than something
-// retryable per-user, and it will surface again on the very next sync for
-// any of the same users.
-func (s *SingBox) QueueUser(ctx context.Context, user *common.User) error {
- s.enqueue(func(c *Config) { c.upsertUser(user) })
- return nil
-}
-
-// enqueue adds mutate to the current pending batch (starting a new one and
-// scheduling its flush check if none is pending) and returns that batch
-// without waiting on it - enqueueSync blocks on the returned batch's done
-// channel itself, QueueUser does not.
-func (s *SingBox) enqueue(mutate func(*Config)) *singBoxPendingBatch {
- s.batchMu.Lock()
- b := s.batch
- isNew := b == nil
- now := time.Now()
- if isNew {
- b = &singBoxPendingBatch{
- done: make(chan struct{}),
- deadline: now.Add(singBoxSyncDebounceMaxWait),
- }
- s.batch = b
- }
- b.mutators = append(b.mutators, mutate)
- b.lastActivity = now
- s.batchMu.Unlock()
-
- if isNew {
- s.scheduleFlushCheck(b)
- }
-
- return b
-}
-
-// scheduleFlushCheck flushes b once singBoxSyncDebounceWindow has passed
-// with no further calls joining it, or once singBoxSyncDebounceMaxWait has
-// elapsed since it was created, whichever comes first. It re-schedules
-// itself with a fresh timer rather than resetting an existing one, which
-// sidesteps the well-known race between time.Timer.Reset and a timer that
-// may have already fired (see the time.Timer docs) at the cost of a few
-// harmless extra timer firings under sustained load. Because this chain
-// only ever calls flushBatch(b) once and then stops (it returns instead of
-// rescheduling right after), b.done can never be closed twice.
-func (s *SingBox) scheduleFlushCheck(b *singBoxPendingBatch) {
- time.AfterFunc(singBoxSyncDebounceWindow, func() {
- s.batchMu.Lock()
- if s.batch != b {
- // Already flushed.
- s.batchMu.Unlock()
- return
- }
- quiet := time.Since(b.lastActivity)
- atDeadline := !time.Now().Before(b.deadline)
- s.batchMu.Unlock()
-
- if quiet >= singBoxSyncDebounceWindow || atDeadline {
- s.flushBatch(b)
- return
- }
- s.scheduleFlushCheck(b)
- })
-}
-
-// flushBatch applies every mutator collected in b to a single cloned
-// candidate config and applies it to sing-box once for the whole batch.
-// Detaching b from s.batch happens before the (potentially slow) restart so
-// calls arriving while a restart is already in flight start a fresh batch
-// instead of blocking indefinitely on batchMu.
-func (s *SingBox) flushBatch(b *singBoxPendingBatch) {
- s.batchMu.Lock()
- if s.batch == b {
- s.batch = nil
- }
- mutators := b.mutators
- s.batchMu.Unlock()
-
- s.syncMu.Lock()
- defer s.syncMu.Unlock()
-
- candidate, err := s.config.Clone()
- if err == nil {
- for _, m := range mutators {
- m(candidate)
- }
- if s.config.sameUsers(candidate) {
- // The batch's net effect left every indexed inbound's user set
- // unchanged - the common case, since most syncs are traffic/online
- // updates or touch users in no indexed inbound. A restart here
- // would drop every session for nothing, so adopt the candidate
- // (cheap, keeps other fields current) without one.
- s.setConfig(candidate)
- } else if reloadErr := s.hotReloadUsersUnlessShutDown(candidate); reloadErr == nil {
- // The user set changed, but our custom sing-box lets us swap it live
- // through the clash_api /inbounds/{tag}/users endpoint (like xray's
- // HandlerService) - so the change takes effect with zero restart and
- // zero dropped sessions. Adopt the candidate to keep the stored
- // config current for the next real restart.
- s.setConfig(candidate)
- } else {
- // Live update unavailable (older sing-box without the endpoint, api
- // unreachable, or the update was rejected) - fall back to the safe
- // restart path so the change is never silently lost.
- log.Printf("sing-box: user hot-reload unavailable, falling back to restart: %v", reloadErr)
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- err = s.applyConfigWithRestart(ctx, candidate)
- cancel()
- }
- }
-
- if err != nil {
- log.Printf("sing-box: batched user sync failed (%d user(s) in batch): %v", len(mutators), err)
- }
-
- b.err = err
- close(b.done)
-}
-
-func (s *SingBox) hotReloadUsersUnlessShutDown(candidate *Config) error {
- s.mu.RLock()
- defer s.mu.RUnlock()
- if s.shutDown {
- return errShutDown
- }
- return s.hotReloadUsers(candidate)
-}
-
-// hotReloadUsers pushes every indexed inbound's user set from the candidate
-// into the already-running core via the clash_api /inbounds/{tag}/users
-// endpoint our custom sing-box exposes. On success the change is live with no
-// restart and no dropped sessions - the sing-box counterpart to xray's live
-// AddUser/RemoveUser. Any failure (endpoint absent on an older sing-box, api
-// unreachable, or a rejected update on any tag) is returned so the caller falls
-// back to the restart path and the change is never lost.
-func (s *SingBox) hotReloadUsers(candidate *Config) error {
- port := candidate.ClashPort()
- if port == 0 {
- return fmt.Errorf("clash api port is not set")
- }
- sets := candidate.UserSets()
- if len(sets) == 0 {
- return nil
- }
- secret := candidate.clashAPISecret()
- client := &http.Client{Timeout: 5 * time.Second}
- for tag, set := range sets {
- endpoint := fmt.Sprintf("http://127.0.0.1:%d/inbounds/%s/users", port, url.PathEscape(tag))
- body, err := json.Marshal(map[string]any{"type": set.Type, "users": set.Users})
- if err != nil {
- return err
- }
- req, err := http.NewRequest(http.MethodPut, endpoint, bytes.NewReader(body))
- if err != nil {
- return err
- }
- req.Header.Set("Content-Type", "application/json")
- if secret != "" {
- req.Header.Set("Authorization", "Bearer "+secret)
- }
- resp, err := client.Do(req)
- if err != nil {
- return fmt.Errorf("user hot-reload for %q: %w", tag, err)
- }
- respBody, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- return fmt.Errorf("user hot-reload for %q: status %d: %s", tag, resp.StatusCode, strings.TrimSpace(withoutSecret(string(respBody), secret)))
- }
- }
- return nil
-}
-
-// applyConfigWithRestart restarts the core with candidate, waits for the API to
-// become healthy, and rolls back to the previous config on any failure. Mirrors
-// xray's Xray.applyConfigWithRestart/restorePreviousConfig.
-func (s *SingBox) applyConfigWithRestart(ctx context.Context, candidate *Config) error {
- previous := s.config
-
- if err := s.restartCoreWithConfig(candidate); err != nil {
- if restoreErr := s.restorePreviousConfig(previous); restoreErr != nil {
- return fmt.Errorf("%w; failed to restore previous sing-box config: %v", err, restoreErr)
- }
- return err
- }
-
- if err := s.checkStatus(ctx); err != nil {
- if restoreErr := s.restorePreviousConfig(previous); restoreErr != nil {
- return fmt.Errorf("%w; failed to restore previous sing-box config: %v", err, restoreErr)
- }
- return err
- }
-
- s.setConfig(candidate)
- return nil
-}
-
-func (s *SingBox) restorePreviousConfig(previous *Config) error {
- if previous == nil {
- return errors.New("previous sing-box config is nil")
- }
-
- log.Println("restoring previous sing-box config after failed restart")
- if err := s.restartCoreWithConfig(previous); err != nil {
- return err
- }
-
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := s.checkStatus(ctx); err != nil {
- return err
- }
-
- s.setConfig(previous)
- return nil
-}
-
-func withoutSecret(text, secret string) string {
- if secret == "" {
- return text
- }
- return strings.ReplaceAll(text, secret, maskedClashSecret)
-}
diff --git a/backend/singbox/user_counters.go b/backend/singbox/user_counters.go
deleted file mode 100644
index cbd46bb5..00000000
--- a/backend/singbox/user_counters.go
+++ /dev/null
@@ -1,169 +0,0 @@
-package singbox
-
-import (
- "context"
- "log"
- "strings"
- "sync"
- "time"
-
- "github.com/pasarguard/node/backend/singbox/api"
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
-)
-
-const (
- userCounterPrefix = "user>>>"
- counterCarryTimeout = 5 * time.Second
-)
-
-type userCarry struct {
- mu sync.Mutex
- values map[string]int64
-}
-
-func (c *userCarry) keep(ctx context.Context, client *api.Client) error {
- resp, err := client.QueryStats(ctx, userCounterPrefix, true)
- if err != nil {
- return err
- }
-
- c.mu.Lock()
- defer c.mu.Unlock()
- for _, stat := range resp.GetStat() {
- if stat.GetValue() == 0 {
- continue
- }
- if c.values == nil {
- c.values = make(map[string]int64)
- }
- c.values[stat.GetName()] += stat.GetValue()
- }
- return nil
-}
-
-func (c *userCarry) take() map[string]int64 {
- c.mu.Lock()
- defer c.mu.Unlock()
- values := c.values
- c.values = nil
- return values
-}
-
-func (c *userCarry) adopt(values map[string]int64) {
- c.mu.Lock()
- defer c.mu.Unlock()
- for name, value := range values {
- if value == 0 {
- continue
- }
- if c.values == nil {
- c.values = make(map[string]int64)
- }
- c.values[name] += value
- }
-}
-
-func (c *userCarry) read(ctx context.Context, client *api.Client, pattern string, reset bool) (*common.StatResponse, error) {
- resp, err := client.QueryStats(ctx, pattern, reset)
- if err != nil {
- return nil, err
- }
- return api.BuildStatResponse(c.merge(pattern, resp.GetStat(), reset)), nil
-}
-
-func (c *userCarry) merge(pattern string, live []*statscmd.Stat, reset bool) []*statscmd.Stat {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- if len(c.values) == 0 {
- return live
- }
-
- position := make(map[string]int, len(live))
- for index, stat := range live {
- position[stat.GetName()] = index
- }
- for name, value := range c.values {
- if !strings.Contains(name, pattern) {
- continue
- }
- if index, ok := position[name]; ok {
- live[index] = &statscmd.Stat{Name: name, Value: live[index].GetValue() + value}
- } else {
- position[name] = len(live)
- live = append(live, &statscmd.Stat{Name: name, Value: value})
- }
- if reset {
- delete(c.values, name)
- }
- }
- return live
-}
-
-func (s *SingBox) carryUnreadCounters() bool {
- s.drainMu.Lock()
- defer s.drainMu.Unlock()
- return s.drainUnreadCounters()
-}
-
-func (s *SingBox) drainUnreadCounters() bool {
- if s.client == nil || s.core == nil || !s.core.Started() {
- return false
- }
- ctx, cancel := context.WithTimeout(context.Background(), counterCarryTimeout)
- defer cancel()
- return s.keepUnreadCounters(ctx)
-}
-
-func (s *SingBox) keepUnreadCounters(ctx context.Context) bool {
- answered := true
- if err := s.users.keep(ctx, s.client); err != nil {
- log.Printf("sing-box: the unread user counters could not be read before the restart and are lost with the old core: %v", err)
- answered = false
- }
- if err := s.inbounds.keep(ctx, s.client); err != nil {
- log.Printf("sing-box: the unread inbound counters could not be read before the restart and are lost with the old core: %v", err)
- answered = false
- }
- return answered
-}
-
-var carriedLedgerPrefixes = [...]string{consumerOutbounds: "outbounds|", consumerInbounds: "inbounds|"}
-
-func (s *SingBox) TakeUnreadCounters() map[string]int64 {
- values := s.users.take()
- for consumer, balance := range s.inbounds.take() {
- for name, value := range balance {
- if value == 0 {
- continue
- }
- if values == nil {
- values = make(map[string]int64)
- }
- values[carriedLedgerPrefixes[consumer]+name] += value
- }
- }
- return values
-}
-
-func (s *SingBox) AdoptUnreadCounters(values map[string]int64) {
- users := make(map[string]int64)
- var ledger [2]map[string]int64
- for name, value := range values {
- if strings.HasPrefix(name, userCounterPrefix) {
- users[name] += value
- continue
- }
- for consumer, prefix := range carriedLedgerPrefixes {
- if counter, ok := strings.CutPrefix(name, prefix); ok {
- if ledger[consumer] == nil {
- ledger[consumer] = make(map[string]int64)
- }
- ledger[consumer][counter] += value
- }
- }
- }
- s.users.adopt(users)
- s.inbounds.adopt(ledger)
-}
diff --git a/backend/xray/api/speedcap.go b/backend/xray/api/speedcap.go
new file mode 100644
index 00000000..dd5c2f98
--- /dev/null
+++ b/backend/xray/api/speedcap.go
@@ -0,0 +1,57 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "strings"
+
+ "github.com/xtls/xray-core/common/serial"
+ "google.golang.org/protobuf/encoding/protowire"
+
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+const setUserSpeedsOperationType = "xray.app.proxyman.speedcap.SetUserSpeedsOperation"
+
+var ErrSpeedCapUnsupported = errors.New("xray core does not support SetUserSpeedsOperation")
+
+func appendVarintField(b []byte, number protowire.Number, value uint64) []byte {
+ if value == 0 {
+ return b
+ }
+ b = protowire.AppendTag(b, number, protowire.VarintType)
+ return protowire.AppendVarint(b, value)
+}
+
+func SetUserSpeedsOperation(change speedcap.Change) *serial.TypedMessage {
+ var value []byte
+ for _, entry := range change.Entries {
+ var item []byte
+ if entry.Email != "" {
+ item = protowire.AppendTag(item, 1, protowire.BytesType)
+ item = protowire.AppendString(item, entry.Email)
+ }
+ item = appendVarintField(item, 2, entry.Down)
+ item = appendVarintField(item, 3, entry.Up)
+ item = appendVarintField(item, 4, entry.Revision)
+ for _, tag := range entry.InboundTags {
+ item = protowire.AppendTag(item, 5, protowire.BytesType)
+ item = protowire.AppendString(item, tag)
+ }
+ value = protowire.AppendTag(value, 1, protowire.BytesType)
+ value = protowire.AppendBytes(value, item)
+ }
+ if change.ReplaceAll {
+ value = appendVarintField(value, 2, 1)
+ }
+ value = appendVarintField(value, 3, change.Snapshot)
+ return &serial.TypedMessage{Type: setUserSpeedsOperationType, Value: value}
+}
+
+func (x *XrayHandler) SetUserSpeeds(ctx context.Context, tag string, change speedcap.Change) error {
+ err := x.AlertInbound(ctx, tag, SetUserSpeedsOperation(change))
+ if err != nil && strings.Contains(err.Error(), "unknown operation") {
+ return ErrSpeedCapUnsupported
+ }
+ return err
+}
diff --git a/backend/xray/api/speedcap_test.go b/backend/xray/api/speedcap_test.go
new file mode 100644
index 00000000..88d90d4b
--- /dev/null
+++ b/backend/xray/api/speedcap_test.go
@@ -0,0 +1,85 @@
+package api
+
+import (
+ "bytes"
+ "encoding/hex"
+ "testing"
+
+ "google.golang.org/protobuf/proto"
+
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+func TestSetUserSpeedsOperationHasTheNodeRequestWireLayout(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ change speedcap.Change
+ }{
+ {"empty scoped diff", speedcap.Change{}},
+ {"scoped diff", speedcap.Change{Entries: []speedcap.Entry{
+ {Email: "12", Down: 10_000_000, Revision: 7},
+ {Email: "13", Down: 20_000_000, Up: 5_000_000, Revision: 1_733_000_000_000_001},
+ {Email: "14", Revision: 9},
+ }}},
+ {"snapshot", speedcap.Change{ReplaceAll: true, Snapshot: 1_733_000_000_000_009, Entries: []speedcap.Entry{
+ {Email: "12", Down: 1, Up: 1, Revision: 1},
+ }}},
+ {"empty snapshot at zero", speedcap.Change{ReplaceAll: true}},
+ {"scoped entries", speedcap.Change{Entries: []speedcap.Entry{
+ {Email: "12", Down: 10_000_000, Revision: 7, InboundTags: []string{"vmess-in", "vless-in"}},
+ {Email: "13", Up: 5_000_000, Revision: 8},
+ }}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ request := &common.SetUserSpeedsRequest{ReplaceAll: c.change.ReplaceAll, SnapshotRevision: c.change.Snapshot}
+ for _, entry := range c.change.Entries {
+ request.Entries = append(request.Entries, &common.SpeedEntry{Email: entry.Email, DownBps: entry.Down, UpBps: entry.Up, Revision: entry.Revision, InboundTags: entry.InboundTags})
+ }
+ want, err := proto.MarshalOptions{Deterministic: true}.Marshal(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ operation := SetUserSpeedsOperation(c.change)
+ if operation.Type != "xray.app.proxyman.speedcap.SetUserSpeedsOperation" {
+ t.Fatalf("operation type %q", operation.Type)
+ }
+ if !bytes.Equal(operation.Value, want) {
+ t.Fatalf("the core operation bytes %x differ from the node request bytes %x", operation.Value, want)
+ }
+
+ var decoded common.SetUserSpeedsRequest
+ if err := proto.Unmarshal(operation.Value, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ if !proto.Equal(&decoded, request) {
+ t.Fatalf("decoded %v, want %v", &decoded, request)
+ }
+ })
+ }
+}
+
+const sharedSpeedCapVector = "0a0b0a0231321080ade20420070a170a0231331080dac40918c096b1022081a0958bf8848a030a060a023134200910011889a0958bf8848a03"
+
+func TestSetUserSpeedsOperationMatchesTheVectorTheCoreDecodes(t *testing.T) {
+ operation := SetUserSpeedsOperation(speedcap.Change{ReplaceAll: true, Snapshot: 1_733_000_000_000_009, Entries: []speedcap.Entry{
+ {Email: "12", Down: 10_000_000, Revision: 7},
+ {Email: "13", Down: 20_000_000, Up: 5_000_000, Revision: 1_733_000_000_000_001},
+ {Email: "14", Revision: 9},
+ }})
+ if got := hex.EncodeToString(operation.Value); got != sharedSpeedCapVector {
+ t.Fatalf("operation bytes %s, the core test decodes %s", got, sharedSpeedCapVector)
+ }
+}
+
+const sharedScopedSpeedCapVector = "0a1f0a0231321080ade20420072a08766c6573732d696e2a08766d6573732d696e0a0b0a02313318c096b1022008"
+
+func TestTheScopedOperationMatchesTheVectorTheCoreDecodes(t *testing.T) {
+ operation := SetUserSpeedsOperation(speedcap.Change{Entries: []speedcap.Entry{
+ {Email: "12", Down: 10_000_000, Revision: 7, InboundTags: []string{"vless-in", "vmess-in"}},
+ {Email: "13", Up: 5_000_000, Revision: 8},
+ }})
+ if got := hex.EncodeToString(operation.Value); got != sharedScopedSpeedCapVector {
+ t.Fatalf("operation bytes %s, the core test decodes %s", got, sharedScopedSpeedCapVector)
+ }
+}
diff --git a/backend/xray/core.go b/backend/xray/core.go
index 66c6ca60..8936572f 100644
--- a/backend/xray/core.go
+++ b/backend/xray/core.go
@@ -46,6 +46,7 @@ type Core struct {
processStart uint64
startupMu sync.RWMutex
runtimeMu sync.RWMutex
+ speedCapFile string
}
func NewXRayCore(executablePath, assetsPath, configPath string, logBufferSize, startupLogTailSize int) (*Core, error) {
@@ -268,6 +269,9 @@ func (c *Core) Start(xConfig *Config, debugMode bool) error {
cmd := exec.Command(c.executablePath, "-c", "stdin:")
cmd.Env = append(os.Environ(), "XRAY_LOCATION_ASSET="+c.assetsPath)
+ if c.speedCapFile != "" {
+ cmd.Env = append(cmd.Env, speedCapFileEnv+"="+c.speedCapFile)
+ }
// Set process attributes for proper process management
setProcAttributes(cmd)
diff --git a/backend/xray/degraded.go b/backend/xray/degraded.go
index d3dbce46..597acdf3 100644
--- a/backend/xray/degraded.go
+++ b/backend/xray/degraded.go
@@ -101,6 +101,7 @@ func (x *Xray) startCoreAndWait(ctx context.Context, config *Config) error {
debug = x.cfg.Debug
}
+ x.speedCaps.MarkDirty()
if err := x.core.Start(config, debug); err != nil {
return err
}
diff --git a/backend/xray/jobs.go b/backend/xray/jobs.go
index fb9822cc..91d0ec05 100644
--- a/backend/xray/jobs.go
+++ b/backend/xray/jobs.go
@@ -71,6 +71,7 @@ func (x *Xray) checkXrayStatus(baseCtx context.Context) error {
if err == nil {
x.core.SwitchToRuntimeLogPhase()
+ x.syncSpeedCaps(baseCtx)
return nil // API check successful
}
diff --git a/backend/xray/speedcap.go b/backend/xray/speedcap.go
new file mode 100644
index 00000000..9c35dfda
--- /dev/null
+++ b/backend/xray/speedcap.go
@@ -0,0 +1,64 @@
+package xray
+
+import (
+ "context"
+ "errors"
+ "log"
+ "time"
+
+ "github.com/pasarguard/node/backend/xray/api"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+const (
+ speedCapFileEnv = "XRAY_SPEED_CAP_FILE"
+ apiInboundTag = "API_INBOUND"
+ speedCapPushTimeout = 10 * time.Second
+)
+
+const (
+ speedCapUnknown int32 = iota
+ speedCapSupported
+ speedCapUnsupported
+)
+
+var ErrSpeedCapUnsupported = api.ErrSpeedCapUnsupported
+
+var errSpeedCapCoreNotReady = errors.New("the xray API is not connected")
+
+func (x *Xray) PushSpeedCaps(ctx context.Context, change speedcap.Change) error {
+ if x.handler == nil {
+ return errSpeedCapCoreNotReady
+ }
+ ctx, cancel := context.WithTimeout(ctx, speedCapPushTimeout)
+ defer cancel()
+ err := x.handler.SetUserSpeeds(ctx, apiInboundTag, change)
+ switch {
+ case err == nil:
+ x.speedCapSupport.Store(speedCapSupported)
+ case errors.Is(err, api.ErrSpeedCapUnsupported):
+ if x.speedCapSupport.Swap(speedCapUnsupported) != speedCapUnsupported {
+ log.Println("this xray core does not support per-user speed caps; the node keeps the caps stored but this core does not enforce them")
+ }
+ }
+ return err
+}
+
+func (x *Xray) SupportsSpeedCaps() bool {
+ return x.speedCapSupport.Load() == speedCapSupported
+}
+
+func (x *Xray) RefusesSpeedCaps() bool {
+ return x.speedCapSupport.Load() == speedCapUnsupported
+}
+
+func (x *Xray) syncSpeedCaps(ctx context.Context) {
+ if x.speedCaps == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(ctx, speedCapPushTimeout)
+ defer cancel()
+ if err := x.speedCaps.Sync(ctx, x.PushSpeedCaps); err != nil && !errors.Is(err, api.ErrSpeedCapUnsupported) {
+ log.Printf("speed caps were not pushed to the started xray core, the next speed change pushes them again: %v", err)
+ }
+}
diff --git a/backend/xray/speedcap_env_unix_test.go b/backend/xray/speedcap_env_unix_test.go
new file mode 100644
index 00000000..0eb31421
--- /dev/null
+++ b/backend/xray/speedcap_env_unix_test.go
@@ -0,0 +1,50 @@
+//go:build unix
+
+package xray
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestTheCoreIsStartedWithTheSpeedCapFile(t *testing.T) {
+ dir := t.TempDir()
+ dump := filepath.Join(dir, "env")
+ fake := filepath.Join(dir, "xray")
+ script := "#!/bin/sh\nif [ \"$1\" = version ]; then echo 'Xray 26.3.27 (fake)'; exit 0; fi\nenv > \"" + dump + "\"\nexec sleep 30\n"
+ if err := os.WriteFile(fake, []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ core, err := NewXRayCore(fake, dir, dir, 100, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ store := filepath.Join(dir, "speedcaps.json")
+ core.speedCapFile = store
+ xrayConfig, err := NewConfig(`{"inbounds": [], "outbounds": [{"protocol": "freedom"}]}`, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := core.Start(xrayConfig, false); err != nil {
+ t.Fatal(err)
+ }
+ defer core.Stop()
+
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ raw, err := os.ReadFile(dump)
+ if err == nil && len(raw) > 0 {
+ if !strings.Contains("\n"+string(raw), "\n"+speedCapFileEnv+"="+store+"\n") {
+ t.Fatalf("the core process environment does not name the speed cap file:\n%s", raw)
+ }
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("the fake core never wrote its environment")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
diff --git a/backend/xray/speedcap_lease_restart_unix_test.go b/backend/xray/speedcap_lease_restart_unix_test.go
new file mode 100644
index 00000000..9888680a
--- /dev/null
+++ b/backend/xray/speedcap_lease_restart_unix_test.go
@@ -0,0 +1,41 @@
+//go:build !windows
+
+package xray
+
+import (
+ "context"
+ "testing"
+
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+func TestACoreRestartLeavesTheSpeedCapLeaseAsItFoundIt(t *testing.T) {
+ stats := &fakeStatsService{}
+ stats.healthy.Store(true)
+ x := newFakeCoreXray(t, stats)
+ store := speedcap.NewMemoryStore()
+ x.speedCaps = store
+ if err := x.restartCoreWithConfig(x.config); err != nil {
+ t.Fatal(err)
+ }
+ keep := func(context.Context, speedcap.Change) error { return nil }
+
+ armed := store.ArmLease()
+ if err := x.Restart(); err != nil {
+ t.Fatal(err)
+ }
+ if expired, _, err := store.ExpireLease(context.Background(), armed, keep); !expired || err != nil {
+ t.Fatalf("a core restart moved or ended the lease it found armed: expired %v, err %v", expired, err)
+ }
+
+ ended := store.ArmLease()
+ if _, err := store.Apply(context.Background(), speedcap.Request{ReplaceAll: true, Snapshot: 1}, keep); err != nil {
+ t.Fatal(err)
+ }
+ if err := x.Restart(); err != nil {
+ t.Fatal(err)
+ }
+ if expired, _, _ := store.ExpireLease(context.Background(), ended, keep); expired {
+ t.Fatal("a core restart armed again a lease the panel's snapshot had ended")
+ }
+}
diff --git a/backend/xray/speedcap_live_test.go b/backend/xray/speedcap_live_test.go
new file mode 100644
index 00000000..35f29b7e
--- /dev/null
+++ b/backend/xray/speedcap_live_test.go
@@ -0,0 +1,418 @@
+package xray
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "math"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/config"
+ "github.com/pasarguard/node/pkg/netutil"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+const speedCapTag = "speed-vless"
+
+type speedHarness struct {
+ t *testing.T
+ backend *Xray
+ store *speedcap.Store
+ storePath string
+ serverPort int
+ alice *common.User
+ bob *common.User
+ alicePort int
+ bobPort int
+ target *streamingTarget
+}
+
+func requireLiveXray(t *testing.T) string {
+ t.Helper()
+ binary := installedXrayBinary()
+ if _, err := os.Stat(binary); err != nil {
+ t.Skipf("xray binary not found at %s", binary)
+ }
+ return binary
+}
+
+func speedServerConfig(t *testing.T, port int) *Config {
+ t.Helper()
+ raw, err := json.Marshal(map[string]any{
+ "log": map[string]any{"loglevel": "warning"},
+ "inbounds": []any{revokeServerInbound(revokeCase{tag: speedCapTag, protocol: Vless, network: "tcp"}, port)},
+ "outbounds": []any{directOutbound(t)},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ xrayConfig, err := NewConfig(string(raw), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return xrayConfig
+}
+
+func startSpeedBackend(t *testing.T, binary string, h *speedHarness) *Xray {
+ t.Helper()
+ cfg := &config.Config{
+ XrayExecutablePath: binary,
+ XrayAssetsPath: assetsPath,
+ GeneratedConfigPath: t.TempDir(),
+ LogBufferSize: 1000,
+ SpeedCapFile: h.storePath,
+ }
+ h.store = speedcap.Open(h.storePath)
+ backend, err := NewWithSpeedCaps(context.Background(), speedServerConfig(t, h.serverPort), []*common.User{h.alice, h.bob}, netutil.FindFreePort(), netutil.FindFreePort(), cfg, h.store)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(backend.Shutdown)
+ h.backend = backend
+ return backend
+}
+
+func startSpeedHarness(t *testing.T) *speedHarness {
+ t.Helper()
+ binary := requireLiveXray(t)
+ h := &speedHarness{
+ t: t,
+ storePath: filepath.Join(t.TempDir(), "speedcaps.json"),
+ serverPort: netutil.FindFreePort(),
+ alice: revokeTestUser("21", []string{speedCapTag}),
+ bob: revokeTestUser("22", []string{speedCapTag}),
+ target: startStreamingTarget(t),
+ }
+ startSpeedBackend(t, binary, h)
+
+ h.alicePort, h.bobPort = netutil.FindFreePort(), netutil.FindFreePort()
+ var inbounds, outbounds, rules []any
+ for _, route := range []struct {
+ name string
+ port int
+ user *common.User
+ }{{"alice", h.alicePort, h.alice}, {"bob", h.bobPort, h.bob}} {
+ inbounds = append(inbounds, map[string]any{
+ "tag": "in-" + route.name,
+ "listen": "127.0.0.1",
+ "port": route.port,
+ "protocol": "dokodemo-door",
+ "settings": map[string]any{"address": h.target.host(), "port": h.target.port(), "network": "tcp"},
+ })
+ outbounds = append(outbounds, revokeClientOutbound(revokeCase{tag: speedCapTag, protocol: Vless, network: "tcp"}, "out-"+route.name, h.serverPort, route.user))
+ rules = append(rules, map[string]any{"type": "field", "inboundTag": []string{"in-" + route.name}, "outboundTag": "out-" + route.name})
+ }
+ startSpeedClient(t, binary, map[string]any{
+ "log": map[string]any{"loglevel": "warning"},
+ "inbounds": inbounds,
+ "outbounds": outbounds,
+ "routing": map[string]any{"rules": rules},
+ })
+ waitForListener(t, h.alicePort)
+ waitForListener(t, h.bobPort)
+ return h
+}
+
+func startSpeedClient(t *testing.T, binary string, clientConfig map[string]any) {
+ t.Helper()
+ raw, err := json.Marshal(clientConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ configFile := filepath.Join(dir, "client.json")
+ if err := os.WriteFile(configFile, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ clientBinary := filepath.Join(dir, "xray-speed-client")
+ content, err := os.ReadFile(binary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(clientBinary, content, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ var output bytes.Buffer
+ cmd := exec.Command(clientBinary, "run", "-c", configFile)
+ cmd.Env = append(os.Environ(), "XRAY_LOCATION_ASSET="+assetsPath)
+ cmd.Stdout = &output
+ cmd.Stderr = &output
+ if err := cmd.Start(); err != nil {
+ t.Fatalf("start xray client: %v", err)
+ }
+ t.Cleanup(func() {
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ if t.Failed() {
+ t.Logf("xray client output:\n%s", output.String())
+ }
+ })
+}
+
+func (h *speedHarness) apply(request speedcap.Request) speedcap.Outcome {
+ h.t.Helper()
+ outcome, err := h.store.Apply(context.Background(), request, h.backend.PushSpeedCaps)
+ if err != nil {
+ h.t.Fatalf("the core did not take the speed caps: %v", err)
+ }
+ return outcome
+}
+
+func capEntry(email string, down, revision uint64) speedcap.Entry {
+ return speedcap.Entry{Email: email, Down: down, Revision: revision}
+}
+
+func probesMbps(probes []*streamProbe, window time.Duration) float64 {
+ sum := func() int64 {
+ var total int64
+ for _, p := range probes {
+ total += p.received.Load()
+ }
+ return total
+ }
+ before := sum()
+ start := time.Now()
+ time.Sleep(window)
+ return float64(sum()-before) * 8 / time.Since(start).Seconds() / 1e6
+}
+
+func requireNear(t *testing.T, label string, got, want, tolerance float64) {
+ t.Helper()
+ if math.Abs(got-want) > want*tolerance {
+ t.Fatalf("%s carried %.2f Mbit/s, want %.2f +-%.0f%%", label, got, want, tolerance*100)
+ }
+ t.Logf("%s carried %.2f Mbit/s (cap %.2f)", label, got, want)
+}
+
+func openProbes(t *testing.T, port, count int) []*streamProbe {
+ t.Helper()
+ probes := make([]*streamProbe, 0, count)
+ for range count {
+ probes = append(probes, openStreamProbe(t, port))
+ }
+ for _, p := range probes {
+ p.waitForBytes(t, "download", 64*1024)
+ }
+ return probes
+}
+
+func requireOpen(t *testing.T, label string, probes []*streamProbe) {
+ t.Helper()
+ for _, p := range probes {
+ if !p.isOpen() {
+ t.Fatalf("a %s connection was closed", label)
+ }
+ }
+}
+
+func TestSpeedCapReachesALiveConnectionWithoutTouchingAccounts(t *testing.T) {
+ h := startSpeedHarness(t)
+ if !h.backend.SupportsSpeedCaps() {
+ t.Fatal("the core did not take the speed caps the node pushed after it started")
+ }
+ alice := openProbes(t, h.alicePort, 4)
+ bob := openProbes(t, h.bobPort, 1)
+
+ accountsBefore, err := h.backend.config.ToBytes()
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{capEntry("21", 8_000_000, 1)}})
+ time.Sleep(2 * time.Second)
+ requireNear(t, "alice capped on her open connections", probesMbps(alice, 5*time.Second), 8, 0.10)
+ if got := probesMbps(bob, 2*time.Second); got < 15 {
+ t.Fatalf("uncapped bob on the same inbound carried only %.2f Mbit/s", got)
+ }
+ accountsAfter, err := h.backend.config.ToBytes()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(accountsBefore) != string(accountsAfter) {
+ t.Fatal("a speed cap change altered the core config the accounts are built from")
+ }
+ requireOpen(t, "capped", alice)
+ requireOpen(t, "bystander", bob)
+
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{capEntry("21", 0, 2)}})
+ time.Sleep(time.Second)
+ if got := probesMbps(alice, 2*time.Second); got < 40 {
+ t.Fatalf("alice carried only %.2f Mbit/s after her cap was removed", got)
+ }
+ requireOpen(t, "uncapped again", alice)
+}
+
+func TestAScopedCapFromTheNodeCoversOnlyTheListedInbound(t *testing.T) {
+ h := startSpeedHarness(t)
+ alice := openProbes(t, h.alicePort, 4)
+
+ elsewhere := capEntry("21", 8_000_000, 1)
+ elsewhere.InboundTags = []string{"another-inbound"}
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{elsewhere}})
+ time.Sleep(time.Second)
+ if got := probesMbps(alice, 3*time.Second); got < 40 {
+ t.Fatalf("alice, capped only on another inbound, carried %.2f Mbit/s", got)
+ }
+
+ here := capEntry("21", 8_000_000, 2)
+ here.InboundTags = []string{"another-inbound", speedCapTag}
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{here}})
+ time.Sleep(2 * time.Second)
+ requireNear(t, "alice once the scope names her inbound", probesMbps(alice, 5*time.Second), 8, 0.10)
+ requireOpen(t, "scoped", alice)
+}
+
+func TestTheCoreFollowsTheNodeThroughADelayedSnapshot(t *testing.T) {
+ h := startSpeedHarness(t)
+ alice := openProbes(t, h.alicePort, 4)
+
+ h.apply(speedcap.Request{ReplaceAll: true, Snapshot: 100, Entries: []speedcap.Entry{capEntry("21", 8_000_000, 100)}})
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{capEntry("21", 16_000_000, 101)}})
+ h.apply(speedcap.Request{ReplaceAll: true, Snapshot: 100, Entries: []speedcap.Entry{capEntry("21", 8_000_000, 100)}})
+ time.Sleep(2 * time.Second)
+ requireNear(t, "alice after a delayed snapshot", probesMbps(alice, 5*time.Second), 16, 0.10)
+
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{capEntry("21", 4_000_000, 99)}})
+ time.Sleep(time.Second)
+ requireNear(t, "alice after a stale diff", probesMbps(alice, 3*time.Second), 16, 0.10)
+}
+
+type windowRecorder struct {
+ mu sync.Mutex
+ start time.Time
+ buckets []int64
+ total atomic.Int64
+}
+
+const recorderBucket = 250 * time.Millisecond
+
+func (w *windowRecorder) add(n int) {
+ w.total.Add(int64(n))
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ index := int(time.Since(w.start) / recorderBucket)
+ for len(w.buckets) <= index {
+ w.buckets = append(w.buckets, 0)
+ }
+ w.buckets[index] += int64(n)
+}
+
+func (w *windowRecorder) maxPerSecond() (int64, int) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ per := int(time.Second / recorderBucket)
+ var best int64
+ at := 0
+ for i := 0; i+per <= len(w.buckets); i++ {
+ var sum int64
+ for _, b := range w.buckets[i : i+per] {
+ sum += b
+ }
+ if sum > best {
+ best, at = sum, i
+ }
+ }
+ return best, at
+}
+
+func persistentDownloads(t *testing.T, port, count int, recorder *windowRecorder) func() {
+ t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ var done sync.WaitGroup
+ for range count {
+ done.Add(1)
+ go func() {
+ defer done.Done()
+ buffer := make([]byte, 64*1024)
+ for ctx.Err() == nil {
+ conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), time.Second)
+ if err != nil {
+ time.Sleep(50 * time.Millisecond)
+ continue
+ }
+ stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
+ for {
+ n, err := conn.Read(buffer)
+ recorder.add(n)
+ if err != nil {
+ break
+ }
+ }
+ stop()
+ _ = conn.Close()
+ time.Sleep(50 * time.Millisecond)
+ }
+ }()
+ }
+ return func() {
+ cancel()
+ done.Wait()
+ }
+}
+
+func TestSpeedCapsHoldThroughACoreRestartWithThePanelOffline(t *testing.T) {
+ h := startSpeedHarness(t)
+ const capBps = 8_000_000
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{capEntry("21", capBps, 1)}})
+
+ recorder := &windowRecorder{start: time.Now()}
+ stop := persistentDownloads(t, h.alicePort, 4, recorder)
+ defer stop()
+ time.Sleep(4 * time.Second)
+
+ restartedAt := time.Since(recorder.start)
+ h.backend.readyPoll = 3 * time.Second
+ if err := h.backend.Restart(); err != nil {
+ t.Fatal(err)
+ }
+ afterRestart := recorder.total.Load()
+ time.Sleep(6 * time.Second)
+ stop()
+
+ perSecondLimit := int64(float64(capBps) / 8 * 2 * 1.10)
+ if most, at := recorder.maxPerSecond(); most > perSecondLimit {
+ t.Fatalf("a 1 s window starting %s in carried %d bytes, more than the %d a %d bit/s cap with its 1 s burst allows; the restart was at %s",
+ time.Duration(at)*recorderBucket, most, perSecondLimit, capBps, restartedAt)
+ }
+ carried := recorder.total.Load() - afterRestart
+ if carried == 0 {
+ t.Fatal("no traffic passed after the restart, the test cannot tell a capped core from a dead one")
+ }
+ most, _ := recorder.maxPerSecond()
+ t.Logf("largest 1 s window %d bytes (limit %d), %d bytes carried in the 6 s after the restart (%.2f Mbit/s)", most, perSecondLimit, carried, float64(carried)*8/6/1e6)
+}
+
+func TestSpeedCapsAreInForceWhenANewNodeProcessStartsTheCore(t *testing.T) {
+ h := startSpeedHarness(t)
+ const capBps = 8_000_000
+ h.apply(speedcap.Request{Entries: []speedcap.Entry{capEntry("21", capBps, 1)}})
+ h.backend.Shutdown()
+
+ recorder := &windowRecorder{start: time.Now()}
+ stop := persistentDownloads(t, h.alicePort, 4, recorder)
+ defer stop()
+ startSpeedBackend(t, requireLiveXray(t), h)
+ time.Sleep(5 * time.Second)
+ stop()
+
+ perSecondLimit := int64(float64(capBps) / 8 * 2 * 1.10)
+ if most, at := recorder.maxPerSecond(); most > perSecondLimit {
+ t.Fatalf("a 1 s window starting %s after the new core started carried %d bytes, more than %d", time.Duration(at)*recorderBucket, most, perSecondLimit)
+ }
+ if recorder.total.Load() == 0 {
+ t.Fatal("no traffic passed through the new core")
+ }
+ most, _ := recorder.maxPerSecond()
+ t.Logf("largest 1 s window %d bytes (limit %d), %d bytes while downloads waited for and then used the new core", most, perSecondLimit, recorder.total.Load())
+ if !h.backend.SupportsSpeedCaps() {
+ t.Fatal("the new core did not take the stored caps")
+ }
+}
diff --git a/backend/xray/speedcap_sync_test.go b/backend/xray/speedcap_sync_test.go
new file mode 100644
index 00000000..84f6d50f
--- /dev/null
+++ b/backend/xray/speedcap_sync_test.go
@@ -0,0 +1,46 @@
+package xray
+
+import (
+ "context"
+ "net"
+ "testing"
+ "time"
+
+ "github.com/pasarguard/node/backend/xray/api"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+func TestTheSpeedCapSyncEndsWithItsCallersContext(t *testing.T) {
+ listener, err := net.Listen("tcp4", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ var held []net.Conn
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ return
+ }
+ held = append(held, conn)
+ }
+ }()
+ handler, err := api.NewXrayAPI(listener.Addr().(*net.TCPAddr).Port)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer handler.Close()
+ x := &Xray{handler: handler, speedCaps: speedcap.NewMemoryStore()}
+
+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ defer cancel()
+ begin := time.Now()
+ x.syncSpeedCaps(ctx)
+ if took := time.Since(begin); took > 2*time.Second {
+ t.Fatalf("the sync against a core API that never answers ran %s past a 300 ms caller deadline", took)
+ }
+ if !x.speedCaps.Dirty() {
+ t.Fatal("a sync that never reached the core left the store clean")
+ }
+}
diff --git a/backend/xray/xray.go b/backend/xray/xray.go
index 1f28c1fc..df673c5b 100644
--- a/backend/xray/xray.go
+++ b/backend/xray/xray.go
@@ -7,12 +7,14 @@ import (
"log"
"path/filepath"
"sync"
+ "sync/atomic"
"time"
"github.com/pasarguard/node/backend"
"github.com/pasarguard/node/backend/xray/api"
"github.com/pasarguard/node/common"
"github.com/pasarguard/node/config"
+ "github.com/pasarguard/node/pkg/speedcap"
)
const fullSyncReadyTimeout = 3 * time.Minute
@@ -36,6 +38,9 @@ type Xray struct {
restartCore func(*Config) error
readyPoll time.Duration
+ speedCaps *speedcap.Store
+ speedCapSupport atomic.Int32
+
fullSyncReady time.Duration
restoreReady time.Duration
restartReady time.Duration
@@ -74,6 +79,10 @@ func (x *Xray) restartReadyLimit() time.Duration {
}
func New(ctx context.Context, xrayConfig *Config, users []*common.User, apiPort, metricPort int, cfg *config.Config) (*Xray, error) {
+ return NewWithSpeedCaps(ctx, xrayConfig, users, apiPort, metricPort, cfg, nil)
+}
+
+func NewWithSpeedCaps(ctx context.Context, xrayConfig *Config, users []*common.User, apiPort, metricPort int, cfg *config.Config, speedCaps *speedcap.Store) (*Xray, error) {
executableAbsolutePath, err := filepath.Abs(cfg.XrayExecutablePath)
if err != nil {
return nil, err
@@ -95,6 +104,7 @@ func New(ctx context.Context, xrayConfig *Config, users []*common.User, apiPort,
cancelFunc: xCancel,
cfg: cfg,
metricPort: metricPort,
+ speedCaps: speedCaps,
}
start := time.Now()
@@ -128,6 +138,7 @@ func New(ctx context.Context, xrayConfig *Config, users []*common.User, apiPort,
return nil, err
}
+ core.speedCapFile = speedCaps.Path()
xray.core = core
handler, err := api.NewXrayAPI(apiPort)
@@ -222,6 +233,7 @@ func (x *Xray) restartLocked(ctx context.Context) error {
func (x *Xray) restartCoreWithConfig(config *Config) error {
answered := x.carryUnreadCounters()
+ x.speedCaps.MarkDirty()
x.mu.Lock()
defer x.mu.Unlock()
if x.shutDown {
diff --git a/common/reserved_wire_numbers_test.go b/common/reserved_wire_numbers_test.go
index 6773d754..46a0a20c 100644
--- a/common/reserved_wire_numbers_test.go
+++ b/common/reserved_wire_numbers_test.go
@@ -26,8 +26,8 @@ func TestTheMTProtoWireNumbersStayReservedAndOldNodesStayCompatible(t *testing.T
for i := 0; i < enum.ReservedNames().Len(); i++ {
names = append(names, string(enum.ReservedNames().Get(i)))
}
- if len(names) != 1 || names[0] != "MTPROTO" {
- t.Fatalf("BackendType reserved names = %v, want [MTPROTO]", names)
+ if len(names) != 2 || names[0] != "MTPROTO" || names[1] != "SING_BOX" {
+ t.Fatalf("BackendType reserved names = %v, want [MTPROTO SING_BOX]", names)
}
msg := (&Proxy{}).ProtoReflect().Descriptor()
@@ -60,10 +60,6 @@ func TestTheMTProtoWireNumbersStayReservedAndOldNodesStayCompatible(t *testing.T
t.Fatalf("Proxy.%s = %d, want %d", n.name, n.got, n.want)
}
}
- if BackendType_SING_BOX != 2 {
- t.Fatalf("SING_BOX = %d, want 2", BackendType_SING_BOX)
- }
-
oldNodePayload := []byte{
0x1a, 0x06, 0x0a, 0x04, 'p', 'a', 's', 's',
0x4a, 0x0a, 0x0a, 0x02, 'm', 't', 0x12, 0x04, 'a', 'b', 'c', 'd',
@@ -91,3 +87,31 @@ func TestTheMTProtoWireNumbersStayReservedAndOldNodesStayCompatible(t *testing.T
}
t.Logf("old-image Proxy decoded: trojan=%q, %d unknown bytes preserved for reserved field 9", p.GetTrojan().GetPassword(), len(p.ProtoReflect().GetUnknown()))
}
+
+func TestBackendType2AndItsOldNameStayReservedSoAnOldPanelIsNeverMisread(t *testing.T) {
+ enum := BackendType(0).Descriptor()
+ if v := enum.Values().ByNumber(2); v != nil {
+ t.Fatalf("BackendType 2 has a value again: %s", v.Name())
+ }
+ if !enum.ReservedRanges().Has(2) {
+ t.Fatal("BackendType does not reserve 2")
+ }
+ if !enum.ReservedNames().Has("SING_BOX") {
+ t.Fatal("BackendType does not reserve the name SING_BOX")
+ }
+ if _, known := BackendType_value["SING_BOX"]; known {
+ t.Fatal("the name SING_BOX still maps to a BackendType value")
+ }
+
+ oldPanelStart := []byte{0x08, 0x02, 0x12, 0x02, '{', '}'}
+ var b Backend
+ if err := proto.Unmarshal(oldPanelStart, &b); err != nil {
+ t.Fatalf("a Start of backend type 2 from an older panel failed to decode: %v", err)
+ }
+ if b.GetType() != BackendType(2) || b.GetConfig() != "{}" {
+ t.Fatalf("an older panel's Start decoded as type %d with config %q, want type 2 with config {}", b.GetType(), b.GetConfig())
+ }
+ if name := b.GetType().String(); name != "2" {
+ t.Fatalf("type 2 from an older panel is read as %q, want the bare number with no backend name", name)
+ }
+}
diff --git a/common/service.pb.go b/common/service.pb.go
index 9bd29341..304096d1 100644
--- a/common/service.pb.go
+++ b/common/service.pb.go
@@ -26,7 +26,6 @@ type BackendType int32
const (
BackendType_XRAY BackendType = 0
BackendType_WIREGUARD BackendType = 1
- BackendType_SING_BOX BackendType = 2
BackendType_OPEN_VPN BackendType = 3
BackendType_L2TP BackendType = 5
)
@@ -36,14 +35,12 @@ var (
BackendType_name = map[int32]string{
0: "XRAY",
1: "WIREGUARD",
- 2: "SING_BOX",
3: "OPEN_VPN",
5: "L2TP",
}
BackendType_value = map[string]int32{
"XRAY": 0,
"WIREGUARD": 1,
- "SING_BOX": 2,
"OPEN_VPN": 3,
"L2TP": 5,
}
@@ -180,6 +177,7 @@ type BaseInfoResponse struct {
FilterRulesStripped bool `protobuf:"varint,5,opt,name=filter_rules_stripped,json=filterRulesStripped,proto3" json:"filter_rules_stripped,omitempty"`
FilterStripReason string `protobuf:"bytes,6,opt,name=filter_strip_reason,json=filterStripReason,proto3" json:"filter_strip_reason,omitempty"`
StrippedRuleTags []string `protobuf:"bytes,7,rep,name=stripped_rule_tags,json=strippedRuleTags,proto3" json:"stripped_rule_tags,omitempty"`
+ SupportsSpeedCap bool `protobuf:"varint,8,opt,name=supports_speed_cap,json=supportsSpeedCap,proto3" json:"supports_speed_cap,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -263,6 +261,13 @@ func (x *BaseInfoResponse) GetStrippedRuleTags() []string {
return nil
}
+func (x *BaseInfoResponse) GetSupportsSpeedCap() bool {
+ if x != nil {
+ return x.SupportsSpeedCap
+ }
+ return false
+}
+
type Backend struct {
state protoimpl.MessageState `protogen:"open.v1"`
Type BackendType `protobuf:"varint,1,opt,name=type,proto3,enum=service.BackendType" json:"type,omitempty"`
@@ -1346,8 +1351,6 @@ func (x *Hysteria) GetAuth() string {
return ""
}
-// sing-box Hysteria2 inbound user credential (distinct from xray-core's
-// native "Hysteria" v1 auth string above — Hysteria2 uses a password).
type Hysteria2 struct {
state protoimpl.MessageState `protogen:"open.v1"`
Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"`
@@ -1897,6 +1900,262 @@ func (x *UsersChunk) GetLast() bool {
return false
}
+type SpeedEntry struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
+ DownBps uint64 `protobuf:"varint,2,opt,name=down_bps,json=downBps,proto3" json:"down_bps,omitempty"`
+ UpBps uint64 `protobuf:"varint,3,opt,name=up_bps,json=upBps,proto3" json:"up_bps,omitempty"`
+ Revision uint64 `protobuf:"varint,4,opt,name=revision,proto3" json:"revision,omitempty"`
+ InboundTags []string `protobuf:"bytes,5,rep,name=inbound_tags,json=inboundTags,proto3" json:"inbound_tags,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SpeedEntry) Reset() {
+ *x = SpeedEntry{}
+ mi := &file_common_service_proto_msgTypes[29]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SpeedEntry) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SpeedEntry) ProtoMessage() {}
+
+func (x *SpeedEntry) ProtoReflect() protoreflect.Message {
+ mi := &file_common_service_proto_msgTypes[29]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SpeedEntry.ProtoReflect.Descriptor instead.
+func (*SpeedEntry) Descriptor() ([]byte, []int) {
+ return file_common_service_proto_rawDescGZIP(), []int{29}
+}
+
+func (x *SpeedEntry) GetEmail() string {
+ if x != nil {
+ return x.Email
+ }
+ return ""
+}
+
+func (x *SpeedEntry) GetDownBps() uint64 {
+ if x != nil {
+ return x.DownBps
+ }
+ return 0
+}
+
+func (x *SpeedEntry) GetUpBps() uint64 {
+ if x != nil {
+ return x.UpBps
+ }
+ return 0
+}
+
+func (x *SpeedEntry) GetRevision() uint64 {
+ if x != nil {
+ return x.Revision
+ }
+ return 0
+}
+
+func (x *SpeedEntry) GetInboundTags() []string {
+ if x != nil {
+ return x.InboundTags
+ }
+ return nil
+}
+
+type SetUserSpeedsRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Entries []*SpeedEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"`
+ ReplaceAll bool `protobuf:"varint,2,opt,name=replace_all,json=replaceAll,proto3" json:"replace_all,omitempty"`
+ SnapshotRevision uint64 `protobuf:"varint,3,opt,name=snapshot_revision,json=snapshotRevision,proto3" json:"snapshot_revision,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SetUserSpeedsRequest) Reset() {
+ *x = SetUserSpeedsRequest{}
+ mi := &file_common_service_proto_msgTypes[30]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SetUserSpeedsRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SetUserSpeedsRequest) ProtoMessage() {}
+
+func (x *SetUserSpeedsRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_common_service_proto_msgTypes[30]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SetUserSpeedsRequest.ProtoReflect.Descriptor instead.
+func (*SetUserSpeedsRequest) Descriptor() ([]byte, []int) {
+ return file_common_service_proto_rawDescGZIP(), []int{30}
+}
+
+func (x *SetUserSpeedsRequest) GetEntries() []*SpeedEntry {
+ if x != nil {
+ return x.Entries
+ }
+ return nil
+}
+
+func (x *SetUserSpeedsRequest) GetReplaceAll() bool {
+ if x != nil {
+ return x.ReplaceAll
+ }
+ return false
+}
+
+func (x *SetUserSpeedsRequest) GetSnapshotRevision() uint64 {
+ if x != nil {
+ return x.SnapshotRevision
+ }
+ return 0
+}
+
+type SpeedRejection struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
+ Backend string `protobuf:"bytes,2,opt,name=backend,proto3" json:"backend,omitempty"`
+ Reason string `protobuf:"bytes,3,opt,name=reason,proto3" json:"reason,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SpeedRejection) Reset() {
+ *x = SpeedRejection{}
+ mi := &file_common_service_proto_msgTypes[31]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SpeedRejection) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SpeedRejection) ProtoMessage() {}
+
+func (x *SpeedRejection) ProtoReflect() protoreflect.Message {
+ mi := &file_common_service_proto_msgTypes[31]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SpeedRejection.ProtoReflect.Descriptor instead.
+func (*SpeedRejection) Descriptor() ([]byte, []int) {
+ return file_common_service_proto_rawDescGZIP(), []int{31}
+}
+
+func (x *SpeedRejection) GetEmail() string {
+ if x != nil {
+ return x.Email
+ }
+ return ""
+}
+
+func (x *SpeedRejection) GetBackend() string {
+ if x != nil {
+ return x.Backend
+ }
+ return ""
+}
+
+func (x *SpeedRejection) GetReason() string {
+ if x != nil {
+ return x.Reason
+ }
+ return ""
+}
+
+type SetUserSpeedsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Rejected []*SpeedRejection `protobuf:"bytes,1,rep,name=rejected,proto3" json:"rejected,omitempty"`
+ HighWater uint64 `protobuf:"varint,2,opt,name=high_water,json=highWater,proto3" json:"high_water,omitempty"`
+ Stale []string `protobuf:"bytes,3,rep,name=stale,proto3" json:"stale,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SetUserSpeedsResponse) Reset() {
+ *x = SetUserSpeedsResponse{}
+ mi := &file_common_service_proto_msgTypes[32]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SetUserSpeedsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SetUserSpeedsResponse) ProtoMessage() {}
+
+func (x *SetUserSpeedsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_common_service_proto_msgTypes[32]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SetUserSpeedsResponse.ProtoReflect.Descriptor instead.
+func (*SetUserSpeedsResponse) Descriptor() ([]byte, []int) {
+ return file_common_service_proto_rawDescGZIP(), []int{32}
+}
+
+func (x *SetUserSpeedsResponse) GetRejected() []*SpeedRejection {
+ if x != nil {
+ return x.Rejected
+ }
+ return nil
+}
+
+func (x *SetUserSpeedsResponse) GetHighWater() uint64 {
+ if x != nil {
+ return x.HighWater
+ }
+ return 0
+}
+
+func (x *SetUserSpeedsResponse) GetStale() []string {
+ if x != nil {
+ return x.Stale
+ }
+ return nil
+}
+
// Service for node management and connection
// Routing (mirrors xray app/router/command, node-friendly shapes)
type RoutingRule struct {
@@ -1909,7 +2168,7 @@ type RoutingRule struct {
func (x *RoutingRule) Reset() {
*x = RoutingRule{}
- mi := &file_common_service_proto_msgTypes[29]
+ mi := &file_common_service_proto_msgTypes[33]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1921,7 +2180,7 @@ func (x *RoutingRule) String() string {
func (*RoutingRule) ProtoMessage() {}
func (x *RoutingRule) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[29]
+ mi := &file_common_service_proto_msgTypes[33]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1934,7 +2193,7 @@ func (x *RoutingRule) ProtoReflect() protoreflect.Message {
// Deprecated: Use RoutingRule.ProtoReflect.Descriptor instead.
func (*RoutingRule) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{29}
+ return file_common_service_proto_rawDescGZIP(), []int{33}
}
func (x *RoutingRule) GetOutboundTag() string {
@@ -1960,7 +2219,7 @@ type RoutingRulesResponse struct {
func (x *RoutingRulesResponse) Reset() {
*x = RoutingRulesResponse{}
- mi := &file_common_service_proto_msgTypes[30]
+ mi := &file_common_service_proto_msgTypes[34]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1972,7 +2231,7 @@ func (x *RoutingRulesResponse) String() string {
func (*RoutingRulesResponse) ProtoMessage() {}
func (x *RoutingRulesResponse) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[30]
+ mi := &file_common_service_proto_msgTypes[34]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1985,7 +2244,7 @@ func (x *RoutingRulesResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RoutingRulesResponse.ProtoReflect.Descriptor instead.
func (*RoutingRulesResponse) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{30}
+ return file_common_service_proto_rawDescGZIP(), []int{34}
}
func (x *RoutingRulesResponse) GetRules() []*RoutingRule {
@@ -2004,7 +2263,7 @@ type BalancerInfoRequest struct {
func (x *BalancerInfoRequest) Reset() {
*x = BalancerInfoRequest{}
- mi := &file_common_service_proto_msgTypes[31]
+ mi := &file_common_service_proto_msgTypes[35]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2016,7 +2275,7 @@ func (x *BalancerInfoRequest) String() string {
func (*BalancerInfoRequest) ProtoMessage() {}
func (x *BalancerInfoRequest) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[31]
+ mi := &file_common_service_proto_msgTypes[35]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2029,7 +2288,7 @@ func (x *BalancerInfoRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use BalancerInfoRequest.ProtoReflect.Descriptor instead.
func (*BalancerInfoRequest) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{31}
+ return file_common_service_proto_rawDescGZIP(), []int{35}
}
func (x *BalancerInfoRequest) GetTag() string {
@@ -2049,7 +2308,7 @@ type BalancerInfoResponse struct {
func (x *BalancerInfoResponse) Reset() {
*x = BalancerInfoResponse{}
- mi := &file_common_service_proto_msgTypes[32]
+ mi := &file_common_service_proto_msgTypes[36]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2061,7 +2320,7 @@ func (x *BalancerInfoResponse) String() string {
func (*BalancerInfoResponse) ProtoMessage() {}
func (x *BalancerInfoResponse) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[32]
+ mi := &file_common_service_proto_msgTypes[36]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2074,7 +2333,7 @@ func (x *BalancerInfoResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use BalancerInfoResponse.ProtoReflect.Descriptor instead.
func (*BalancerInfoResponse) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{32}
+ return file_common_service_proto_rawDescGZIP(), []int{36}
}
func (x *BalancerInfoResponse) GetOverrideTarget() string {
@@ -2109,7 +2368,7 @@ type TestRouteRequest struct {
func (x *TestRouteRequest) Reset() {
*x = TestRouteRequest{}
- mi := &file_common_service_proto_msgTypes[33]
+ mi := &file_common_service_proto_msgTypes[37]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2121,7 +2380,7 @@ func (x *TestRouteRequest) String() string {
func (*TestRouteRequest) ProtoMessage() {}
func (x *TestRouteRequest) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[33]
+ mi := &file_common_service_proto_msgTypes[37]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2134,7 +2393,7 @@ func (x *TestRouteRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use TestRouteRequest.ProtoReflect.Descriptor instead.
func (*TestRouteRequest) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{33}
+ return file_common_service_proto_rawDescGZIP(), []int{37}
}
func (x *TestRouteRequest) GetInboundTag() string {
@@ -2220,7 +2479,7 @@ type RouteResult struct {
func (x *RouteResult) Reset() {
*x = RouteResult{}
- mi := &file_common_service_proto_msgTypes[34]
+ mi := &file_common_service_proto_msgTypes[38]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2232,7 +2491,7 @@ func (x *RouteResult) String() string {
func (*RouteResult) ProtoMessage() {}
func (x *RouteResult) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[34]
+ mi := &file_common_service_proto_msgTypes[38]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2245,7 +2504,7 @@ func (x *RouteResult) ProtoReflect() protoreflect.Message {
// Deprecated: Use RouteResult.ProtoReflect.Descriptor instead.
func (*RouteResult) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{34}
+ return file_common_service_proto_rawDescGZIP(), []int{38}
}
func (x *RouteResult) GetOutboundTag() string {
@@ -2296,7 +2555,7 @@ type AddRoutingRuleRequest struct {
func (x *AddRoutingRuleRequest) Reset() {
*x = AddRoutingRuleRequest{}
- mi := &file_common_service_proto_msgTypes[35]
+ mi := &file_common_service_proto_msgTypes[39]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2308,7 +2567,7 @@ func (x *AddRoutingRuleRequest) String() string {
func (*AddRoutingRuleRequest) ProtoMessage() {}
func (x *AddRoutingRuleRequest) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[35]
+ mi := &file_common_service_proto_msgTypes[39]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2321,7 +2580,7 @@ func (x *AddRoutingRuleRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use AddRoutingRuleRequest.ProtoReflect.Descriptor instead.
func (*AddRoutingRuleRequest) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{35}
+ return file_common_service_proto_rawDescGZIP(), []int{39}
}
func (x *AddRoutingRuleRequest) GetRule() string {
@@ -2347,7 +2606,7 @@ type RemoveBackendRequest struct {
func (x *RemoveBackendRequest) Reset() {
*x = RemoveBackendRequest{}
- mi := &file_common_service_proto_msgTypes[36]
+ mi := &file_common_service_proto_msgTypes[40]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2359,7 +2618,7 @@ func (x *RemoveBackendRequest) String() string {
func (*RemoveBackendRequest) ProtoMessage() {}
func (x *RemoveBackendRequest) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[36]
+ mi := &file_common_service_proto_msgTypes[40]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2372,7 +2631,7 @@ func (x *RemoveBackendRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RemoveBackendRequest.ProtoReflect.Descriptor instead.
func (*RemoveBackendRequest) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{36}
+ return file_common_service_proto_rawDescGZIP(), []int{40}
}
func (x *RemoveBackendRequest) GetType() BackendType {
@@ -2391,7 +2650,7 @@ type BackendList struct {
func (x *BackendList) Reset() {
*x = BackendList{}
- mi := &file_common_service_proto_msgTypes[37]
+ mi := &file_common_service_proto_msgTypes[41]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2403,7 +2662,7 @@ func (x *BackendList) String() string {
func (*BackendList) ProtoMessage() {}
func (x *BackendList) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[37]
+ mi := &file_common_service_proto_msgTypes[41]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2416,7 +2675,7 @@ func (x *BackendList) ProtoReflect() protoreflect.Message {
// Deprecated: Use BackendList.ProtoReflect.Descriptor instead.
func (*BackendList) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{37}
+ return file_common_service_proto_rawDescGZIP(), []int{41}
}
func (x *BackendList) GetTypes() []BackendType {
@@ -2435,7 +2694,7 @@ type RemoveRoutingRuleRequest struct {
func (x *RemoveRoutingRuleRequest) Reset() {
*x = RemoveRoutingRuleRequest{}
- mi := &file_common_service_proto_msgTypes[38]
+ mi := &file_common_service_proto_msgTypes[42]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2447,7 +2706,7 @@ func (x *RemoveRoutingRuleRequest) String() string {
func (*RemoveRoutingRuleRequest) ProtoMessage() {}
func (x *RemoveRoutingRuleRequest) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[38]
+ mi := &file_common_service_proto_msgTypes[42]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2460,7 +2719,7 @@ func (x *RemoveRoutingRuleRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RemoveRoutingRuleRequest.ProtoReflect.Descriptor instead.
func (*RemoveRoutingRuleRequest) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{38}
+ return file_common_service_proto_rawDescGZIP(), []int{42}
}
func (x *RemoveRoutingRuleRequest) GetRuleTag() string {
@@ -2480,7 +2739,7 @@ type OverrideBalancerTargetRequest struct {
func (x *OverrideBalancerTargetRequest) Reset() {
*x = OverrideBalancerTargetRequest{}
- mi := &file_common_service_proto_msgTypes[39]
+ mi := &file_common_service_proto_msgTypes[43]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2492,7 +2751,7 @@ func (x *OverrideBalancerTargetRequest) String() string {
func (*OverrideBalancerTargetRequest) ProtoMessage() {}
func (x *OverrideBalancerTargetRequest) ProtoReflect() protoreflect.Message {
- mi := &file_common_service_proto_msgTypes[39]
+ mi := &file_common_service_proto_msgTypes[43]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2505,7 +2764,7 @@ func (x *OverrideBalancerTargetRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use OverrideBalancerTargetRequest.ProtoReflect.Descriptor instead.
func (*OverrideBalancerTargetRequest) Descriptor() ([]byte, []int) {
- return file_common_service_proto_rawDescGZIP(), []int{39}
+ return file_common_service_proto_rawDescGZIP(), []int{43}
}
func (x *OverrideBalancerTargetRequest) GetBalancerTag() string {
@@ -2527,7 +2786,7 @@ var File_common_service_proto protoreflect.FileDescriptor
const file_common_service_proto_rawDesc = "" +
"\n" +
"\x14common/service.proto\x12\aservice\"\a\n" +
- "\x05Empty\"\xb3\x02\n" +
+ "\x05Empty\"\xe1\x02\n" +
"\x10BaseInfoResponse\x12\x18\n" +
"\astarted\x18\x01 \x01(\bR\astarted\x12!\n" +
"\fcore_version\x18\x02 \x01(\tR\vcoreVersion\x12!\n" +
@@ -2535,7 +2794,8 @@ const file_common_service_proto_rawDesc = "" +
"\x12supported_backends\x18\x04 \x03(\tR\x11supportedBackends\x122\n" +
"\x15filter_rules_stripped\x18\x05 \x01(\bR\x13filterRulesStripped\x12.\n" +
"\x13filter_strip_reason\x18\x06 \x01(\tR\x11filterStripReason\x12,\n" +
- "\x12stripped_rule_tags\x18\a \x03(\tR\x10strippedRuleTags\"\xba\x01\n" +
+ "\x12stripped_rule_tags\x18\a \x03(\tR\x10strippedRuleTags\x12,\n" +
+ "\x12supports_speed_cap\x18\b \x01(\bR\x10supportsSpeedCap\"\xba\x01\n" +
"\aBackend\x12(\n" +
"\x04type\x18\x01 \x01(\x0e2\x14.service.BackendTypeR\x04type\x12\x16\n" +
"\x06config\x18\x02 \x01(\tR\x06config\x12#\n" +
@@ -2653,7 +2913,28 @@ const file_common_service_proto_rawDesc = "" +
"UsersChunk\x12#\n" +
"\x05users\x18\x01 \x03(\v2\r.service.UserR\x05users\x12\x14\n" +
"\x05index\x18\x02 \x01(\x04R\x05index\x12\x12\n" +
- "\x04last\x18\x03 \x01(\bR\x04last\"K\n" +
+ "\x04last\x18\x03 \x01(\bR\x04last\"\x93\x01\n" +
+ "\n" +
+ "SpeedEntry\x12\x14\n" +
+ "\x05email\x18\x01 \x01(\tR\x05email\x12\x19\n" +
+ "\bdown_bps\x18\x02 \x01(\x04R\adownBps\x12\x15\n" +
+ "\x06up_bps\x18\x03 \x01(\x04R\x05upBps\x12\x1a\n" +
+ "\brevision\x18\x04 \x01(\x04R\brevision\x12!\n" +
+ "\finbound_tags\x18\x05 \x03(\tR\vinboundTags\"\x93\x01\n" +
+ "\x14SetUserSpeedsRequest\x12-\n" +
+ "\aentries\x18\x01 \x03(\v2\x13.service.SpeedEntryR\aentries\x12\x1f\n" +
+ "\vreplace_all\x18\x02 \x01(\bR\n" +
+ "replaceAll\x12+\n" +
+ "\x11snapshot_revision\x18\x03 \x01(\x04R\x10snapshotRevision\"X\n" +
+ "\x0eSpeedRejection\x12\x14\n" +
+ "\x05email\x18\x01 \x01(\tR\x05email\x12\x18\n" +
+ "\abackend\x18\x02 \x01(\tR\abackend\x12\x16\n" +
+ "\x06reason\x18\x03 \x01(\tR\x06reason\"\x81\x01\n" +
+ "\x15SetUserSpeedsResponse\x123\n" +
+ "\brejected\x18\x01 \x03(\v2\x17.service.SpeedRejectionR\brejected\x12\x1d\n" +
+ "\n" +
+ "high_water\x18\x02 \x01(\x04R\thighWater\x12\x14\n" +
+ "\x05stale\x18\x03 \x03(\tR\x05stale\"K\n" +
"\vRoutingRule\x12!\n" +
"\foutbound_tag\x18\x01 \x01(\tR\voutboundTag\x12\x19\n" +
"\brule_tag\x18\x02 \x01(\tR\aruleTag\"B\n" +
@@ -2701,20 +2982,19 @@ const file_common_service_proto_rawDesc = "" +
"\brule_tag\x18\x01 \x01(\tR\aruleTag\"Z\n" +
"\x1dOverrideBalancerTargetRequest\x12!\n" +
"\fbalancer_tag\x18\x01 \x01(\tR\vbalancerTag\x12\x16\n" +
- "\x06target\x18\x02 \x01(\tR\x06target*[\n" +
+ "\x06target\x18\x02 \x01(\tR\x06target*]\n" +
"\vBackendType\x12\b\n" +
"\x04XRAY\x10\x00\x12\r\n" +
"\tWIREGUARD\x10\x01\x12\f\n" +
- "\bSING_BOX\x10\x02\x12\f\n" +
"\bOPEN_VPN\x10\x03\x12\b\n" +
- "\x04L2TP\x10\x05\"\x04\b\x04\x10\x04*\aMTPROTO*_\n" +
+ "\x04L2TP\x10\x05\"\x04\b\x04\x10\x04\"\x04\b\x02\x10\x02*\aMTPROTO*\bSING_BOX*_\n" +
"\bStatType\x12\r\n" +
"\tOutbounds\x10\x00\x12\f\n" +
"\bOutbound\x10\x01\x12\f\n" +
"\bInbounds\x10\x02\x12\v\n" +
"\aInbound\x10\x03\x12\r\n" +
"\tUsersStat\x10\x04\x12\f\n" +
- "\bUserStat\x10\x052\x88\v\n" +
+ "\bUserStat\x10\x052\xda\v\n" +
"\vNodeService\x126\n" +
"\x05Start\x12\x10.service.Backend\x1a\x19.service.BaseInfoResponse\"\x00\x12(\n" +
"\x04Stop\x12\x0e.service.Empty\x1a\x0e.service.Empty\"\x00\x120\n" +
@@ -2732,7 +3012,8 @@ const file_common_service_proto_rawDesc = "" +
"\x18GetUserOnlineIpListStats\x12\x14.service.StatRequest\x1a\".service.StatsOnlineIpListResponse\"\x00\x12-\n" +
"\bSyncUser\x12\r.service.User\x1a\x0e.service.Empty\"\x00(\x01\x12-\n" +
"\tSyncUsers\x12\x0e.service.Users\x1a\x0e.service.Empty\"\x00\x12;\n" +
- "\x10SyncUsersChunked\x12\x13.service.UsersChunk\x1a\x0e.service.Empty\"\x00(\x01\x12C\n" +
+ "\x10SyncUsersChunked\x12\x13.service.UsersChunk\x1a\x0e.service.Empty\"\x00(\x01\x12P\n" +
+ "\rSetUserSpeeds\x12\x1d.service.SetUserSpeedsRequest\x1a\x1e.service.SetUserSpeedsResponse\"\x00\x12C\n" +
"\x10ListRoutingRules\x12\x0e.service.Empty\x1a\x1d.service.RoutingRulesResponse\"\x00\x12P\n" +
"\x0fGetBalancerInfo\x12\x1c.service.BalancerInfoRequest\x1a\x1d.service.BalancerInfoResponse\"\x00\x12>\n" +
"\tTestRoute\x12\x19.service.TestRouteRequest\x1a\x14.service.RouteResult\"\x00\x12B\n" +
@@ -2753,7 +3034,7 @@ func file_common_service_proto_rawDescGZIP() []byte {
}
var file_common_service_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
-var file_common_service_proto_msgTypes = make([]protoimpl.MessageInfo, 42)
+var file_common_service_proto_msgTypes = make([]protoimpl.MessageInfo, 46)
var file_common_service_proto_goTypes = []any{
(BackendType)(0), // 0: service.BackendType
(StatType)(0), // 1: service.StatType
@@ -2786,26 +3067,30 @@ var file_common_service_proto_goTypes = []any{
(*User)(nil), // 28: service.User
(*Users)(nil), // 29: service.Users
(*UsersChunk)(nil), // 30: service.UsersChunk
- (*RoutingRule)(nil), // 31: service.RoutingRule
- (*RoutingRulesResponse)(nil), // 32: service.RoutingRulesResponse
- (*BalancerInfoRequest)(nil), // 33: service.BalancerInfoRequest
- (*BalancerInfoResponse)(nil), // 34: service.BalancerInfoResponse
- (*TestRouteRequest)(nil), // 35: service.TestRouteRequest
- (*RouteResult)(nil), // 36: service.RouteResult
- (*AddRoutingRuleRequest)(nil), // 37: service.AddRoutingRuleRequest
- (*RemoveBackendRequest)(nil), // 38: service.RemoveBackendRequest
- (*BackendList)(nil), // 39: service.BackendList
- (*RemoveRoutingRuleRequest)(nil), // 40: service.RemoveRoutingRuleRequest
- (*OverrideBalancerTargetRequest)(nil), // 41: service.OverrideBalancerTargetRequest
- nil, // 42: service.StatsOnlineIpListResponse.IpsEntry
- nil, // 43: service.TestRouteRequest.AttributesEntry
+ (*SpeedEntry)(nil), // 31: service.SpeedEntry
+ (*SetUserSpeedsRequest)(nil), // 32: service.SetUserSpeedsRequest
+ (*SpeedRejection)(nil), // 33: service.SpeedRejection
+ (*SetUserSpeedsResponse)(nil), // 34: service.SetUserSpeedsResponse
+ (*RoutingRule)(nil), // 35: service.RoutingRule
+ (*RoutingRulesResponse)(nil), // 36: service.RoutingRulesResponse
+ (*BalancerInfoRequest)(nil), // 37: service.BalancerInfoRequest
+ (*BalancerInfoResponse)(nil), // 38: service.BalancerInfoResponse
+ (*TestRouteRequest)(nil), // 39: service.TestRouteRequest
+ (*RouteResult)(nil), // 40: service.RouteResult
+ (*AddRoutingRuleRequest)(nil), // 41: service.AddRoutingRuleRequest
+ (*RemoveBackendRequest)(nil), // 42: service.RemoveBackendRequest
+ (*BackendList)(nil), // 43: service.BackendList
+ (*RemoveRoutingRuleRequest)(nil), // 44: service.RemoveRoutingRuleRequest
+ (*OverrideBalancerTargetRequest)(nil), // 45: service.OverrideBalancerTargetRequest
+ nil, // 46: service.StatsOnlineIpListResponse.IpsEntry
+ nil, // 47: service.TestRouteRequest.AttributesEntry
}
var file_common_service_proto_depIdxs = []int32{
0, // 0: service.Backend.type:type_name -> service.BackendType
28, // 1: service.Backend.users:type_name -> service.User
6, // 2: service.StatResponse.stats:type_name -> service.Stat
1, // 3: service.StatRequest.type:type_name -> service.StatType
- 42, // 4: service.StatsOnlineIpListResponse.ips:type_name -> service.StatsOnlineIpListResponse.IpsEntry
+ 46, // 4: service.StatsOnlineIpListResponse.ips:type_name -> service.StatsOnlineIpListResponse.IpsEntry
11, // 5: service.LatencyResponse.latencies:type_name -> service.Latency
16, // 6: service.Proxy.vmess:type_name -> service.Vmess
17, // 7: service.Proxy.vless:type_name -> service.Vless
@@ -2821,59 +3106,63 @@ var file_common_service_proto_depIdxs = []int32{
27, // 17: service.User.proxies:type_name -> service.Proxy
28, // 18: service.Users.users:type_name -> service.User
28, // 19: service.UsersChunk.users:type_name -> service.User
- 31, // 20: service.RoutingRulesResponse.rules:type_name -> service.RoutingRule
- 43, // 21: service.TestRouteRequest.attributes:type_name -> service.TestRouteRequest.AttributesEntry
- 0, // 22: service.RemoveBackendRequest.type:type_name -> service.BackendType
- 0, // 23: service.BackendList.types:type_name -> service.BackendType
- 4, // 24: service.NodeService.Start:input_type -> service.Backend
- 2, // 25: service.NodeService.Stop:input_type -> service.Empty
- 4, // 26: service.NodeService.AddBackend:input_type -> service.Backend
- 38, // 27: service.NodeService.RemoveBackend:input_type -> service.RemoveBackendRequest
- 2, // 28: service.NodeService.ListBackends:input_type -> service.Empty
- 2, // 29: service.NodeService.GetBaseInfo:input_type -> service.Empty
- 2, // 30: service.NodeService.GetLogs:input_type -> service.Empty
- 2, // 31: service.NodeService.GetSystemStats:input_type -> service.Empty
- 2, // 32: service.NodeService.GetBackendStats:input_type -> service.Empty
- 8, // 33: service.NodeService.GetStats:input_type -> service.StatRequest
- 12, // 34: service.NodeService.GetOutboundsLatency:input_type -> service.LatencyRequest
- 8, // 35: service.NodeService.GetUserOnlineStats:input_type -> service.StatRequest
- 8, // 36: service.NodeService.GetUserOnlineIpListStats:input_type -> service.StatRequest
- 28, // 37: service.NodeService.SyncUser:input_type -> service.User
- 29, // 38: service.NodeService.SyncUsers:input_type -> service.Users
- 30, // 39: service.NodeService.SyncUsersChunked:input_type -> service.UsersChunk
- 2, // 40: service.NodeService.ListRoutingRules:input_type -> service.Empty
- 33, // 41: service.NodeService.GetBalancerInfo:input_type -> service.BalancerInfoRequest
- 35, // 42: service.NodeService.TestRoute:input_type -> service.TestRouteRequest
- 37, // 43: service.NodeService.AddRoutingRule:input_type -> service.AddRoutingRuleRequest
- 40, // 44: service.NodeService.RemoveRoutingRule:input_type -> service.RemoveRoutingRuleRequest
- 41, // 45: service.NodeService.OverrideBalancerTarget:input_type -> service.OverrideBalancerTargetRequest
- 3, // 46: service.NodeService.Start:output_type -> service.BaseInfoResponse
- 2, // 47: service.NodeService.Stop:output_type -> service.Empty
- 2, // 48: service.NodeService.AddBackend:output_type -> service.Empty
- 2, // 49: service.NodeService.RemoveBackend:output_type -> service.Empty
- 39, // 50: service.NodeService.ListBackends:output_type -> service.BackendList
- 3, // 51: service.NodeService.GetBaseInfo:output_type -> service.BaseInfoResponse
- 5, // 52: service.NodeService.GetLogs:output_type -> service.Log
- 15, // 53: service.NodeService.GetSystemStats:output_type -> service.SystemStatsResponse
- 14, // 54: service.NodeService.GetBackendStats:output_type -> service.BackendStatsResponse
- 7, // 55: service.NodeService.GetStats:output_type -> service.StatResponse
- 13, // 56: service.NodeService.GetOutboundsLatency:output_type -> service.LatencyResponse
- 9, // 57: service.NodeService.GetUserOnlineStats:output_type -> service.OnlineStatResponse
- 10, // 58: service.NodeService.GetUserOnlineIpListStats:output_type -> service.StatsOnlineIpListResponse
- 2, // 59: service.NodeService.SyncUser:output_type -> service.Empty
- 2, // 60: service.NodeService.SyncUsers:output_type -> service.Empty
- 2, // 61: service.NodeService.SyncUsersChunked:output_type -> service.Empty
- 32, // 62: service.NodeService.ListRoutingRules:output_type -> service.RoutingRulesResponse
- 34, // 63: service.NodeService.GetBalancerInfo:output_type -> service.BalancerInfoResponse
- 36, // 64: service.NodeService.TestRoute:output_type -> service.RouteResult
- 2, // 65: service.NodeService.AddRoutingRule:output_type -> service.Empty
- 2, // 66: service.NodeService.RemoveRoutingRule:output_type -> service.Empty
- 2, // 67: service.NodeService.OverrideBalancerTarget:output_type -> service.Empty
- 46, // [46:68] is the sub-list for method output_type
- 24, // [24:46] is the sub-list for method input_type
- 24, // [24:24] is the sub-list for extension type_name
- 24, // [24:24] is the sub-list for extension extendee
- 0, // [0:24] is the sub-list for field type_name
+ 31, // 20: service.SetUserSpeedsRequest.entries:type_name -> service.SpeedEntry
+ 33, // 21: service.SetUserSpeedsResponse.rejected:type_name -> service.SpeedRejection
+ 35, // 22: service.RoutingRulesResponse.rules:type_name -> service.RoutingRule
+ 47, // 23: service.TestRouteRequest.attributes:type_name -> service.TestRouteRequest.AttributesEntry
+ 0, // 24: service.RemoveBackendRequest.type:type_name -> service.BackendType
+ 0, // 25: service.BackendList.types:type_name -> service.BackendType
+ 4, // 26: service.NodeService.Start:input_type -> service.Backend
+ 2, // 27: service.NodeService.Stop:input_type -> service.Empty
+ 4, // 28: service.NodeService.AddBackend:input_type -> service.Backend
+ 42, // 29: service.NodeService.RemoveBackend:input_type -> service.RemoveBackendRequest
+ 2, // 30: service.NodeService.ListBackends:input_type -> service.Empty
+ 2, // 31: service.NodeService.GetBaseInfo:input_type -> service.Empty
+ 2, // 32: service.NodeService.GetLogs:input_type -> service.Empty
+ 2, // 33: service.NodeService.GetSystemStats:input_type -> service.Empty
+ 2, // 34: service.NodeService.GetBackendStats:input_type -> service.Empty
+ 8, // 35: service.NodeService.GetStats:input_type -> service.StatRequest
+ 12, // 36: service.NodeService.GetOutboundsLatency:input_type -> service.LatencyRequest
+ 8, // 37: service.NodeService.GetUserOnlineStats:input_type -> service.StatRequest
+ 8, // 38: service.NodeService.GetUserOnlineIpListStats:input_type -> service.StatRequest
+ 28, // 39: service.NodeService.SyncUser:input_type -> service.User
+ 29, // 40: service.NodeService.SyncUsers:input_type -> service.Users
+ 30, // 41: service.NodeService.SyncUsersChunked:input_type -> service.UsersChunk
+ 32, // 42: service.NodeService.SetUserSpeeds:input_type -> service.SetUserSpeedsRequest
+ 2, // 43: service.NodeService.ListRoutingRules:input_type -> service.Empty
+ 37, // 44: service.NodeService.GetBalancerInfo:input_type -> service.BalancerInfoRequest
+ 39, // 45: service.NodeService.TestRoute:input_type -> service.TestRouteRequest
+ 41, // 46: service.NodeService.AddRoutingRule:input_type -> service.AddRoutingRuleRequest
+ 44, // 47: service.NodeService.RemoveRoutingRule:input_type -> service.RemoveRoutingRuleRequest
+ 45, // 48: service.NodeService.OverrideBalancerTarget:input_type -> service.OverrideBalancerTargetRequest
+ 3, // 49: service.NodeService.Start:output_type -> service.BaseInfoResponse
+ 2, // 50: service.NodeService.Stop:output_type -> service.Empty
+ 2, // 51: service.NodeService.AddBackend:output_type -> service.Empty
+ 2, // 52: service.NodeService.RemoveBackend:output_type -> service.Empty
+ 43, // 53: service.NodeService.ListBackends:output_type -> service.BackendList
+ 3, // 54: service.NodeService.GetBaseInfo:output_type -> service.BaseInfoResponse
+ 5, // 55: service.NodeService.GetLogs:output_type -> service.Log
+ 15, // 56: service.NodeService.GetSystemStats:output_type -> service.SystemStatsResponse
+ 14, // 57: service.NodeService.GetBackendStats:output_type -> service.BackendStatsResponse
+ 7, // 58: service.NodeService.GetStats:output_type -> service.StatResponse
+ 13, // 59: service.NodeService.GetOutboundsLatency:output_type -> service.LatencyResponse
+ 9, // 60: service.NodeService.GetUserOnlineStats:output_type -> service.OnlineStatResponse
+ 10, // 61: service.NodeService.GetUserOnlineIpListStats:output_type -> service.StatsOnlineIpListResponse
+ 2, // 62: service.NodeService.SyncUser:output_type -> service.Empty
+ 2, // 63: service.NodeService.SyncUsers:output_type -> service.Empty
+ 2, // 64: service.NodeService.SyncUsersChunked:output_type -> service.Empty
+ 34, // 65: service.NodeService.SetUserSpeeds:output_type -> service.SetUserSpeedsResponse
+ 36, // 66: service.NodeService.ListRoutingRules:output_type -> service.RoutingRulesResponse
+ 38, // 67: service.NodeService.GetBalancerInfo:output_type -> service.BalancerInfoResponse
+ 40, // 68: service.NodeService.TestRoute:output_type -> service.RouteResult
+ 2, // 69: service.NodeService.AddRoutingRule:output_type -> service.Empty
+ 2, // 70: service.NodeService.RemoveRoutingRule:output_type -> service.Empty
+ 2, // 71: service.NodeService.OverrideBalancerTarget:output_type -> service.Empty
+ 49, // [49:72] is the sub-list for method output_type
+ 26, // [26:49] is the sub-list for method input_type
+ 26, // [26:26] is the sub-list for extension type_name
+ 26, // [26:26] is the sub-list for extension extendee
+ 0, // [0:26] is the sub-list for field type_name
}
func init() { file_common_service_proto_init() }
@@ -2887,7 +3176,7 @@ func file_common_service_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_service_proto_rawDesc), len(file_common_service_proto_rawDesc)),
NumEnums: 2,
- NumMessages: 42,
+ NumMessages: 46,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/common/service.proto b/common/service.proto
index 98fb3cf7..f7bab131 100644
--- a/common/service.proto
+++ b/common/service.proto
@@ -15,16 +15,18 @@ message BaseInfoResponse {
bool filter_rules_stripped = 5;
string filter_strip_reason = 6;
repeated string stripped_rule_tags = 7;
+ bool supports_speed_cap = 8;
}
enum BackendType {
XRAY = 0;
WIREGUARD = 1;
- SING_BOX = 2;
OPEN_VPN = 3;
L2TP = 5;
reserved 4;
reserved "MTPROTO";
+ reserved 2;
+ reserved "SING_BOX";
}
message Backend {
@@ -147,8 +149,6 @@ message Hysteria {
string auth = 1;
}
-// sing-box Hysteria2 inbound user credential (distinct from xray-core's
-// native "Hysteria" v1 auth string above — Hysteria2 uses a password).
message Hysteria2 {
string password = 1;
}
@@ -214,6 +214,32 @@ message UsersChunk {
bool last = 3;
}
+message SpeedEntry {
+ string email = 1;
+ uint64 down_bps = 2;
+ uint64 up_bps = 3;
+ uint64 revision = 4;
+ repeated string inbound_tags = 5;
+}
+
+message SetUserSpeedsRequest {
+ repeated SpeedEntry entries = 1;
+ bool replace_all = 2;
+ uint64 snapshot_revision = 3;
+}
+
+message SpeedRejection {
+ string email = 1;
+ string backend = 2;
+ string reason = 3;
+}
+
+message SetUserSpeedsResponse {
+ repeated SpeedRejection rejected = 1;
+ uint64 high_water = 2;
+ repeated string stale = 3;
+}
+
// Service for node management and connection
// Routing (mirrors xray app/router/command, node-friendly shapes)
message RoutingRule {
@@ -287,6 +313,7 @@ service NodeService {
rpc SyncUser (stream User) returns (Empty) {}
rpc SyncUsers (Users) returns (Empty) {}
rpc SyncUsersChunked (stream UsersChunk) returns (Empty) {}
+ rpc SetUserSpeeds (SetUserSpeedsRequest) returns (SetUserSpeedsResponse) {}
rpc ListRoutingRules (Empty) returns (RoutingRulesResponse) {}
rpc GetBalancerInfo (BalancerInfoRequest) returns (BalancerInfoResponse) {}
rpc TestRoute (TestRouteRequest) returns (RouteResult) {}
diff --git a/common/service_grpc.pb.go b/common/service_grpc.pb.go
index 207901c8..d48cc8f0 100644
--- a/common/service_grpc.pb.go
+++ b/common/service_grpc.pb.go
@@ -35,6 +35,7 @@ const (
NodeService_SyncUser_FullMethodName = "/service.NodeService/SyncUser"
NodeService_SyncUsers_FullMethodName = "/service.NodeService/SyncUsers"
NodeService_SyncUsersChunked_FullMethodName = "/service.NodeService/SyncUsersChunked"
+ NodeService_SetUserSpeeds_FullMethodName = "/service.NodeService/SetUserSpeeds"
NodeService_ListRoutingRules_FullMethodName = "/service.NodeService/ListRoutingRules"
NodeService_GetBalancerInfo_FullMethodName = "/service.NodeService/GetBalancerInfo"
NodeService_TestRoute_FullMethodName = "/service.NodeService/TestRoute"
@@ -65,6 +66,7 @@ type NodeServiceClient interface {
SyncUser(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[User, Empty], error)
SyncUsers(ctx context.Context, in *Users, opts ...grpc.CallOption) (*Empty, error)
SyncUsersChunked(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[UsersChunk, Empty], error)
+ SetUserSpeeds(ctx context.Context, in *SetUserSpeedsRequest, opts ...grpc.CallOption) (*SetUserSpeedsResponse, error)
ListRoutingRules(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*RoutingRulesResponse, error)
GetBalancerInfo(ctx context.Context, in *BalancerInfoRequest, opts ...grpc.CallOption) (*BalancerInfoResponse, error)
TestRoute(ctx context.Context, in *TestRouteRequest, opts ...grpc.CallOption) (*RouteResult, error)
@@ -256,6 +258,16 @@ func (c *nodeServiceClient) SyncUsersChunked(ctx context.Context, opts ...grpc.C
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type NodeService_SyncUsersChunkedClient = grpc.ClientStreamingClient[UsersChunk, Empty]
+func (c *nodeServiceClient) SetUserSpeeds(ctx context.Context, in *SetUserSpeedsRequest, opts ...grpc.CallOption) (*SetUserSpeedsResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(SetUserSpeedsResponse)
+ err := c.cc.Invoke(ctx, NodeService_SetUserSpeeds_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
func (c *nodeServiceClient) ListRoutingRules(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*RoutingRulesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RoutingRulesResponse)
@@ -338,6 +350,7 @@ type NodeServiceServer interface {
SyncUser(grpc.ClientStreamingServer[User, Empty]) error
SyncUsers(context.Context, *Users) (*Empty, error)
SyncUsersChunked(grpc.ClientStreamingServer[UsersChunk, Empty]) error
+ SetUserSpeeds(context.Context, *SetUserSpeedsRequest) (*SetUserSpeedsResponse, error)
ListRoutingRules(context.Context, *Empty) (*RoutingRulesResponse, error)
GetBalancerInfo(context.Context, *BalancerInfoRequest) (*BalancerInfoResponse, error)
TestRoute(context.Context, *TestRouteRequest) (*RouteResult, error)
@@ -402,6 +415,9 @@ func (UnimplementedNodeServiceServer) SyncUsers(context.Context, *Users) (*Empty
func (UnimplementedNodeServiceServer) SyncUsersChunked(grpc.ClientStreamingServer[UsersChunk, Empty]) error {
return status.Error(codes.Unimplemented, "method SyncUsersChunked not implemented")
}
+func (UnimplementedNodeServiceServer) SetUserSpeeds(context.Context, *SetUserSpeedsRequest) (*SetUserSpeedsResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method SetUserSpeeds not implemented")
+}
func (UnimplementedNodeServiceServer) ListRoutingRules(context.Context, *Empty) (*RoutingRulesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListRoutingRules not implemented")
}
@@ -700,6 +716,24 @@ func _NodeService_SyncUsersChunked_Handler(srv interface{}, stream grpc.ServerSt
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type NodeService_SyncUsersChunkedServer = grpc.ClientStreamingServer[UsersChunk, Empty]
+func _NodeService_SetUserSpeeds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SetUserSpeedsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(NodeServiceServer).SetUserSpeeds(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: NodeService_SetUserSpeeds_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(NodeServiceServer).SetUserSpeeds(ctx, req.(*SetUserSpeedsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
func _NodeService_ListRoutingRules_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty)
if err := dec(in); err != nil {
@@ -867,6 +901,10 @@ var NodeService_ServiceDesc = grpc.ServiceDesc{
MethodName: "SyncUsers",
Handler: _NodeService_SyncUsers_Handler,
},
+ {
+ MethodName: "SetUserSpeeds",
+ Handler: _NodeService_SetUserSpeeds_Handler,
+ },
{
MethodName: "ListRoutingRules",
Handler: _NodeService_ListRoutingRules_Handler,
diff --git a/config/config.go b/config/config.go
index a6ec7826..3d273274 100644
--- a/config/config.go
+++ b/config/config.go
@@ -18,7 +18,6 @@ type Config struct {
NodeHost string
XrayExecutablePath string
XrayAssetsPath string
- SingBoxExecutablePath string
OpenVPNExecutablePath string
SslCertFile string
SslKeyFile string
@@ -31,6 +30,8 @@ type Config struct {
StatsUpdateIntervalSeconds int
StatsCleanupIntervalSeconds int
GrpcMaxConcurrentStreams uint32
+ SpeedCapFile string
+ SpeedCapLeaseSeconds int
// WireGuard host routing (Linux). See .env.example for semantics.
WGHostRouting bool
@@ -51,7 +52,6 @@ func Load() (*Config, error) {
ServicePort: GetEnvAsInt("SERVICE_PORT", 62050),
XrayExecutablePath: GetEnv("XRAY_EXECUTABLE_PATH", "/usr/local/bin/xray"),
XrayAssetsPath: GetEnv("XRAY_ASSETS_PATH", "/usr/local/share/xray"),
- SingBoxExecutablePath: GetEnv("SINGBOX_EXECUTABLE_PATH", "/usr/local/bin/sing-box"),
OpenVPNExecutablePath: GetEnv("OPENVPN_EXECUTABLE_PATH", "/usr/sbin/openvpn"),
SslCertFile: GetEnv("SSL_CERT_FILE", "/var/lib/pg-node/certs/ssl_cert.pem"),
SslKeyFile: GetEnv("SSL_KEY_FILE", "/var/lib/pg-node/certs/ssl_key.pem"),
@@ -63,6 +63,8 @@ func Load() (*Config, error) {
StatsUpdateIntervalSeconds: GetEnvAsInt("STATS_UPDATE_INTERVAL_SECONDS", 10),
StatsCleanupIntervalSeconds: GetEnvAsInt("STATS_CLEANUP_INTERVAL_SECONDS", 300),
GrpcMaxConcurrentStreams: uint32(GetEnvAsInt("GRPC_MAX_CONCURRENT_STREAMS", 64)),
+ SpeedCapFile: GetEnv("SPEED_CAP_FILE", "/var/lib/pg-node/speedcaps/speed_caps.json"),
+ SpeedCapLeaseSeconds: GetEnvAsInt("SPEED_CAP_LEASE_SECONDS", 600),
WGHostRouting: GetEnvAsBool("PG_NODE_WG_HOST_ROUTING", true),
WGNATOutputInterface: GetEnv("PG_NODE_WG_NAT_OUTPUT_INTERFACE", ""),
diff --git a/config/config_test.go b/config/config_test.go
index 8934e9b9..f102b821 100644
--- a/config/config_test.go
+++ b/config/config_test.go
@@ -189,3 +189,49 @@ func TestLoadFallsBackToLoopbackOnInvalidNodeHost(t *testing.T) {
})
}
}
+
+func TestSpeedCapFileDefaultsUnderTheNodeDataDirectory(t *testing.T) {
+ t.Setenv("API_KEY", uuid.NewString())
+ t.Setenv("SPEED_CAP_FILE", "")
+ os.Unsetenv("SPEED_CAP_FILE")
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+ if cfg.SpeedCapFile != "/var/lib/pg-node/speedcaps/speed_caps.json" {
+ t.Fatalf("SpeedCapFile = %q", cfg.SpeedCapFile)
+ }
+
+ t.Setenv("SPEED_CAP_FILE", "/data/caps.json")
+ cfg, err = Load()
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+ if cfg.SpeedCapFile != "/data/caps.json" {
+ t.Fatalf("SPEED_CAP_FILE was ignored: %q", cfg.SpeedCapFile)
+ }
+}
+
+func TestSpeedCapLeaseDefaultsToTenMinutes(t *testing.T) {
+ t.Setenv("API_KEY", uuid.NewString())
+ t.Setenv("SPEED_CAP_LEASE_SECONDS", "")
+ os.Unsetenv("SPEED_CAP_LEASE_SECONDS")
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+ if cfg.SpeedCapLeaseSeconds != 600 {
+ t.Fatalf("SpeedCapLeaseSeconds = %d", cfg.SpeedCapLeaseSeconds)
+ }
+
+ t.Setenv("SPEED_CAP_LEASE_SECONDS", "45")
+ cfg, err = Load()
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+ if cfg.SpeedCapLeaseSeconds != 45 {
+ t.Fatalf("SPEED_CAP_LEASE_SECONDS was ignored: %d", cfg.SpeedCapLeaseSeconds)
+ }
+}
diff --git a/controller/base_info_test.go b/controller/base_info_test.go
index 307b74d7..ec05b280 100644
--- a/controller/base_info_test.go
+++ b/controller/base_info_test.go
@@ -77,7 +77,7 @@ func TestBaseInfoResponseWithoutDegradation(t *testing.T) {
}
func TestNodeVersionIsPinned(t *testing.T) {
- if NodeVersion != "0.6.27" {
- t.Fatalf("NodeVersion = %q, want %q", NodeVersion, "0.6.27")
+ if NodeVersion != "0.6.29" {
+ t.Fatalf("NodeVersion = %q, want %q", NodeVersion, "0.6.29")
}
}
diff --git a/controller/controller.go b/controller/controller.go
index 9ee9dcc9..ef8f2f6c 100644
--- a/controller/controller.go
+++ b/controller/controller.go
@@ -12,20 +12,20 @@ import (
"github.com/pasarguard/node/backend"
"github.com/pasarguard/node/backend/l2tp"
"github.com/pasarguard/node/backend/openvpn"
- "github.com/pasarguard/node/backend/singbox"
"github.com/pasarguard/node/backend/wireguard"
"github.com/pasarguard/node/backend/xray"
"github.com/pasarguard/node/common"
"github.com/pasarguard/node/config"
"github.com/pasarguard/node/pkg/netutil"
+ "github.com/pasarguard/node/pkg/speedcap"
"github.com/pasarguard/node/pkg/sysstats"
)
-const NodeVersion = "0.6.27"
+const NodeVersion = "0.6.29"
const keepAliveGrace = 5 * time.Second
-var supportedBackends = []string{"xray", "wireguard", "sing_box", "open_vpn", "l2tp"}
+var supportedBackends = []string{"xray", "wireguard", "open_vpn", "l2tp"}
type Service interface {
Disconnect()
@@ -55,6 +55,10 @@ type Controller struct {
syncDrainGrace time.Duration
newBackend func(context.Context, *common.Backend, int, int) (backend.Backend, error)
carried map[common.BackendType]map[string]int64
+ speedCaps *speedcap.Store
+ speedCapLease time.Duration
+ leaseTimer *time.Timer
+ armedLease uint64
ownRxTotal int64
ownTxTotal int64
@@ -67,10 +71,12 @@ type Controller struct {
func New(cfg *config.Config) *Controller {
_, cancel := context.WithCancel(context.Background())
return &Controller{
- cfg: cfg,
- apiPort: netutil.FindFreePort(),
- metricPort: netutil.FindFreePort(),
- cancelFunc: cancel,
+ cfg: cfg,
+ apiPort: netutil.FindFreePort(),
+ metricPort: netutil.FindFreePort(),
+ cancelFunc: cancel,
+ speedCaps: speedcap.Open(cfg.SpeedCapFile),
+ speedCapLease: time.Duration(cfg.SpeedCapLeaseSeconds) * time.Second,
}
}
@@ -188,7 +194,7 @@ func (c *Controller) buildBackend(ctx context.Context, b *common.Backend, apiPor
if err != nil {
return nil, err
}
- return xray.New(ctx, config, b.GetUsers(), apiPort, metricPort, c.cfg)
+ return xray.NewWithSpeedCaps(ctx, config, b.GetUsers(), apiPort, metricPort, c.cfg, c.speedCaps)
case common.BackendType_WIREGUARD:
config, err := wireguard.NewConfig(b.GetConfig())
@@ -197,13 +203,6 @@ func (c *Controller) buildBackend(ctx context.Context, b *common.Backend, apiPor
}
return wireguard.New(c.cfg, config, b.GetUsers())
- case common.BackendType_SING_BOX:
- config, err := singbox.NewConfig(b.GetConfig())
- if err != nil {
- return nil, err
- }
- return singbox.New(ctx, config, b.GetUsers(), apiPort, metricPort, c.cfg)
-
case common.BackendType_OPEN_VPN:
config, err := openvpn.NewConfig(b.GetConfig())
if err != nil {
@@ -486,6 +485,10 @@ func (c *Controller) BaseInfoResponse() *common.BaseInfoResponse {
response.FilterStripReason = degradation.Reason
response.StrippedRuleTags = degradation.StrippedRuleTags
}
+
+ if capper, ok := c.backend.(speedCapBackend); ok && c.primaryType == common.BackendType_XRAY {
+ response.SupportsSpeedCap = capper.SupportsSpeedCaps()
+ }
}
return response
diff --git a/controller/lifecycle.go b/controller/lifecycle.go
index fd296177..51c5cf5f 100644
--- a/controller/lifecycle.go
+++ b/controller/lifecycle.go
@@ -180,6 +180,7 @@ func (c *Controller) ReplaceBackend(ctx context.Context, b *common.Backend) erro
}
return err
}
+ c.armSpeedCapLease()
return nil
}
@@ -189,6 +190,7 @@ func (c *Controller) Close() {
defer c.unlockLifecycle()
c.closed = true
+ c.stopSpeedCapLease()
c.disconnect()
}
diff --git a/controller/multi_backend.go b/controller/multi_backend.go
index 10c0d183..96a7ddd9 100644
--- a/controller/multi_backend.go
+++ b/controller/multi_backend.go
@@ -22,7 +22,6 @@ type extraBackend struct {
var multiInstanceBackends = map[common.BackendType]bool{
common.BackendType_WIREGUARD: true,
- common.BackendType_SING_BOX: true,
common.BackendType_OPEN_VPN: true,
common.BackendType_L2TP: true,
}
diff --git a/controller/multi_backend_test.go b/controller/multi_backend_test.go
index d5f31068..1e8b5b54 100644
--- a/controller/multi_backend_test.go
+++ b/controller/multi_backend_test.go
@@ -149,7 +149,7 @@ func TestQueueUserAllReachesEveryBackend(t *testing.T) {
primary := &queueingBackend{}
extraQueued := &queueingBackend{}
extraPlain := &recordingBackend{}
- c := controllerWithExtras(primary, common.BackendType_SING_BOX,
+ c := controllerWithExtras(primary, common.BackendType_XRAY,
extraBackend{backendType: common.BackendType_L2TP, backend: extraQueued},
extraBackend{backendType: common.BackendType_OPEN_VPN, backend: extraPlain})
@@ -254,7 +254,7 @@ func TestOnlineIpListsAreUnionedKeepingTheNewestTimestamp(t *testing.T) {
}
func TestXrayIsRefusedAsAnExtraBackend(t *testing.T) {
- c := controllerWithExtras(&recordingBackend{}, common.BackendType_SING_BOX)
+ c := controllerWithExtras(&recordingBackend{}, common.BackendType_WIREGUARD)
err := c.AttachBackend(context.Background(), &common.Backend{Type: common.BackendType_XRAY})
if !errors.Is(err, ErrBackendTypeNotShareable) {
@@ -304,10 +304,10 @@ func TestDetachShutsTheBackendDownAndForgetsIt(t *testing.T) {
func TestBackendTypesListsPrimaryFirst(t *testing.T) {
c := controllerWithExtras(&recordingBackend{}, common.BackendType_XRAY,
extraBackend{backendType: common.BackendType_L2TP, backend: &recordingBackend{}},
- extraBackend{backendType: common.BackendType_SING_BOX, backend: &recordingBackend{}})
+ extraBackend{backendType: common.BackendType_OPEN_VPN, backend: &recordingBackend{}})
types := c.BackendTypes()
- want := []common.BackendType{common.BackendType_XRAY, common.BackendType_L2TP, common.BackendType_SING_BOX}
+ want := []common.BackendType{common.BackendType_XRAY, common.BackendType_L2TP, common.BackendType_OPEN_VPN}
if len(types) != len(want) {
t.Fatalf("expected %d backends, got %v", len(want), types)
}
@@ -324,7 +324,7 @@ func TestShutdownExtrasStopsEveryExtraBackend(t *testing.T) {
primary := &recordingBackend{}
c := controllerWithExtras(primary, common.BackendType_XRAY,
extraBackend{backendType: common.BackendType_L2TP, backend: first},
- extraBackend{backendType: common.BackendType_SING_BOX, backend: second})
+ extraBackend{backendType: common.BackendType_OPEN_VPN, backend: second})
c.shutdownExtras()
@@ -357,7 +357,7 @@ func TestUnsupportedStatTypeIsNotLoggedAsAFailure(t *testing.T) {
mixed := joinBackendErrors([]backendResult[any]{
{backendType: common.BackendType_WIREGUARD, err: notSupported},
- {backendType: common.BackendType_SING_BOX, err: realFailure},
+ {backendType: common.BackendType_OPEN_VPN, err: realFailure},
})
unexpected := 0
for _, err := range mixed {
@@ -398,7 +398,7 @@ func TestAttachBuiltInstallsAtMostOnePerTypeUnderConcurrency(t *testing.T) {
wg.Add(1)
go func(i int) {
defer wg.Done()
- errs[i] = c.attachBuilt(common.BackendType_SING_BOX, built[i])
+ errs[i] = c.attachBuilt(common.BackendType_OPEN_VPN, built[i])
}(i)
}
wg.Wait()
@@ -466,10 +466,10 @@ func TestAttachBuiltRejectsASecondOfTheSameTypeAndShutsItDown(t *testing.T) {
primary := &recordingBackend{name: "primary"}
first := &recordingBackend{name: "first"}
c := controllerWithExtras(primary, common.BackendType_XRAY,
- extraBackend{backendType: common.BackendType_SING_BOX, backend: first})
+ extraBackend{backendType: common.BackendType_OPEN_VPN, backend: first})
second := &recordingBackend{name: "second"}
- err := c.attachBuilt(common.BackendType_SING_BOX, second)
+ err := c.attachBuilt(common.BackendType_OPEN_VPN, second)
if err == nil {
t.Fatal("attaching a second backend of a type already present must fail")
}
diff --git a/controller/rest/backends_test.go b/controller/rest/backends_test.go
index 3bf862d9..f59c9081 100644
--- a/controller/rest/backends_test.go
+++ b/controller/rest/backends_test.go
@@ -1,75 +1,13 @@
package rest
import (
- "encoding/json"
- "math/rand/v2"
- "net"
"net/http"
- "os"
+ "strings"
"testing"
"github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
)
-const (
- firstTestPort = 20000
- testPortSpan = 10000
-)
-
-func restFreeTCPPort(t *testing.T) int {
- t.Helper()
- for range 1000 {
- port := firstTestPort + rand.IntN(testPortSpan)
- if listenPortIsFree(port) {
- return port
- }
- }
- t.Fatalf("no port between %d and %d is free on both 127.0.0.1 and the wildcard", firstTestPort, firstTestPort+testPortSpan-1)
- return 0
-}
-
-func listenPortIsFree(port int) bool {
- for _, addr := range []*net.TCPAddr{{IP: net.IPv4(127, 0, 0, 1), Port: port}, {Port: port}} {
- l, err := net.ListenTCP("tcp", addr)
- if err != nil {
- return false
- }
- _ = l.Close()
- }
- return true
-}
-
-func singBoxTestConfig(t *testing.T, port int) string {
- t.Helper()
- cfg := map[string]any{
- "log": map[string]any{"level": "error"},
- "inbounds": []any{map[string]any{
- "type": "shadowsocks",
- "tag": "ss-extra",
- "listen": "127.0.0.1",
- "listen_port": port,
- "method": "chacha20-ietf-poly1305",
- "password": "TFpVSnpFOEJqSEJEY0kyQQ==",
- "users": []any{},
- }},
- "outbounds": []any{map[string]any{"type": "direct"}},
- }
- raw, err := json.Marshal(cfg)
- if err != nil {
- t.Fatalf("marshal sing-box config: %v", err)
- }
- return string(raw)
-}
-
-func requireSingBoxBinary(t *testing.T) {
- t.Helper()
- path := config.GetEnv("SINGBOX_EXECUTABLE_PATH", "/usr/local/bin/sing-box")
- if _, err := os.Stat(path); err != nil {
- t.Skipf("no sing-box binary at %s; set SINGBOX_EXECUTABLE_PATH=/path/to/sing-box to run it", path)
- }
-}
-
func listBackends(t *testing.T) []common.BackendType {
t.Helper()
response := &common.BackendList{}
@@ -79,20 +17,6 @@ func listBackends(t *testing.T) []common.BackendType {
return response.GetTypes()
}
-func addExtraBackend(t *testing.T, backendType common.BackendType, config string) {
- t.Helper()
- add := &common.Backend{Type: backendType, Config: config, Users: []*common.User{}}
- if err := sharedTestCtx.createAuthenticatedRequest(http.MethodPost, "/backend", add, &common.Empty{}); err != nil {
- t.Fatalf("POST /backend (%v): %v", backendType, err)
- }
- t.Cleanup(func() {
- _ = sharedTestCtx.createAuthenticatedRequest(
- http.MethodDelete, "/backend",
- &common.RemoveBackendRequest{Type: backendType}, &common.Empty{},
- )
- })
-}
-
func TestREST_ListBackendsReportsThePrimaryAlone(t *testing.T) {
types := listBackends(t)
if len(types) != 1 || types[0] != common.BackendType_XRAY {
@@ -100,34 +24,25 @@ func TestREST_ListBackendsReportsThePrimaryAlone(t *testing.T) {
}
}
-func TestREST_StatsStillWorkWithTwoBackends(t *testing.T) {
- requireSingBoxBinary(t)
-
- addExtraBackend(t, common.BackendType_SING_BOX, singBoxTestConfig(t, restFreeTCPPort(t)))
-
- stats := &common.StatResponse{}
- if err := sharedTestCtx.createAuthenticatedRequest(http.MethodGet, "/stats?type=Outbounds&reset=false", nil, stats); err != nil {
- t.Fatalf("GET /stats with two backends: %v", err)
+func TestREST_TheRemovedBackendType2IsRefusedAndThePrimaryKeepsRunning(t *testing.T) {
+ removed := &common.Backend{
+ Type: common.BackendType(2),
+ Config: `{"log":{"level":"error"},"inbounds":[],"outbounds":[{"type":"direct"}]}`,
+ Users: []*common.User{},
}
-}
-
-func TestREST_AddRemoveSingBoxBackend(t *testing.T) {
- requireSingBoxBinary(t)
-
- addExtraBackend(t, common.BackendType_SING_BOX, singBoxTestConfig(t, restFreeTCPPort(t)))
-
- types := listBackends(t)
- if len(types) != 2 || types[0] != common.BackendType_XRAY || types[1] != common.BackendType_SING_BOX {
- t.Fatalf("expected [XRAY SING_BOX] with the primary first, got %v", types)
+ err := sharedTestCtx.createAuthenticatedRequest(http.MethodPost, "/backend", removed, &common.Empty{})
+ if err == nil || !strings.Contains(err.Error(), "400 Bad Request") {
+ t.Fatalf("POST /backend of backend type 2 must be refused with 400 Bad Request, got %v", err)
}
-
- remove := &common.RemoveBackendRequest{Type: common.BackendType_SING_BOX}
- if err := sharedTestCtx.createAuthenticatedRequest(http.MethodDelete, "/backend", remove, &common.Empty{}); err != nil {
- t.Fatalf("DELETE /backend: %v", err)
+ err = sharedTestCtx.createAuthenticatedRequest(http.MethodDelete, "/backend", &common.RemoveBackendRequest{Type: common.BackendType(2)}, &common.Empty{})
+ if err == nil || !strings.Contains(err.Error(), "404 Not Found") {
+ t.Fatalf("DELETE /backend of backend type 2 must report 404 Not Found, got %v", err)
}
-
- types = listBackends(t)
- if len(types) != 1 || types[0] != common.BackendType_XRAY {
- t.Fatalf("removing the extra backend must leave the primary alone, got %v", types)
+ if types := listBackends(t); len(types) != 1 || types[0] != common.BackendType_XRAY {
+ t.Fatalf("the refusals must leave the Xray primary as the only backend, got %v", types)
+ }
+ stats := &common.StatResponse{}
+ if err := sharedTestCtx.createAuthenticatedRequest(http.MethodGet, "/stats?type=Outbounds&reset=false", nil, stats); err != nil {
+ t.Fatalf("GET /stats after the refusals: %v", err)
}
}
diff --git a/controller/rest/middleware.go b/controller/rest/middleware.go
index 7e7af530..27eeb73a 100644
--- a/controller/rest/middleware.go
+++ b/controller/rest/middleware.go
@@ -96,6 +96,9 @@ func (s *Service) trackRequest(next http.Handler) http.Handler {
}
s.NewRequest()
defer s.NewRequest()
+ if r.Method == http.MethodPut && r.URL.Path == userSpeedsPath {
+ s.EndSpeedCapLease()
+ }
next.ServeHTTP(w, r)
})
diff --git a/controller/rest/service.go b/controller/rest/service.go
index ef919a7e..997f2b9e 100644
--- a/controller/rest/service.go
+++ b/controller/rest/service.go
@@ -22,6 +22,8 @@ func New(cfg *config.Config) *Service {
return s
}
+const userSpeedsPath = "/user/speeds"
+
func (s *Service) setRouter() {
router := chi.NewRouter()
@@ -53,6 +55,7 @@ func (s *Service) setRouter() {
statsGroup.Get("/system", s.GetSystemStats)
})
private.Put("/user/sync", s.SyncUser)
+ private.Put(userSpeedsPath, s.SetUserSpeeds)
private.Put("/users/sync", s.SyncUsers)
private.Put("/users/sync/chunked", s.SyncUsersChunked)
diff --git a/controller/rest/speedcap.go b/controller/rest/speedcap.go
new file mode 100644
index 00000000..92af5f1d
--- /dev/null
+++ b/controller/rest/speedcap.go
@@ -0,0 +1,53 @@
+package rest
+
+import (
+ "io"
+ "net/http"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/pasarguard/node/common"
+)
+
+func speedCapFailureStatus(err error) int {
+ switch status.Code(err) {
+ case codes.Unimplemented:
+ return http.StatusNotImplemented
+ case codes.Unavailable:
+ return http.StatusServiceUnavailable
+ case codes.InvalidArgument:
+ return http.StatusBadRequest
+ }
+ return http.StatusInternalServerError
+}
+
+func (s *Service) SetUserSpeeds(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "Failed to read request body", http.StatusBadRequest)
+ return
+ }
+ defer r.Body.Close()
+
+ request := &common.SetUserSpeedsRequest{}
+ if err = proto.Unmarshal(body, request); err != nil {
+ http.Error(w, "Failed to decode speed caps", http.StatusBadRequest)
+ return
+ }
+
+ response, err := s.ApplyUserSpeeds(r.Context(), request)
+ if err != nil {
+ http.Error(w, status.Convert(err).Message(), speedCapFailureStatus(err))
+ return
+ }
+
+ raw, err := proto.Marshal(response)
+ if err != nil {
+ http.Error(w, "Failed to encode response", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ _, _ = w.Write(raw)
+}
diff --git a/controller/rest/speedcap_lease_test.go b/controller/rest/speedcap_lease_test.go
new file mode 100644
index 00000000..423feecd
--- /dev/null
+++ b/controller/rest/speedcap_lease_test.go
@@ -0,0 +1,89 @@
+package rest
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/config"
+ "github.com/pasarguard/node/pkg/netutil"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+func TestASpeedPutTheBackendGateRefusesStillEndsTheSpeedCapLease(t *testing.T) {
+ dir := t.TempDir()
+ key := uuid.New()
+ cfg := config.NewTestConfig(dir, key)
+ cfg.XrayAssetsPath = dir
+ cfg.SpeedCapFile = filepath.Join(dir, "speed_caps.json")
+ cfg.SpeedCapLeaseSeconds = 1
+ s := New(cfg)
+ t.Cleanup(s.Close)
+
+ xrayConfig, err := json.Marshal(map[string]any{
+ "log": map[string]any{"loglevel": "warning"},
+ "inbounds": []any{map[string]any{
+ "tag": "speed-in", "listen": "127.0.0.1", "port": netutil.FindFreePort(), "protocol": "vless",
+ "settings": map[string]any{"clients": []any{}, "decryption": "none"},
+ }},
+ "outbounds": []any{map[string]any{"tag": "direct", "protocol": "freedom"}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ serve := func(method, path string, message proto.Message) *httptest.ResponseRecorder {
+ t.Helper()
+ var body []byte
+ if message != nil {
+ if body, err = proto.Marshal(message); err != nil {
+ t.Fatal(err)
+ }
+ }
+ req := httptest.NewRequest(method, path, bytes.NewReader(body))
+ req.RemoteAddr = keepAliveOwnerIP + ":40000"
+ req.Header.Set("x-api-key", key.String())
+ rec := httptest.NewRecorder()
+ s.Router.ServeHTTP(rec, req)
+ return rec
+ }
+ start := func() {
+ t.Helper()
+ if rec := serve(http.MethodPost, "/start", &common.Backend{Type: common.BackendType_XRAY, Config: string(xrayConfig)}); rec.Code != http.StatusOK {
+ t.Fatalf("the Start answered %d %q", rec.Code, rec.Body.String())
+ }
+ }
+ snapshot := func(revision uint64) *httptest.ResponseRecorder {
+ t.Helper()
+ return serve(http.MethodPut, "/user/speeds", &common.SetUserSpeedsRequest{ReplaceAll: true, SnapshotRevision: revision, Entries: []*common.SpeedEntry{{Email: "21", DownBps: 8_000_000, Revision: revision}}})
+ }
+
+ start()
+ if rec := snapshot(5); rec.Code != http.StatusOK {
+ if rec.Code == http.StatusNotImplemented {
+ t.Skipf("this xray core cannot cap speeds: %s", rec.Body.String())
+ }
+ t.Fatalf("the first snapshot answered %d %q", rec.Code, rec.Body.String())
+ }
+ start()
+ if rec := serve(http.MethodPut, "/stop", nil); rec.Code != http.StatusOK {
+ t.Fatalf("the Stop answered %d %q", rec.Code, rec.Body.String())
+ }
+
+ for refused := time.Now(); time.Since(refused) < 3*time.Second; time.Sleep(100 * time.Millisecond) {
+ if rec := snapshot(6); rec.Code < 500 || !strings.Contains(rec.Body.String(), "backend not initialized") {
+ t.Fatalf("a snapshot to a stopped node answered %d %q, want the backend gate's error", rec.Code, rec.Body.String())
+ }
+ }
+ if state := speedcap.Open(cfg.SpeedCapFile).State(); len(state.Entries) != 1 || state.Entries[0].Down != 8_000_000 {
+ t.Fatalf("the panel kept sending snapshots that the backend gate refused, yet the lease cleared the stored caps: %+v", state)
+ }
+}
diff --git a/controller/rest/speedcap_test.go b/controller/rest/speedcap_test.go
new file mode 100644
index 00000000..009db1ad
--- /dev/null
+++ b/controller/rest/speedcap_test.go
@@ -0,0 +1,59 @@
+package rest
+
+import (
+ "bytes"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "google.golang.org/protobuf/proto"
+
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/controller"
+)
+
+func TestSpeedCapFailuresMapToTheStatusThePanelReads(t *testing.T) {
+ for _, c := range []struct {
+ err error
+ want int
+ }{
+ {controller.ErrSpeedCapNeedsXray, http.StatusNotImplemented},
+ {controller.ErrSpeedCapUnsupportedCore, http.StatusNotImplemented},
+ {controller.ErrBackendNotInitialized, http.StatusServiceUnavailable},
+ {errors.New("disk full"), http.StatusInternalServerError},
+ } {
+ if got := speedCapFailureStatus(c.err); got != c.want {
+ t.Fatalf("%v maps to %d, want %d", c.err, got, c.want)
+ }
+ }
+}
+
+func TestSetUserSpeedsIsGatedLikeEveryOtherPrivateRoute(t *testing.T) {
+ body, err := proto.Marshal(&common.SetUserSpeedsRequest{Entries: []*common.SpeedEntry{{Email: "12", DownBps: 10_000_000, Revision: 1}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ put := func(s *Service, key string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPut, "/user/speeds", bytes.NewReader(body))
+ req.RemoteAddr = "127.0.0.1:40000"
+ req.Header.Set("x-api-key", key)
+ rec := httptest.NewRecorder()
+ s.Router.ServeHTTP(rec, req)
+ return rec
+ }
+
+ s, key := newKeepAliveTestService(t)
+ s.Connect("10.9.9.9", 0)
+ if rec := put(s, key.String()); rec.Code != http.StatusForbidden {
+ t.Fatalf("another client got %d %q, want 403", rec.Code, rec.Body.String())
+ }
+
+ s, key = newKeepAliveTestService(t)
+ s.Connect("127.0.0.1", 0)
+ rec := put(s, key.String())
+ if rec.Code == http.StatusNotImplemented || rec.Code < 500 || !strings.Contains(rec.Body.String(), "backend not initialized") {
+ t.Fatalf("without a backend the route answered %d %q, want the backend gate's retryable error", rec.Code, rec.Body.String())
+ }
+}
diff --git a/controller/rpc/method_gates_test.go b/controller/rpc/method_gates_test.go
new file mode 100644
index 00000000..e73de627
--- /dev/null
+++ b/controller/rpc/method_gates_test.go
@@ -0,0 +1,94 @@
+package rpc
+
+import (
+ "context"
+ "sort"
+ "testing"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/pasarguard/node/common"
+)
+
+var publicMethods = map[string]bool{
+ "/service.NodeService/Start": true,
+ "/service.NodeService/GetBaseInfo": true,
+}
+
+var knownUnclassifiedRPCs = map[string]bool{
+ "/service.NodeService/GetOutboundsLatency": true,
+}
+
+func nodeServiceMethods(t *testing.T) []string {
+ t.Helper()
+ service := common.File_common_service_proto.Services().ByName("NodeService")
+ if service == nil {
+ t.Fatal("NodeService is missing from the proto")
+ }
+ methods := make([]string, 0, service.Methods().Len())
+ for i := 0; i < service.Methods().Len(); i++ {
+ methods = append(methods, "/service.NodeService/"+string(service.Methods().Get(i).Name()))
+ }
+ sort.Strings(methods)
+ return methods
+}
+
+func TestEveryNodeServiceRPCHasExactlyOneGate(t *testing.T) {
+ sets := map[string]map[string]bool{
+ "backendMethods": backendMethods,
+ "currentClientMethods": currentClientMethods,
+ "publicMethods": publicMethods,
+ "knownUnclassifiedRPCs": knownUnclassifiedRPCs,
+ }
+ known := make(map[string]bool)
+ for _, method := range nodeServiceMethods(t) {
+ known[method] = true
+ var in []string
+ for name, set := range sets {
+ if set[method] {
+ in = append(in, name)
+ }
+ }
+ if len(in) != 1 {
+ t.Errorf("%s is in %v; every RPC must be in exactly one of backendMethods, currentClientMethods, publicMethods or knownUnclassifiedRPCs", method, in)
+ }
+ }
+ for name, set := range sets {
+ for method := range set {
+ if !known[method] {
+ t.Errorf("%s names %s, which NodeService does not have", name, method)
+ }
+ }
+ }
+}
+
+func TestSetUserSpeedsIsGatedLikeEveryOtherBackendCall(t *testing.T) {
+ info := &grpc.UnaryServerInfo{FullMethod: "/service.NodeService/SetUserSpeeds"}
+ request := &common.SetUserSpeedsRequest{Entries: []*common.SpeedEntry{{Email: "12", DownBps: 10_000_000, Revision: 1}}}
+
+ t.Run("another client", func(t *testing.T) {
+ s, key := newKeepAliveTestService(t)
+ s.Connect("10.9.9.9", 0)
+ _, err := ConditionalMiddleware(s)(withAPIKey(key.String()), request, info, func(ctx context.Context, req any) (any, error) {
+ t.Error("SetUserSpeeds ran for a client that does not control the node")
+ return s.SetUserSpeeds(ctx, req.(*common.SetUserSpeedsRequest))
+ })
+ if status.Code(err) != codes.PermissionDenied {
+ t.Fatalf("err = %v, want PermissionDenied", err)
+ }
+ })
+
+ t.Run("no backend", func(t *testing.T) {
+ s, key := newKeepAliveTestService(t)
+ s.Connect("127.0.0.1", 0)
+ _, err := ConditionalMiddleware(s)(withAPIKey(key.String()), request, info, func(ctx context.Context, req any) (any, error) {
+ t.Error("SetUserSpeeds ran without a backend")
+ return s.SetUserSpeeds(ctx, req.(*common.SetUserSpeedsRequest))
+ })
+ if status.Code(err) != codes.Unavailable {
+ t.Fatalf("err = %v, want Unavailable", err)
+ }
+ })
+}
diff --git a/controller/rpc/middleware.go b/controller/rpc/middleware.go
index df9d03c0..6e100ae9 100644
--- a/controller/rpc/middleware.go
+++ b/controller/rpc/middleware.go
@@ -15,6 +15,8 @@ import (
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"google.golang.org/grpc/tap"
+
+ "github.com/pasarguard/node/common"
)
func clientIPFromContext(ctx context.Context) string {
@@ -159,6 +161,9 @@ func trackRequestMiddleware(s *Service) grpc.UnaryServerInterceptor {
}
s.NewRequest()
defer s.NewRequest()
+ if info.FullMethod == common.NodeService_SetUserSpeeds_FullMethodName {
+ s.EndSpeedCapLease()
+ }
return handler(ctx, req)
}
@@ -296,6 +301,7 @@ var backendMethods = map[string]bool{
"/service.NodeService/AddRoutingRule": true,
"/service.NodeService/RemoveRoutingRule": true,
"/service.NodeService/OverrideBalancerTarget": true,
+ "/service.NodeService/SetUserSpeeds": true,
}
var currentClientMethods = map[string]bool{
diff --git a/controller/rpc/preauth/removed_backend_type_test.go b/controller/rpc/preauth/removed_backend_type_test.go
new file mode 100644
index 00000000..f94505c0
--- /dev/null
+++ b/controller/rpc/preauth/removed_backend_type_test.go
@@ -0,0 +1,70 @@
+package preauth_test
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/pasarguard/node/common"
+)
+
+const removedBackendType = common.BackendType(2)
+
+func removedBackendRequest(t *testing.T) *common.Backend {
+ t.Helper()
+ return &common.Backend{
+ Type: removedBackendType,
+ Config: fmt.Sprintf(`{"log":{"level":"error"},"inbounds":[{"type":"shadowsocks","tag":"ss-extra","listen":"127.0.0.1","listen_port":%d,"method":"chacha20-ietf-poly1305","password":"TFpVSnpFOEJqSEJEY0kyQQ==","users":[]}],"outbounds":[{"type":"direct"}]}`, unusedListenPort(t)),
+ Users: []*common.User{panelUser(1, []string{"ss-extra"})},
+ KeepAlive: 60,
+ }
+}
+
+func TestTheRemovedBackendType2IsRefusedAndTheNodeKeepsServing(t *testing.T) {
+ client, key := authenticatedClient(t)
+
+ ctx, cancel := context.WithTimeout(withKey(key.String()), 60*time.Second)
+ defer cancel()
+
+ if _, err := client.Start(ctx, removedBackendRequest(t)); err == nil || !strings.Contains(status.Convert(err).Message(), "invalid backend type") {
+ t.Fatalf("a Start of backend type 2 must be refused as an invalid backend type, got %v", err)
+ }
+ if _, err := client.AddBackend(ctx, removedBackendRequest(t)); status.Code(err) != codes.InvalidArgument {
+ t.Fatalf("an AddBackend of backend type 2 on a node without a backend must be refused with InvalidArgument, got %v", err)
+ }
+
+ info, err := client.Start(ctx, &common.Backend{
+ Type: common.BackendType_XRAY,
+ Config: fmt.Sprintf(`{"log":{"loglevel":"warning"},"inbounds":[{"tag":"removed-type","listen":"127.0.0.1","port":%d,"protocol":"trojan","settings":{"clients":[]},"streamSettings":{"network":"tcp","security":"none"}}],"outbounds":[{"protocol":"freedom","tag":"direct"}]}`, unusedListenPort(t)),
+ KeepAlive: 60,
+ })
+ if err != nil {
+ t.Fatalf("the node must still start an Xray backend after refusing backend type 2, got %v", err)
+ }
+ if !info.GetStarted() {
+ t.Fatal("the Xray backend started after the refusals reports started = false")
+ }
+ if slices.Contains(info.GetSupportedBackends(), "sing_box") {
+ t.Fatalf("the node still advertises sing_box among its backends: %v", info.GetSupportedBackends())
+ }
+
+ if _, err := client.AddBackend(ctx, removedBackendRequest(t)); status.Code(err) != codes.InvalidArgument {
+ t.Fatalf("an AddBackend of backend type 2 next to a running Xray must be refused with InvalidArgument, got %v", err)
+ }
+ if _, err := client.RemoveBackend(ctx, &common.RemoveBackendRequest{Type: removedBackendType}); status.Code(err) != codes.NotFound {
+ t.Fatalf("a RemoveBackend of backend type 2 must report NotFound, got %v", err)
+ }
+ list, err := client.ListBackends(ctx, &common.Empty{})
+ if err != nil {
+ t.Fatalf("ListBackends after the refusals: %v", err)
+ }
+ if types := list.GetTypes(); len(types) != 1 || types[0] != common.BackendType_XRAY {
+ t.Fatalf("the refusals must leave the running Xray as the only backend, got %v", types)
+ }
+}
diff --git a/controller/rpc/speedcap.go b/controller/rpc/speedcap.go
new file mode 100644
index 00000000..740cdc9d
--- /dev/null
+++ b/controller/rpc/speedcap.go
@@ -0,0 +1,11 @@
+package rpc
+
+import (
+ "context"
+
+ "github.com/pasarguard/node/common"
+)
+
+func (s *Service) SetUserSpeeds(ctx context.Context, request *common.SetUserSpeedsRequest) (*common.SetUserSpeedsResponse, error) {
+ return s.ApplyUserSpeeds(ctx, request)
+}
diff --git a/controller/rpc/speedcap_lease_test.go b/controller/rpc/speedcap_lease_test.go
new file mode 100644
index 00000000..7197526c
--- /dev/null
+++ b/controller/rpc/speedcap_lease_test.go
@@ -0,0 +1,86 @@
+package rpc
+
+import (
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/config"
+ "github.com/pasarguard/node/pkg/netutil"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+func TestASnapshotTheBackendGateRefusesStillEndsTheSpeedCapLease(t *testing.T) {
+ dir := t.TempDir()
+ key := uuid.New()
+ cfg := config.NewTestConfig(dir, key)
+ cfg.XrayAssetsPath = dir
+ cfg.SpeedCapFile = filepath.Join(dir, "speed_caps.json")
+ cfg.SpeedCapLeaseSeconds = 1
+ s := New(cfg)
+ t.Cleanup(s.Close)
+
+ xrayConfig, err := json.Marshal(map[string]any{
+ "log": map[string]any{"loglevel": "warning"},
+ "inbounds": []any{map[string]any{
+ "tag": "speed-in", "listen": "127.0.0.1", "port": netutil.FindFreePort(), "protocol": "vless",
+ "settings": map[string]any{"clients": []any{}, "decryption": "none"},
+ }},
+ "outbounds": []any{map[string]any{"tag": "direct", "protocol": "freedom"}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ call := func(method string, request any, handler grpc.UnaryHandler) error {
+ ctx := fromClient(metadata.NewIncomingContext(context.Background(), metadata.Pairs("x-api-key", key.String())), ownerPanel)
+ _, err := ConditionalMiddleware(s)(ctx, request, &grpc.UnaryServerInfo{FullMethod: method}, handler)
+ return err
+ }
+ start := func() {
+ t.Helper()
+ err := call(common.NodeService_Start_FullMethodName, &common.Backend{Type: common.BackendType_XRAY, Config: string(xrayConfig)}, func(ctx context.Context, request any) (any, error) {
+ return s.Start(ctx, request.(*common.Backend))
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ snapshot := func(revision uint64) error {
+ request := &common.SetUserSpeedsRequest{ReplaceAll: true, SnapshotRevision: revision, Entries: []*common.SpeedEntry{{Email: "21", DownBps: 8_000_000, Revision: revision}}}
+ return call(common.NodeService_SetUserSpeeds_FullMethodName, request, func(ctx context.Context, request any) (any, error) {
+ return s.SetUserSpeeds(ctx, request.(*common.SetUserSpeedsRequest))
+ })
+ }
+
+ start()
+ if err := snapshot(5); err != nil {
+ if status.Code(err) == codes.Unimplemented {
+ t.Skipf("this xray core cannot cap speeds: %v", err)
+ }
+ t.Fatal(err)
+ }
+ start()
+ if err := call(common.NodeService_Stop_FullMethodName, &common.Empty{}, func(ctx context.Context, request any) (any, error) {
+ return s.Stop(ctx, request.(*common.Empty))
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ for refused := time.Now(); time.Since(refused) < 3*time.Second; time.Sleep(100 * time.Millisecond) {
+ if err := snapshot(6); status.Code(err) != codes.Unavailable {
+ t.Fatalf("a snapshot to a stopped node answered %v, want the backend gate's Unavailable", err)
+ }
+ }
+ if state := speedcap.Open(cfg.SpeedCapFile).State(); len(state.Entries) != 1 || state.Entries[0].Down != 8_000_000 {
+ t.Fatalf("the panel kept sending snapshots that the backend gate refused, yet the lease cleared the stored caps: %+v", state)
+ }
+}
diff --git a/controller/singbox_api_guard_test.go b/controller/singbox_api_guard_test.go
deleted file mode 100644
index 06b0adc8..00000000
--- a/controller/singbox_api_guard_test.go
+++ /dev/null
@@ -1,227 +0,0 @@
-package controller
-
-import (
- "bufio"
- "context"
- "encoding/binary"
- "fmt"
- "io"
- "net"
- "net/http"
- "strconv"
- "strings"
- "testing"
- "time"
-
- "github.com/google/uuid"
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials/insecure"
-
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/pkg/netutil"
-)
-
-type vlessTarget struct {
- kind byte
- address []byte
- port int
-}
-
-func ipTarget(ip string, port int) vlessTarget {
- parsed := net.ParseIP(ip)
- if v4 := parsed.To4(); v4 != nil && !strings.Contains(ip, ":") {
- return vlessTarget{kind: 1, address: v4, port: port}
- }
- return vlessTarget{kind: 3, address: parsed.To16(), port: port}
-}
-
-func domainTarget(name string, port int) vlessTarget {
- return vlessTarget{kind: 2, address: append([]byte{byte(len(name))}, name...), port: port}
-}
-
-type vlessConn struct {
- net.Conn
- reader *bufio.Reader
- header bool
-}
-
-func (c *vlessConn) Read(p []byte) (int, error) {
- if !c.header {
- var head [2]byte
- if _, err := io.ReadFull(c.reader, head[:]); err != nil {
- return 0, err
- }
- if _, err := c.reader.Discard(int(head[1])); err != nil {
- return 0, err
- }
- c.header = true
- }
- return c.reader.Read(p)
-}
-
-func dialThroughVLESS(inboundPort int, id uuid.UUID, target vlessTarget) (net.Conn, error) {
- conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(inboundPort)), 3*time.Second)
- if err != nil {
- return nil, err
- }
- request := []byte{0}
- request = append(request, id[:]...)
- request = append(request, 0, 1)
- request = binary.BigEndian.AppendUint16(request, uint16(target.port))
- request = append(request, target.kind)
- request = append(request, target.address...)
- if _, err := conn.Write(request); err != nil {
- _ = conn.Close()
- return nil, err
- }
- return &vlessConn{Conn: conn, reader: bufio.NewReader(conn)}, nil
-}
-
-func throughVLESS(t *testing.T, inboundPort int, id uuid.UUID, target vlessTarget, payload string) string {
- t.Helper()
- conn, err := dialThroughVLESS(inboundPort, id, target)
- if err != nil {
- t.Fatalf("dialing the VLESS inbound: %v", err)
- }
- defer conn.Close()
- if _, err := io.WriteString(conn, payload); err != nil {
- return ""
- }
- _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
- reply, _ := io.ReadAll(conn)
- return string(reply)
-}
-
-func queryStatsThroughVLESS(inboundPort int, id uuid.UUID, statsPort int) (int, error) {
- client, err := grpc.NewClient("passthrough:///stats-through-vless",
- grpc.WithTransportCredentials(insecure.NewCredentials()),
- grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {
- return dialThroughVLESS(inboundPort, id, ipTarget("127.0.0.1", statsPort))
- }))
- if err != nil {
- return 0, err
- }
- defer client.Close()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- resp, err := statscmd.NewStatsServiceClient(client).QueryStats(ctx, &statscmd.QueryStatsRequest{Patterns: []string{"user>>>"}, Reset_: true})
- if err != nil {
- return 0, err
- }
- return len(resp.GetStat()), nil
-}
-
-func serveReached(t *testing.T, network, address string) int {
- t.Helper()
- listener, err := net.Listen(network, address)
- if err != nil {
- t.Logf("no %s listener on %s: %v", network, address, err)
- return 0
- }
- server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "reached") })}
- go func() { _ = server.Serve(listener) }()
- t.Cleanup(func() { _ = server.Close() })
- return listener.Addr().(*net.TCPAddr).Port
-}
-
-func singBoxGuardRequest(inboundPort int, users ...*common.User) *common.Backend {
- return &common.Backend{
- Type: common.BackendType_SING_BOX,
- Config: fmt.Sprintf(`{"log": {"level": "warn"}, "inbounds": [{"type": "vless", "tag": "vless-in", "listen": "127.0.0.1", "listen_port": %d, "users": []}], "outbounds": [{"type": "direct", "tag": "direct"}], "route": {"rules": [{"network": ["tcp", "udp"], "action": "route", "outbound": "direct"}]}}`,
- inboundPort),
- KeepAlive: 600,
- Users: users,
- }
-}
-
-func startGuardedSingBox(t *testing.T, aliceID uuid.UUID) (*Controller, int, int, int) {
- t.Helper()
- c := startSingBoxController(t)
- c.mu.RLock()
- statsPort, clashPort := c.apiPort, c.metricPort
- c.mu.RUnlock()
- inboundPort := netutil.FindFreePort()
- replaceBackend(t, c, singBoxGuardRequest(inboundPort, singBoxReplacementUser("1.alice", aliceID)))
- return c, inboundPort, statsPort, clashPort
-}
-
-func clashRequest(method, path, body, authorization string) string {
- return fmt.Sprintf("%s %s HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n%sContent-Length: %d\r\n\r\n%s",
- method, path, authorization, len(body), body)
-}
-
-func TestASingBoxUserCannotReachTheNodeAPIsThroughTheProxy(t *testing.T) {
- aliceID := uuid.New()
- c, inboundPort, statsPort, clashPort := startGuardedSingBox(t, aliceID)
- moved := downloadThroughNode(t, replacementTrafficHost(t), inboundPort, aliceID, 8<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", moved)
-
- v4 := serveReached(t, "tcp4", "127.0.0.1:0")
- v6 := serveReached(t, "tcp6", "[::1]:0")
- get := clashRequest(http.MethodGet, "/", "", "")
- attempts := []struct {
- what string
- target vlessTarget
- }{
- {"the clash API at 127.0.0.1", ipTarget("127.0.0.1", clashPort)},
- {"the clash API at localhost", domainTarget("localhost", clashPort)},
- {"a loopback listener at 127.0.0.1", ipTarget("127.0.0.1", v4)},
- {"a loopback listener at 0.0.0.0", ipTarget("0.0.0.0", v4)},
- {"a loopback listener at ::ffff:127.0.0.1", ipTarget("::ffff:127.0.0.1", v4)},
- }
- if v6 != 0 {
- attempts = append(attempts, struct {
- what string
- target vlessTarget
- }{"a loopback listener at ::1", ipTarget("::1", v6)})
- }
- for _, attempt := range attempts {
- if reply := throughVLESS(t, inboundPort, aliceID, attempt.target, get); reply != "" {
- t.Errorf("a user reached %s through the proxy: %q", attempt.what, reply)
- }
- }
- if counters, err := queryStatsThroughVLESS(inboundPort, aliceID, statsPort); err == nil {
- t.Errorf("a user reached the stats API through the proxy and reset %d user counters", counters)
- }
- put := clashRequest(http.MethodPut, "/inbounds/vless-in/users", `{"type":"vless","users":[]}`, "")
- if reply := throughVLESS(t, inboundPort, aliceID, ipTarget("127.0.0.1", clashPort), put); reply != "" {
- t.Errorf("a user replaced the users of vless-in through the proxy: %q", reply)
- }
-
- expectNodeCounters(t, "alice after the attempts", countersOf(mustNodeCounters(t, c, common.StatType_UsersStat, true), "1.alice"), map[string]int64{"1.alice|downlink": moved})
- after := downloadThroughNode(t, replacementTrafficHost(t), inboundPort, aliceID, 4<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", after)
-}
-
-func TestTheSingBoxClashAPIRefusesARequestWithoutItsSecret(t *testing.T) {
- aliceID := uuid.New()
- c, inboundPort, _, clashPort := startGuardedSingBox(t, aliceID)
- for _, request := range []struct {
- what string
- payload string
- }{
- {"a GET without a secret", clashRequest(http.MethodGet, "/", "", "")},
- {"a user replacement without a secret", clashRequest(http.MethodPut, "/inbounds/vless-in/users", `{"type":"vless","users":[]}`, "")},
- {"a user replacement with a wrong secret", clashRequest(http.MethodPut, "/inbounds/vless-in/users", `{"type":"vless","users":[]}`, "Authorization: Bearer wrong\r\n")},
- } {
- conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(clashPort)), 3*time.Second)
- if err != nil {
- t.Fatalf("dialing the clash API: %v", err)
- }
- _, _ = io.WriteString(conn, request.payload)
- _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
- resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
- if err != nil {
- _ = conn.Close()
- t.Fatalf("%s: %v", request.what, err)
- }
- _ = resp.Body.Close()
- _ = conn.Close()
- if resp.StatusCode != http.StatusUnauthorized {
- t.Errorf("%s got status %d, want %d", request.what, resp.StatusCode, http.StatusUnauthorized)
- }
- }
- moved := downloadThroughNode(t, replacementTrafficHost(t), inboundPort, aliceID, 4<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", moved)
-}
diff --git a/controller/singbox_guard_dns_test.go b/controller/singbox_guard_dns_test.go
deleted file mode 100644
index 223a6146..00000000
--- a/controller/singbox_guard_dns_test.go
+++ /dev/null
@@ -1,239 +0,0 @@
-package controller
-
-import (
- "context"
- "encoding/binary"
- "encoding/json"
- "fmt"
- "net"
- "net/http"
- "regexp"
- "strings"
- "sync"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/google/uuid"
-
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/pkg/netutil"
-)
-
-type testResolver struct {
- conn net.PacketConn
- answers map[string]net.IP
- mu sync.Mutex
- asked map[string]int
-}
-
-func startTestResolver(t *testing.T, answers map[string]net.IP) *testResolver {
- t.Helper()
- conn, err := net.ListenPacket("udp4", "127.0.0.1:0")
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { _ = conn.Close() })
- resolver := &testResolver{conn: conn, answers: answers, asked: map[string]int{}}
- go resolver.serve()
- return resolver
-}
-
-func dnsQuestion(packet []byte) (string, uint16, int, bool) {
- if len(packet) < 12 {
- return "", 0, 0, false
- }
- var labels []string
- offset := 12
- for {
- if offset >= len(packet) {
- return "", 0, 0, false
- }
- size := int(packet[offset])
- offset++
- if size == 0 {
- break
- }
- if offset+size > len(packet) {
- return "", 0, 0, false
- }
- labels = append(labels, strings.ToLower(string(packet[offset:offset+size])))
- offset += size
- }
- if offset+4 > len(packet) {
- return "", 0, 0, false
- }
- return strings.Join(labels, "."), binary.BigEndian.Uint16(packet[offset:]), offset + 4, true
-}
-
-func (r *testResolver) serve() {
- buf := make([]byte, 1500)
- for {
- n, from, err := r.conn.ReadFrom(buf)
- if err != nil {
- return
- }
- name, kind, end, ok := dnsQuestion(buf[:n])
- if !ok {
- continue
- }
- key := fmt.Sprintf("%s/%d", name, kind)
- r.mu.Lock()
- r.asked[key]++
- r.mu.Unlock()
- reply := append([]byte{buf[0], buf[1], 0x81, 0x80, 0, 1, 0, 0, 0, 0, 0, 0}, buf[12:end]...)
- if answer := r.answers[key]; answer != nil {
- binary.BigEndian.PutUint16(reply[6:], 1)
- reply = append(reply, 0xc0, 0x0c)
- reply = binary.BigEndian.AppendUint16(reply, kind)
- reply = append(reply, 0, 1, 0, 0, 0, 0)
- reply = binary.BigEndian.AppendUint16(reply, uint16(len(answer)))
- reply = append(reply, answer...)
- }
- _, _ = r.conn.WriteTo(reply, from)
- }
-}
-
-func (r *testResolver) port() int {
- return r.conn.LocalAddr().(*net.UDPAddr).Port
-}
-
-func (r *testResolver) times(key string) int {
- r.mu.Lock()
- defer r.mu.Unlock()
- return r.asked[key]
-}
-
-type countedListener struct {
- port int
- hits atomic.Int64
-}
-
-func serveCounted(t *testing.T, address string) *countedListener {
- t.Helper()
- listener, err := net.Listen("tcp4", address)
- if err != nil {
- t.Fatal(err)
- }
- counted := &countedListener{port: listener.Addr().(*net.TCPAddr).Port}
- server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- counted.hits.Add(1)
- _, _ = w.Write([]byte("reached"))
- })}
- go func() { _ = server.Serve(listener) }()
- t.Cleanup(func() { _ = server.Close() })
- return counted
-}
-
-type coreLog struct {
- mu sync.Mutex
- lines []string
-}
-
-var (
- logColor = regexp.MustCompile("\x1b\\[[0-9;]*m")
- logConnLine = regexp.MustCompile(`\[(\d+) [^\]]*\] (.*)$`)
- logResolved = "router: resolved ["
- logRejected = "=> reject"
- logRoutedOut = "=> route("
-)
-
-func collectCoreLog(t *testing.T, c *Controller) *coreLog {
- t.Helper()
- ctx, cancel := context.WithCancel(context.Background())
- t.Cleanup(cancel)
- logs := c.Backend().SubscribeLogs(ctx)
- collected := &coreLog{}
- go func() {
- for {
- select {
- case <-ctx.Done():
- return
- case line, ok := <-logs:
- if !ok {
- return
- }
- collected.mu.Lock()
- collected.lines = append(collected.lines, logColor.ReplaceAllString(line, ""))
- collected.mu.Unlock()
- }
- }
- }()
- return collected
-}
-
-func (l *coreLog) verdict(address string) (rejected, routed bool) {
- l.mu.Lock()
- defer l.mu.Unlock()
- connections := map[string]bool{}
- for _, line := range l.lines {
- if match := logConnLine.FindStringSubmatch(line); match != nil && strings.HasPrefix(match[2], logResolved) && strings.Contains(match[2], address) {
- connections[match[1]] = true
- }
- }
- for _, line := range l.lines {
- match := logConnLine.FindStringSubmatch(line)
- if match == nil || !connections[match[1]] {
- continue
- }
- rejected = rejected || strings.Contains(match[2], logRejected)
- routed = routed || strings.Contains(match[2], logRoutedOut)
- }
- return rejected, routed
-}
-
-func TestNamesThatResolveToMappedLoopbackOrLinkLocalAddressesAreRejected(t *testing.T) {
- host := replacementTrafficHost(t)
- resolver := startTestResolver(t, map[string]net.IP{
- "mapped-loop.guard.test/28": net.ParseIP("::ffff:127.0.0.1").To16(),
- "mapped-any.guard.test/28": net.ParseIP("::ffff:0.0.0.0").To16(),
- "link-local.guard.test/1": net.ParseIP("169.254.1.2").To4(),
- "allowed.guard.test/1": net.ParseIP(host).To4(),
- })
- loopback := serveCounted(t, "127.0.0.1:0")
- allowed := serveCounted(t, net.JoinHostPort(host, "0"))
-
- c := startSingBoxController(t)
- aliceID := uuid.New()
- inboundPort := netutil.FindFreePort()
- raw, _ := json.Marshal(map[string]any{
- "log": map[string]any{"level": "debug"},
- "dns": map[string]any{"servers": []any{map[string]any{"type": "udp", "tag": "test-dns", "server": "127.0.0.1", "server_port": resolver.port()}}, "final": "test-dns", "disable_cache": true},
- "inbounds": []any{map[string]any{"type": "vless", "tag": "vless-in", "listen": "127.0.0.1", "listen_port": inboundPort, "users": []any{}}},
- "outbounds": []any{map[string]any{"type": "direct", "tag": "direct"}},
- "route": map[string]any{"default_domain_resolver": "test-dns", "rules": []any{map[string]any{"network": []any{"tcp", "udp"}, "action": "route", "outbound": "direct"}}},
- })
- replaceBackend(t, c, &common.Backend{Type: common.BackendType_SING_BOX, Config: string(raw), KeepAlive: 600, Users: []*common.User{singBoxReplacementUser("1.alice", aliceID)}})
- coreLogs := collectCoreLog(t, c)
- get := clashRequest(http.MethodGet, "/", "", "")
-
- for name, question := range map[string]string{"mapped-loop.guard.test": "mapped-loop.guard.test/28", "mapped-any.guard.test": "mapped-any.guard.test/28"} {
- _ = throughVLESS(t, inboundPort, aliceID, domainTarget(name, loopback.port), get)
- if resolver.times(question) == 0 {
- t.Errorf("%s never reached the test resolver as %s", name, question)
- }
- }
- if hits := loopback.hits.Load(); hits != 0 {
- t.Errorf("names that resolve to an IPv4-mapped loopback or unspecified address reached the loopback listener %d times", hits)
- }
-
- started := time.Now()
- _ = throughVLESS(t, inboundPort, aliceID, domainTarget("link-local.guard.test", 9), get)
- closedAfter := time.Since(started)
- if resolver.times("link-local.guard.test/1") == 0 {
- t.Error("link-local.guard.test never reached the test resolver")
- }
- var rejected, routed bool
- for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
- if rejected, routed = coreLogs.verdict("169.254.1.2"); rejected || routed {
- break
- }
- }
- if !rejected || routed || closedAfter > time.Second {
- t.Errorf("a name that resolves to 169.254.1.2 was not rejected before a dial: rejected %v, routed to an outbound %v, closed after %s", rejected, routed, closedAfter.Round(time.Millisecond))
- }
-
- if reply := throughVLESS(t, inboundPort, aliceID, domainTarget("allowed.guard.test", allowed.port), get); !strings.HasSuffix(reply, "reached") || allowed.hits.Load() != 1 {
- t.Errorf("a name that resolves to the host address %s did not reach its listener: %q", host, reply)
- }
-}
diff --git a/controller/singbox_guard_inbounds_test.go b/controller/singbox_guard_inbounds_test.go
deleted file mode 100644
index 7b6d1a87..00000000
--- a/controller/singbox_guard_inbounds_test.go
+++ /dev/null
@@ -1,195 +0,0 @@
-package controller
-
-import (
- "bufio"
- "context"
- "encoding/binary"
- "encoding/json"
- "fmt"
- "io"
- "net"
- "net/http"
- "strconv"
- "strings"
- "testing"
- "time"
-
- "github.com/google/uuid"
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials/insecure"
-
- statscmd "github.com/pasarguard/node/backend/singbox/api/proto"
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/pkg/netutil"
-)
-
-func socksConnect(proxyPort int, host string, port int) (net.Conn, error) {
- conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(proxyPort)), 3*time.Second)
- if err != nil {
- return nil, err
- }
- _ = conn.SetDeadline(time.Now().Add(5 * time.Second))
- if _, err := conn.Write([]byte{5, 1, 0}); err != nil {
- _ = conn.Close()
- return nil, err
- }
- var method [2]byte
- if _, err := io.ReadFull(conn, method[:]); err != nil || method[1] != 0 {
- _ = conn.Close()
- return nil, fmt.Errorf("socks method %v: %v", method, err)
- }
- request := []byte{5, 1, 0, 1}
- request = append(request, net.ParseIP(host).To4()...)
- request = binary.BigEndian.AppendUint16(request, uint16(port))
- if _, err := conn.Write(request); err != nil {
- _ = conn.Close()
- return nil, err
- }
- var head [10]byte
- if _, err := io.ReadFull(conn, head[:]); err != nil {
- _ = conn.Close()
- return nil, err
- }
- if head[1] != 0 {
- _ = conn.Close()
- return nil, fmt.Errorf("socks connect refused with code %d", head[1])
- }
- _ = conn.SetDeadline(time.Time{})
- return conn, nil
-}
-
-func httpConnect(proxyPort int, host string, port int) (net.Conn, error) {
- conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(proxyPort)), 3*time.Second)
- if err != nil {
- return nil, err
- }
- _ = conn.SetDeadline(time.Now().Add(5 * time.Second))
- target := net.JoinHostPort(host, strconv.Itoa(port))
- if _, err := fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", target, target); err != nil {
- _ = conn.Close()
- return nil, err
- }
- reader := bufio.NewReader(conn)
- resp, err := http.ReadResponse(reader, nil)
- if err != nil {
- _ = conn.Close()
- return nil, err
- }
- _ = resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- _ = conn.Close()
- return nil, fmt.Errorf("http connect refused with status %d", resp.StatusCode)
- }
- _ = conn.SetDeadline(time.Time{})
- return &bufferedConn{Conn: conn, reader: reader}, nil
-}
-
-type bufferedConn struct {
- net.Conn
- reader *bufio.Reader
-}
-
-func (c *bufferedConn) Read(p []byte) (int, error) {
- return c.reader.Read(p)
-}
-
-func exchangeThrough(dial func() (net.Conn, error), payload string) string {
- conn, err := dial()
- if err != nil {
- return ""
- }
- defer conn.Close()
- if _, err := io.WriteString(conn, payload); err != nil {
- return ""
- }
- _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
- reply, _ := io.ReadAll(conn)
- return string(reply)
-}
-
-func queryStatsThrough(dial func() (net.Conn, error)) (int, error) {
- client, err := grpc.NewClient("passthrough:///stats-through-a-proxy",
- grpc.WithTransportCredentials(insecure.NewCredentials()),
- grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return dial() }))
- if err != nil {
- return 0, err
- }
- defer client.Close()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- resp, err := statscmd.NewStatsServiceClient(client).QueryStats(ctx, &statscmd.QueryStatsRequest{Patterns: []string{"user>>>"}, Reset_: true})
- if err != nil {
- return 0, err
- }
- return len(resp.GetStat()), nil
-}
-
-type proxyInbounds struct {
- vless, mixed, http, direct int
-}
-
-func singBoxProxyInboundsRequest(ports proxyInbounds, forwardTo int, users ...*common.User) *common.Backend {
- raw, _ := json.Marshal(map[string]any{
- "log": map[string]any{"level": "warn"},
- "inbounds": []any{
- map[string]any{"type": "vless", "tag": "vless-in", "listen": "127.0.0.1", "listen_port": ports.vless, "users": []any{}},
- map[string]any{"type": "mixed", "tag": "mixed-in", "listen": "127.0.0.1", "listen_port": ports.mixed},
- map[string]any{"type": "http", "tag": "http-in", "listen": "127.0.0.1", "listen_port": ports.http},
- map[string]any{"type": "direct", "tag": "forward-in", "listen": "127.0.0.1", "listen_port": ports.direct, "override_address": "127.0.0.1", "override_port": forwardTo},
- },
- "outbounds": []any{map[string]any{"type": "direct", "tag": "direct"}},
- "route": map[string]any{"rules": []any{map[string]any{"network": []any{"tcp", "udp"}, "action": "route", "outbound": "direct"}}},
- })
- return &common.Backend{Type: common.BackendType_SING_BOX, Config: string(raw), KeepAlive: 600, Users: users}
-}
-
-func startSingBoxWithProxyInbounds(t *testing.T, aliceID uuid.UUID, forwardTo int) (*Controller, proxyInbounds, int, int) {
- t.Helper()
- c := startSingBoxController(t)
- c.mu.RLock()
- statsPort, clashPort := c.apiPort, c.metricPort
- c.mu.RUnlock()
- ports := proxyInbounds{vless: netutil.FindFreePort(), mixed: netutil.FindFreePort(), http: netutil.FindFreePort(), direct: netutil.FindFreePort()}
- replaceBackend(t, c, singBoxProxyInboundsRequest(ports, forwardTo, singBoxReplacementUser("1.alice", aliceID)))
- return c, ports, statsPort, clashPort
-}
-
-func TestAnInboundTheNodeDoesNotManageCannotReachTheNodeAPIs(t *testing.T) {
- aliceID := uuid.New()
- v4 := serveReached(t, "tcp4", "127.0.0.1:0")
- c, ports, statsPort, clashPort := startSingBoxWithProxyInbounds(t, aliceID, v4)
- moved := downloadThroughNode(t, replacementTrafficHost(t), ports.vless, aliceID, 8<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", moved)
-
- get := clashRequest(http.MethodGet, "/", "", "")
- for what, dial := range map[string]func() (net.Conn, error){
- "the clash API through mixed": func() (net.Conn, error) { return socksConnect(ports.mixed, "127.0.0.1", clashPort) },
- "a loopback listener through mixed": func() (net.Conn, error) { return socksConnect(ports.mixed, "127.0.0.1", v4) },
- "the clash API through http": func() (net.Conn, error) { return httpConnect(ports.http, "127.0.0.1", clashPort) },
- "a loopback listener through http": func() (net.Conn, error) { return httpConnect(ports.http, "127.0.0.1", v4) },
- } {
- if reply := exchangeThrough(dial, get); strings.Contains(reply, "HTTP/1.") {
- t.Errorf("a user reached %s: %q", what, reply)
- }
- }
- for what, dial := range map[string]func() (net.Conn, error){
- "mixed": func() (net.Conn, error) { return socksConnect(ports.mixed, "127.0.0.1", statsPort) },
- "http": func() (net.Conn, error) { return httpConnect(ports.http, "127.0.0.1", statsPort) },
- } {
- if counters, err := queryStatsThrough(dial); err == nil {
- t.Errorf("a user reached the stats API through %s and reset %d user counters", what, counters)
- }
- }
- expectNodeCounters(t, "alice after the attempts", countersOf(mustNodeCounters(t, c, common.StatType_UsersStat, true), "1.alice"), map[string]int64{"1.alice|downlink": moved})
-}
-
-func TestADirectInboundStillForwardsToItsLoopbackService(t *testing.T) {
- v4 := serveReached(t, "tcp4", "127.0.0.1:0")
- _, ports, _, _ := startSingBoxWithProxyInbounds(t, uuid.New(), v4)
- reply := exchangeThrough(func() (net.Conn, error) {
- return net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(ports.direct)), 3*time.Second)
- }, clashRequest(http.MethodGet, "/", "", ""))
- if !strings.HasSuffix(reply, "reached") {
- t.Fatalf("the direct inbound that forwards to 127.0.0.1:%d did not reach it: %q", v4, reply)
- }
-}
diff --git a/controller/singbox_replacement_counters_test.go b/controller/singbox_replacement_counters_test.go
deleted file mode 100644
index 1209b8e9..00000000
--- a/controller/singbox_replacement_counters_test.go
+++ /dev/null
@@ -1,188 +0,0 @@
-package controller
-
-import (
- "context"
- "errors"
- "fmt"
- "net"
- "os"
- "strconv"
- "syscall"
- "testing"
- "time"
-
- "github.com/google/uuid"
-
- "github.com/pasarguard/node/common"
- "github.com/pasarguard/node/config"
- "github.com/pasarguard/node/pkg/netutil"
-)
-
-func singBoxForReplacement(t *testing.T) string {
- t.Helper()
- for _, candidate := range []string{os.Getenv("SINGBOX_EXECUTABLE_PATH"), os.Getenv("SINGBOX_SMOKE_BINARY"), "/usr/local/bin/sing-box"} {
- if candidate == "" {
- continue
- }
- if _, err := os.Stat(candidate); err == nil {
- return candidate
- }
- }
- t.Skip("no sing-box binary: set SINGBOX_EXECUTABLE_PATH")
- return ""
-}
-
-func singBoxReplacementRequest(inboundPort int, users ...*common.User) *common.Backend {
- return &common.Backend{
- Type: common.BackendType_SING_BOX,
- Config: fmt.Sprintf(`{"log": {"level": "warn"}, "inbounds": [{"type": "vless", "tag": "vless-in", "listen": "127.0.0.1", "listen_port": %d, "users": []}], "outbounds": [{"type": "direct"}]}`,
- inboundPort),
- KeepAlive: 600,
- Users: users,
- }
-}
-
-func singBoxReplacementUser(email string, id uuid.UUID) *common.User {
- return &common.User{Email: email, Inbounds: []string{"vless-in"}, Proxies: &common.Proxy{Vless: &common.Vless{Id: id.String()}}}
-}
-
-func startSingBoxController(t *testing.T) *Controller {
- t.Helper()
- binary := singBoxForReplacement(t)
- cfg := config.NewTestConfig(t.TempDir(), uuid.New())
- cfg.SingBoxExecutablePath = binary
- c := New(cfg)
- t.Cleanup(c.Close)
- return c
-}
-
-func singBoxUptime(t *testing.T, c *Controller) uint32 {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- stats, err := c.Backend().GetSysStats(ctx)
- if err != nil {
- t.Fatalf("GetSysStats: %v", err)
- }
- return stats.GetUptime()
-}
-
-func TestReplacingASingBoxBackendCarriesItsUnreadTrafficToTheNextOne(t *testing.T) {
- c := startSingBoxController(t)
- aliceID := uuid.New()
- inboundPort := netutil.FindFreePort()
- request := singBoxReplacementRequest(inboundPort, singBoxReplacementUser("1.alice", aliceID))
- replaceBackend(t, c, request)
-
- moved := downloadThroughNode(t, replacementTrafficHost(t), inboundPort, aliceID, 24<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", moved)
-
- replaceBackend(t, c, request)
- expectNodeCounters(t, "users after the replacement", countersOf(mustNodeCounters(t, c, common.StatType_UsersStat, true), "1.alice"), map[string]int64{"1.alice|downlink": moved})
- expectNodeCounters(t, "outbounds after the replacement", countersOf(mustNodeCounters(t, c, common.StatType_Outbounds, true), "vless-in"), map[string]int64{"vless-in|downlink": moved})
- expectNodeCounters(t, "inbounds after the replacement", countersOf(mustNodeCounters(t, c, common.StatType_Inbounds, true), "vless-in"), map[string]int64{"vless-in|downlink": moved})
- expectNodeCounters(t, "users read again", countersOf(mustNodeCounters(t, c, common.StatType_UsersStat, true), "1.alice"), map[string]int64{})
- expectNodeCounters(t, "inbounds read again", countersOf(mustNodeCounters(t, c, common.StatType_Inbounds, true), "vless-in"), map[string]int64{})
-
- after := downloadThroughNode(t, replacementTrafficHost(t), inboundPort, aliceID, 8<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", after)
- expectNodeCounters(t, "users after traffic on the new backend", countersOf(mustNodeCounters(t, c, common.StatType_UsersStat, true), "1.alice"), map[string]int64{"1.alice|downlink": after})
-}
-
-func TestResetReadsRacingSingBoxReplacementsBillEveryByteOnce(t *testing.T) {
- c := startSingBoxController(t)
- aliceID := uuid.New()
- inboundPort := netutil.FindFreePort()
- request := singBoxReplacementRequest(inboundPort, singBoxReplacementUser("1.alice", aliceID))
- replaceBackend(t, c, request)
-
- moved := billEveryByteOnceAcrossRacingReplacements(t, c, racingReplacements{
- request: request,
- user: "1.alice",
- outbound: "vless-in",
- download: func(t *testing.T, size int) int64 {
- return downloadThroughNode(t, replacementTrafficHost(t), inboundPort, aliceID, size)
- },
- })
- expectNodeCounters(t, "inbounds, never read while the replacements raced", countersOf(mustNodeCounters(t, c, common.StatType_Inbounds, true), "vless-in"), map[string]int64{"vless-in|downlink": moved})
-}
-
-func TestASingBoxBackendWhoseNextPortIsTakenStartsAndHotReloadsUsers(t *testing.T) {
- c := startSingBoxController(t)
- c.mu.RLock()
- next := c.apiPort + 1
- c.mu.RUnlock()
- held, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(next)))
- switch {
- case err == nil:
- defer held.Close()
- case errors.Is(err, syscall.EADDRINUSE):
- t.Logf("port %d next to the stats API port is already taken", next)
- default:
- t.Fatalf("taking port %d next to the stats API port: %v", next, err)
- }
-
- aliceID, carolID := uuid.New(), uuid.New()
- alice := singBoxReplacementUser("1.alice", aliceID)
- inboundPort := netutil.FindFreePort()
- replaceBackend(t, c, singBoxReplacementRequest(inboundPort, alice))
-
- waitUntilTrue(t, "the sing-box core has been up for two seconds", func() bool { return singBoxUptime(t, c) >= 2 })
- before := singBoxUptime(t, c)
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
- if err := c.SyncUsersAll(ctx, []*common.User{alice, singBoxReplacementUser("3.carol", carolID)}); err != nil {
- t.Fatalf("a full sync that adds carol: %v", err)
- }
- if after := singBoxUptime(t, c); after < before {
- t.Fatalf("the full sync that adds carol restarted sing-box (uptime %d s, then %d s) instead of reloading its users", before, after)
- }
- moved := downloadThroughNode(t, replacementTrafficHost(t), inboundPort, carolID, 4<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "3.carol", moved)
-}
-
-func TestASingBoxExtraKeepsItsUnreadTrafficAcrossADetachAndAPrimaryReplacement(t *testing.T) {
- singBox := singBoxForReplacement(t)
- var xray string
- for _, binary := range xrayBinariesForReplacement(t) {
- xray = binary
- break
- }
- dir := t.TempDir()
- cfg := config.NewTestConfig(dir, uuid.New())
- cfg.XrayExecutablePath = xray
- cfg.XrayAssetsPath = dir
- cfg.SingBoxExecutablePath = singBox
- c := New(cfg)
- t.Cleanup(c.Close)
-
- primary := replacementRequest(t, "127.0.0.1", netutil.FindFreePort())
- replaceBackend(t, c, primary)
- aliceID := uuid.New()
- extraPort := netutil.FindFreePort()
- extra := singBoxReplacementRequest(extraPort, singBoxReplacementUser("1.alice", aliceID))
- attach := func(when string) {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
- defer cancel()
- if err := c.AttachBackend(ctx, extra); err != nil {
- t.Fatalf("AttachBackend %s: %v", when, err)
- }
- }
- attach("at the start")
-
- first := downloadThroughNode(t, replacementTrafficHost(t), extraPort, aliceID, 16<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", first)
- if err := c.DetachBackend(common.BackendType_SING_BOX); err != nil {
- t.Fatalf("DetachBackend: %v", err)
- }
- attach("after the detach")
- expectNodeCounters(t, "users after the extra was detached and attached again", countersOf(mustNodeCounters(t, c, common.StatType_UsersStat, true), "1.alice"), map[string]int64{"1.alice|downlink": first})
-
- second := downloadThroughNode(t, replacementTrafficHost(t), extraPort, aliceID, 8<<20)
- waitForNodeDownlink(t, c, common.StatType_UsersStat, "1.alice", second)
- replaceBackend(t, c, primary)
- attach("after the primary was replaced")
- expectNodeCounters(t, "users after the primary was replaced and the extra attached again", countersOf(mustNodeCounters(t, c, common.StatType_UsersStat, true), "1.alice"), map[string]int64{"1.alice|downlink": second})
- expectNodeCounters(t, "inbounds of the extra, never read before", countersOf(mustNodeCounters(t, c, common.StatType_Inbounds, true), "vless-in"), map[string]int64{"vless-in|downlink": first + second})
-}
diff --git a/controller/speedcap.go b/controller/speedcap.go
new file mode 100644
index 00000000..ba34f952
--- /dev/null
+++ b/controller/speedcap.go
@@ -0,0 +1,167 @@
+package controller
+
+import (
+ "context"
+ "errors"
+ "log"
+ "time"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/pasarguard/node/backend/xray"
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+const speedCapBackendName = "xray"
+
+const speedCapLeaseExpireTimeout = 15 * time.Second
+
+var (
+ ErrSpeedCapNeedsXray = status.Error(codes.Unimplemented, "per-user speed caps need the xray backend as this node's primary backend")
+ ErrSpeedCapUnsupportedCore = status.Error(codes.Unimplemented, "the xray core on this node does not support per-user speed caps")
+ errSpeedCapNoCore = errors.New("no xray core is running on this node")
+)
+
+type speedCapBackend interface {
+ PushSpeedCaps(context.Context, speedcap.Change) error
+ SupportsSpeedCaps() bool
+ RefusesSpeedCaps() bool
+}
+
+func speedRequest(request *common.SetUserSpeedsRequest) speedcap.Request {
+ entries := make([]speedcap.Entry, 0, len(request.GetEntries()))
+ for _, entry := range request.GetEntries() {
+ entries = append(entries, speedcap.Entry{
+ Email: entry.GetEmail(),
+ Down: entry.GetDownBps(),
+ Up: entry.GetUpBps(),
+ Revision: entry.GetRevision(),
+ InboundTags: entry.GetInboundTags(),
+ })
+ }
+ return speedcap.Request{Entries: entries, ReplaceAll: request.GetReplaceAll(), Snapshot: request.GetSnapshotRevision()}
+}
+
+func speedResponse(outcome speedcap.Outcome) *common.SetUserSpeedsResponse {
+ response := &common.SetUserSpeedsResponse{HighWater: outcome.HighWater, Stale: outcome.Stale}
+ for _, rejection := range outcome.Rejected {
+ response.Rejected = append(response.Rejected, &common.SpeedRejection{
+ Email: rejection.Email,
+ Backend: speedCapBackendName,
+ Reason: rejection.Reason,
+ })
+ }
+ return response
+}
+
+func (c *Controller) ApplyUserSpeeds(ctx context.Context, request *common.SetUserSpeedsRequest) (*common.SetUserSpeedsResponse, error) {
+ c.lifecycleMu.RLock()
+ defer c.lifecycleMu.RUnlock()
+
+ c.mu.RLock()
+ primary, primaryType := c.backend, c.primaryType
+ c.mu.RUnlock()
+ if primary == nil {
+ return nil, ErrBackendNotInitialized
+ }
+ capper, ok := primary.(speedCapBackend)
+ if !ok || primaryType != common.BackendType_XRAY {
+ return nil, ErrSpeedCapNeedsXray
+ }
+ if capper.RefusesSpeedCaps() {
+ return nil, ErrSpeedCapUnsupportedCore
+ }
+
+ ctx, done := c.userSyncs.track(ctx)
+ defer done()
+
+ outcome, err := c.speedCaps.Apply(ctx, speedRequest(request), capper.PushSpeedCaps)
+ switch {
+ case err == nil:
+ return speedResponse(outcome), nil
+ case errors.Is(err, xray.ErrSpeedCapUnsupported):
+ return nil, ErrSpeedCapUnsupportedCore
+ case errors.Is(err, speedcap.ErrPersist):
+ return nil, status.Error(codes.Internal, err.Error())
+ default:
+ return nil, status.Errorf(codes.Unavailable, "the speed caps are stored on the node but the xray core did not take them yet: %v", err)
+ }
+}
+
+func (c *Controller) armSpeedCapLease() {
+ if c.speedCaps == nil || c.speedCapLease <= 0 {
+ return
+ }
+ lease := c.speedCaps.ArmLease()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.leaseTimer != nil {
+ c.leaseTimer.Stop()
+ }
+ c.armedLease = lease
+ c.leaseTimer = time.AfterFunc(c.speedCapLease, func() { c.checkSpeedCapLease(lease, true) })
+}
+
+func (c *Controller) EndSpeedCapLease() {
+ if c.speedCaps != nil {
+ c.speedCaps.EndLease()
+ }
+}
+
+func (c *Controller) renewSpeedCapLease(lease uint64, quiet bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.leaseTimer == nil || c.armedLease != lease {
+ return
+ }
+ c.leaseTimer = time.AfterFunc(c.speedCapLease, func() { c.checkSpeedCapLease(lease, quiet) })
+}
+
+func (c *Controller) stopSpeedCapLease() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.leaseTimer != nil {
+ c.leaseTimer.Stop()
+ c.leaseTimer = nil
+ }
+}
+
+func (c *Controller) checkSpeedCapLease(lease uint64, quietBefore bool) {
+ quiet := time.Since(c.LastRequest()) >= c.speedCapLease/2
+ if quiet || quietBefore {
+ c.renewSpeedCapLease(lease, quiet)
+ return
+ }
+ c.expireSpeedCapLease(lease)
+}
+
+func (c *Controller) expireSpeedCapLease(lease uint64) {
+ c.lifecycleMu.RLock()
+ defer c.lifecycleMu.RUnlock()
+
+ push := func(context.Context, speedcap.Change) error { return errSpeedCapNoCore }
+ c.mu.RLock()
+ primary, primaryType := c.backend, c.primaryType
+ c.mu.RUnlock()
+ if capper, ok := primary.(speedCapBackend); ok && primaryType == common.BackendType_XRAY {
+ push = capper.PushSpeedCaps
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), speedCapLeaseExpireTimeout)
+ defer cancel()
+ ctx, done := c.userSyncs.track(ctx)
+ defer done()
+ expired, cleared, err := c.speedCaps.ExpireLease(ctx, lease, push)
+ switch {
+ case errors.Is(err, speedcap.ErrPersist):
+ log.Printf("speed caps: the panel that holds the node was heard within half a lease before two lease checks in a row (every %s) and has sent no speed caps since its Start, but the node could not save the cleared set, so it keeps its stored caps and checks the lease again in %s: %v", c.speedCapLease, c.speedCapLease, err)
+ c.renewSpeedCapLease(lease, false)
+ case !expired:
+ case err != nil:
+ log.Printf("speed caps: the panel that holds the node was heard within half a lease before two lease checks in a row (every %s) and has sent no speed caps since its Start; cleared %d stored caps and tombstones, the core takes the empty set on its next push or start: %v", c.speedCapLease, cleared, err)
+ default:
+ log.Printf("speed caps: the panel that holds the node was heard within half a lease before two lease checks in a row (every %s) and has sent no speed caps since its Start; cleared %d stored caps and tombstones and the core holds none", c.speedCapLease, cleared)
+ }
+}
diff --git a/controller/speedcap_live_test.go b/controller/speedcap_live_test.go
new file mode 100644
index 00000000..df643297
--- /dev/null
+++ b/controller/speedcap_live_test.go
@@ -0,0 +1,166 @@
+package controller
+
+import (
+ "context"
+ "encoding/binary"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/config"
+ "github.com/pasarguard/node/pkg/netutil"
+)
+
+func liveSpeedCapController(t *testing.T, lease time.Duration) *Controller {
+ t.Helper()
+ binary := os.Getenv("XRAY_EXECUTABLE_PATH")
+ if binary == "" {
+ binary = "/usr/local/bin/xray"
+ }
+ if _, err := os.Stat(binary); err != nil {
+ t.Skipf("no xray binary at %s", binary)
+ }
+ dir := t.TempDir()
+ cfg := config.NewTestConfig(dir, uuid.New())
+ cfg.XrayExecutablePath = binary
+ cfg.XrayAssetsPath = dir
+ cfg.SpeedCapFile = filepath.Join(dir, "speed_caps.json")
+ c := New(cfg)
+ c.speedCapLease = lease
+ t.Cleanup(c.Close)
+ return c
+}
+
+func endlessTarget(t *testing.T, host string) *net.TCPAddr {
+ t.Helper()
+ listener, err := net.Listen("tcp4", net.JoinHostPort(host, "0"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { listener.Close() })
+ go func() {
+ chunk := make([]byte, 32*1024)
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ return
+ }
+ go func() {
+ defer conn.Close()
+ for {
+ if _, err := conn.Write(chunk); err != nil {
+ return
+ }
+ }
+ }()
+ }
+ }()
+ return listener.Addr().(*net.TCPAddr)
+}
+
+func vlessDownloadMbps(t *testing.T, inboundPort int, id uuid.UUID, target *net.TCPAddr) float64 {
+ t.Helper()
+ conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(inboundPort)), 3*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ request := []byte{0}
+ request = append(request, id[:]...)
+ request = append(request, 0, 1)
+ request = binary.BigEndian.AppendUint16(request, uint16(target.Port))
+ request = append(request, 1)
+ request = append(request, target.IP.To4()...)
+ if _, err := conn.Write(request); err != nil {
+ t.Fatal(err)
+ }
+ var received atomic.Int64
+ go func() {
+ buf := make([]byte, 64*1024)
+ for {
+ n, err := conn.Read(buf)
+ received.Add(int64(n))
+ if err != nil {
+ return
+ }
+ }
+ }()
+ time.Sleep(1500 * time.Millisecond)
+ before, begin := received.Load(), time.Now()
+ time.Sleep(2 * time.Second)
+ return float64(received.Load()-before) * 8 / time.Since(begin).Seconds() / 1e6
+}
+
+type liveCappedAlice struct {
+ c *Controller
+ request *common.Backend
+ port int
+ id uuid.UUID
+ target *net.TCPAddr
+}
+
+func capAliceOnTheRealCore(t *testing.T, lease time.Duration) *liveCappedAlice {
+ t.Helper()
+ alice := &liveCappedAlice{c: liveSpeedCapController(t, lease), port: netutil.FindFreePort(), id: uuid.New()}
+ host := replacementTrafficHost(t)
+ alice.target = endlessTarget(t, host)
+ alice.request = replacementRequest(t, host, alice.port, replacementUser("21", alice.id))
+ alice.startLikeThePanel(t)
+ if _, err := alice.c.ApplyUserSpeeds(context.Background(), speedSnapshot(5, &common.SpeedEntry{Email: "21", DownBps: 8_000_000, Revision: 5})); err != nil {
+ if status.Code(err) == codes.Unimplemented {
+ t.Skipf("this xray core cannot cap speeds: %v", err)
+ }
+ t.Fatal(err)
+ }
+ if rate := alice.mbps(t); rate > 8*1.15 {
+ t.Fatalf("alice downloads at %.2f Mbit/s right after the panel's snapshot capped her at 8", rate)
+ }
+ return alice
+}
+
+func (a *liveCappedAlice) startLikeThePanel(t *testing.T) {
+ t.Helper()
+ a.c.NewRequest()
+ replaceBackend(t, a.c, a.request)
+ a.c.Connect("127.0.0.1", a.request.GetKeepAlive())
+}
+
+func (a *liveCappedAlice) mbps(t *testing.T) float64 {
+ t.Helper()
+ return vlessDownloadMbps(t, a.port, a.id, a.target)
+}
+
+func TestASpeedCapHoldsOnTheRealCoreWhileThePanelIsSilentAfterAStart(t *testing.T) {
+ alice := capAliceOnTheRealCore(t, 2*time.Second)
+ alice.startLikeThePanel(t)
+ silentSince := time.Now()
+ time.Sleep(time.Until(silentSince.Add(3 * alice.c.speedCapLease)))
+ rate := alice.mbps(t)
+ t.Logf("alice %s after a Start the panel never followed: %.2f Mbit/s against a cap of 8, node store %+v", time.Since(silentSince).Round(time.Second), rate, alice.c.speedCaps.State())
+ if rate > 8*1.15 {
+ t.Fatalf("alice lost her cap while the panel was silent after its Start: %.2f Mbit/s against a cap of 8", rate)
+ }
+}
+
+func TestOneStrayRequestAfterAStartLeavesTheCapOnTheRealCore(t *testing.T) {
+ alice := capAliceOnTheRealCore(t, 2*time.Second)
+ alice.startLikeThePanel(t)
+ silentSince := time.Now()
+ time.Sleep(time.Until(silentSince.Add(alice.c.speedCapLease * 7 / 10)))
+ alice.c.NewRequest()
+ time.Sleep(time.Until(silentSince.Add(3 * alice.c.speedCapLease)))
+ rate := alice.mbps(t)
+ t.Logf("alice %s after a Start the panel followed with one request 0.7 lease later: %.2f Mbit/s against a cap of 8, node store %+v", time.Since(silentSince).Round(time.Second), rate, alice.c.speedCaps.State())
+ if rate > 8*1.15 {
+ t.Fatalf("one request after a Start from an otherwise silent panel took alice's cap: %.2f Mbit/s against a cap of 8", rate)
+ }
+}
diff --git a/controller/speedcap_test.go b/controller/speedcap_test.go
new file mode 100644
index 00000000..aa592490
--- /dev/null
+++ b/controller/speedcap_test.go
@@ -0,0 +1,571 @@
+package controller
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/pasarguard/node/backend"
+ "github.com/pasarguard/node/backend/xray"
+ "github.com/pasarguard/node/common"
+ "github.com/pasarguard/node/pkg/speedcap"
+)
+
+type fakeSpeedBackend struct {
+ backend.Backend
+ pushes []speedcap.Change
+ failures []error
+ supported bool
+ refused bool
+ core *speedcap.Store
+}
+
+func (f *fakeSpeedBackend) Started() bool { return true }
+func (f *fakeSpeedBackend) Version() string { return "26.3.27" }
+
+func (f *fakeSpeedBackend) PushSpeedCaps(_ context.Context, change speedcap.Change) error {
+ if len(f.failures) > 0 {
+ err := f.failures[0]
+ f.failures = f.failures[1:]
+ if errors.Is(err, xray.ErrSpeedCapUnsupported) {
+ f.refused = true
+ }
+ return err
+ }
+ f.supported = true
+ f.pushes = append(f.pushes, change)
+ if f.core != nil {
+ request := speedcap.Request{Entries: change.Entries, ReplaceAll: change.ReplaceAll, Snapshot: change.Snapshot}
+ if _, err := f.core.Apply(context.Background(), request, func(context.Context, speedcap.Change) error { return nil }); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (f *fakeSpeedBackend) SupportsSpeedCaps() bool { return f.supported }
+func (f *fakeSpeedBackend) RefusesSpeedCaps() bool { return f.refused }
+
+func speedController(t *testing.T, b backend.Backend, backendType common.BackendType) *Controller {
+ t.Helper()
+ return &Controller{backend: b, primaryType: backendType, speedCaps: speedcap.Open(filepath.Join(t.TempDir(), "speedcaps.json"))}
+}
+
+func syncedSpeedController(t *testing.T, fake *fakeSpeedBackend) *Controller {
+ t.Helper()
+ c := speedController(t, fake, common.BackendType_XRAY)
+ if err := c.speedCaps.Sync(context.Background(), fake.PushSpeedCaps); err != nil {
+ t.Fatal(err)
+ }
+ if c.speedCaps.Dirty() {
+ t.Fatal("the store is still dirty after the core took the whole set")
+ }
+ fake.pushes = nil
+ return c
+}
+
+func speedEntryRequest(email string, down, revision uint64) *common.SetUserSpeedsRequest {
+ return &common.SetUserSpeedsRequest{Entries: []*common.SpeedEntry{{Email: email, DownBps: down, Revision: revision}}}
+}
+
+func requireCode(t *testing.T, err error, want codes.Code) {
+ t.Helper()
+ if got := status.Code(err); got != want {
+ t.Fatalf("got %v (%v), want %v", got, err, want)
+ }
+}
+
+func TestSpeedCapsWithoutABackendAreRetriedLater(t *testing.T) {
+ c := &Controller{speedCaps: speedcap.NewMemoryStore()}
+ _, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 1))
+ requireCode(t, err, codes.Unavailable)
+}
+
+func TestSpeedCapsOnANonXrayPrimaryAreUnsupported(t *testing.T) {
+ c := speedController(t, &fakeSpeedBackend{supported: true}, common.BackendType_WIREGUARD)
+ _, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 1))
+ requireCode(t, err, codes.Unimplemented)
+ if c.BaseInfoResponse().GetSupportsSpeedCap() {
+ t.Fatal("a wireguard primary reports speed cap support")
+ }
+}
+
+func TestSpeedCapsOnAnUnpatchedCoreAreUnsupported(t *testing.T) {
+ fake := &fakeSpeedBackend{failures: []error{xray.ErrSpeedCapUnsupported}}
+ c := speedController(t, fake, common.BackendType_XRAY)
+ _, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 1))
+ requireCode(t, err, codes.Unimplemented)
+
+ _, err = c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 2))
+ requireCode(t, err, codes.Unimplemented)
+ if c.BaseInfoResponse().GetSupportsSpeedCap() {
+ t.Fatal("an unpatched core reports speed cap support")
+ }
+}
+
+func TestSpeedCapsAreRetriedUntilTheCoreTakesThem(t *testing.T) {
+ fake := &fakeSpeedBackend{}
+ c := syncedSpeedController(t, fake)
+ fake.failures = []error{errors.New("connection refused")}
+ _, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 1))
+ requireCode(t, err, codes.Unavailable)
+
+ response, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 1))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if response.GetHighWater() != 1 || len(response.GetRejected()) != 0 {
+ t.Fatalf("unexpected response %v", response)
+ }
+ if len(fake.pushes) != 1 || !fake.pushes[0].ReplaceAll || len(fake.pushes[0].Entries) != 1 {
+ t.Fatalf("the retry pushed %+v, want the whole set once", fake.pushes)
+ }
+ if !c.BaseInfoResponse().GetSupportsSpeedCap() {
+ t.Fatal("a core that took the caps does not report support")
+ }
+}
+
+func TestSpeedCapResponseCarriesRejectionsAndTheHighWater(t *testing.T) {
+ c := speedController(t, &fakeSpeedBackend{}, common.BackendType_XRAY)
+ request := &common.SetUserSpeedsRequest{Entries: []*common.SpeedEntry{
+ {Email: "", DownBps: 10_000_000, Revision: 4},
+ {Email: "13", DownBps: 10_000_000, Revision: 57},
+ {Email: "14", DownBps: 10_000_000},
+ }}
+ response, err := c.ApplyUserSpeeds(context.Background(), request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if response.GetHighWater() != 57 {
+ t.Fatalf("high water %d, want 57", response.GetHighWater())
+ }
+ if len(response.GetRejected()) != 2 {
+ t.Fatalf("rejected %v, want the empty email and the zero revision", response.GetRejected())
+ }
+ for _, rejection := range response.GetRejected() {
+ if rejection.GetBackend() != "xray" || rejection.GetReason() == "" {
+ t.Fatalf("incomplete rejection %v", rejection)
+ }
+ }
+
+ stale, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("13", 1, 2))
+ if err != nil || len(stale.GetRejected()) != 0 || stale.GetHighWater() != 57 {
+ t.Fatalf("a stale entry answered %v, %v; want a quiet success with high water 57", stale, err)
+ }
+}
+
+func TestARetryAfterAFailedCoreApplyIsAppliedAndNotStale(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := syncedSpeedController(t, fake)
+ fake.failures = []error{errors.New("connection refused")}
+
+ _, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 1))
+ requireCode(t, err, codes.Unavailable)
+
+ response, err := c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 10_000_000, 1))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(response.GetStale()) != 0 {
+ t.Fatalf("the retry of a change the core missed answered stale %v", response.GetStale())
+ }
+ core := fake.core.State().Entries
+ if len(core) != 1 || core[0].Email != "12" || core[0].Down != 10_000_000 {
+ t.Fatalf("the core holds %+v after the retry, want 12 capped at 10 Mbit/s", core)
+ }
+
+ response, err = c.ApplyUserSpeeds(context.Background(), speedEntryRequest("12", 20_000_000, 1))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(response.GetStale()) != 1 || response.GetStale()[0] != "12" {
+ t.Fatalf("an equal revision with another cap answered stale %v, want [12]", response.GetStale())
+ }
+ if core := fake.core.State().Entries; core[0].Down != 10_000_000 {
+ t.Fatalf("an equal revision with another cap changed the core to %+v", core)
+ }
+}
+
+func (f *fakeSpeedBackend) Shutdown() {}
+
+func leaseController(t *testing.T, fake *fakeSpeedBackend, lease time.Duration) *Controller {
+ t.Helper()
+ c := syncedSpeedController(t, fake)
+ c.speedCapLease = lease
+ c.newBackend = func(context.Context, *common.Backend, int, int) (backend.Backend, error) { return fake, nil }
+ t.Cleanup(c.stopSpeedCapLease)
+ return c
+}
+
+func startFromPanel(t *testing.T, c *Controller) {
+ t.Helper()
+ c.NewRequest()
+ if err := c.ReplaceBackend(context.Background(), &common.Backend{Type: common.BackendType_XRAY}); err != nil {
+ t.Fatal(err)
+ }
+ c.NewRequest()
+}
+
+func keepPanelTalking(t *testing.T, c *Controller) {
+ t.Helper()
+ stop := make(chan struct{})
+ done := make(chan struct{})
+ c.NewRequest()
+ go func() {
+ defer close(done)
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-stop:
+ return
+ case <-ticker.C:
+ c.NewRequest()
+ }
+ }
+ }()
+ t.Cleanup(func() {
+ close(stop)
+ <-done
+ })
+}
+
+func waitForTheLeaseToClear(t *testing.T, c *Controller, fake *fakeSpeedBackend, within time.Duration) speedcap.State {
+ t.Helper()
+ deadline := time.Now().Add(within)
+ for len(c.speedCaps.State().Entries) != 0 {
+ if time.Now().After(deadline) {
+ t.Fatalf("the lease did not clear the caps within %s: %+v", within, c.speedCaps.State())
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ return requireNodeAndCoreAgree(t, c, fake)
+}
+
+func blockTheStoreDirectory(t *testing.T, path string) func() {
+ t.Helper()
+ dir := filepath.Dir(path)
+ moved := dir + ".moved"
+ if err := os.Rename(dir, moved); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(dir, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return func() {
+ if err := os.Remove(dir); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(moved, dir); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func applySpeeds(t *testing.T, c *Controller, request *common.SetUserSpeedsRequest) *common.SetUserSpeedsResponse {
+ t.Helper()
+ response, err := c.ApplyUserSpeeds(context.Background(), request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return response
+}
+
+func speedSnapshot(snapshot uint64, entries ...*common.SpeedEntry) *common.SetUserSpeedsRequest {
+ return &common.SetUserSpeedsRequest{ReplaceAll: true, SnapshotRevision: snapshot, Entries: entries}
+}
+
+func requireNodeAndCoreAgree(t *testing.T, c *Controller, fake *fakeSpeedBackend) speedcap.State {
+ t.Helper()
+ node, core := c.speedCaps.State(), fake.core.State()
+ if node.Floor != core.Floor || len(node.Entries) != len(core.Entries) {
+ t.Fatalf("the node holds %+v, the core %+v", node, core)
+ }
+ for i := range node.Entries {
+ if !reflect.DeepEqual(node.Entries[i], core.Entries[i]) {
+ t.Fatalf("the node holds %+v, the core %+v", node, core)
+ }
+ }
+ return node
+}
+
+func seedLeaseCaps(t *testing.T, c *Controller) {
+ t.Helper()
+ applySpeeds(t, c, speedSnapshot(100, &common.SpeedEntry{Email: "12", DownBps: 10_000_000, Revision: 100}))
+ applySpeeds(t, c, speedEntryRequest("13", 20_000_000, 105))
+}
+
+func TestCapsFromAPanelThatKeepsCallingWithoutASnapshotAreClearedAtTheSecondLeaseCheck(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+
+ keepPanelTalking(t, c)
+ started := time.Now()
+ startFromPanel(t, c)
+
+ state := waitForTheLeaseToClear(t, c, fake, 3*time.Second)
+ if took := time.Since(started); took < 600*time.Millisecond {
+ t.Fatalf("a panel that keeps calling lost its caps %s after its Start, before the second lease check at 600ms", took.Round(time.Millisecond))
+ }
+ if len(state.Entries) != 0 || state.Floor != 105 {
+ t.Fatalf("after the lease the node holds %+v, want no entries and the floor at the high water 105", state)
+ }
+
+ response := applySpeeds(t, c, speedEntryRequest("13", 20_000_000, 103))
+ if len(response.GetStale()) != 1 || response.GetHighWater() != 105 {
+ t.Fatalf("a delayed diff below the high water answered %v, want it stale with high water 105", response)
+ }
+ if state := requireNodeAndCoreAgree(t, c, fake); len(state.Entries) != 0 {
+ t.Fatalf("a delayed diff below the high water revived %+v", state)
+ }
+
+ applySpeeds(t, c, speedSnapshot(106, &common.SpeedEntry{Email: "12", DownBps: 10_000_000, Revision: 100}))
+ state = requireNodeAndCoreAgree(t, c, fake)
+ if len(state.Entries) != 1 || state.Entries[0].Email != "12" || state.Entries[0].Down != 10_000_000 {
+ t.Fatalf("a panel that came back with a snapshot at the high water left %+v", state)
+ }
+}
+
+func TestASnapshotInsideTheLeaseKeepsTheCaps(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+
+ keepPanelTalking(t, c)
+ startFromPanel(t, c)
+ applySpeeds(t, c, speedSnapshot(110, &common.SpeedEntry{Email: "12", DownBps: 10_000_000, Revision: 100}))
+ time.Sleep(700 * time.Millisecond)
+
+ state := requireNodeAndCoreAgree(t, c, fake)
+ if len(state.Entries) != 1 || state.Entries[0].Email != "12" {
+ t.Fatalf("a panel that sent its snapshot inside the lease lost its caps: %+v", state)
+ }
+}
+
+func TestACoreRestartTheNodeStartsNeitherArmsNorClearsTheLease(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+ keepPanelTalking(t, c)
+
+ restartCore := func() {
+ c.speedCaps.MarkDirty()
+ if err := c.speedCaps.Sync(context.Background(), fake.PushSpeedCaps); err != nil {
+ t.Fatal(err)
+ }
+ }
+ restartCore()
+ time.Sleep(700 * time.Millisecond)
+ if state := requireNodeAndCoreAgree(t, c, fake); len(state.Entries) != 2 {
+ t.Fatalf("a core restart the node started cleared the caps: %+v", state)
+ }
+
+ startFromPanel(t, c)
+ applySpeeds(t, c, speedSnapshot(110, &common.SpeedEntry{Email: "12", DownBps: 10_000_000, Revision: 100}))
+ restartCore()
+ time.Sleep(700 * time.Millisecond)
+ if state := requireNodeAndCoreAgree(t, c, fake); len(state.Entries) != 1 {
+ t.Fatalf("a core restart after the panel's snapshot re-armed the lease: %+v", state)
+ }
+
+ startFromPanel(t, c)
+ restartCore()
+ if state := waitForTheLeaseToClear(t, c, fake, 3*time.Second); state.Floor != 110 {
+ t.Fatalf("after a core restart inside the lease the node holds %+v, want no entries and the floor at the high water 110", state)
+ }
+}
+
+func TestOneStrayRequestFromAnOtherwiseSilentPanelKeepsItsCaps(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+
+ startFromPanel(t, c)
+ time.Sleep(210 * time.Millisecond)
+ c.NewRequest()
+ time.Sleep(1100 * time.Millisecond)
+
+ state := requireNodeAndCoreAgree(t, c, fake)
+ if len(state.Entries) != 2 || state.Floor != 100 {
+ t.Fatalf("four leases after a Start that the panel followed with a single request 0.7 lease later, the node holds %+v, want both caps kept at floor 100", state)
+ }
+}
+
+func TestAPanelThatFallsSilentAfterAStartKeepsTheCapsPastTheLease(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+
+ startFromPanel(t, c)
+ time.Sleep(1200 * time.Millisecond)
+
+ state := requireNodeAndCoreAgree(t, c, fake)
+ if len(state.Entries) != 2 || state.Floor != 100 {
+ t.Fatalf("four leases after a Start the panel never followed with a request, the node holds %+v, want both caps kept at floor 100", state)
+ }
+}
+
+func TestASnapshotReadBeforeANewerDiffLandsAfterThePanelWasSilentPastTheLease(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+
+ startFromPanel(t, c)
+ time.Sleep(1200 * time.Millisecond)
+ keepPanelTalking(t, c)
+
+ response := applySpeeds(t, c, speedSnapshot(104, &common.SpeedEntry{Email: "12", DownBps: 10_000_000, Revision: 100}))
+ if len(response.GetStale()) != 0 || response.GetHighWater() != 105 {
+ t.Fatalf("the snapshot the panel read before its diff 105 answered %v, want it applied with high water 105", response)
+ }
+ time.Sleep(700 * time.Millisecond)
+ state := requireNodeAndCoreAgree(t, c, fake)
+ want := []speedcap.Entry{{Email: "12", Down: 10_000_000, Revision: 104}, {Email: "13", Down: 20_000_000, Revision: 105}}
+ if !reflect.DeepEqual(state.Entries, want) || state.Floor != 104 {
+ t.Fatalf("after the panel came back with its snapshot the node holds %+v, want %+v at floor 104", state, want)
+ }
+}
+
+func TestAPanelBackFromASilenceHasAWholeLeaseToSendItsSnapshot(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+
+ startFromPanel(t, c)
+ time.Sleep(1150 * time.Millisecond)
+ back := time.Now()
+ keepPanelTalking(t, c)
+ time.Sleep(250 * time.Millisecond)
+ if state := requireNodeAndCoreAgree(t, c, fake); len(state.Entries) != 2 {
+ t.Fatalf("the lease cleared the caps %s after the panel came back from a silence: %+v", time.Since(back).Round(time.Millisecond), state)
+ }
+
+ state := waitForTheLeaseToClear(t, c, fake, 3*time.Second)
+ if took := time.Since(back); took < 300*time.Millisecond || state.Floor != 105 {
+ t.Fatalf("a panel back from a silence that sent no snapshot lost its caps %s after it came back, with %+v; want them kept a whole lease of 300ms, then cleared to the floor 105", took.Round(time.Millisecond), state)
+ }
+}
+
+func TestACheckOfAnOlderLeaseNeverReplacesTheTimerOfANewerStartOrOfAClosedNode(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, time.Hour)
+ startFromPanel(t, c)
+ older := c.armedLease
+ startFromPanel(t, c)
+ c.mu.RLock()
+ newer := c.leaseTimer
+ c.mu.RUnlock()
+
+ c.renewSpeedCapLease(older, true)
+ c.mu.RLock()
+ kept := c.leaseTimer
+ c.mu.RUnlock()
+ if kept != newer {
+ t.Fatal("a check of the lease of an older Start replaced the timer of the newer one")
+ }
+
+ c.stopSpeedCapLease()
+ c.renewSpeedCapLease(c.armedLease, true)
+ c.mu.RLock()
+ left := c.leaseTimer
+ c.mu.RUnlock()
+ if left != nil {
+ left.Stop()
+ t.Fatal("a check of the lease armed a new timer after the node stopped the lease")
+ }
+}
+
+type hangingSpeedBackend struct {
+ *fakeSpeedBackend
+ hang atomic.Bool
+ hung chan struct{}
+ once sync.Once
+}
+
+func (h *hangingSpeedBackend) PushSpeedCaps(ctx context.Context, change speedcap.Change) error {
+ if h.hang.Load() {
+ h.once.Do(func() { close(h.hung) })
+ <-ctx.Done()
+ return ctx.Err()
+ }
+ return h.fakeSpeedBackend.PushSpeedCaps(ctx, change)
+}
+
+func TestAStartDoesNotWaitOutAHungLeaseEndPush(t *testing.T) {
+ h := &hangingSpeedBackend{fakeSpeedBackend: &fakeSpeedBackend{core: speedcap.NewMemoryStore()}, hung: make(chan struct{})}
+ c := &Controller{backend: h, primaryType: common.BackendType_XRAY, speedCaps: speedcap.Open(filepath.Join(t.TempDir(), "speedcaps.json")), speedCapLease: 300 * time.Millisecond, syncDrainGrace: 200 * time.Millisecond}
+ c.newBackend = func(context.Context, *common.Backend, int, int) (backend.Backend, error) { return h, nil }
+ t.Cleanup(c.stopSpeedCapLease)
+ if err := c.speedCaps.Sync(context.Background(), h.PushSpeedCaps); err != nil {
+ t.Fatal(err)
+ }
+ seedLeaseCaps(t, c)
+
+ keepPanelTalking(t, c)
+ h.hang.Store(true)
+ startFromPanel(t, c)
+ select {
+ case <-h.hung:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the lease end never pushed to the core")
+ }
+ h.hang.Store(false)
+
+ begin := time.Now()
+ if err := c.ReplaceBackend(context.Background(), &common.Backend{Type: common.BackendType_XRAY}); err != nil {
+ t.Fatal(err)
+ }
+ if waited := time.Since(begin); waited > 3*time.Second {
+ t.Fatalf("a Start waited %s behind a lease-end push the core never answered, past the %s drain grace", waited.Round(time.Millisecond), c.syncDrainGrace)
+ }
+}
+
+func TestALeaseEndThatCannotSaveKeepsTheCapsAndTriesAgain(t *testing.T) {
+
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := leaseController(t, fake, 300*time.Millisecond)
+ seedLeaseCaps(t, c)
+ unblock := blockTheStoreDirectory(t, c.speedCaps.Path())
+
+ keepPanelTalking(t, c)
+ startFromPanel(t, c)
+ time.Sleep(1000 * time.Millisecond)
+ if state := requireNodeAndCoreAgree(t, c, fake); len(state.Entries) != 2 {
+ t.Fatalf("a lease end that could not save the cleared set left %+v, want both caps kept on the node and the core", state)
+ }
+
+ unblock()
+ if state := waitForTheLeaseToClear(t, c, fake, 3*time.Second); state.Floor != 105 {
+ t.Fatalf("the lease end after the save works again left %+v, want no entries and the floor at the high water 105", state)
+ }
+}
+
+func TestTheScopeReachesTheStoreAndTheCore(t *testing.T) {
+ fake := &fakeSpeedBackend{core: speedcap.NewMemoryStore()}
+ c := syncedSpeedController(t, fake)
+ scoped := &common.SpeedEntry{Email: "12", DownBps: 10_000_000, Revision: 1, InboundTags: []string{"vmess-in", "vless-in"}}
+ response := applySpeeds(t, c, &common.SetUserSpeedsRequest{Entries: []*common.SpeedEntry{scoped}})
+ if len(response.GetStale()) != 0 || len(response.GetRejected()) != 0 {
+ t.Fatalf("unexpected response %v", response)
+ }
+ state := requireNodeAndCoreAgree(t, c, fake)
+ if want := []string{"vless-in", "vmess-in"}; len(state.Entries) != 1 || !reflect.DeepEqual(state.Entries[0].InboundTags, want) {
+ t.Fatalf("the node holds %+v, want the scope %v", state, want)
+ }
+
+ narrower := &common.SpeedEntry{Email: "12", DownBps: 10_000_000, Revision: 1, InboundTags: []string{"vless-in"}}
+ response = applySpeeds(t, c, &common.SetUserSpeedsRequest{Entries: []*common.SpeedEntry{narrower}})
+ if !reflect.DeepEqual(response.GetStale(), []string{"12"}) {
+ t.Fatalf("an equal revision with another scope answered stale %v", response.GetStale())
+ }
+}
diff --git a/docs/upstream-parity.md b/docs/upstream-parity.md
index ca3bd16d..739d5040 100644
--- a/docs/upstream-parity.md
+++ b/docs/upstream-parity.md
@@ -1,14 +1,15 @@
# Upstream parity
-This fork tracks [PasarGuard/node](https://github.com/PasarGuard/node), and the node image builds three third-party
-upstreams: Xray-core, sing-box and sing-quic. It built mtg too until the MTProto backend was removed on 2026-11-10.
+This fork tracks [PasarGuard/node](https://github.com/PasarGuard/node), and the node image builds one third-party
+upstream: Xray-core. It built sing-box and sing-quic too until feature 004 removed the sing-box server core (ordered on
+2026-12-01), and mtg until the MTProto backend was removed on 2026-11-10.
This page records which upstream changes the fork has taken, which it has refused and why, and which upstream work is still pending. The daily drift check (`scripts/upstream_drift.sh`, run
by `.github/workflows/upstream-drift.yml`) keeps it honest. It fails when an item is neither ported nor waived with a
reason. An item is any of these:
- a commit on any PasarGuard/node branch or tag;
-- a published security advisory of any of the four repositories;
-- a security-looking commit on any active branch of the three third-party upstreams;
+- a published security advisory of either repository, PasarGuard/node or Xray-core;
+- a security-looking commit on any active branch of the third-party upstream;
- a third-party release published after our pin.
State as of 2026-09-24, release 0.6.21. The PasarGuard/node section was re-checked on 2026-10-07 (see
@@ -309,11 +310,14 @@ Of the 44 upstream tags on 2026-11-02, the 42 from `v0.0.1` to `v0.5.4` are in t
are not merged; their commits are ported or waived one by one.
PR #61, "add MTProto proxy backend via telemt", is open and not merged. It adds `MTPROTO = 2` to `BackendType` and a
-telemt-based backend. The fork ran its own mtg-based MTProto backend as `MTPROTO = 4` until 2026-11-10, when the owner
-had the feature removed; `MTPROTO = 4` and `Proxy mtproto = 9` are now `reserved` in `common/service.proto` so no later
-field reuses them and a node on the previous image stays wire-compatible. The collision that blocks #61 is therefore no
-longer a competing backend but the numbers themselves: upstream's `MTPROTO = 2` is the fork's `SING_BOX = 2` and
-upstream's `Proxy mtproto = 8` is the fork's `open_vpn = 8`. It stays rejected. Revisit it if upstream merges it.
+telemt-based backend, the Telegram proxy. The fork ran its own mtg-based MTProto backend as `MTPROTO = 4` until
+2026-11-10, when the owner had the Telegram proxy removed from the fork, and on 2026-12-02 the owner confirmed that it
+stays out. `MTPROTO = 4` and `Proxy mtproto = 9` are `reserved` in `common/service.proto` so no later field reuses them
+and a node on the previous image stays wire-compatible. #61 is therefore rejected by the owner's decision, and its
+numbers would collide as well: upstream's `MTPROTO = 2` is the fork's `BackendType 2`, which stays reserved by number
+and by name (`SING_BOX`) since feature 004 removed that backend, and upstream's `Proxy mtproto = 8` is the fork's
+`open_vpn = 8`. If upstream merges it, only its changes outside the MTProto backend are reviewed; the same holds for
+#120 on `dev`, whose generic retry-later sync error is ported or refused on its own once a release contains it.
Open upstream pull requests whose heads live on contributors' forks are not branches of PasarGuard/node, so the check
does not see them. On 2026-09-24 they were:
@@ -331,31 +335,28 @@ until they are ported or waived.
## Third-party upstreams
-The node image also builds three third-party upstreams. U6 (2026-09-24) found two HIGH Xray fixes that had shipped
-upstream months after our pin, and nothing had noticed them. The drift check therefore watches these upstreams too.
+The node image also builds one third-party upstream, Xray-core. U6 (2026-09-24) found two HIGH Xray fixes that had
+shipped upstream months after our pin, and nothing had noticed them. The drift check therefore watches it too.
### Pins
-The script reads every pin from the checked commit, never from a hardcoded value, through the same Dockerfile reader as the xray build (so a declaration on a continuation line or behind a CRLF counts), and the way docker resolves it: from the `ARG` declaration in the stage that builds (`xray-builder` for `XRAY_COMMIT`, `singbox-builder` for the sing-box pins), falling back to a global declaration only when that stage declares the `ARG` without a value. Two declarations with a value in that stage, or two global ones it falls back to, stop the run with exit 2, and so does a Dockerfile in which that stage does not exist the way docker reads it (a continuation line can swallow its `FROM`):
+The script reads every pin from the checked commit, never from a hardcoded value, through the same Dockerfile reader as the xray build (so a declaration on a continuation line or behind a CRLF counts), and the way docker resolves it: from the `ARG` declaration in the stage that builds (`xray-builder` for `XRAY_COMMIT`), falling back to a global declaration only when that stage declares the `ARG` without a value. Two declarations with a value in that stage, or two global ones it falls back to, stop the run with exit 2, and so does a Dockerfile in which that stage does not exist the way docker reads it (a continuation line can swallow its `FROM`):
| component | upstream | pin read from | pin on 2026-11-15 | line branch |
|---|---|---|---|---|
| `xray` | XTLS/Xray-core | `Dockerfile` `ARG XRAY_COMMIT` | `d2758a023cd7` (`v26.3.27`), held for the v0.8.25 rollout while `go.mod` stays on `676eaf66f8f0` (`v26.11.9`); see [State on 2026-11-15](#state-on-2026-11-15-the-xray-binary-is-held-on-v26327-for-the-v0825-rollout) | `main` |
-| `sing-box` | SagerNet/sing-box | `Dockerfile` `ARG SINGBOX_VERSION`, an upstream tag | `v1.13.21` (`628cb31ffa79`); fork `SINGBOX_COMMIT` `f92b2cdb67bc` | `oldstable` |
-| `sing-quic` | SagerNet/sing-quic | the `require` line of the sing-box fork's `go.mod` at `SINGBOX_COMMIT`, fetched from `SINGBOX_REPO` | `v0.6.5` (`d83826c306d7`) | `main` |
Retired on 2026-11-10: `mtg` (9seconds/mtg) was read from the node `go.mod` `require` of
`github.com/9seconds/mtg/v2`. The MTProto backend was removed that day, `go mod tidy` dropped the `require` and the
`replace` of Free-Guy-IR/mtg with it, and `mtg` was removed from the drift check's components, so the node no longer
links or pins mtg.
-Two rules keep the pins honest:
+Retired in feature 004: `sing-box` (SagerNet/sing-box, read from `Dockerfile` `ARG SINGBOX_VERSION`) and `sing-quic`
+(SagerNet/sing-quic, read from the `require` line of the sing-box fork's `go.mod` at `SINGBOX_COMMIT`). The owner had
+the sing-box server core removed («کامل بردارش», 2026-12-01): `backend/singbox`, the `singbox-builder` stage and its
+binary left the node, so nothing reads those pins any more. Both left the drift check's components, and their 42
+commit waivers and their one advisory waiver left `.github/upstream-waivers.txt`.
-- **sing-box.** The fork is a squashed import, so reachability cannot tell which upstream release it is based on.
- `SINGBOX_VERSION` must always name the upstream release the fork's tree is based on.
-- **sing-quic.** The sing-box fork `replace`s sing-quic with its `third_party` copy, which makes the `require` line
- inert, so nothing else keeps it honest. When the vendored copy is upgraded, the `require` line must be bumped to the
- same version.
### Rules
For each component the script fetches every upstream branch and tag. It fetches commit objects only
@@ -464,8 +465,8 @@ Why the rules look like this:
The check's awk programs use no regular-expression interval such as `{64}`, because mawk 1.3.4 20200120 (the
awk of Ubuntu 22.04) reads one as plain text and would refuse every digest-pinned builder. A test runs the check
under an awk that rejects any program with an interval.
- It then counts only for the xray component. A header in a patch that nothing applies, or one that names a node,
- sing-box or sing-quic commit, ports nothing; those components are ported by commit trailers.
+ It then counts only for the xray component. A header in a patch that nothing applies, or one that names a node
+ commit, ports nothing; node commits are ported by commit trailers.
- **Carried in 0.6.21.** The Xray patch files and commits of 0.6.21 carry `Upstream:` lines for:
- `e5a9fb752e0dcc127dd1740316c853571c16052f` and `8f15190c230fe6975c9b18e31316c6bc494f3863`, the QUIC sniffer;
- `711aea4e34b0a00073d2fea6577f28a5d7c9b5eb`, trusted X-Forwarded-For;
@@ -487,10 +488,6 @@ Why the rules look like this:
`8f15190` name them.
- `598bde7` is not carried: its race is fixed by a fork patch with no `Upstream:` line, see
[Fork deviations in the Xray build](#fork-deviations-in-the-xray-build).
-- **sing-box and sing-quic.** The normal port is a pin move: the fork is rebased on a newer release, and
- `SINGBOX_VERSION` or the `require` line is bumped. The items then become reachable from the pin and disappear. A
- single fix cherry-picked into the fork without a pin move needs an `Upstream:` line in the node commit that moves
- `SINGBOX_COMMIT`.
### State on 2026-09-24
@@ -1233,13 +1230,6 @@ The scheduled drift run on `main` (`92a8aa57afcf`, v0.8.25) has been red since 2
### Not covered
-- **SagerNet/sing, sing-vmess, grpc-go and other Go dependencies.** The sing-box fork vendors or requires them. The
- govulncheck CI job scans the node module and, since 2026-11-22, the Xray binary, but not sing-box, so it does not
- cover them. On 2026-10-10, govulncheck v1.8.0 with
- Go 1.26.9 on `./cmd/sing-box` at `SINGBOX_COMMIT` `4a87f50`, with the image's build tags, found no standard library
- id. It found 20 symbol-reachable ids in x/net 0.50.0, x/crypto 0.48.0 (ssh), x/text 0.34.0 and grpc 1.79.1. The
- node binds the sing-box gRPC and clash APIs to 127.0.0.1 and serves Hysteria2 over QUIC, so their HTTP/2 server paths
- are reachable only from the host itself. Moving the sing-box fork's dependencies is a separate, open decision.
- **Open pull requests on contributors' forks** (listed above).
- **Pre-release tags** (alpha, beta, rc). Their commits are covered by rule 2 on the active branches.
- **Alpine packages.** Since 0.6.21 the alpine and golang base images are pinned by digest, and the geo data comes from
@@ -1646,8 +1636,7 @@ shipped.
### FORK DEVIATION: freedom refuses the local host for user inbounds (patches/xray-freedom-local-host.patch)
- **Why:** the node's port-only API guard closes the API and metric ports, but a user could still reach any other
- loopback port, such as the sing-box extras' v2ray_api and clash_api ports that FindFreePort picks at runtime,
- through a name that resolves to 127.0.0.1 when a panel rule matches in the first routing pass.
+ loopback port through a name that resolves to 127.0.0.1 when a panel rule matches in the first routing pass.
- **What:** freedom refuses a loopback (127.0.0.0/8, `::1`, IPv4-mapped loopback) or unspecified (`0.0.0.0`, `::`)
destination for connections from the vless, vmess, trojan, hysteria, wireguard and shadowsocks inbounds, the names
those inbounds set in `session.Inbound` at the pin. It checks a literal or freedom-resolved address before dialing;
@@ -1773,7 +1762,7 @@ shipped.
## The drift check
-`scripts/upstream_drift.sh` runs four sections: `node`, `xray`, `sing-box` and `sing-quic`. The node section
+`scripts/upstream_drift.sh` runs two sections: `node` and `xray`. The node section
fetches every PasarGuard/node branch and tag, pruning deleted ones, into `refs/upstream-drift/node/heads/*` and
`refs/upstream-drift/node/tags/*`. It then lists every non-merge upstream commit that is reachable from any of them and
not from the checked commit. The label on each line names the branches that contain the commit, or its tags when no
@@ -1821,9 +1810,9 @@ reachable and never listed. The check exits 0 when nothing is `UNPORTED`, 1 when
failed fetch, a failed API call, a missing pin, or a malformed waiver.
The release-only rule reads one branch per component, the release line the pin tracks: `main` for Xray-core and
-sing-quic, `oldstable` for sing-box, `master` for mtg, and upstream `main` for the node fork itself. A
+upstream `main` for the node fork itself. A
security-looking commit after the pin that no tag of that component contains and that its release line does not carry
-is `DEVONLY`: it sits on another branch, including a newer release line such as sing-box `stable`, and it blocks
+is `DEVONLY`: it sits on another branch, and it blocks
nothing until a tag reaches it. Release completeness is untouched by this: a commit a tag contains stays `UNPORTED`
wherever else it lives, a commit on the pinned release line stays `UNPORTED` even before it is tagged, and an upstream
release after the pin is still an item of its own that must be taken or waived by its tag commit.
@@ -1907,8 +1896,8 @@ bash scripts/upstream_drift.sh
```
- It needs `git`, `curl` and `jq`. The GitHub API allows 60 unauthenticated requests an hour. A full run makes at least
- 10, one pair per component. With `GITHUB_TOKEN` set, it sends that token instead.
-- `DRIFT_COMPONENTS="node xray"` runs only the named sections. The default is all five.
+ 4, one pair per component. With `GITHUB_TOKEN` set, it sends that token instead.
+- `DRIFT_COMPONENTS=node` runs only the named sections. The default is both, `node xray`.
- `DRIFT_CACHE=` keeps the third-party repositories and the advisory answers in ``, instead of a temporary
directory. `UPSTREAM_FETCH=0` then skips every fetch and API call, and it reuses the node refs and that cache.
- `DRIFT_TARGET=[` checks another branch or commit instead of `HEAD`.
diff --git a/patches/xray-per-user-speed-cap.patch b/patches/xray-per-user-speed-cap.patch
new file mode 100644
index 00000000..eede1145
--- /dev/null
+++ b/patches/xray-per-user-speed-cap.patch
@@ -0,0 +1,3756 @@
+diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go
+index e6f8965..23f215e 100644
+--- a/app/dispatcher/default.go
++++ b/app/dispatcher/default.go
+@@ -7,6 +7,7 @@ import (
+ "sync"
+ "time"
+
++ "github.com/xtls/xray-core/app/proxyman/speedcap"
+ "github.com/xtls/xray-core/common"
+ "github.com/xtls/xray-core/common/buf"
+ "github.com/xtls/xray-core/common/errors"
+@@ -160,6 +161,8 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran
+ }
+
+ if user != nil && len(user.Email) > 0 {
++ inboundLink.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Uplink, inboundLink.Writer)
++ outboundLink.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Downlink, outboundLink.Writer)
+ p := d.policy.ForLevel(user.Level)
+ if p.Stats.UserUplink {
+ name := "user>>>" + user.Email + ">>>traffic>>>uplink"
+@@ -200,6 +203,10 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
+ user = sessionInbound.User
+ }
+
++ if user != nil && len(user.Email) > 0 {
++ link.Reader = speedcap.NewReader(ctx, user.Email, sessionInbound.Tag, link.Reader)
++ link.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Downlink, link.Writer)
++ }
+ link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader}
+
+ if user != nil && len(user.Email) > 0 {
+diff --git a/app/dispatcher/speedcap_test.go b/app/dispatcher/speedcap_test.go
+new file mode 100644
+index 0000000..0674c1a
+--- /dev/null
++++ b/app/dispatcher/speedcap_test.go
+@@ -0,0 +1,102 @@
++package dispatcher_test
++
++import (
++ "context"
++ "math"
++ "testing"
++ "time"
++
++ "github.com/xtls/xray-core/app/dispatcher"
++ "github.com/xtls/xray-core/app/policy"
++ "github.com/xtls/xray-core/app/proxyman/speedcap"
++ "github.com/xtls/xray-core/app/stats"
++ "github.com/xtls/xray-core/common/buf"
++ "github.com/xtls/xray-core/common/net"
++ "github.com/xtls/xray-core/common/protocol"
++ "github.com/xtls/xray-core/common/session"
++ "github.com/xtls/xray-core/transport"
++)
++
++type nullWriter struct{}
++
++func (nullWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
++ buf.ReleaseMulti(mb)
++ return nil
++}
++
++type endlessReader struct{}
++
++func (endlessReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
++ b := buf.New()
++ b.Extend(buf.Size)
++ return buf.MultiBuffer{b}, nil
++}
++
++func TestWrapLinkCapsTheUserAndKeepsTheStatsWriterOutermost(t *testing.T) {
++ const email = "dispatcher-speedcap@test"
++ ctx := context.Background()
++ manager, err := stats.NewManager(ctx, &stats.Config{})
++ if err != nil {
++ t.Fatal(err)
++ }
++ policies, err := policy.New(ctx, &policy.Config{Level: map[uint32]*policy.Policy{
++ 0: {Stats: &policy.Policy_Stats{UserUplink: true, UserDownlink: true}},
++ }})
++ if err != nil {
++ t.Fatal(err)
++ }
++ speedcap.Default().Apply([]speedcap.Entry{{Email: email, Down: 8_000_000, Revision: 1}}, false, 0)
++ defer speedcap.Default().Apply([]speedcap.Entry{{Email: email, Revision: 2}}, false, 0)
++
++ connCtx := session.ContextWithInbound(ctx, &session.Inbound{
++ User: &protocol.MemoryUser{Email: email},
++ Source: net.TCPDestination(net.LocalHostIP, 40000),
++ })
++ link := dispatcher.WrapLink(connCtx, policies, manager, &transport.Link{Reader: endlessReader{}, Writer: nullWriter{}})
++
++ statWriter, ok := link.Writer.(*dispatcher.SizeStatWriter)
++ if !ok {
++ t.Fatalf("the downlink writer is %T, the user stats writer must stay outermost for splice accounting", link.Writer)
++ }
++ if _, ok := statWriter.Writer.(*speedcap.Writer); !ok {
++ t.Fatalf("the user stats writer wraps %T, not the speed cap writer", statWriter.Writer)
++ }
++ timeoutReader, ok := link.Reader.(*buf.TimeoutWrapperReader)
++ if !ok {
++ t.Fatalf("the uplink reader is %T, sniffing needs the timeout wrapper outermost", link.Reader)
++ }
++ if _, ok := timeoutReader.Reader.(*speedcap.Reader); !ok {
++ t.Fatalf("the timeout wrapper reads from %T, not the speed cap reader", timeoutReader.Reader)
++ }
++
++ var written int64
++ warm := time.Now()
++ for time.Since(warm) < 1500*time.Millisecond {
++ written += buf.Size
++ if err := link.Writer.WriteMultiBuffer(endlessChunk()); err != nil {
++ t.Fatal(err)
++ }
++ }
++ measured := int64(0)
++ start := time.Now()
++ for time.Since(start) < 4*time.Second {
++ measured += buf.Size
++ written += buf.Size
++ if err := link.Writer.WriteMultiBuffer(endlessChunk()); err != nil {
++ t.Fatal(err)
++ }
++ }
++ mbps := float64(measured) * 8 / time.Since(start).Seconds() / 1e6
++ if math.Abs(mbps-8) > 0.8 {
++ t.Fatalf("a capped user's downlink ran at %.2f Mbit/s, want 8 +-10%%", mbps)
++ }
++ counter := manager.GetCounter("user>>>" + email + ">>>traffic>>>downlink")
++ if counter == nil || counter.Value() != written {
++ t.Fatalf("the user downlink counter does not match the bytes written: counter %v, written %d", counter, written)
++ }
++}
++
++func endlessChunk() buf.MultiBuffer {
++ mb, _ := endlessReader{}.ReadMultiBuffer()
++ return mb
++}
+diff --git a/app/proxyman/speedcap/bucket.go b/app/proxyman/speedcap/bucket.go
+new file mode 100644
+index 0000000..7612a90
+--- /dev/null
++++ b/app/proxyman/speedcap/bucket.go
+@@ -0,0 +1,109 @@
++package speedcap
++
++import (
++ "context"
++ "sync"
++ "time"
++)
++
++const burstWindow = time.Second
++
++type bucket struct {
++ mu sync.Mutex
++ rate float64
++ burst float64
++ tokens float64
++ last time.Time
++ used time.Time
++ changed chan struct{}
++}
++
++func bytesPerSecond(bps uint64) float64 {
++ return float64(bps) / 8
++}
++
++func newBucket(bps uint64, now time.Time) *bucket {
++ rate := bytesPerSecond(bps)
++ burst := rate * burstWindow.Seconds()
++ return &bucket{rate: rate, burst: burst, tokens: burst, last: now, used: now, changed: make(chan struct{})}
++}
++
++func (b *bucket) refillLocked(now time.Time) {
++ if elapsed := now.Sub(b.last); elapsed > 0 {
++ b.tokens = min(b.burst, b.tokens+elapsed.Seconds()*b.rate)
++ b.last = now
++ }
++}
++
++func (b *bucket) reserve(n int64, now time.Time) (time.Duration, float64, <-chan struct{}) {
++ b.mu.Lock()
++ defer b.mu.Unlock()
++ b.used = now
++ if b.rate <= 0 {
++ return 0, 0, nil
++ }
++ b.refillLocked(now)
++ b.tokens -= float64(n)
++ if b.tokens >= 0 {
++ return 0, b.rate, nil
++ }
++ return time.Duration(-b.tokens / b.rate * float64(time.Second)), b.rate, b.changed
++}
++
++func (b *bucket) current() (float64, <-chan struct{}) {
++ b.mu.Lock()
++ defer b.mu.Unlock()
++ return b.rate, b.changed
++}
++
++func (b *bucket) setRate(bps uint64, now time.Time) {
++ b.mu.Lock()
++ defer b.mu.Unlock()
++ b.refillLocked(now)
++ b.rate = bytesPerSecond(bps)
++ b.burst = b.rate * burstWindow.Seconds()
++ b.tokens = min(b.tokens, b.burst)
++ close(b.changed)
++ b.changed = make(chan struct{})
++}
++
++func (b *bucket) idleFor(now time.Time) time.Duration {
++ b.mu.Lock()
++ defer b.mu.Unlock()
++ b.refillLocked(now)
++ if b.tokens < 0 {
++ return 0
++ }
++ return now.Sub(b.used)
++}
++
++func (b *bucket) wait(ctx context.Context, n int64, clock func() time.Time) {
++ now := clock()
++ delay, rate, changed := b.reserve(n, now)
++ if delay <= 0 {
++ return
++ }
++ deadline := now.Add(delay)
++ timer := time.NewTimer(delay)
++ defer timer.Stop()
++ for {
++ select {
++ case <-timer.C:
++ return
++ case <-ctx.Done():
++ return
++ case <-changed:
++ next, nextChanged := b.current()
++ if next <= 0 {
++ return
++ }
++ now = clock()
++ remaining := time.Duration(float64(deadline.Sub(now)) * rate / next)
++ if remaining <= 0 {
++ return
++ }
++ rate, changed, deadline = next, nextChanged, now.Add(remaining)
++ timer.Reset(remaining)
++ }
++ }
++}
+diff --git a/app/proxyman/speedcap/config.pb.go b/app/proxyman/speedcap/config.pb.go
+new file mode 100644
+index 0000000..f044574
+--- /dev/null
++++ b/app/proxyman/speedcap/config.pb.go
+@@ -0,0 +1,227 @@
++// Code generated by protoc-gen-go. DO NOT EDIT.
++// versions:
++// protoc-gen-go v1.36.11
++// protoc v7.36.2
++// source: app/proxyman/speedcap/config.proto
++
++package speedcap
++
++import (
++ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
++ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
++ reflect "reflect"
++ sync "sync"
++ unsafe "unsafe"
++)
++
++const (
++ // Verify that this generated code is sufficiently up-to-date.
++ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
++ // Verify that runtime/protoimpl is sufficiently up-to-date.
++ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
++)
++
++type SpeedEntry struct {
++ state protoimpl.MessageState `protogen:"open.v1"`
++ Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
++ DownBps uint64 `protobuf:"varint,2,opt,name=down_bps,json=downBps,proto3" json:"down_bps,omitempty"`
++ UpBps uint64 `protobuf:"varint,3,opt,name=up_bps,json=upBps,proto3" json:"up_bps,omitempty"`
++ Revision uint64 `protobuf:"varint,4,opt,name=revision,proto3" json:"revision,omitempty"`
++ InboundTags []string `protobuf:"bytes,5,rep,name=inbound_tags,json=inboundTags,proto3" json:"inbound_tags,omitempty"`
++ unknownFields protoimpl.UnknownFields
++ sizeCache protoimpl.SizeCache
++}
++
++func (x *SpeedEntry) Reset() {
++ *x = SpeedEntry{}
++ mi := &file_app_proxyman_speedcap_config_proto_msgTypes[0]
++ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
++ ms.StoreMessageInfo(mi)
++}
++
++func (x *SpeedEntry) String() string {
++ return protoimpl.X.MessageStringOf(x)
++}
++
++func (*SpeedEntry) ProtoMessage() {}
++
++func (x *SpeedEntry) ProtoReflect() protoreflect.Message {
++ mi := &file_app_proxyman_speedcap_config_proto_msgTypes[0]
++ if x != nil {
++ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
++ if ms.LoadMessageInfo() == nil {
++ ms.StoreMessageInfo(mi)
++ }
++ return ms
++ }
++ return mi.MessageOf(x)
++}
++
++// Deprecated: Use SpeedEntry.ProtoReflect.Descriptor instead.
++func (*SpeedEntry) Descriptor() ([]byte, []int) {
++ return file_app_proxyman_speedcap_config_proto_rawDescGZIP(), []int{0}
++}
++
++func (x *SpeedEntry) GetEmail() string {
++ if x != nil {
++ return x.Email
++ }
++ return ""
++}
++
++func (x *SpeedEntry) GetDownBps() uint64 {
++ if x != nil {
++ return x.DownBps
++ }
++ return 0
++}
++
++func (x *SpeedEntry) GetUpBps() uint64 {
++ if x != nil {
++ return x.UpBps
++ }
++ return 0
++}
++
++func (x *SpeedEntry) GetRevision() uint64 {
++ if x != nil {
++ return x.Revision
++ }
++ return 0
++}
++
++func (x *SpeedEntry) GetInboundTags() []string {
++ if x != nil {
++ return x.InboundTags
++ }
++ return nil
++}
++
++type SetUserSpeedsOperation struct {
++ state protoimpl.MessageState `protogen:"open.v1"`
++ Entries []*SpeedEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"`
++ ReplaceAll bool `protobuf:"varint,2,opt,name=replace_all,json=replaceAll,proto3" json:"replace_all,omitempty"`
++ SnapshotRevision uint64 `protobuf:"varint,3,opt,name=snapshot_revision,json=snapshotRevision,proto3" json:"snapshot_revision,omitempty"`
++ unknownFields protoimpl.UnknownFields
++ sizeCache protoimpl.SizeCache
++}
++
++func (x *SetUserSpeedsOperation) Reset() {
++ *x = SetUserSpeedsOperation{}
++ mi := &file_app_proxyman_speedcap_config_proto_msgTypes[1]
++ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
++ ms.StoreMessageInfo(mi)
++}
++
++func (x *SetUserSpeedsOperation) String() string {
++ return protoimpl.X.MessageStringOf(x)
++}
++
++func (*SetUserSpeedsOperation) ProtoMessage() {}
++
++func (x *SetUserSpeedsOperation) ProtoReflect() protoreflect.Message {
++ mi := &file_app_proxyman_speedcap_config_proto_msgTypes[1]
++ if x != nil {
++ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
++ if ms.LoadMessageInfo() == nil {
++ ms.StoreMessageInfo(mi)
++ }
++ return ms
++ }
++ return mi.MessageOf(x)
++}
++
++// Deprecated: Use SetUserSpeedsOperation.ProtoReflect.Descriptor instead.
++func (*SetUserSpeedsOperation) Descriptor() ([]byte, []int) {
++ return file_app_proxyman_speedcap_config_proto_rawDescGZIP(), []int{1}
++}
++
++func (x *SetUserSpeedsOperation) GetEntries() []*SpeedEntry {
++ if x != nil {
++ return x.Entries
++ }
++ return nil
++}
++
++func (x *SetUserSpeedsOperation) GetReplaceAll() bool {
++ if x != nil {
++ return x.ReplaceAll
++ }
++ return false
++}
++
++func (x *SetUserSpeedsOperation) GetSnapshotRevision() uint64 {
++ if x != nil {
++ return x.SnapshotRevision
++ }
++ return 0
++}
++
++var File_app_proxyman_speedcap_config_proto protoreflect.FileDescriptor
++
++const file_app_proxyman_speedcap_config_proto_rawDesc = "" +
++ "\n" +
++ "\"app/proxyman/speedcap/config.proto\x12\x1axray.app.proxyman.speedcap\"\x93\x01\n" +
++ "\n" +
++ "SpeedEntry\x12\x14\n" +
++ "\x05email\x18\x01 \x01(\tR\x05email\x12\x19\n" +
++ "\bdown_bps\x18\x02 \x01(\x04R\adownBps\x12\x15\n" +
++ "\x06up_bps\x18\x03 \x01(\x04R\x05upBps\x12\x1a\n" +
++ "\brevision\x18\x04 \x01(\x04R\brevision\x12!\n" +
++ "\finbound_tags\x18\x05 \x03(\tR\vinboundTags\"\xa8\x01\n" +
++ "\x16SetUserSpeedsOperation\x12@\n" +
++ "\aentries\x18\x01 \x03(\v2&.xray.app.proxyman.speedcap.SpeedEntryR\aentries\x12\x1f\n" +
++ "\vreplace_all\x18\x02 \x01(\bR\n" +
++ "replaceAll\x12+\n" +
++ "\x11snapshot_revision\x18\x03 \x01(\x04R\x10snapshotRevisionBp\n" +
++ "\x1ecom.xray.app.proxyman.speedcapP\x01Z/github.com/xtls/xray-core/app/proxyman/speedcap\xaa\x02\x1aXray.App.Proxyman.Speedcapb\x06proto3"
++
++var (
++ file_app_proxyman_speedcap_config_proto_rawDescOnce sync.Once
++ file_app_proxyman_speedcap_config_proto_rawDescData []byte
++)
++
++func file_app_proxyman_speedcap_config_proto_rawDescGZIP() []byte {
++ file_app_proxyman_speedcap_config_proto_rawDescOnce.Do(func() {
++ file_app_proxyman_speedcap_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_proxyman_speedcap_config_proto_rawDesc), len(file_app_proxyman_speedcap_config_proto_rawDesc)))
++ })
++ return file_app_proxyman_speedcap_config_proto_rawDescData
++}
++
++var file_app_proxyman_speedcap_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
++var file_app_proxyman_speedcap_config_proto_goTypes = []any{
++ (*SpeedEntry)(nil), // 0: xray.app.proxyman.speedcap.SpeedEntry
++ (*SetUserSpeedsOperation)(nil), // 1: xray.app.proxyman.speedcap.SetUserSpeedsOperation
++}
++var file_app_proxyman_speedcap_config_proto_depIdxs = []int32{
++ 0, // 0: xray.app.proxyman.speedcap.SetUserSpeedsOperation.entries:type_name -> xray.app.proxyman.speedcap.SpeedEntry
++ 1, // [1:1] is the sub-list for method output_type
++ 1, // [1:1] is the sub-list for method input_type
++ 1, // [1:1] is the sub-list for extension type_name
++ 1, // [1:1] is the sub-list for extension extendee
++ 0, // [0:1] is the sub-list for field type_name
++}
++
++func init() { file_app_proxyman_speedcap_config_proto_init() }
++func file_app_proxyman_speedcap_config_proto_init() {
++ if File_app_proxyman_speedcap_config_proto != nil {
++ return
++ }
++ type x struct{}
++ out := protoimpl.TypeBuilder{
++ File: protoimpl.DescBuilder{
++ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
++ RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_speedcap_config_proto_rawDesc), len(file_app_proxyman_speedcap_config_proto_rawDesc)),
++ NumEnums: 0,
++ NumMessages: 2,
++ NumExtensions: 0,
++ NumServices: 0,
++ },
++ GoTypes: file_app_proxyman_speedcap_config_proto_goTypes,
++ DependencyIndexes: file_app_proxyman_speedcap_config_proto_depIdxs,
++ MessageInfos: file_app_proxyman_speedcap_config_proto_msgTypes,
++ }.Build()
++ File_app_proxyman_speedcap_config_proto = out.File
++ file_app_proxyman_speedcap_config_proto_goTypes = nil
++ file_app_proxyman_speedcap_config_proto_depIdxs = nil
++}
+diff --git a/app/proxyman/speedcap/config.proto b/app/proxyman/speedcap/config.proto
+new file mode 100644
+index 0000000..02b04f4
+--- /dev/null
++++ b/app/proxyman/speedcap/config.proto
+@@ -0,0 +1,21 @@
++syntax = "proto3";
++
++package xray.app.proxyman.speedcap;
++option csharp_namespace = "Xray.App.Proxyman.Speedcap";
++option go_package = "github.com/xtls/xray-core/app/proxyman/speedcap";
++option java_package = "com.xray.app.proxyman.speedcap";
++option java_multiple_files = true;
++
++message SpeedEntry {
++ string email = 1;
++ uint64 down_bps = 2;
++ uint64 up_bps = 3;
++ uint64 revision = 4;
++ repeated string inbound_tags = 5;
++}
++
++message SetUserSpeedsOperation {
++ repeated SpeedEntry entries = 1;
++ bool replace_all = 2;
++ uint64 snapshot_revision = 3;
++}
+diff --git a/app/proxyman/speedcap/differential_test.go b/app/proxyman/speedcap/differential_test.go
+new file mode 100644
+index 0000000..1042ea2
+--- /dev/null
++++ b/app/proxyman/speedcap/differential_test.go
+@@ -0,0 +1,364 @@
++package speedcap
++
++import (
++ "context"
++ "errors"
++ "fmt"
++ "math/rand"
++ "path/filepath"
++ "slices"
++ "sort"
++ "strings"
++ "testing"
++
++ "google.golang.org/protobuf/encoding/protowire"
++ "google.golang.org/protobuf/proto"
++
++ node "github.com/xtls/xray-core/testing/speedcapnode"
++)
++
++func nodeEncode(change node.Change) []byte {
++ appendVarint := func(b []byte, n protowire.Number, v uint64) []byte {
++ if v == 0 {
++ return b
++ }
++ b = protowire.AppendTag(b, n, protowire.VarintType)
++ return protowire.AppendVarint(b, v)
++ }
++ var value []byte
++ for _, e := range change.Entries {
++ var item []byte
++ if e.Email != "" {
++ item = protowire.AppendTag(item, 1, protowire.BytesType)
++ item = protowire.AppendString(item, e.Email)
++ }
++ item = appendVarint(item, 2, e.Down)
++ item = appendVarint(item, 3, e.Up)
++ item = appendVarint(item, 4, e.Revision)
++ for _, tag := range e.InboundTags {
++ item = protowire.AppendTag(item, 5, protowire.BytesType)
++ item = protowire.AppendString(item, tag)
++ }
++ value = protowire.AppendTag(value, 1, protowire.BytesType)
++ value = protowire.AppendBytes(value, item)
++ }
++ if change.ReplaceAll {
++ value = appendVarint(value, 2, 1)
++ }
++ return appendVarint(value, 3, change.Snapshot)
++}
++
++type mirroredCore struct {
++ reg *Registry
++ mode int
++}
++
++func (c *mirroredCore) push(_ context.Context, change node.Change) error {
++ if c.mode == 1 {
++ return errors.New("core unavailable")
++ }
++ var op SetUserSpeedsOperation
++ if err := proto.Unmarshal(nodeEncode(change), &op); err != nil {
++ return err
++ }
++ op.ApplyTo(c.reg)
++ if c.mode == 2 {
++ return errors.New("answer lost after the core applied it")
++ }
++ return nil
++}
++
++type oracleRecord struct {
++ down, up, rev uint64
++ scope string
++}
++
++func oracleScope(down, up uint64, tags []string) string {
++ if down == 0 && up == 0 {
++ return ""
++ }
++ set := map[string]bool{}
++ for _, tag := range tags {
++ if tag != "" {
++ set[tag] = true
++ }
++ }
++ kept := make([]string, 0, len(set))
++ for tag := range set {
++ kept = append(kept, tag)
++ }
++ sort.Strings(kept)
++ return strings.Join(kept, ",")
++}
++
++var scopeProbes = []string{"in-a", "in-b", "in-c", "in-x", ""}
++
++func enforcedScope(reg *Registry, email string) string {
++ u := reg.lookup(Normalize(email))
++ if u == nil {
++ return ""
++ }
++ s := u.scope.Load()
++ if s == nil {
++ return ""
++ }
++ kept := make([]string, 0, len(*s))
++ for tag := range *s {
++ kept = append(kept, tag)
++ }
++ sort.Strings(kept)
++ return strings.Join(kept, ",")
++}
++
++type oracle struct {
++ floor uint64
++ recs map[string]oracleRecord
++}
++
++func (o *oracle) apply(req node.Request) {
++ if req.ReplaceAll && req.Snapshot < o.floor {
++ return
++ }
++ listed := map[string]bool{}
++ for _, e := range req.Entries {
++ if e.Email == "" || e.Revision == 0 {
++ continue
++ }
++ key := strings.ToLower(e.Email)
++ if req.ReplaceAll {
++ listed[key] = true
++ }
++ st := o.recs[key]
++ if req.ReplaceAll {
++ if st.rev <= req.Snapshot || e.Revision > st.rev {
++ o.recs[key] = oracleRecord{e.Down, e.Up, max(e.Revision, req.Snapshot), oracleScope(e.Down, e.Up, e.InboundTags)}
++ }
++ } else if e.Revision > max(st.rev, o.floor) {
++ o.recs[key] = oracleRecord{e.Down, e.Up, e.Revision, oracleScope(e.Down, e.Up, e.InboundTags)}
++ }
++ }
++ if req.ReplaceAll {
++ for k, r := range o.recs {
++ if !listed[k] && r.rev <= req.Snapshot {
++ delete(o.recs, k)
++ }
++ }
++ o.floor = req.Snapshot
++ for k, r := range o.recs {
++ if r.down == 0 && r.up == 0 && r.rev <= o.floor {
++ delete(o.recs, k)
++ }
++ }
++ }
++}
++
++func (o *oracle) high() uint64 {
++ h := o.floor
++ for _, r := range o.recs {
++ h = max(h, r.rev)
++ }
++ return h
++}
++
++func compareWithOracle(o *oracle, nodeState node.State, core State, reg *Registry) error {
++ if nodeState.Floor != o.floor {
++ return fmt.Errorf("node floor %d, oracle floor %d", nodeState.Floor, o.floor)
++ }
++ if len(nodeState.Entries) != len(o.recs) {
++ return fmt.Errorf("node holds %d records, oracle %d: node=%v oracle=%v", len(nodeState.Entries), len(o.recs), nodeState.Entries, o.recs)
++ }
++ for _, e := range nodeState.Entries {
++ if r, ok := o.recs[e.Email]; !ok || r.down != e.Down || r.up != e.Up || r.scope != strings.Join(e.InboundTags, ",") || max(r.rev, o.floor) != max(e.Revision, nodeState.Floor) {
++ return fmt.Errorf("node record %v, oracle %v", e, o.recs[e.Email])
++ }
++ }
++ if core.Floor != nodeState.Floor {
++ return fmt.Errorf("core floor %d, node floor %d", core.Floor, nodeState.Floor)
++ }
++ if len(core.Entries) != len(nodeState.Entries) {
++ return fmt.Errorf("core holds %v, node holds %v", core.Entries, nodeState.Entries)
++ }
++ for i := range core.Entries {
++ c, n := core.Entries[i], nodeState.Entries[i]
++ if c.Email != n.Email || c.Down != n.Down || c.Up != n.Up || !slices.Equal(c.InboundTags, n.InboundTags) || max(c.Revision, core.Floor) != max(n.Revision, nodeState.Floor) {
++ return fmt.Errorf("core %v, node %v", c, n)
++ }
++ }
++ for _, e := range core.Entries {
++ down, up := reg.Limit(e.Email)
++ if down != e.Down || up != e.Up {
++ return fmt.Errorf("core enforces %d/%d for %s while its record says %d/%d", down, up, e.Email, e.Down, e.Up)
++ }
++ }
++ for key, u := range *reg.users.Load() {
++ r, ok := o.recs[key]
++ if !ok || (r.down == 0 && r.up == 0) || u.slots[Downlink].bps.Load() != r.down || u.slots[Uplink].bps.Load() != r.up {
++ return fmt.Errorf("core user table holds %s with %d/%d, records %v", key, u.slots[Downlink].bps.Load(), u.slots[Uplink].bps.Load(), r)
++ }
++ for _, tag := range scopeProbes {
++ want := r.scope == "" || slices.Contains(strings.Split(r.scope, ","), tag)
++ if u.covers(tag) != want {
++ return fmt.Errorf("core caps %s on %q: %v, the oracle scope is %q", key, tag, u.covers(tag), r.scope)
++ }
++ }
++ }
++ return nil
++}
++
++func randomRequest(rng *rand.Rand, o *oracle) node.Request {
++ emails := []string{"1", "2", "3", "4", "5"}
++ caps := [][2]uint64{{0, 0}, {10, 0}, {20, 5}, {30, 30}}
++ high := o.high()
++ pick := func(lo, hi uint64) uint64 {
++ if hi < lo {
++ return lo
++ }
++ return lo + uint64(rng.Int63n(int64(hi-lo+1)))
++ }
++ var lo uint64
++ if high > 3 {
++ lo = high - 3
++ }
++ req := node.Request{ReplaceAll: rng.Intn(10) < 4}
++ if req.ReplaceAll {
++ var snapshotLow uint64
++ if o.floor > 2 {
++ snapshotLow = o.floor - 2
++ }
++ req.Snapshot = pick(snapshotLow, high+3)
++ }
++ for i := rng.Intn(5); i > 0; i-- {
++ c := caps[rng.Intn(len(caps))]
++ e := node.Entry{Email: emails[rng.Intn(len(emails))], Down: c[0], Up: c[1], Revision: pick(lo, high+3)}
++ if rng.Intn(2) == 0 {
++ for j := rng.Intn(4); j >= 0; j-- {
++ e.InboundTags = append(e.InboundTags, scopeProbes[[]int{0, 1, 2, 4}[rng.Intn(4)]])
++ }
++ }
++ if rng.Intn(25) == 0 {
++ e.Revision = 0
++ }
++ if rng.Intn(40) == 0 {
++ e.Email = ""
++ }
++ req.Entries = append(req.Entries, e)
++ }
++ return req
++}
++
++func checkOutcome(req node.Request, out node.Outcome, o *oracle, reg *Registry) error {
++ var wantRejected []string
++ for _, e := range req.Entries {
++ if e.Email == "" || e.Revision == 0 {
++ wantRejected = append(wantRejected, e.Email)
++ }
++ }
++ if len(out.Rejected) != len(wantRejected) {
++ return fmt.Errorf("rejected %v, want %v", out.Rejected, wantRejected)
++ }
++ if out.HighWater != o.high() {
++ return fmt.Errorf("high water %d, oracle %d", out.HighWater, o.high())
++ }
++ stale := map[string]bool{}
++ for _, s := range out.Stale {
++ stale[strings.ToLower(s)] = true
++ }
++ differs := map[string]bool{}
++ for _, e := range req.Entries {
++ if e.Email == "" || e.Revision == 0 {
++ continue
++ }
++ down, up := reg.Limit(e.Email)
++ if down != e.Down || up != e.Up || enforcedScope(reg, e.Email) != oracleScope(e.Down, e.Up, e.InboundTags) {
++ differs[strings.ToLower(e.Email)] = true
++ }
++ }
++ for k := range differs {
++ if !stale[k] {
++ return fmt.Errorf("entry for %s differs from the enforced cap but is not stale (stale=%v)", k, out.Stale)
++ }
++ }
++ for k := range stale {
++ if !differs[k] {
++ return fmt.Errorf("%s reported stale although every entry for it matches the enforced cap", k)
++ }
++ }
++ return nil
++}
++
++func runDifferential(t *testing.T, seed int64, steps int, path string) {
++ rng := rand.New(rand.NewSource(seed))
++ ctx := context.Background()
++ o := &oracle{recs: map[string]oracleRecord{}}
++ store := node.Open(path)
++ core := &mirroredCore{reg: NewRegistry()}
++ restartCore := func() {
++ core.reg = NewRegistry()
++ if path != "" {
++ if err := core.reg.LoadFile(path); err != nil {
++ t.Fatalf("seed %d: the core could not load the node file: %v", seed, err)
++ }
++ } else {
++ state := store.State()
++ entries := make([]Entry, 0, len(state.Entries))
++ for _, e := range state.Entries {
++ entries = append(entries, Entry{Email: e.Email, Down: e.Down, Up: e.Up, Revision: e.Revision, InboundTags: e.InboundTags})
++ }
++ core.reg.Restore(State{Floor: state.Floor, Entries: entries})
++ }
++ store.MarkDirty()
++ }
++ for step := 0; step < steps; step++ {
++ switch roll := rng.Intn(100); {
++ case roll < 4:
++ restartCore()
++ continue
++ case roll < 6 && path != "":
++ store = node.Open(path)
++ restartCore()
++ continue
++ case roll < 9:
++ core.mode = 0
++ if err := store.Sync(ctx, core.push); err != nil {
++ t.Fatalf("seed %d step %d: sync failed: %v", seed, step, err)
++ }
++ if err := compareWithOracle(o, store.State(), core.reg.Snapshot(), core.reg); err != nil {
++ t.Fatalf("seed %d step %d after sync: %v", seed, step, err)
++ }
++ continue
++ }
++ req := randomRequest(rng, o)
++ core.mode = 0
++ if r := rng.Intn(10); r == 0 {
++ core.mode = 1
++ } else if r == 1 {
++ core.mode = 2
++ }
++ out, err := store.Apply(ctx, req, core.push)
++ o.apply(req)
++ if err != nil {
++ if core.mode == 0 {
++ t.Fatalf("seed %d step %d: unexpected error %v", seed, step, err)
++ }
++ continue
++ }
++ if err := compareWithOracle(o, store.State(), core.reg.Snapshot(), core.reg); err != nil {
++ t.Fatalf("seed %d step %d request %+v: %v", seed, step, req, err)
++ }
++ if err := checkOutcome(req, out, o, core.reg); err != nil {
++ t.Fatalf("seed %d step %d request %+v: %v", seed, step, req, err)
++ }
++ }
++}
++
++func TestTheNodeStoreAndTheCoreRegistryStayIdenticalInMemory(t *testing.T) {
++ for seed := int64(1); seed <= 400; seed++ {
++ runDifferential(t, seed, 400, "")
++ }
++}
++
++func TestTheNodeStoreAndTheCoreRegistryStayIdenticalThroughTheFile(t *testing.T) {
++ for seed := int64(1001); seed <= 1006; seed++ {
++ runDifferential(t, seed, 150, filepath.Join(t.TempDir(), "speed_caps.json"))
++ }
++}
+diff --git a/app/proxyman/speedcap/limiter_test.go b/app/proxyman/speedcap/limiter_test.go
+new file mode 100644
+index 0000000..9951946
+--- /dev/null
++++ b/app/proxyman/speedcap/limiter_test.go
+@@ -0,0 +1,339 @@
++package speedcap
++
++import (
++ "context"
++ "math"
++ "sync"
++ "sync/atomic"
++ "testing"
++ "time"
++
++ "github.com/xtls/xray-core/common/buf"
++)
++
++type countingSink struct {
++ bytes atomic.Int64
++}
++
++func (s *countingSink) WriteMultiBuffer(mb buf.MultiBuffer) error {
++ s.bytes.Add(int64(mb.Len()))
++ buf.ReleaseMulti(mb)
++ return nil
++}
++
++type discardSink struct{}
++
++func (discardSink) WriteMultiBuffer(buf.MultiBuffer) error { return nil }
++
++func chunk(size int32) buf.MultiBuffer {
++ b := buf.New()
++ b.Extend(size)
++ return buf.MultiBuffer{b}
++}
++
++func chunks(count int) buf.MultiBuffer {
++ mb := make(buf.MultiBuffer, 0, count)
++ for range count {
++ mb = append(mb, chunk(buf.Size)...)
++ }
++ return mb
++}
++
++type load struct {
++ cancel context.CancelFunc
++ done sync.WaitGroup
++ sink *countingSink
++}
++
++func startWriters(r *Registry, email string, writers int) (*load, []*Writer) {
++ ctx, cancel := context.WithCancel(context.Background())
++ l := &load{cancel: cancel, sink: &countingSink{}}
++ all := make([]*Writer, 0, writers)
++ for range writers {
++ w := r.NewWriter(ctx, email, "", Downlink, l.sink)
++ all = append(all, w)
++ l.done.Add(1)
++ go func() {
++ defer l.done.Done()
++ for ctx.Err() == nil {
++ _ = w.WriteMultiBuffer(chunk(buf.Size))
++ }
++ }()
++ }
++ return l, all
++}
++
++func (l *load) stop() {
++ l.cancel()
++ l.done.Wait()
++}
++
++func (l *load) mbps(window time.Duration) float64 {
++ before := l.sink.bytes.Load()
++ time.Sleep(window)
++ return float64(l.sink.bytes.Load()-before) * 8 / window.Seconds() / 1e6
++}
++
++func requireWithin(t *testing.T, label string, got, want, tolerance float64) {
++ t.Helper()
++ if math.Abs(got-want) > want*tolerance {
++ t.Fatalf("%s carried %.2f Mbit/s, want %.2f +-%.0f%%", label, got, want, tolerance*100)
++ }
++ t.Logf("%s carried %.2f Mbit/s (cap %.2f)", label, got, want)
++}
++
++func TestCapHoldsForEightWritersOverThirtySeconds(t *testing.T) {
++ if testing.Short() {
++ t.Skip("30 second measurement")
++ }
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 10_000_000, 0, 1)}, false, 0)
++
++ capped, _ := startWriters(r, "alice", 8)
++ defer capped.stop()
++ free, _ := startWriters(r, "bob", 1)
++ defer free.stop()
++
++ start := time.Now()
++ freeBefore := free.sink.bytes.Load()
++ time.Sleep(30 * time.Second)
++ elapsed := time.Since(start).Seconds()
++ cappedMbps := float64(capped.sink.bytes.Load()) * 8 / elapsed / 1e6
++ freeMbps := float64(free.sink.bytes.Load()-freeBefore) * 8 / elapsed / 1e6
++
++ requireWithin(t, "alice over 30 s with 8 writers", cappedMbps, 10, 0.10)
++ if freeMbps < 200 {
++ t.Fatalf("uncapped bob carried only %.2f Mbit/s next to the capped user", freeMbps)
++ }
++ t.Logf("uncapped bob carried %.0f Mbit/s", freeMbps)
++}
++
++func TestLiveWritersFollowCapChangesWithoutReconnecting(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 10_000_000, 0, 1)}, false, 0)
++ l, writers := startWriters(r, "alice", 8)
++ defer l.stop()
++
++ time.Sleep(1500 * time.Millisecond)
++ requireWithin(t, "alice at 10 Mbit/s", l.mbps(5*time.Second), 10, 0.10)
++
++ r.Apply([]Entry{entry("alice", 20_000_000, 0, 2)}, false, 0)
++ time.Sleep(1500 * time.Millisecond)
++ requireWithin(t, "alice raised to 20 Mbit/s", l.mbps(5*time.Second), 20, 0.10)
++
++ r.Apply([]Entry{entry("alice", 5_000_000, 0, 3)}, false, 0)
++ time.Sleep(1500 * time.Millisecond)
++ requireWithin(t, "alice lowered to 5 Mbit/s", l.mbps(5*time.Second), 5, 0.10)
++
++ r.Apply([]Entry{entry("alice", 0, 0, 4)}, false, 0)
++ time.Sleep(500 * time.Millisecond)
++ if got := l.mbps(2 * time.Second); got < 200 {
++ t.Fatalf("alice carried only %.2f Mbit/s after the cap was removed", got)
++ }
++ for _, w := range writers {
++ if w.state.Load() == nil {
++ t.Fatal("a live writer never resolved its cap")
++ }
++ }
++}
++
++func TestLoweredCapDoesNotLeakTheOldBurst(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 400_000_000, 0, 1)}, false, 0)
++ sink := &countingSink{}
++ w := r.NewWriter(context.Background(), "alice", "", Downlink, sink)
++ _ = w.WriteMultiBuffer(chunk(1))
++
++ r.Apply([]Entry{entry("alice", 1_000_000, 0, 2)}, false, 0)
++ ctx, cancel := context.WithCancel(context.Background())
++ var done sync.WaitGroup
++ done.Add(1)
++ go func() {
++ defer done.Done()
++ for ctx.Err() == nil {
++ _ = w.WriteMultiBuffer(chunk(buf.Size))
++ }
++ }()
++ time.Sleep(3 * time.Second)
++ cancel()
++ done.Wait()
++
++ limit := int64(1_000_000/8*(3+1)) + int64(2*buf.Size)
++ if got := sink.bytes.Load(); got > limit {
++ t.Fatalf("after lowering the cap to 1 Mbit/s the writer pushed %d bytes in 3 s, more than %d", got, limit)
++ }
++}
++
++func TestRemovingTheCapWakesSleepingWriters(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 80_000, 0, 1)}, false, 0)
++ w := r.NewWriter(context.Background(), "alice", "", Downlink, discardSink{})
++ _ = w.WriteMultiBuffer(chunks(2))
++
++ returned := make(chan time.Duration, 1)
++ go func() {
++ start := time.Now()
++ _ = w.WriteMultiBuffer(chunks(8))
++ _ = w.WriteMultiBuffer(chunks(8))
++ returned <- time.Since(start)
++ }()
++ time.Sleep(300 * time.Millisecond)
++ r.Apply([]Entry{entry("alice", 0, 0, 2)}, false, 0)
++
++ select {
++ case took := <-returned:
++ if took > 2*time.Second {
++ t.Fatalf("writers slept %s after the cap was removed", took)
++ }
++ case <-time.After(3 * time.Second):
++ t.Fatal("a writer kept sleeping after the cap was removed")
++ }
++}
++
++func TestCancelledConnectionStopsWaiting(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 80_000, 0, 1)}, false, 0)
++ ctx, cancel := context.WithCancel(context.Background())
++ w := r.NewWriter(ctx, "alice", "", Downlink, discardSink{})
++ _ = w.WriteMultiBuffer(chunks(2))
++
++ returned := make(chan struct{})
++ go func() {
++ _ = w.WriteMultiBuffer(chunks(8))
++ close(returned)
++ }()
++ time.Sleep(200 * time.Millisecond)
++ cancel()
++ select {
++ case <-returned:
++ case <-time.After(2 * time.Second):
++ t.Fatal("a writer of a closed connection kept waiting for tokens")
++ }
++}
++
++func TestUplinkReaderIsCappedOnlyWhenAnUploadCapExists(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 10_000_000, 0, 1)}, false, 0)
++ reader := r.NewReader(context.Background(), "alice", "", readerFunc(func() (buf.MultiBuffer, error) {
++ return chunk(buf.Size), nil
++ }))
++ start := time.Now()
++ var total int64
++ for time.Since(start) < 500*time.Millisecond {
++ mb, _ := reader.ReadMultiBuffer()
++ total += int64(mb.Len())
++ buf.ReleaseMulti(mb)
++ }
++ if mbps := float64(total) * 8 / time.Since(start).Seconds() / 1e6; mbps < 200 {
++ t.Fatalf("upload ran at %.2f Mbit/s although only the download is capped", mbps)
++ }
++
++ r.Apply([]Entry{entry("alice", 10_000_000, 4_000_000, 2)}, false, 0)
++ warm := time.Now()
++ for time.Since(warm) < 1500*time.Millisecond {
++ mb, _ := reader.ReadMultiBuffer()
++ buf.ReleaseMulti(mb)
++ }
++ total = 0
++ start = time.Now()
++ for time.Since(start) < 3*time.Second {
++ mb, _ := reader.ReadMultiBuffer()
++ total += int64(mb.Len())
++ buf.ReleaseMulti(mb)
++ }
++ requireWithin(t, "alice upload at 4 Mbit/s", float64(total)*8/time.Since(start).Seconds()/1e6, 4, 0.10)
++}
++
++type readerFunc func() (buf.MultiBuffer, error)
++
++func (f readerFunc) ReadMultiBuffer() (buf.MultiBuffer, error) { return f() }
++
++func TestIdleBucketIsReapedAndTheCapKept(t *testing.T) {
++ r := NewRegistry()
++ now := time.Unix(1_800_000_000, 0)
++ r.now = func() time.Time { return now }
++ r.Apply([]Entry{entry("alice", 10_000_000, 2_000_000, 1)}, false, 0)
++
++ if got := r.Buckets(); got != 0 {
++ t.Fatalf("%d buckets exist before any traffic", got)
++ }
++ down := r.NewWriter(context.Background(), "alice", "", Downlink, discardSink{})
++ _ = down.WriteMultiBuffer(chunk(1000))
++ if got := r.Buckets(); got != 1 {
++ t.Fatalf("%d buckets after the first capped download write, want 1", got)
++ }
++
++ now = now.Add(DefaultIdle - time.Second)
++ if reaped := r.Reap(); reaped != 0 {
++ t.Fatalf("a bucket idle for less than %s was reaped", DefaultIdle)
++ }
++ now = now.Add(time.Second)
++ if reaped := r.Reap(); reaped != 1 {
++ t.Fatalf("reaped %d buckets after %s idle, want 1", reaped, DefaultIdle)
++ }
++ if got := r.Buckets(); got != 0 {
++ t.Fatalf("%d buckets remain after the reap", got)
++ }
++ requireCaps(t, r, "alice", 10_000_000, 2_000_000)
++
++ _ = down.WriteMultiBuffer(chunk(1000))
++ if got := r.Buckets(); got != 1 {
++ t.Fatalf("the bucket was not recreated on the next write, %d exist", got)
++ }
++}
++
++func TestUncappedWritesTakeNoBucketNoLockAndNoAllocation(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 10_000_000, 0, 1)}, false, 0)
++ w := r.NewWriter(context.Background(), "bob", "", Downlink, discardSink{})
++ mb := chunk(buf.Size)
++ _ = w.WriteMultiBuffer(mb)
++
++ r.mu.Lock()
++ finished := make(chan struct{})
++ go func() {
++ for range 1000 {
++ _ = w.WriteMultiBuffer(mb)
++ }
++ close(finished)
++ }()
++ select {
++ case <-finished:
++ case <-time.After(2 * time.Second):
++ r.mu.Unlock()
++ t.Fatal("uncapped writes waited for the registry lock")
++ }
++ r.mu.Unlock()
++
++ if allocs := testing.AllocsPerRun(1000, func() { _ = w.WriteMultiBuffer(mb) }); allocs != 0 {
++ t.Fatalf("an uncapped write allocated %.1f times", allocs)
++ }
++ if got := r.Buckets(); got != 0 {
++ t.Fatalf("uncapped traffic created %d buckets", got)
++ }
++ if r.lookup("bob") != nil {
++ t.Fatal("uncapped traffic created limiter state for bob")
++ }
++}
++
++func BenchmarkUncappedWrite(b *testing.B) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 10_000_000, 0, 1)}, false, 0)
++ w := r.NewWriter(context.Background(), "bob", "", Downlink, discardSink{})
++ mb := chunk(buf.Size)
++ b.ReportAllocs()
++ b.ResetTimer()
++ for range b.N {
++ _ = w.WriteMultiBuffer(mb)
++ }
++}
++
++func BenchmarkUnwrappedWrite(b *testing.B) {
++ var w buf.Writer = discardSink{}
++ mb := chunk(buf.Size)
++ b.ReportAllocs()
++ b.ResetTimer()
++ for range b.N {
++ _ = w.WriteMultiBuffer(mb)
++ }
++}
+diff --git a/app/proxyman/speedcap/link.go b/app/proxyman/speedcap/link.go
+new file mode 100644
+index 0000000..29b4383
+--- /dev/null
++++ b/app/proxyman/speedcap/link.go
+@@ -0,0 +1,107 @@
++package speedcap
++
++import (
++ "context"
++ "sync/atomic"
++
++ "github.com/xtls/xray-core/common"
++ "github.com/xtls/xray-core/common/buf"
++ "github.com/xtls/xray-core/common/protocol"
++)
++
++type resolution struct {
++ generation uint64
++ user *user
++}
++
++type limiter struct {
++ ctx context.Context
++ registry *Registry
++ key string
++ tag string
++ dir Direction
++ state atomic.Pointer[resolution]
++}
++
++func (l *limiter) slot() *slot {
++ generation := l.registry.generation.Load()
++ state := l.state.Load()
++ if state == nil || state.generation != generation {
++ u := l.registry.lookup(l.key)
++ if u != nil && !u.covers(l.tag) {
++ u = nil
++ }
++ state = &resolution{generation: generation, user: u}
++ l.state.Store(state)
++ }
++ if state.user == nil {
++ return nil
++ }
++ return &state.user.slots[l.dir]
++}
++
++func (l *limiter) take(n int32) {
++ if s := l.slot(); s != nil {
++ s.take(l.ctx, int64(n), l.registry)
++ }
++}
++
++func (l *limiter) init(r *Registry, ctx context.Context, email, tag string, dir Direction) {
++ if ctx == nil {
++ ctx = context.Background()
++ }
++ l.ctx, l.registry, l.key, l.tag, l.dir = ctx, r, Normalize(email), tag, dir
++}
++
++type Writer struct {
++ limiter
++ next buf.Writer
++}
++
++func (r *Registry) NewWriter(ctx context.Context, email, tag string, dir Direction, next buf.Writer) *Writer {
++ w := &Writer{next: next}
++ w.init(r, ctx, email, tag, dir)
++ return w
++}
++
++func NewWriter(ctx context.Context, email, tag string, dir Direction, next buf.Writer) *Writer {
++ return Default().NewWriter(ctx, email, tag, dir, next)
++}
++
++func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error {
++ w.take(mb.Len())
++ return w.next.WriteMultiBuffer(mb)
++}
++
++func (w *Writer) Close() error {
++ return common.Close(w.next)
++}
++
++func (w *Writer) Interrupt() {
++ common.Interrupt(w.next)
++}
++
++type Reader struct {
++ limiter
++ next buf.Reader
++}
++
++func (r *Registry) NewReader(ctx context.Context, email, tag string, next buf.Reader) *Reader {
++ reader := &Reader{next: next}
++ reader.init(r, ctx, email, tag, Uplink)
++ return reader
++}
++
++func NewReader(ctx context.Context, email, tag string, next buf.Reader) *Reader {
++ return Default().NewReader(ctx, email, tag, next)
++}
++
++func (r *Reader) ReadMultiBuffer() (buf.MultiBuffer, error) {
++ mb, err := r.next.ReadMultiBuffer()
++ r.take(mb.Len())
++ return mb, err
++}
++
++func CappedUser(user *protocol.MemoryUser, tag string) bool {
++ return user != nil && user.Email != "" && Default().CappedOn(user.Email, tag)
++}
+diff --git a/app/proxyman/speedcap/operation.go b/app/proxyman/speedcap/operation.go
+new file mode 100644
+index 0000000..351a332
+--- /dev/null
++++ b/app/proxyman/speedcap/operation.go
+@@ -0,0 +1,35 @@
++package speedcap
++
++import (
++ "context"
++
++ "github.com/xtls/xray-core/common/errors"
++ "github.com/xtls/xray-core/features/inbound"
++)
++
++func (op *SetUserSpeedsOperation) SpeedEntries() []Entry {
++ entries := make([]Entry, 0, len(op.GetEntries()))
++ for _, entry := range op.GetEntries() {
++ entries = append(entries, Entry{
++ Email: entry.GetEmail(),
++ Down: entry.GetDownBps(),
++ Up: entry.GetUpBps(),
++ Revision: entry.GetRevision(),
++ InboundTags: entry.GetInboundTags(),
++ })
++ }
++ return entries
++}
++
++func (op *SetUserSpeedsOperation) ApplyTo(registry *Registry) Result {
++ return registry.Apply(op.SpeedEntries(), op.GetReplaceAll(), op.GetSnapshotRevision())
++}
++
++func (op *SetUserSpeedsOperation) ApplyInbound(ctx context.Context, _ inbound.Handler) error {
++ result := op.ApplyTo(Default())
++ for _, invalid := range result.Invalid {
++ errors.LogWarning(ctx, "speed cap entry for ", invalid.Email, " skipped: ", invalid.Reason)
++ }
++ errors.LogInfo(ctx, "speed caps: ", result.Applied, " applied, ", result.Removed, " removed, ", result.Ignored, " already current")
++ return nil
++}
+diff --git a/app/proxyman/speedcap/operation_test.go b/app/proxyman/speedcap/operation_test.go
+new file mode 100644
+index 0000000..7a2c18e
+--- /dev/null
++++ b/app/proxyman/speedcap/operation_test.go
+@@ -0,0 +1,93 @@
++package speedcap
++
++import (
++ "context"
++ "encoding/hex"
++ "testing"
++
++ "google.golang.org/protobuf/proto"
++
++ "github.com/xtls/xray-core/common/serial"
++)
++
++const nodeSpeedCapVector = "0a0b0a0231321080ade20420070a170a0231331080dac40918c096b1022081a0958bf8848a030a060a023134200910011889a0958bf8848a03"
++
++func TestTheNodeEncodingDecodesIntoTheOperation(t *testing.T) {
++ raw, err := hex.DecodeString(nodeSpeedCapVector)
++ if err != nil {
++ t.Fatal(err)
++ }
++ instance, err := (&serial.TypedMessage{Type: "xray.app.proxyman.speedcap.SetUserSpeedsOperation", Value: raw}).GetInstance()
++ if err != nil {
++ t.Fatalf("the operation type is not registered: %v", err)
++ }
++ op, ok := instance.(*SetUserSpeedsOperation)
++ if !ok {
++ t.Fatalf("decoded %T", instance)
++ }
++ want := &SetUserSpeedsOperation{ReplaceAll: true, SnapshotRevision: 1_733_000_000_000_009, Entries: []*SpeedEntry{
++ {Email: "12", DownBps: 10_000_000, Revision: 7},
++ {Email: "13", DownBps: 20_000_000, UpBps: 5_000_000, Revision: 1_733_000_000_000_001},
++ {Email: "14", Revision: 9},
++ }}
++ if !proto.Equal(op, want) {
++ t.Fatalf("decoded %v, want %v", op, want)
++ }
++
++ r := NewRegistry()
++ result := op.ApplyTo(r)
++ if result.Applied != 3 || len(result.Invalid) != 0 {
++ t.Fatalf("unexpected result %+v", result)
++ }
++ requireCaps(t, r, "12", 10_000_000, 0)
++ requireCaps(t, r, "13", 20_000_000, 5_000_000)
++ requireCaps(t, r, "14", 0, 0)
++}
++
++func TestOperationAppliesToTheProcessRegistry(t *testing.T) {
++ op := &SetUserSpeedsOperation{Entries: []*SpeedEntry{{Email: "operation-test@node", DownBps: 3_000_000, Revision: 1}}}
++ if err := op.ApplyInbound(context.Background(), nil); err != nil {
++ t.Fatal(err)
++ }
++ if down, _ := Default().Limit("operation-test@node"); down != 3_000_000 {
++ t.Fatalf("the process registry holds %d", down)
++ }
++ if CappedUser(nil, "") {
++ t.Fatal("a missing user reads as capped")
++ }
++}
++
++const nodeScopedSpeedCapVector = "0a1f0a0231321080ade20420072a08766c6573732d696e2a08766d6573732d696e0a0b0a02313318c096b1022008"
++
++func TestTheScopedNodeEncodingDecodesIntoTheOperation(t *testing.T) {
++ raw, err := hex.DecodeString(nodeScopedSpeedCapVector)
++ if err != nil {
++ t.Fatal(err)
++ }
++ instance, err := (&serial.TypedMessage{Type: "xray.app.proxyman.speedcap.SetUserSpeedsOperation", Value: raw}).GetInstance()
++ if err != nil {
++ t.Fatalf("the operation type is not registered: %v", err)
++ }
++ op, ok := instance.(*SetUserSpeedsOperation)
++ if !ok {
++ t.Fatalf("decoded %T", instance)
++ }
++ want := &SetUserSpeedsOperation{Entries: []*SpeedEntry{
++ {Email: "12", DownBps: 10_000_000, Revision: 7, InboundTags: []string{"vless-in", "vmess-in"}},
++ {Email: "13", UpBps: 5_000_000, Revision: 8},
++ }}
++ if !proto.Equal(op, want) {
++ t.Fatalf("decoded %v, want %v", op, want)
++ }
++
++ r := NewRegistry()
++ if result := op.ApplyTo(r); result.Applied != 2 || len(result.Invalid) != 0 {
++ t.Fatalf("unexpected result %+v", result)
++ }
++ if !r.CappedOn("12", "vless-in") || !r.CappedOn("12", "vmess-in") || r.CappedOn("12", "trojan-in") {
++ t.Fatal("the scope of 12 does not follow the decoded inbound tags")
++ }
++ if !r.CappedOn("13", "trojan-in") {
++ t.Fatal("an entry without inbound tags does not cover every inbound")
++ }
++}
+diff --git a/app/proxyman/speedcap/registry.go b/app/proxyman/speedcap/registry.go
+new file mode 100644
+index 0000000..3670d10
+--- /dev/null
++++ b/app/proxyman/speedcap/registry.go
+@@ -0,0 +1,448 @@
++package speedcap
++
++import (
++ "context"
++ "encoding/json"
++ "os"
++ "slices"
++ "sort"
++ "strconv"
++ "strings"
++ "sync"
++ "sync/atomic"
++ "time"
++
++ "github.com/xtls/xray-core/common/errors"
++)
++
++const (
++ FileEnv = "XRAY_SPEED_CAP_FILE"
++ DefaultIdle = 10 * time.Minute
++ reapInterval = time.Minute
++)
++
++type Direction int
++
++const (
++ Downlink Direction = iota
++ Uplink
++)
++
++type Entry struct {
++ Email string `json:"email"`
++ Down uint64 `json:"down_bps"`
++ Up uint64 `json:"up_bps"`
++ Revision uint64 `json:"revision"`
++ InboundTags []string `json:"inbound_tags,omitempty"`
++}
++
++type State struct {
++ Floor uint64 `json:"floor"`
++ Entries []Entry `json:"entries"`
++}
++
++type Invalid struct {
++ Email string
++ Reason string
++}
++
++type Result struct {
++ Applied int
++ Removed int
++ Ignored int
++ Invalid []Invalid
++}
++
++type record struct {
++ down uint64
++ up uint64
++ revision uint64
++ tags string
++}
++
++type scope map[string]struct{}
++
++func canonicalTags(down, up uint64, tags []string) string {
++ if down == 0 && up == 0 {
++ return ""
++ }
++ kept := make([]string, 0, len(tags))
++ for _, tag := range tags {
++ if tag != "" {
++ kept = append(kept, tag)
++ }
++ }
++ sort.Strings(kept)
++ var b strings.Builder
++ for _, tag := range slices.Compact(kept) {
++ b.WriteString(strconv.Itoa(len(tag)))
++ b.WriteByte(':')
++ b.WriteString(tag)
++ }
++ return b.String()
++}
++
++func splitTags(key string) []string {
++ var tags []string
++ for key != "" {
++ colon := strings.IndexByte(key, ':')
++ size, _ := strconv.Atoi(key[:colon])
++ tags = append(tags, key[colon+1:colon+1+size])
++ key = key[colon+1+size:]
++ }
++ return tags
++}
++
++func scopeOf(key string) *scope {
++ if key == "" {
++ return nil
++ }
++ s := make(scope)
++ for _, tag := range splitTags(key) {
++ s[tag] = struct{}{}
++ }
++ return &s
++}
++
++type slot struct {
++ bps atomic.Uint64
++ bucket atomic.Pointer[bucket]
++}
++
++type user struct {
++ slots [2]slot
++ scope atomic.Pointer[scope]
++}
++
++func (u *user) covers(tag string) bool {
++ s := u.scope.Load()
++ if s == nil {
++ return true
++ }
++ _, ok := (*s)[tag]
++ return ok
++}
++
++type table = map[string]*user
++
++type Registry struct {
++ mu sync.Mutex
++ records map[string]record
++ floor uint64
++ users atomic.Pointer[table]
++ generation atomic.Uint64
++ idle time.Duration
++ now func() time.Time
++}
++
++func NewRegistry() *Registry {
++ r := &Registry{records: make(map[string]record), idle: DefaultIdle, now: time.Now}
++ empty := make(table)
++ r.users.Store(&empty)
++ return r
++}
++
++func Normalize(email string) string {
++ return strings.ToLower(email)
++}
++
++func invalidReason(entry Entry) string {
++ switch {
++ case entry.Email == "":
++ return "email must not be empty"
++ case entry.Revision == 0:
++ return "revision must be positive"
++ }
++ return ""
++}
++
++func (r *Registry) Apply(entries []Entry, replaceAll bool, snapshot uint64) Result {
++ r.mu.Lock()
++ defer r.mu.Unlock()
++
++ var result Result
++ if replaceAll && snapshot < r.floor {
++ result.Ignored = len(entries)
++ return result
++ }
++
++ now := r.now()
++ current := *r.users.Load()
++ var next table
++ var listed map[string]struct{}
++ if replaceAll {
++ listed = make(map[string]struct{}, len(entries))
++ }
++ for _, entry := range entries {
++ key := Normalize(entry.Email)
++ if reason := invalidReason(entry); reason != "" {
++ result.Invalid = append(result.Invalid, Invalid{Email: entry.Email, Reason: reason})
++ continue
++ }
++ if listed != nil {
++ listed[key] = struct{}{}
++ }
++ stored, known := r.records[key]
++ if !accepts(stored.revision, entry.Revision, r.floor, replaceAll, snapshot) {
++ result.Ignored++
++ continue
++ }
++ revision := entry.Revision
++ if replaceAll {
++ revision = max(revision, snapshot)
++ }
++ updated := record{down: entry.Down, up: entry.Up, revision: revision, tags: canonicalTags(entry.Down, entry.Up, entry.InboundTags)}
++ if known && stored == updated {
++ result.Ignored++
++ continue
++ }
++ r.records[key] = updated
++ next = r.setLocked(current, next, key, updated, now)
++ result.Applied++
++ }
++
++ if replaceAll {
++ for key, rec := range r.records {
++ if _, ok := listed[key]; ok || rec.revision > snapshot {
++ continue
++ }
++ delete(r.records, key)
++ if rec.down != 0 || rec.up != 0 {
++ next = r.setLocked(current, next, key, record{}, now)
++ result.Removed++
++ }
++ }
++ r.floor = snapshot
++ for key, rec := range r.records {
++ if rec.down == 0 && rec.up == 0 && rec.revision <= snapshot {
++ delete(r.records, key)
++ }
++ }
++ }
++
++ if next != nil {
++ r.users.Store(&next)
++ }
++ if result.Applied > 0 || result.Removed > 0 {
++ r.generation.Add(1)
++ }
++ return result
++}
++
++func accepts(stored, revision, floor uint64, replaceAll bool, snapshot uint64) bool {
++ if replaceAll {
++ return stored <= snapshot || revision > stored
++ }
++ return revision > max(stored, floor)
++}
++
++func (r *Registry) setLocked(current, next table, key string, rec record, now time.Time) table {
++ view := current
++ if next != nil {
++ view = next
++ }
++ u := view[key]
++ if rec.down == 0 && rec.up == 0 {
++ if u == nil {
++ return next
++ }
++ u.slots[Downlink].set(0, now)
++ u.slots[Uplink].set(0, now)
++ next = copyTable(current, next)
++ delete(next, key)
++ return next
++ }
++ if u == nil {
++ u = &user{}
++ u.slots[Downlink].bps.Store(rec.down)
++ u.slots[Uplink].bps.Store(rec.up)
++ u.scope.Store(scopeOf(rec.tags))
++ next = copyTable(current, next)
++ next[key] = u
++ return next
++ }
++ u.scope.Store(scopeOf(rec.tags))
++ u.slots[Downlink].set(rec.down, now)
++ u.slots[Uplink].set(rec.up, now)
++ return next
++}
++
++func copyTable(current, next table) table {
++ if next != nil {
++ return next
++ }
++ next = make(table, len(current)+1)
++ for key, u := range current {
++ next[key] = u
++ }
++ return next
++}
++
++func (s *slot) set(bps uint64, now time.Time) {
++ if s.bps.Swap(bps) == bps {
++ return
++ }
++ b := s.bucket.Load()
++ if b == nil {
++ return
++ }
++ if bps == 0 {
++ s.bucket.Store(nil)
++ }
++ b.setRate(bps, now)
++}
++
++func (r *Registry) lookup(key string) *user {
++ return (*r.users.Load())[key]
++}
++
++func (r *Registry) ensure(s *slot) *bucket {
++ r.mu.Lock()
++ defer r.mu.Unlock()
++ if b := s.bucket.Load(); b != nil {
++ return b
++ }
++ bps := s.bps.Load()
++ if bps == 0 {
++ return nil
++ }
++ b := newBucket(bps, r.now())
++ s.bucket.Store(b)
++ return b
++}
++
++func (s *slot) take(ctx context.Context, n int64, r *Registry) {
++ if n <= 0 || s.bps.Load() == 0 {
++ return
++ }
++ b := s.bucket.Load()
++ if b == nil {
++ if b = r.ensure(s); b == nil {
++ return
++ }
++ }
++ b.wait(ctx, n, r.now)
++}
++
++func (r *Registry) Limit(email string) (down, up uint64) {
++ u := r.lookup(Normalize(email))
++ if u == nil {
++ return 0, 0
++ }
++ return u.slots[Downlink].bps.Load(), u.slots[Uplink].bps.Load()
++}
++
++func (r *Registry) Capped(email string) bool {
++ down, up := r.Limit(email)
++ return down > 0 || up > 0
++}
++
++func (r *Registry) CappedOn(email, tag string) bool {
++ u := r.lookup(Normalize(email))
++ return u != nil && u.covers(tag) && (u.slots[Downlink].bps.Load() > 0 || u.slots[Uplink].bps.Load() > 0)
++}
++
++func (r *Registry) Generation() uint64 {
++ return r.generation.Load()
++}
++
++func (r *Registry) HighWater() uint64 {
++ r.mu.Lock()
++ defer r.mu.Unlock()
++ high := r.floor
++ for _, rec := range r.records {
++ high = max(high, rec.revision)
++ }
++ return high
++}
++
++func (r *Registry) Buckets() int {
++ r.mu.Lock()
++ defer r.mu.Unlock()
++ count := 0
++ for _, u := range *r.users.Load() {
++ for i := range u.slots {
++ if u.slots[i].bucket.Load() != nil {
++ count++
++ }
++ }
++ }
++ return count
++}
++
++func (r *Registry) Reap() int {
++ r.mu.Lock()
++ defer r.mu.Unlock()
++ now := r.now()
++ reaped := 0
++ for _, u := range *r.users.Load() {
++ for i := range u.slots {
++ s := &u.slots[i]
++ if b := s.bucket.Load(); b != nil && b.idleFor(now) >= r.idle {
++ s.bucket.Store(nil)
++ reaped++
++ }
++ }
++ }
++ return reaped
++}
++
++func (r *Registry) Snapshot() State {
++ r.mu.Lock()
++ defer r.mu.Unlock()
++ state := State{Floor: r.floor, Entries: make([]Entry, 0, len(r.records))}
++ for key, rec := range r.records {
++ state.Entries = append(state.Entries, Entry{Email: key, Down: rec.down, Up: rec.up, Revision: rec.revision, InboundTags: splitTags(rec.tags)})
++ }
++ sort.Slice(state.Entries, func(i, j int) bool { return state.Entries[i].Email < state.Entries[j].Email })
++ return state
++}
++
++func (r *Registry) Restore(state State) Result {
++ return r.Apply(state.Entries, true, state.Floor)
++}
++
++func (r *Registry) LoadFile(path string) error {
++ raw, err := os.ReadFile(path)
++ if os.IsNotExist(err) {
++ return nil
++ }
++ if err != nil {
++ return err
++ }
++ var state State
++ if err := json.Unmarshal(raw, &state); err != nil {
++ return err
++ }
++ result := r.Restore(state)
++ if len(result.Invalid) > 0 {
++ return errors.New(len(result.Invalid), " invalid entries were skipped")
++ }
++ return nil
++}
++
++func (r *Registry) reapLoop(interval time.Duration) {
++ ticker := time.NewTicker(interval)
++ defer ticker.Stop()
++ for range ticker.C {
++ r.Reap()
++ }
++}
++
++var (
++ defaultOnce sync.Once
++ defaultRegistry *Registry
++)
++
++func Default() *Registry {
++ defaultOnce.Do(func() {
++ defaultRegistry = NewRegistry()
++ if path := os.Getenv(FileEnv); path != "" {
++ if err := defaultRegistry.LoadFile(path); err != nil {
++ errors.LogError(context.Background(), "speed caps in ", path, " were not loaded: ", err)
++ }
++ }
++ go defaultRegistry.reapLoop(reapInterval)
++ })
++ return defaultRegistry
++}
+diff --git a/app/proxyman/speedcap/registry_test.go b/app/proxyman/speedcap/registry_test.go
+new file mode 100644
+index 0000000..ae788f2
+--- /dev/null
++++ b/app/proxyman/speedcap/registry_test.go
+@@ -0,0 +1,272 @@
++package speedcap
++
++import (
++ "os"
++ "path/filepath"
++ "reflect"
++ "testing"
++)
++
++func capsOf(r *Registry, email string) (uint64, uint64) {
++ return r.Limit(email)
++}
++
++func entry(email string, down, up, revision uint64) Entry {
++ return Entry{Email: email, Down: down, Up: up, Revision: revision}
++}
++
++func requireCaps(t *testing.T, r *Registry, email string, down, up uint64) {
++ t.Helper()
++ gotDown, gotUp := capsOf(r, email)
++ if gotDown != down || gotUp != up {
++ t.Fatalf("%s is capped at down=%d up=%d, want down=%d up=%d", email, gotDown, gotUp, down, up)
++ }
++}
++
++func TestScopedDiffTouchesOnlyListedEmails(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 10_000_000, 0, 1), entry("bob", 20_000_000, 5_000_000, 2)}, false, 0)
++ bobBefore := r.lookup("bob")
++
++ result := r.Apply([]Entry{entry("alice", 15_000_000, 0, 3)}, false, 0)
++ if result.Applied != 1 || result.Ignored != 0 || len(result.Invalid) != 0 {
++ t.Fatalf("unexpected result %+v", result)
++ }
++ requireCaps(t, r, "alice", 15_000_000, 0)
++ requireCaps(t, r, "bob", 20_000_000, 5_000_000)
++ if r.lookup("bob") != bobBefore {
++ t.Fatal("a diff for alice replaced bob's limiter state")
++ }
++}
++
++func TestZeroCapsRemoveTheCapAndKeepATombstone(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("alice", 10_000_000, 0, 4)}, false, 0)
++ r.Apply([]Entry{entry("alice", 0, 0, 5)}, false, 0)
++ requireCaps(t, r, "alice", 0, 0)
++ if r.lookup("alice") != nil {
++ t.Fatal("an uncapped email still holds limiter state")
++ }
++
++ result := r.Apply([]Entry{entry("alice", 10_000_000, 0, 4)}, false, 0)
++ if result.Ignored != 1 || result.Applied != 0 {
++ t.Fatalf("a stale diff below the tombstone was not ignored: %+v", result)
++ }
++ requireCaps(t, r, "alice", 0, 0)
++}
++
++func TestDelayedSnapshotDoesNotOverwriteANewerDiff(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 10_000_000, 0, 7)}, true, 7)
++ r.Apply([]Entry{entry("x", 20_000_000, 0, 8)}, false, 0)
++
++ result := r.Apply([]Entry{entry("x", 10_000_000, 0, 7)}, true, 7)
++ if result.Applied != 0 || result.Removed != 0 {
++ t.Fatalf("the delayed snapshot changed state: %+v", result)
++ }
++ requireCaps(t, r, "x", 20_000_000, 0)
++
++ result = r.Apply([]Entry{entry("x", 5_000_000, 0, 6)}, false, 0)
++ if result.Ignored != 1 {
++ t.Fatalf("a diff at or below the snapshot was not ignored: %+v", result)
++ }
++ requireCaps(t, r, "x", 20_000_000, 0)
++}
++
++func TestDelayedSnapshotKeepsAnUnlistedNewerEmail(t *testing.T) {
++ r := NewRegistry()
++ r.Apply(nil, true, 7)
++ r.Apply([]Entry{entry("x", 20_000_000, 0, 8)}, false, 0)
++ r.Apply(nil, true, 7)
++ requireCaps(t, r, "x", 20_000_000, 0)
++}
++
++func TestDelayedDiffAfterASnapshotThatDroppedTheEmailIsIgnored(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 10_000_000, 0, 3)}, false, 0)
++ result := r.Apply(nil, true, 9)
++ if result.Removed != 1 {
++ t.Fatalf("the snapshot did not remove the unlisted email: %+v", result)
++ }
++ requireCaps(t, r, "x", 0, 0)
++
++ result = r.Apply([]Entry{entry("x", 30_000_000, 0, 9)}, false, 0)
++ if result.Ignored != 1 {
++ t.Fatalf("a diff at the snapshot revision was applied: %+v", result)
++ }
++ requireCaps(t, r, "x", 0, 0)
++}
++
++func TestSnapshotBelowTheFloorIsIgnored(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 10_000_000, 0, 4)}, true, 12)
++ result := r.Apply([]Entry{entry("y", 10_000_000, 0, 5)}, true, 11)
++ if result.Applied != 0 || result.Removed != 0 || result.Ignored != 1 {
++ t.Fatalf("a snapshot below the floor changed state: %+v", result)
++ }
++ requireCaps(t, r, "x", 10_000_000, 0)
++ requireCaps(t, r, "y", 0, 0)
++ if got := r.Snapshot().Floor; got != 12 {
++ t.Fatalf("floor moved to %d", got)
++ }
++}
++
++func TestSnapshotAtRevisionZeroIsAccepted(t *testing.T) {
++ r := NewRegistry()
++ result := r.Apply([]Entry{entry("x", 10_000_000, 0, 1)}, true, 0)
++ if result.Applied != 1 {
++ t.Fatalf("a snapshot at revision 0 listing a revision 1 entry was not applied: %+v", result)
++ }
++ requireCaps(t, r, "x", 10_000_000, 0)
++
++ empty := NewRegistry()
++ result = empty.Apply(nil, true, 0)
++ if result.Applied != 0 || result.Removed != 0 || result.Ignored != 0 || len(result.Invalid) != 0 {
++ t.Fatalf("an empty snapshot at revision 0 was not a quiet no-op: %+v", result)
++ }
++}
++
++func TestSnapshotDiscardsTombstonesAtOrBelowIt(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("a", 10_000_000, 0, 2), entry("a", 0, 0, 3), entry("b", 0, 0, 9)}, false, 0)
++ r.Apply(nil, true, 5)
++ state := r.Snapshot()
++ want := State{Floor: 5, Entries: []Entry{entry("b", 0, 0, 9)}}
++ if !reflect.DeepEqual(state, want) {
++ t.Fatalf("state after the snapshot is %+v, want %+v", state, want)
++ }
++}
++
++func TestInvalidEntriesAreReportedAndTheRestApplied(t *testing.T) {
++ r := NewRegistry()
++ result := r.Apply([]Entry{entry("", 10_000_000, 0, 3), entry("y", 10_000_000, 0, 0), entry("z", 10_000_000, 0, 4)}, false, 0)
++ if result.Applied != 1 || len(result.Invalid) != 2 {
++ t.Fatalf("unexpected result %+v", result)
++ }
++ requireCaps(t, r, "z", 10_000_000, 0)
++ requireCaps(t, r, "y", 0, 0)
++}
++
++func TestDuplicateDiffIsAQuietNoOp(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 10_000_000, 0, 3)}, false, 0)
++ generation := r.Generation()
++ result := r.Apply([]Entry{entry("x", 10_000_000, 0, 3)}, false, 0)
++ if result.Ignored != 1 || result.Applied != 0 || len(result.Invalid) != 0 {
++ t.Fatalf("a duplicate diff was not a quiet no-op: %+v", result)
++ }
++ if r.Generation() != generation {
++ t.Fatal("a no-op bumped the generation")
++ }
++}
++
++func TestEmailsAreMatchedCaseInsensitively(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("Alice@Example", 10_000_000, 0, 1)}, false, 0)
++ requireCaps(t, r, "alice@example", 10_000_000, 0)
++}
++
++func TestStateFileRestoresCapsFloorAndTombstones(t *testing.T) {
++ path := filepath.Join(t.TempDir(), "speedcaps.json")
++ raw := `{"version":1,"floor":4,"high":9,"entries":[{"email":"a","down_bps":10000000,"up_bps":2000000,"revision":6},{"email":"b","down_bps":0,"up_bps":0,"revision":9}]}`
++ if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
++ t.Fatal(err)
++ }
++
++ r := NewRegistry()
++ if err := r.LoadFile(path); err != nil {
++ t.Fatal(err)
++ }
++ requireCaps(t, r, "a", 10_000_000, 2_000_000)
++ want := State{Floor: 4, Entries: []Entry{entry("a", 10_000_000, 2_000_000, 6), entry("b", 0, 0, 9)}}
++ if got := r.Snapshot(); !reflect.DeepEqual(got, want) {
++ t.Fatalf("restored state %+v, want %+v", got, want)
++ }
++
++ result := r.Apply([]Entry{entry("b", 10_000_000, 0, 8)}, false, 0)
++ if result.Ignored != 1 {
++ t.Fatalf("a diff below the restored tombstone was applied: %+v", result)
++ }
++}
++
++func TestStateFileThatDoesNotExistIsEmpty(t *testing.T) {
++ r := NewRegistry()
++ if err := r.LoadFile(filepath.Join(t.TempDir(), "absent.json")); err != nil {
++ t.Fatal(err)
++ }
++ if len(r.Snapshot().Entries) != 0 {
++ t.Fatal("caps appeared from a missing file")
++ }
++}
++
++func TestCorruptStateFileIsAnError(t *testing.T) {
++ path := filepath.Join(t.TempDir(), "speedcaps.json")
++ if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
++ t.Fatal(err)
++ }
++ if err := NewRegistry().LoadFile(path); err == nil {
++ t.Fatal("a corrupt cap file loaded without an error")
++ }
++}
++
++func TestSnapshotRestoresStateAfterThePanelCounterWentBack(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 10_000_000, 0, 50), entry("y", 30_000_000, 0, 57)}, true, 40)
++ result := r.Apply([]Entry{entry("x", 99_000_000, 0, 1)}, false, 0)
++ if result.Ignored != 1 {
++ t.Fatalf("a diff below the stored revisions was applied: %+v", result)
++ }
++ if got := r.HighWater(); got != 57 {
++ t.Fatalf("high water %d, want 57", got)
++ }
++
++ result = r.Apply([]Entry{entry("x", 5_000_000, 0, 2), entry("z", 7_000_000, 0, 3)}, true, 57)
++ if result.Applied != 2 || result.Removed != 1 {
++ t.Fatalf("the snapshot at the high water did not rebuild the state: %+v", result)
++ }
++ requireCaps(t, r, "x", 5_000_000, 0)
++ requireCaps(t, r, "z", 7_000_000, 0)
++ requireCaps(t, r, "y", 0, 0)
++ want := State{Floor: 57, Entries: []Entry{entry("x", 5_000_000, 0, 57), entry("z", 7_000_000, 0, 57)}}
++ if got := r.Snapshot(); !reflect.DeepEqual(got, want) {
++ t.Fatalf("state %+v, want %+v", got, want)
++ }
++}
++
++func TestSnapshotWinsOverAnOlderStoredRevisionEvenWithAnOldEntryRevision(t *testing.T) {
++ const base = 1_000
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 20_000_000, 0, base+10)}, false, 0)
++ r.Apply([]Entry{entry("x", 10_000_000, 0, base-5)}, true, base+10)
++ requireCaps(t, r, "x", 10_000_000, 0)
++ if got := r.Snapshot().Entries[0].Revision; got != base+10 {
++ t.Fatalf("stored revision %d, want the snapshot revision %d", got, base+10)
++ }
++}
++
++func TestIdenticalSnapshotIsAQuietNoOp(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 10_000_000, 0, 3)}, true, 9)
++ generation := r.Generation()
++ result := r.Apply([]Entry{entry("x", 10_000_000, 0, 3)}, true, 9)
++ if result.Applied != 0 || result.Removed != 0 || result.Ignored != 1 {
++ t.Fatalf("a repeated snapshot changed state: %+v", result)
++ }
++ if r.Generation() != generation {
++ t.Fatal("a repeated snapshot bumped the generation")
++ }
++}
++
++func TestInvalidSnapshotEntriesCountAsNotListed(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{entry("x", 10_000_000, 0, 3), entry("y", 20_000_000, 0, 4)}, false, 0)
++ result := r.Apply([]Entry{entry("x", 10_000_000, 0, 0), entry("y", 20_000_000, 0, 4)}, true, 9)
++ if len(result.Invalid) != 1 || result.Removed != 1 {
++ t.Fatalf("unexpected result %+v", result)
++ }
++ requireCaps(t, r, "x", 0, 0)
++ requireCaps(t, r, "y", 20_000_000, 0)
++ if got := r.Snapshot(); len(got.Entries) != 1 || got.Entries[0].Email != "y" || got.Floor != 9 {
++ t.Fatalf("an invalid entry kept an old record: %+v", got)
++ }
++}
+diff --git a/app/proxyman/speedcap/scope_test.go b/app/proxyman/speedcap/scope_test.go
+new file mode 100644
+index 0000000..47bdfc5
+--- /dev/null
++++ b/app/proxyman/speedcap/scope_test.go
+@@ -0,0 +1,180 @@
++package speedcap
++
++import (
++ "context"
++ "os"
++ "path/filepath"
++ "reflect"
++ "sync"
++ "testing"
++ "time"
++
++ "github.com/xtls/xray-core/common/buf"
++)
++
++func scoped(email string, down, revision uint64, tags ...string) Entry {
++ return Entry{Email: email, Down: down, Revision: revision, InboundTags: tags}
++}
++
++type taggedLoad struct {
++ cancel context.CancelFunc
++ done sync.WaitGroup
++ sinks map[string]*countingSink
++}
++
++func startTaggedWriters(r *Registry, email string, tags ...string) (*taggedLoad, []*Writer) {
++ ctx, cancel := context.WithCancel(context.Background())
++ l := &taggedLoad{cancel: cancel, sinks: make(map[string]*countingSink)}
++ var writers []*Writer
++ for _, tag := range tags {
++ sink := &countingSink{}
++ l.sinks[tag] = sink
++ for range 4 {
++ w := r.NewWriter(ctx, email, tag, Downlink, sink)
++ writers = append(writers, w)
++ l.done.Add(1)
++ go func() {
++ defer l.done.Done()
++ for ctx.Err() == nil {
++ _ = w.WriteMultiBuffer(chunk(buf.Size))
++ }
++ }()
++ }
++ }
++ return l, writers
++}
++
++func (l *taggedLoad) stop() {
++ l.cancel()
++ l.done.Wait()
++}
++
++func (l *taggedLoad) mbps(window time.Duration) map[string]float64 {
++ before := make(map[string]int64, len(l.sinks))
++ for tag, sink := range l.sinks {
++ before[tag] = sink.bytes.Load()
++ }
++ start := time.Now()
++ time.Sleep(window)
++ elapsed := time.Since(start).Seconds()
++ rates := make(map[string]float64, len(l.sinks))
++ for tag, sink := range l.sinks {
++ rates[tag] = float64(sink.bytes.Load()-before[tag]) * 8 / elapsed / 1e6
++ }
++ return rates
++}
++
++func TestAScopedCapCoversOnlyItsInboundsThroughOneBucket(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{scoped("alice", 8_000_000, 1, "in-a", "in-c")}, false, 0)
++ l, _ := startTaggedWriters(r, "alice", "in-a", "in-b", "in-c")
++ defer l.stop()
++
++ time.Sleep(1500 * time.Millisecond)
++ rates := l.mbps(5 * time.Second)
++ requireWithin(t, "alice on in-a and in-c together", rates["in-a"]+rates["in-c"], 8, 0.10)
++ if rates["in-b"] < 200 {
++ t.Fatalf("alice on the unlisted in-b carried only %.2f Mbit/s", rates["in-b"])
++ }
++ if r.CappedOn("alice", "in-b") || !r.CappedOn("alice", "in-a") {
++ t.Fatal("CappedOn does not follow the scope")
++ }
++}
++
++func TestAScopeChangeReachesLiveWritersWithoutNewOnes(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{scoped("alice", 8_000_000, 1, "in-a")}, false, 0)
++ l, writers := startTaggedWriters(r, "alice", "in-a", "in-b")
++ defer l.stop()
++
++ time.Sleep(1500 * time.Millisecond)
++ rates := l.mbps(4 * time.Second)
++ requireWithin(t, "alice on in-a", rates["in-a"], 8, 0.10)
++ if rates["in-b"] < 200 {
++ t.Fatalf("alice on in-b carried only %.2f Mbit/s before the scope moved", rates["in-b"])
++ }
++
++ r.Apply([]Entry{scoped("alice", 8_000_000, 2, "in-b")}, false, 0)
++ time.Sleep(1500 * time.Millisecond)
++ rates = l.mbps(4 * time.Second)
++ requireWithin(t, "alice on in-b after the scope moved", rates["in-b"], 8, 0.10)
++ if rates["in-a"] < 200 {
++ t.Fatalf("alice on in-a carried only %.2f Mbit/s after the scope left it", rates["in-a"])
++ }
++
++ r.Apply([]Entry{scoped("alice", 8_000_000, 3)}, false, 0)
++ time.Sleep(1500 * time.Millisecond)
++ rates = l.mbps(4 * time.Second)
++ requireWithin(t, "alice on every inbound under an unscoped cap", rates["in-a"]+rates["in-b"], 8, 0.10)
++ for _, w := range writers {
++ if w.state.Load() == nil {
++ t.Fatal("a live writer never resolved its cap")
++ }
++ }
++}
++
++func TestScopeIsPartOfTheRecordAndTheFile(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{scoped("x", 10_000_000, 3, "in-b", "in-a", "in-b")}, false, 0)
++ want := State{Floor: 0, Entries: []Entry{scoped("x", 10_000_000, 3, "in-a", "in-b")}}
++ if got := r.Snapshot(); !reflect.DeepEqual(got, want) {
++ t.Fatalf("snapshot %+v, want %+v", got, want)
++ }
++ result := r.Apply([]Entry{scoped("x", 10_000_000, 4, "in-a")}, false, 0)
++ if result.Applied != 1 {
++ t.Fatalf("a scope change was not applied: %+v", result)
++ }
++
++ path := filepath.Join(t.TempDir(), "speed_caps.json")
++ raw := `{"floor":2,"entries":[{"email":"y","down_bps":5000000,"up_bps":0,"revision":7,"inbound_tags":["in-z"]}]}`
++ if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
++ t.Fatal(err)
++ }
++ loaded := NewRegistry()
++ if err := loaded.LoadFile(path); err != nil {
++ t.Fatal(err)
++ }
++ if !loaded.CappedOn("y", "in-z") || loaded.CappedOn("y", "in-other") {
++ t.Fatal("the scope in the file was not loaded")
++ }
++}
++
++func TestTheCanonicalScopeIsExactForEveryTag(t *testing.T) {
++ r := NewRegistry()
++ r.Apply([]Entry{
++ scoped("joined", 1_000_000, 1, "in-a\x00in-b", "2:in-c"),
++ scoped("blank", 1_000_000, 1, ""),
++ scoped("cleared", 0, 1, "in-a"),
++ }, false, 0)
++ for _, c := range []struct {
++ email, tag string
++ capped bool
++ }{
++ {"joined", "in-a\x00in-b", true},
++ {"joined", "2:in-c", true},
++ {"joined", "in-a", false},
++ {"joined", "in-b", false},
++ {"joined", "in-c", false},
++ {"blank", "", true},
++ {"blank", "in-any", true},
++ {"cleared", "in-a", false},
++ } {
++ if got := r.CappedOn(c.email, c.tag); got != c.capped {
++ t.Errorf("CappedOn(%q, %q) = %v, want %v", c.email, c.tag, got, c.capped)
++ }
++ }
++ want := State{Entries: []Entry{
++ {Email: "blank", Down: 1_000_000, Revision: 1},
++ {Email: "cleared", Revision: 1},
++ scoped("joined", 1_000_000, 1, "2:in-c", "in-a\x00in-b"),
++ }}
++ if got := r.Snapshot(); !reflect.DeepEqual(got, want) {
++ t.Fatalf("snapshot %+v, want %+v", got, want)
++ }
++ if result := r.Apply([]Entry{scoped("cleared", 0, 2, "in-b")}, false, 0); result.Applied != 1 {
++ t.Fatalf("a newer tombstone was not applied: %+v", result)
++ }
++ if result := r.Apply([]Entry{{Email: "cleared", Revision: 2}}, false, 0); result.Ignored != 1 {
++ t.Fatalf("an equal tombstone with other tags was not a no-op: %+v", result)
++ }
++}
+diff --git a/proxy/proxy.go b/proxy/proxy.go
+index dbd81d6..bbc7ae1 100644
+--- a/proxy/proxy.go
++++ b/proxy/proxy.go
+@@ -17,6 +17,7 @@ import (
+
+ "github.com/pires/go-proxyproto"
+ "github.com/xtls/xray-core/app/dispatcher"
++ "github.com/xtls/xray-core/app/proxyman/speedcap"
+ "github.com/xtls/xray-core/common/buf"
+ "github.com/xtls/xray-core/common/errors"
+ "github.com/xtls/xray-core/common/net"
+@@ -743,7 +744,7 @@ func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net
+ for {
+ inbound := session.InboundFromContext(ctx)
+ outbounds := session.OutboundsFromContext(ctx)
+- var splice = inbound.CanSpliceCopy == 1
++ var splice = inbound.CanSpliceCopy == 1 && !speedcap.CappedUser(inbound.User, inbound.Tag)
+ for _, ob := range outbounds {
+ if ob.CanSpliceCopy != 1 {
+ splice = false
+@@ -757,7 +758,7 @@ func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net
+ if inTimer != nil {
+ inTimer.SetTimeout(24 * time.Hour)
+ }
+- w, err := tc.ReadFrom(readerConn)
++ w, capped, err := spliceUntilCapped(tc, readerConn, inbound)
+ if readCounter != nil {
+ readCounter.Add(w) // outbound stats
+ }
+@@ -767,6 +768,10 @@ func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net
+ if statWriter != nil {
+ statWriter.Counter.Add(w) // user stats
+ }
++ if capped {
++ errors.LogDebug(ctx, "CopyRawConn splice stopped for a speed capped user")
++ continue
++ }
+ if err != nil && errors.Cause(err) != io.EOF {
+ return err
+ }
+@@ -791,6 +796,22 @@ func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net
+ }
+ }
+
++const spliceChunk = 256 << 10
++
++func spliceUntilCapped(tc *net.TCPConn, readerConn net.Conn, inbound *session.Inbound) (int64, bool, error) {
++ var total int64
++ for {
++ w, err := tc.ReadFrom(&io.LimitedReader{R: readerConn, N: spliceChunk})
++ total += w
++ if err != nil || w < spliceChunk {
++ return total, false, err
++ }
++ if speedcap.CappedUser(inbound.User, inbound.Tag) {
++ return total, true, nil
++ }
++ }
++}
++
+ func readV(ctx context.Context, reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, readCounter stats.Counter) error {
+ errors.LogDebug(ctx, "CopyRawConn (maybe) readv")
+ if err := buf.Copy(reader, writer, buf.UpdateActivity(timer), buf.AddToStatCounter(readCounter)); err != nil {
+diff --git a/testing/scenarios/speedcap_test.go b/testing/scenarios/speedcap_test.go
+new file mode 100644
+index 0000000..60f3963
+--- /dev/null
++++ b/testing/scenarios/speedcap_test.go
+@@ -0,0 +1,818 @@
++package scenarios
++
++import (
++ "bytes"
++ "context"
++ stdtls "crypto/tls"
++ "crypto/x509"
++ "encoding/json"
++ "fmt"
++ "math"
++ gonet "net"
++ "net/netip"
++ "os"
++ "os/exec"
++ "path/filepath"
++ "runtime"
++ "strings"
++ "sync"
++ "sync/atomic"
++ "testing"
++ "time"
++
++ "github.com/xtls/xray-core/app/commander"
++ "github.com/xtls/xray-core/app/log"
++ "github.com/xtls/xray-core/app/policy"
++ "github.com/xtls/xray-core/app/proxyman"
++ "github.com/xtls/xray-core/app/proxyman/command"
++ "github.com/xtls/xray-core/app/router"
++ "github.com/xtls/xray-core/app/stats"
++ clog "github.com/xtls/xray-core/common/log"
++ "github.com/xtls/xray-core/common/net"
++ "github.com/xtls/xray-core/common/protocol"
++ "github.com/xtls/xray-core/common/protocol/tls/cert"
++ "github.com/xtls/xray-core/common/serial"
++ "github.com/xtls/xray-core/common/uuid"
++ core "github.com/xtls/xray-core/core"
++ "github.com/xtls/xray-core/proxy/dokodemo"
++ "github.com/xtls/xray-core/proxy/freedom"
++ "github.com/xtls/xray-core/proxy/vless"
++ vlessinbound "github.com/xtls/xray-core/proxy/vless/inbound"
++ vlessoutbound "github.com/xtls/xray-core/proxy/vless/outbound"
++ "github.com/xtls/xray-core/proxy/vmess"
++ vmessinbound "github.com/xtls/xray-core/proxy/vmess/inbound"
++ vmessoutbound "github.com/xtls/xray-core/proxy/vmess/outbound"
++ "github.com/xtls/xray-core/testing/servers/tcp"
++ "github.com/xtls/xray-core/transport/internet"
++ transtcp "github.com/xtls/xray-core/transport/internet/tcp"
++ "github.com/xtls/xray-core/transport/internet/tls"
++ "google.golang.org/grpc"
++ "google.golang.org/grpc/credentials/insecure"
++ "google.golang.org/protobuf/encoding/protowire"
++ "google.golang.org/protobuf/proto"
++)
++
++const speedCapOperationType = "xray.app.proxyman.speedcap.SetUserSpeedsOperation"
++
++type speedEntry struct {
++ email string
++ down uint64
++ up uint64
++ revision uint64
++ tags []string
++}
++
++func speedCapOperation(replaceAll bool, snapshot uint64, entries ...speedEntry) *serial.TypedMessage {
++ var value []byte
++ for _, e := range entries {
++ var item []byte
++ item = protowire.AppendTag(item, 1, protowire.BytesType)
++ item = protowire.AppendString(item, e.email)
++ if e.down != 0 {
++ item = protowire.AppendTag(item, 2, protowire.VarintType)
++ item = protowire.AppendVarint(item, e.down)
++ }
++ if e.up != 0 {
++ item = protowire.AppendTag(item, 3, protowire.VarintType)
++ item = protowire.AppendVarint(item, e.up)
++ }
++ if e.revision != 0 {
++ item = protowire.AppendTag(item, 4, protowire.VarintType)
++ item = protowire.AppendVarint(item, e.revision)
++ }
++ for _, tag := range e.tags {
++ item = protowire.AppendTag(item, 5, protowire.BytesType)
++ item = protowire.AppendString(item, tag)
++ }
++ value = protowire.AppendTag(value, 1, protowire.BytesType)
++ value = protowire.AppendBytes(value, item)
++ }
++ if replaceAll {
++ value = protowire.AppendTag(value, 2, protowire.VarintType)
++ value = protowire.AppendVarint(value, 1)
++ }
++ if snapshot != 0 {
++ value = protowire.AppendTag(value, 3, protowire.VarintType)
++ value = protowire.AppendVarint(value, snapshot)
++ }
++ return &serial.TypedMessage{Type: speedCapOperationType, Value: value}
++}
++
++func setUserSpeeds(t *testing.T, apiPort net.Port, tag string, operation *serial.TypedMessage) {
++ t.Helper()
++ conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", apiPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
++ if err != nil {
++ t.Fatal(err)
++ }
++ defer conn.Close()
++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
++ defer cancel()
++ if _, err := command.NewHandlerServiceClient(conn).AlterInbound(ctx, &command.AlterInboundRequest{Tag: tag, Operation: operation}); err != nil {
++ t.Fatalf("the core refused SetUserSpeeds: %v", err)
++ }
++}
++
++type streamServer struct {
++ listener net.Listener
++ tls *stdtls.Config
++ mu sync.Mutex
++ conns map[net.Conn]struct{}
++}
++
++type streamTarget struct {
++ ip gonet.IP
++ port net.Port
++}
++
++func targetHostAddress(t *testing.T) gonet.IP {
++ t.Helper()
++ ifaces, err := gonet.Interfaces()
++ if err != nil {
++ t.Fatal(err)
++ }
++ for _, iface := range ifaces {
++ if iface.Flags&gonet.FlagUp == 0 || iface.Flags&gonet.FlagLoopback != 0 {
++ continue
++ }
++ addrs, err := iface.Addrs()
++ if err != nil {
++ continue
++ }
++ for _, addr := range addrs {
++ ipNet, ok := addr.(*gonet.IPNet)
++ if !ok || ipNet.IP.To4() == nil {
++ continue
++ }
++ if ip, ok := netip.AddrFromSlice(ipNet.IP.To4()); ok && ip.IsPrivate() {
++ return ipNet.IP.To4()
++ }
++ }
++ }
++ t.Skip("this host has no non-loopback private IPv4 address for the download target")
++ return nil
++}
++
++func startStreamServer(t *testing.T, tlsConfig *stdtls.Config) streamTarget {
++ t.Helper()
++ ip := targetHostAddress(t)
++ listener, err := net.Listen("tcp4", gonet.JoinHostPort(ip.String(), "0"))
++ if err != nil {
++ t.Fatal(err)
++ }
++ s := &streamServer{listener: listener, tls: tlsConfig, conns: make(map[net.Conn]struct{})}
++ go s.serve()
++ t.Cleanup(s.close)
++ return streamTarget{ip: ip, port: net.Port(listener.Addr().(*net.TCPAddr).Port)}
++}
++
++func allowingFreedom(target streamTarget) *core.OutboundHandlerConfig {
++ allow := &freedom.PrivateTargetRule{Ip: []*router.GeoIP{{Cidr: []*router.CIDR{{Ip: target.ip, Prefix: 32}}}}}
++ return &core.OutboundHandlerConfig{ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.PrivateTargetRule{allow}})}
++}
++
++func (s *streamServer) serve() {
++ for {
++ conn, err := s.listener.Accept()
++ if err != nil {
++ return
++ }
++ if s.tls != nil {
++ conn = stdtls.Server(conn, s.tls)
++ }
++ s.mu.Lock()
++ s.conns[conn] = struct{}{}
++ s.mu.Unlock()
++ go s.stream(conn)
++ }
++}
++
++func (s *streamServer) stream(conn net.Conn) {
++ defer func() {
++ s.mu.Lock()
++ delete(s.conns, conn)
++ s.mu.Unlock()
++ conn.Close()
++ }()
++ payload := bytes.Repeat([]byte{'s'}, 32*1024)
++ for written := 0; ; written++ {
++ chunk := payload
++ if s.tls != nil && written < 64 {
++ chunk = payload[:4096]
++ time.Sleep(time.Millisecond)
++ }
++ if _, err := conn.Write(chunk); err != nil {
++ return
++ }
++ }
++}
++
++func (s *streamServer) close() {
++ s.listener.Close()
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ for conn := range s.conns {
++ conn.Close()
++ }
++}
++
++type downloads struct {
++ received atomic.Int64
++ ended atomic.Int32
++ conns []net.Conn
++}
++
++func startDownloads(t *testing.T, port net.Port, count int, trust *x509.CertPool) *downloads {
++ t.Helper()
++ d := &downloads{}
++ for range count {
++ conn, err := (&net.Dialer{Timeout: 5 * time.Second}).Dial("tcp4", fmt.Sprintf("127.0.0.1:%d", port))
++ if err != nil {
++ t.Fatal(err)
++ }
++ if trust != nil {
++ conn = stdtls.Client(conn, &stdtls.Config{RootCAs: trust, MinVersion: stdtls.VersionTLS13, ServerName: "localhost"})
++ }
++ if _, err := conn.Write([]byte("GET /stream\n")); err != nil {
++ t.Fatal(err)
++ }
++ d.conns = append(d.conns, conn)
++ go func() {
++ buffer := make([]byte, 64*1024)
++ for {
++ n, err := conn.Read(buffer)
++ d.received.Add(int64(n))
++ if err != nil {
++ d.ended.Add(1)
++ return
++ }
++ }
++ }()
++ }
++ t.Cleanup(d.close)
++ return d
++}
++
++func (d *downloads) close() {
++ for _, conn := range d.conns {
++ conn.Close()
++ }
++}
++
++func (d *downloads) waitFor(t *testing.T, want int64) {
++ t.Helper()
++ deadline := time.Now().Add(20 * time.Second)
++ for d.received.Load() < want {
++ if time.Now().After(deadline) {
++ t.Fatalf("downloads carried only %d of %d bytes", d.received.Load(), want)
++ }
++ time.Sleep(20 * time.Millisecond)
++ }
++}
++
++func (d *downloads) mbps(window time.Duration) float64 {
++ before := d.received.Load()
++ start := time.Now()
++ time.Sleep(window)
++ return float64(d.received.Load()-before) * 8 / time.Since(start).Seconds() / 1e6
++}
++
++func requireRate(t *testing.T, label string, got, want float64) {
++ t.Helper()
++ if math.Abs(got-want) > want*0.10 {
++ t.Fatalf("%s carried %.2f Mbit/s, want %.2f +-10%%", label, got, want)
++ }
++ t.Logf("%s carried %.2f Mbit/s (cap %.2f)", label, got, want)
++}
++
++type lockedBuffer struct {
++ mu sync.Mutex
++ b bytes.Buffer
++}
++
++func (l *lockedBuffer) Write(p []byte) (int, error) {
++ l.mu.Lock()
++ defer l.mu.Unlock()
++ return l.b.Write(p)
++}
++
++func (l *lockedBuffer) count(marker string) int {
++ l.mu.Lock()
++ defer l.mu.Unlock()
++ return strings.Count(l.b.String(), marker)
++}
++
++func (l *lockedBuffer) waitFor(marker string, within time.Duration) bool {
++ deadline := time.Now().Add(within)
++ for l.count(marker) == 0 {
++ if time.Now().After(deadline) {
++ return false
++ }
++ time.Sleep(50 * time.Millisecond)
++ }
++ return true
++}
++
++var (
++ speedCapBuildOnce sync.Once
++ speedCapBuilt string
++ speedCapBuildErr error
++)
++
++func speedCapBinary(t *testing.T) string {
++ t.Helper()
++ if path := os.Getenv("XRAY_SPEEDCAP_BINARY"); path != "" {
++ return path
++ }
++ speedCapBuildOnce.Do(func() {
++ genTestBinaryPath()
++ speedCapBuilt = testBinaryPath + "-speedcap"
++ cmd := exec.Command("go", "build", "-trimpath", "-ldflags", "-s -w -buildid=", "-o", speedCapBuilt, GetSourcePath())
++ cmd.Env = append(os.Environ(), "GOFLAGS=", "CGO_ENABLED=0")
++ if output, err := cmd.CombinedOutput(); err != nil {
++ speedCapBuildErr = fmt.Errorf("building the xray binary the scenarios run: %v: %s", err, output)
++ }
++ })
++ if speedCapBuildErr != nil {
++ t.Fatal(speedCapBuildErr)
++ }
++ return speedCapBuilt
++}
++
++func startCapturedXray(t *testing.T, config *core.Config, env ...string) *lockedBuffer {
++ t.Helper()
++ binary := speedCapBinary(t)
++ raw, err := proto.Marshal(withDefaultApps(config))
++ if err != nil {
++ t.Fatal(err)
++ }
++ output := &lockedBuffer{}
++ cmd := exec.Command(binary, "-config=stdin:", "-format=pb")
++ cmd.Stdin = bytes.NewReader(raw)
++ cmd.Stdout = output
++ cmd.Stderr = output
++ cmd.Env = append(os.Environ(), env...)
++ if err := cmd.Start(); err != nil {
++ t.Fatal(err)
++ }
++ t.Cleanup(func() {
++ cmd.Process.Kill()
++ cmd.Wait()
++ if t.Failed() {
++ t.Logf("xray output:\n%s", output.b.String())
++ }
++ })
++ return output
++}
++
++func waitListening(t *testing.T, ports ...net.Port) {
++ t.Helper()
++ for _, port := range ports {
++ deadline := time.Now().Add(10 * time.Second)
++ for {
++ conn, err := (&net.Dialer{Timeout: 200 * time.Millisecond}).Dial("tcp4", fmt.Sprintf("127.0.0.1:%d", port))
++ if err == nil {
++ conn.Close()
++ break
++ }
++ if time.Now().After(deadline) {
++ t.Fatalf("port %d never started listening", port)
++ }
++ time.Sleep(50 * time.Millisecond)
++ }
++ }
++}
++
++func speedCapPolicy() *serial.TypedMessage {
++ return serial.ToTypedMessage(&policy.Config{
++ Level: map[uint32]*policy.Policy{
++ 0: {
++ Timeout: &policy.Policy_Timeout{
++ UplinkOnly: &policy.Second{Value: 0},
++ DownlinkOnly: &policy.Second{Value: 0},
++ },
++ Stats: &policy.Policy_Stats{UserUplink: true, UserDownlink: true},
++ },
++ },
++ })
++}
++
++func apiApps(apiTag string) []*serial.TypedMessage {
++ return []*serial.TypedMessage{
++ serial.ToTypedMessage(&commander.Config{
++ Tag: apiTag,
++ Service: []*serial.TypedMessage{serial.ToTypedMessage(&command.Config{})},
++ }),
++ serial.ToTypedMessage(&stats.Config{}),
++ serial.ToTypedMessage(&router.Config{
++ Rule: []*router.RoutingRule{{
++ InboundTag: []string{apiTag},
++ TargetTag: &router.RoutingRule_Tag{Tag: apiTag},
++ }},
++ }),
++ speedCapPolicy(),
++ }
++}
++
++func apiInbound(apiTag string, apiPort net.Port) *core.InboundHandlerConfig {
++ return &core.InboundHandlerConfig{
++ Tag: apiTag,
++ ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
++ PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(apiPort)}},
++ Listen: net.NewIPOrDomain(net.LocalHostIP),
++ }),
++ ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
++ Address: net.NewIPOrDomain(net.LocalHostIP),
++ Port: uint32(apiPort),
++ Networks: []net.Network{net.Network_TCP},
++ }),
++ }
++}
++
++func listenOn(port net.Port, stream *internet.StreamConfig) *serial.TypedMessage {
++ return serial.ToTypedMessage(&proxyman.ReceiverConfig{
++ PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(port)}},
++ Listen: net.NewIPOrDomain(net.LocalHostIP),
++ StreamSettings: stream,
++ })
++}
++
++type speedClientRoute struct {
++ port net.Port
++ target streamTarget
++ outbound *core.OutboundHandlerConfig
++}
++
++func speedCapClient(routes ...speedClientRoute) *core.Config {
++ config := &core.Config{App: []*serial.TypedMessage{speedCapPolicy()}}
++ rules := make([]*router.RoutingRule, 0, len(routes))
++ for i, route := range routes {
++ inTag := fmt.Sprintf("in-%d", i)
++ outTag := fmt.Sprintf("out-%d", i)
++ config.Inbound = append(config.Inbound, &core.InboundHandlerConfig{
++ Tag: inTag,
++ ReceiverSettings: listenOn(route.port, nil),
++ ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
++ Address: net.NewIPOrDomain(net.IPAddress(route.target.ip)),
++ Port: uint32(route.target.port),
++ Networks: []net.Network{net.Network_TCP},
++ }),
++ })
++ route.outbound.Tag = outTag
++ config.Outbound = append(config.Outbound, route.outbound)
++ rules = append(rules, &router.RoutingRule{InboundTag: []string{inTag}, TargetTag: &router.RoutingRule_Tag{Tag: outTag}})
++ }
++ config.App = append(config.App, serial.ToTypedMessage(&router.Config{Rule: rules}))
++ return config
++}
++
++func vlessOut(serverPort net.Port, id string, flow string, stream *internet.StreamConfig) *core.OutboundHandlerConfig {
++ outbound := &core.OutboundHandlerConfig{
++ ProxySettings: serial.ToTypedMessage(&vlessoutbound.Config{
++ Vnext: &protocol.ServerEndpoint{
++ Address: net.NewIPOrDomain(net.LocalHostIP),
++ Port: uint32(serverPort),
++ User: &protocol.User{Account: serial.ToTypedMessage(&vless.Account{Id: id, Flow: flow, Encryption: "none"})},
++ },
++ }),
++ }
++ if stream != nil {
++ outbound.SenderSettings = serial.ToTypedMessage(&proxyman.SenderConfig{StreamSettings: stream})
++ }
++ return outbound
++}
++
++func vmessOut(serverPort net.Port, id string) *core.OutboundHandlerConfig {
++ return &core.OutboundHandlerConfig{
++ ProxySettings: serial.ToTypedMessage(&vmessoutbound.Config{
++ Receiver: &protocol.ServerEndpoint{
++ Address: net.NewIPOrDomain(net.LocalHostIP),
++ Port: uint32(serverPort),
++ User: &protocol.User{Account: serial.ToTypedMessage(&vmess.Account{
++ Id: id,
++ SecuritySettings: &protocol.SecurityConfig{Type: protocol.SecurityType_AES128_GCM},
++ })},
++ },
++ }),
++ }
++}
++
++type plainSpeedCapLab struct {
++ apiPort net.Port
++ target streamTarget
++ aliceVL net.Port
++ aliceVM net.Port
++ bobVL net.Port
++ serverOut *lockedBuffer
++}
++
++func startPlainSpeedCapLab(t *testing.T, env ...string) *plainSpeedCapLab {
++ t.Helper()
++ target := startStreamServer(t, nil)
++ aliceVLESS := uuid.New()
++ aliceVMess := uuid.New()
++ bobVLESS := uuid.New()
++
++ lab := &plainSpeedCapLab{apiPort: tcp.PickPort(), target: target}
++ vlessPort := tcp.PickPort()
++ vmessPort := tcp.PickPort()
++ server := &core.Config{
++ App: apiApps("api"),
++ Inbound: []*core.InboundHandlerConfig{
++ apiInbound("api", lab.apiPort),
++ {
++ Tag: "vless",
++ ReceiverSettings: listenOn(vlessPort, nil),
++ ProxySettings: serial.ToTypedMessage(&vlessinbound.Config{
++ Decryption: "none",
++ Clients: []*protocol.User{
++ {Email: "alice", Account: serial.ToTypedMessage(&vless.Account{Id: aliceVLESS.String()})},
++ {Email: "bob", Account: serial.ToTypedMessage(&vless.Account{Id: bobVLESS.String()})},
++ },
++ }),
++ },
++ {
++ Tag: "vmess",
++ ReceiverSettings: listenOn(vmessPort, nil),
++ ProxySettings: serial.ToTypedMessage(&vmessinbound.Config{
++ User: []*protocol.User{{Email: "alice", Account: serial.ToTypedMessage(&vmess.Account{Id: aliceVMess.String()})}},
++ }),
++ },
++ },
++ Outbound: []*core.OutboundHandlerConfig{allowingFreedom(target)},
++ }
++ lab.serverOut = startCapturedXray(t, server, env...)
++
++ lab.aliceVL, lab.aliceVM, lab.bobVL = tcp.PickPort(), tcp.PickPort(), tcp.PickPort()
++ startCapturedXray(t, speedCapClient(
++ speedClientRoute{port: lab.aliceVL, target: target, outbound: vlessOut(vlessPort, aliceVLESS.String(), "", nil)},
++ speedClientRoute{port: lab.aliceVM, target: target, outbound: vmessOut(vmessPort, aliceVMess.String())},
++ speedClientRoute{port: lab.bobVL, target: target, outbound: vlessOut(vlessPort, bobVLESS.String(), "", nil)},
++ ))
++ waitListening(t, lab.apiPort, vlessPort, vmessPort, lab.aliceVL, lab.aliceVM, lab.bobVL)
++ return lab
++}
++
++func TestSpeedCapHoldsAcrossProtocolsAndParallelConnections(t *testing.T) {
++ lab := startPlainSpeedCapLab(t)
++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: "alice", down: 10_000_000, revision: 1}))
++
++ alice := startDownloads(t, lab.aliceVL, 4, nil)
++ aliceVMess := startDownloads(t, lab.aliceVM, 4, nil)
++ bob := startDownloads(t, lab.bobVL, 2, nil)
++ alice.waitFor(t, 1)
++ aliceVMess.waitFor(t, 1)
++ bob.waitFor(t, 1)
++
++ start := time.Now()
++ aliceBefore := alice.received.Load() + aliceVMess.received.Load()
++ bobBefore := bob.received.Load()
++ time.Sleep(30 * time.Second)
++ elapsed := time.Since(start).Seconds()
++ aliceMbps := float64(alice.received.Load()+aliceVMess.received.Load()-aliceBefore) * 8 / elapsed / 1e6
++ bobMbps := float64(bob.received.Load()-bobBefore) * 8 / elapsed / 1e6
++
++ requireRate(t, "alice over 30 s on 4 VLESS and 4 VMess connections", aliceMbps, 10)
++ if bobMbps < 100 {
++ t.Fatalf("uncapped bob on the same inbound and source address carried only %.2f Mbit/s", bobMbps)
++ }
++ t.Logf("uncapped bob carried %.0f Mbit/s", bobMbps)
++}
++
++func TestSpeedCapChangesReachLiveConnections(t *testing.T) {
++ lab := startPlainSpeedCapLab(t)
++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: "alice", down: 10_000_000, revision: 1}))
++ alice := startDownloads(t, lab.aliceVL, 8, nil)
++ alice.waitFor(t, 1)
++ time.Sleep(2 * time.Second)
++ requireRate(t, "alice at 10 Mbit/s", alice.mbps(6*time.Second), 10)
++
++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: "alice", down: 20_000_000, revision: 2}))
++ time.Sleep(2 * time.Second)
++ requireRate(t, "alice raised to 20 Mbit/s on the same connections", alice.mbps(6*time.Second), 20)
++
++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: "alice", down: 5_000_000, revision: 1}))
++ time.Sleep(2 * time.Second)
++ requireRate(t, "alice after a stale revision 1 diff", alice.mbps(4*time.Second), 20)
++
++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: "alice", revision: 3}))
++ time.Sleep(time.Second)
++ if got := alice.mbps(3 * time.Second); got < 100 {
++ t.Fatalf("alice carried only %.2f Mbit/s after the cap was removed", got)
++ }
++ if ended := alice.ended.Load(); ended != 0 {
++ t.Fatalf("%d of alice's connections were closed by the cap changes", ended)
++ }
++}
++
++func TestSpeedCapFileIsInForceBeforeTheFirstConnection(t *testing.T) {
++ state, err := json.Marshal(map[string]any{
++ "floor": 0,
++ "entries": []map[string]any{{"email": "alice", "down_bps": 10_000_000, "up_bps": 0, "revision": 1}},
++ })
++ if err != nil {
++ t.Fatal(err)
++ }
++ path := filepath.Join(t.TempDir(), "speedcaps.json")
++ if err := os.WriteFile(path, state, 0o600); err != nil {
++ t.Fatal(err)
++ }
++ lab := startPlainSpeedCapLab(t, "XRAY_SPEED_CAP_FILE="+path)
++
++ alice := startDownloads(t, lab.aliceVL, 8, nil)
++ start := time.Now()
++ time.Sleep(5 * time.Second)
++ firstWindow := float64(alice.received.Load()) * 8 / time.Since(start).Seconds() / 1e6
++ if firstWindow > 10*6.0/5.0*1.10 {
++ t.Fatalf("alice carried %.2f Mbit/s in the first 5 s after the core started, the persisted 10 Mbit/s cap was not in force", firstWindow)
++ }
++ requireRate(t, "alice in the next window", alice.mbps(5*time.Second), 10)
++}
++
++type visionLab struct {
++ apiPort net.Port
++ alice net.Port
++ bob net.Port
++ trust *x509.CertPool
++ serverOut *lockedBuffer
++}
++
++func startVisionLab(t *testing.T) *visionLab {
++ t.Helper()
++ targetCert, _ := cert.MustGenerate(nil, cert.CommonName("localhost"), cert.DNSNames("localhost"))
++ certPEM, keyPEM := targetCert.ToPEM()
++ pair, err := stdtls.X509KeyPair(certPEM, keyPEM)
++ if err != nil {
++ t.Fatal(err)
++ }
++ trust := x509.NewCertPool()
++ if !trust.AppendCertsFromPEM(certPEM) {
++ t.Fatal("the target certificate did not parse")
++ }
++ target := startStreamServer(t, &stdtls.Config{Certificates: []stdtls.Certificate{pair}, MinVersion: stdtls.VersionTLS13})
++
++ proxyCert, proxyHash := cert.MustGenerate(nil, cert.CommonName("localhost"))
++ aliceID, bobID := uuid.New(), uuid.New()
++ lab := &visionLab{apiPort: tcp.PickPort(), trust: trust}
++ serverPort := tcp.PickPort()
++ server := &core.Config{
++ App: append(apiApps("api"), serial.ToTypedMessage(&log.Config{
++ ErrorLogLevel: clog.Severity_Debug,
++ ErrorLogType: log.LogType_Console,
++ })),
++ Inbound: []*core.InboundHandlerConfig{
++ apiInbound("api", lab.apiPort),
++ {
++ Tag: "vision",
++ ReceiverSettings: listenOn(serverPort, &internet.StreamConfig{
++ ProtocolName: "tcp",
++ SecurityType: serial.GetMessageType(&tls.Config{}),
++ SecuritySettings: []*serial.TypedMessage{
++ serial.ToTypedMessage(&tls.Config{Certificate: []*tls.Certificate{tls.ParseCertificate(proxyCert)}}),
++ },
++ }),
++ ProxySettings: serial.ToTypedMessage(&vlessinbound.Config{
++ Decryption: "none",
++ Clients: []*protocol.User{
++ {Email: "alice", Account: serial.ToTypedMessage(&vless.Account{Id: aliceID.String(), Flow: vless.XRV})},
++ {Email: "bob", Account: serial.ToTypedMessage(&vless.Account{Id: bobID.String(), Flow: vless.XRV})},
++ },
++ }),
++ },
++ },
++ Outbound: []*core.OutboundHandlerConfig{allowingFreedom(target)},
++ }
++ lab.serverOut = startCapturedXray(t, server)
++
++ clientStream := func() *internet.StreamConfig {
++ return &internet.StreamConfig{
++ ProtocolName: "tcp",
++ TransportSettings: []*internet.TransportConfig{{ProtocolName: "tcp", Settings: serial.ToTypedMessage(&transtcp.Config{})}},
++ SecurityType: serial.GetMessageType(&tls.Config{}),
++ SecuritySettings: []*serial.TypedMessage{serial.ToTypedMessage(&tls.Config{PinnedPeerCertSha256: [][]byte{proxyHash[:]}})},
++ }
++ }
++ lab.alice, lab.bob = tcp.PickPort(), tcp.PickPort()
++ startCapturedXray(t, speedCapClient(
++ speedClientRoute{port: lab.alice, target: target, outbound: vlessOut(serverPort, aliceID.String(), vless.XRV, clientStream())},
++ speedClientRoute{port: lab.bob, target: target, outbound: vlessOut(serverPort, bobID.String(), vless.XRV, clientStream())},
++ ))
++ waitListening(t, lab.apiPort, serverPort, lab.alice, lab.bob)
++ return lab
++}
++
++const spliceMarker = "CopyRawConn splice"
++
++func TestSpeedCapRefusesVisionSpliceForCappedUsers(t *testing.T) {
++ if runtime.GOOS != "linux" {
++ t.Skip("Vision splice exists only on Linux")
++ }
++ lab := startVisionLab(t)
++
++ bob := startDownloads(t, lab.bob, 2, lab.trust)
++ bob.waitFor(t, 4<<20)
++ if !lab.serverOut.waitFor(spliceMarker, 15*time.Second) {
++ t.Fatal("an uncapped Vision user was not spliced, the test cannot tell a refused splice from a missing one")
++ }
++ bob.close()
++ time.Sleep(500 * time.Millisecond)
++
++ setUserSpeeds(t, lab.apiPort, "vision", speedCapOperation(false, 0, speedEntry{email: "alice", down: 10_000_000, revision: 1}))
++ splicesBefore := lab.serverOut.count(spliceMarker)
++ alice := startDownloads(t, lab.alice, 4, lab.trust)
++ alice.waitFor(t, 1)
++ time.Sleep(2 * time.Second)
++ requireRate(t, "capped alice over Vision", alice.mbps(8*time.Second), 10)
++ if spliced := lab.serverOut.count(spliceMarker) - splicesBefore; spliced != 0 {
++ t.Fatalf("a capped Vision user was spliced %d times", spliced)
++ }
++}
++
++func TestSpeedCapStopsASpliceThatIsAlreadyRunning(t *testing.T) {
++ if runtime.GOOS != "linux" {
++ t.Skip("Vision splice exists only on Linux")
++ }
++ lab := startVisionLab(t)
++
++ bob := startDownloads(t, lab.bob, 4, lab.trust)
++ bob.waitFor(t, 8<<20)
++ if !lab.serverOut.waitFor(spliceMarker, 15*time.Second) {
++ t.Fatal("the uncapped Vision downloads were not spliced")
++ }
++ if got := bob.mbps(2 * time.Second); got < 100 {
++ t.Fatalf("spliced downloads carried only %.2f Mbit/s before the cap", got)
++ }
++
++ setUserSpeeds(t, lab.apiPort, "vision", speedCapOperation(false, 0, speedEntry{email: "bob", down: 10_000_000, revision: 1}))
++ time.Sleep(3 * time.Second)
++ requireRate(t, "bob capped while spliced", bob.mbps(8*time.Second), 10)
++ if ended := bob.ended.Load(); ended != 0 {
++ t.Fatalf("%d spliced connections were closed when the cap arrived", ended)
++ }
++}
++
++func TestSpeedCapScopeDecidesTheVisionSplice(t *testing.T) {
++ if runtime.GOOS != "linux" {
++ t.Skip("Vision splice exists only on Linux")
++ }
++ lab := startVisionLab(t)
++ setUserSpeeds(t, lab.apiPort, "vision", speedCapOperation(false, 0,
++ speedEntry{email: "bob", down: 10_000_000, revision: 1, tags: []string{"elsewhere"}},
++ speedEntry{email: "alice", down: 10_000_000, revision: 1, tags: []string{"vision"}},
++ ))
++
++ bob := startDownloads(t, lab.bob, 2, lab.trust)
++ bob.waitFor(t, 4<<20)
++ if !lab.serverOut.waitFor(spliceMarker, 15*time.Second) {
++ t.Fatal("a Vision user capped only on another inbound was not spliced")
++ }
++ if got := bob.mbps(2 * time.Second); got < 100 {
++ t.Fatalf("bob, capped only on another inbound, carried %.2f Mbit/s over Vision", got)
++ }
++ bob.close()
++ time.Sleep(500 * time.Millisecond)
++
++ splicesBefore := lab.serverOut.count(spliceMarker)
++ alice := startDownloads(t, lab.alice, 4, lab.trust)
++ alice.waitFor(t, 1)
++ time.Sleep(2 * time.Second)
++ requireRate(t, "alice capped on the Vision inbound", alice.mbps(8*time.Second), 10)
++ if spliced := lab.serverOut.count(spliceMarker) - splicesBefore; spliced != 0 {
++ t.Fatalf("a Vision user capped on this inbound was spliced %d times", spliced)
++ }
++}
++
++func TestSpeedCapScopeCapsOneInboundAndLeavesTheOther(t *testing.T) {
++ lab := startPlainSpeedCapLab(t)
++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: "alice", down: 10_000_000, revision: 1, tags: []string{"vless"}}))
++
++ overVLESS := startDownloads(t, lab.aliceVL, 4, nil)
++ overVMess := startDownloads(t, lab.aliceVM, 4, nil)
++ overVLESS.waitFor(t, 1)
++ overVMess.waitFor(t, 1)
++ time.Sleep(2 * time.Second)
++ vless, vmess := concurrentMbps(overVLESS, overVMess, 8*time.Second)
++ requireRate(t, "alice on the capped vless inbound", vless, 10)
++ if vmess < 100 {
++ t.Fatalf("alice on the uncapped vmess inbound carried only %.2f Mbit/s", vmess)
++ }
++ t.Logf("alice on the uncapped vmess inbound carried %.0f Mbit/s", vmess)
++
++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: "alice", down: 10_000_000, revision: 2, tags: []string{"vmess"}}))
++ time.Sleep(2 * time.Second)
++ vless, vmess = concurrentMbps(overVLESS, overVMess, 8*time.Second)
++ requireRate(t, "alice on vmess after the scope moved", vmess, 10)
++ if vless < 100 {
++ t.Fatalf("alice on vless carried only %.2f Mbit/s after the scope left it", vless)
++ }
++ if ended := overVLESS.ended.Load() + overVMess.ended.Load(); ended != 0 {
++ t.Fatalf("%d of alice's connections were closed when the scope moved", ended)
++ }
++}
++
++func concurrentMbps(a, b *downloads, window time.Duration) (float64, float64) {
++ beforeA, beforeB := a.received.Load(), b.received.Load()
++ start := time.Now()
++ time.Sleep(window)
++ elapsed := time.Since(start).Seconds()
++ return float64(a.received.Load()-beforeA) * 8 / elapsed / 1e6, float64(b.received.Load()-beforeB) * 8 / elapsed / 1e6
++}
+diff --git a/testing/speedcapnode/store.go b/testing/speedcapnode/store.go
+new file mode 100644
+index 0000000..9034e13
+--- /dev/null
++++ b/testing/speedcapnode/store.go
+@@ -0,0 +1,461 @@
++package speedcapnode
++
++import (
++ "context"
++ "encoding/json"
++ "errors"
++ "fmt"
++ "log"
++ "os"
++ "path/filepath"
++ "slices"
++ "sort"
++ "strconv"
++ "strings"
++ "sync"
++ "sync/atomic"
++ "time"
++)
++
++const stateVersion = 1
++
++var ErrPersist = errors.New("speed caps could not be persisted")
++
++type Entry struct {
++ Email string `json:"email"`
++ Down uint64 `json:"down_bps"`
++ Up uint64 `json:"up_bps"`
++ Revision uint64 `json:"revision"`
++ InboundTags []string `json:"inbound_tags,omitempty"`
++}
++
++type State struct {
++ Version int `json:"version"`
++ Floor uint64 `json:"floor"`
++ Entries []Entry `json:"entries"`
++}
++
++type Request struct {
++ Entries []Entry
++ ReplaceAll bool
++ Snapshot uint64
++}
++
++type Change struct {
++ Entries []Entry
++ ReplaceAll bool
++ Snapshot uint64
++}
++
++type Rejection struct {
++ Email string
++ Reason string
++}
++
++type Outcome struct {
++ Rejected []Rejection
++ Stale []string
++ HighWater uint64
++ Changed int
++ Pushed bool
++}
++
++type PushFunc func(context.Context, Change) error
++
++type record struct {
++ down uint64
++ up uint64
++ revision uint64
++ tags string
++}
++
++func canonicalTags(down, up uint64, tags []string) string {
++ if down == 0 && up == 0 {
++ return ""
++ }
++ kept := make([]string, 0, len(tags))
++ for _, tag := range tags {
++ if tag != "" {
++ kept = append(kept, tag)
++ }
++ }
++ sort.Strings(kept)
++ var b strings.Builder
++ for _, tag := range slices.Compact(kept) {
++ b.WriteString(strconv.Itoa(len(tag)))
++ b.WriteByte(':')
++ b.WriteString(tag)
++ }
++ return b.String()
++}
++
++func splitTags(key string) []string {
++ var tags []string
++ for key != "" {
++ colon := strings.IndexByte(key, ':')
++ size, _ := strconv.Atoi(key[:colon])
++ tags = append(tags, key[colon+1:colon+1+size])
++ key = key[colon+1+size:]
++ }
++ return tags
++}
++
++type Store struct {
++ mu sync.Mutex
++ path string
++ floor uint64
++ records map[string]record
++ failed bool
++ synced uint64
++ epoch atomic.Uint64
++ leaseGen uint64
++ leaseArmed bool
++}
++
++func Normalize(email string) string {
++ return strings.ToLower(email)
++}
++
++func NewMemoryStore() *Store {
++ s := &Store{records: make(map[string]record)}
++ s.epoch.Store(1)
++ return s
++}
++
++func (s *Store) dirtyLocked() bool {
++ return s.failed || s.epoch.Load() != s.synced
++}
++
++func (s *Store) pushLocked(ctx context.Context, change Change, push PushFunc) error {
++ epoch := s.epoch.Load()
++ if err := push(ctx, change); err != nil {
++ s.failed = true
++ return err
++ }
++ s.failed = false
++ s.synced = epoch
++ return nil
++}
++
++func Open(path string) *Store {
++ s := NewMemoryStore()
++ s.path = path
++ if path == "" {
++ return s
++ }
++ raw, err := os.ReadFile(path)
++ switch {
++ case errors.Is(err, os.ErrNotExist):
++ return s
++ case err != nil:
++ log.Printf("speed caps: %s could not be read, starting without caps until the panel resends them: %v", path, err)
++ return s
++ }
++ var state State
++ if err := json.Unmarshal(raw, &state); err != nil {
++ kept := fmt.Sprintf("%s.corrupt-%d", path, time.Now().Unix())
++ if renameErr := os.Rename(path, kept); renameErr != nil {
++ log.Printf("speed caps: %s is corrupt (%v) and could not be moved aside: %v", path, err, renameErr)
++ } else {
++ log.Printf("speed caps: %s is corrupt (%v), kept as %s, starting without caps until the panel resends them", path, err, kept)
++ }
++ return s
++ }
++ s.floor = state.Floor
++ for _, entry := range state.Entries {
++ key := Normalize(entry.Email)
++ if key == "" || entry.Revision == 0 {
++ continue
++ }
++ s.records[key] = record{down: entry.Down, up: entry.Up, revision: entry.Revision, tags: canonicalTags(entry.Down, entry.Up, entry.InboundTags)}
++ }
++ return s
++}
++
++func (s *Store) Path() string {
++ if s == nil {
++ return ""
++ }
++ return s.path
++}
++
++func invalidReason(entry Entry) string {
++ switch {
++ case entry.Email == "":
++ return "email must not be empty"
++ case entry.Revision == 0:
++ return "revision must be positive"
++ }
++ return ""
++}
++
++func accepts(stored, revision, floor uint64, replaceAll bool, snapshot uint64) bool {
++ if replaceAll {
++ return stored <= snapshot || revision > stored
++ }
++ return revision > max(stored, floor)
++}
++
++type plan struct {
++ floor uint64
++ records map[string]record
++ changed []string
++ rejected []Rejection
++ stale []string
++}
++
++func (s *Store) plan(request Request) plan {
++ p := s.planChanges(request)
++ p.markStale(request.Entries)
++ return p
++}
++
++func (s *Store) planChanges(request Request) plan {
++ p := plan{floor: s.floor, records: make(map[string]record, len(s.records))}
++ for key, rec := range s.records {
++ p.records[key] = rec
++ }
++ ignored := request.ReplaceAll && request.Snapshot < s.floor
++
++ touched := make(map[string]struct{})
++ listed := make(map[string]struct{})
++ for _, entry := range request.Entries {
++ key := Normalize(entry.Email)
++ if reason := invalidReason(entry); reason != "" {
++ p.rejected = append(p.rejected, Rejection{Email: entry.Email, Reason: reason})
++ continue
++ }
++ if request.ReplaceAll {
++ listed[key] = struct{}{}
++ }
++ stored, known := p.records[key]
++ if ignored || !accepts(stored.revision, entry.Revision, p.floor, request.ReplaceAll, request.Snapshot) {
++ continue
++ }
++ revision := entry.Revision
++ if request.ReplaceAll {
++ revision = max(revision, request.Snapshot)
++ }
++ updated := record{down: entry.Down, up: entry.Up, revision: revision, tags: canonicalTags(entry.Down, entry.Up, entry.InboundTags)}
++ if known && stored == updated {
++ continue
++ }
++ p.records[key] = updated
++ touched[key] = struct{}{}
++ }
++
++ if ignored {
++ return p
++ }
++
++ if request.ReplaceAll {
++ for key, rec := range p.records {
++ if _, ok := listed[key]; ok || rec.revision > request.Snapshot {
++ continue
++ }
++ delete(p.records, key)
++ touched[key] = struct{}{}
++ }
++ if request.Snapshot != p.floor {
++ touched[""] = struct{}{}
++ }
++ p.floor = request.Snapshot
++ for key, rec := range p.records {
++ if rec.down == 0 && rec.up == 0 && rec.revision <= p.floor {
++ delete(p.records, key)
++ }
++ }
++ }
++
++ for key := range touched {
++ p.changed = append(p.changed, key)
++ }
++ sort.Strings(p.changed)
++ return p
++}
++
++func (p *plan) markStale(entries []Entry) {
++ reported := make(map[string]struct{})
++ for _, entry := range entries {
++ if invalidReason(entry) != "" {
++ continue
++ }
++ key := Normalize(entry.Email)
++ if _, seen := reported[key]; seen {
++ continue
++ }
++ if current := p.records[key]; current.down != entry.Down || current.up != entry.Up || current.tags != canonicalTags(entry.Down, entry.Up, entry.InboundTags) {
++ reported[key] = struct{}{}
++ p.stale = append(p.stale, entry.Email)
++ }
++ }
++}
++
++func stateOf(floor uint64, records map[string]record) State {
++ state := State{Version: stateVersion, Floor: floor, Entries: make([]Entry, 0, len(records))}
++ for key, rec := range records {
++ state.Entries = append(state.Entries, Entry{Email: key, Down: rec.down, Up: rec.up, Revision: rec.revision, InboundTags: splitTags(rec.tags)})
++ }
++ sort.Slice(state.Entries, func(i, j int) bool { return state.Entries[i].Email < state.Entries[j].Email })
++ return state
++}
++
++func (s *Store) persist(state State) error {
++ if s.path == "" {
++ return nil
++ }
++ raw, err := json.Marshal(state)
++ if err != nil {
++ return err
++ }
++ dir := filepath.Dir(s.path)
++ if err := os.MkdirAll(dir, 0o700); err != nil {
++ return err
++ }
++ tmp, err := os.CreateTemp(dir, filepath.Base(s.path)+".tmp-*")
++ if err != nil {
++ return err
++ }
++ tmpName := tmp.Name()
++ defer os.Remove(tmpName)
++ if _, err := tmp.Write(raw); err != nil {
++ tmp.Close()
++ return err
++ }
++ if err := tmp.Chmod(0o600); err != nil {
++ tmp.Close()
++ return err
++ }
++ if err := tmp.Sync(); err != nil {
++ tmp.Close()
++ return err
++ }
++ if err := tmp.Close(); err != nil {
++ return err
++ }
++ if err := os.Rename(tmpName, s.path); err != nil {
++ return err
++ }
++ if d, err := os.Open(dir); err == nil {
++ _ = d.Sync()
++ _ = d.Close()
++ }
++ return nil
++}
++
++func highWater(floor uint64, records map[string]record) uint64 {
++ high := floor
++ for _, rec := range records {
++ high = max(high, rec.revision)
++ }
++ return high
++}
++
++func (s *Store) mirrorLocked() Change {
++ state := stateOf(s.floor, s.records)
++ return Change{Entries: state.Entries, ReplaceAll: true, Snapshot: s.floor}
++}
++
++func (s *Store) diffLocked(keys []string) Change {
++ change := Change{Entries: make([]Entry, 0, len(keys))}
++ for _, key := range keys {
++ rec := s.records[key]
++ change.Entries = append(change.Entries, Entry{Email: key, Down: rec.down, Up: rec.up, Revision: rec.revision, InboundTags: splitTags(rec.tags)})
++ }
++ return change
++}
++
++func (s *Store) Apply(ctx context.Context, request Request, push PushFunc) (Outcome, error) {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ if request.ReplaceAll {
++ s.leaseArmed = false
++ }
++ return s.applyLocked(ctx, request, push)
++}
++
++func (s *Store) applyLocked(ctx context.Context, request Request, push PushFunc) (Outcome, error) {
++ p := s.plan(request)
++ outcome := Outcome{Rejected: p.rejected, Stale: p.stale, Changed: len(p.changed)}
++ if len(p.changed) > 0 {
++ if err := s.persist(stateOf(p.floor, p.records)); err != nil {
++ return outcome, fmt.Errorf("%w: %v", ErrPersist, err)
++ }
++ s.floor, s.records = p.floor, p.records
++ }
++ outcome.HighWater = highWater(s.floor, s.records)
++
++ dirty := s.dirtyLocked()
++ if len(p.changed) == 0 && !dirty {
++ return outcome, nil
++ }
++ change := s.mirrorLocked()
++ if !dirty && !request.ReplaceAll {
++ change = s.diffLocked(p.changed)
++ }
++ if err := s.pushLocked(ctx, change, push); err != nil {
++ return outcome, err
++ }
++ outcome.Pushed = true
++ return outcome, nil
++}
++
++func (s *Store) ArmLease() uint64 {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ s.leaseGen++
++ s.leaseArmed = true
++ return s.leaseGen
++}
++
++func (s *Store) EndLease() {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ s.leaseArmed = false
++}
++
++func (s *Store) ExpireLease(ctx context.Context, lease uint64, push PushFunc) (bool, int, error) {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ if !s.leaseArmed || lease != s.leaseGen {
++ return false, 0, nil
++ }
++ cleared := len(s.records)
++ _, err := s.applyLocked(ctx, Request{ReplaceAll: true, Snapshot: highWater(s.floor, s.records)}, push)
++ if errors.Is(err, ErrPersist) {
++ return false, 0, err
++ }
++ s.leaseArmed = false
++ return true, cleared, err
++}
++
++func (s *Store) Sync(ctx context.Context, push PushFunc) error {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ return s.pushLocked(ctx, s.mirrorLocked(), push)
++}
++
++func (s *Store) MarkDirty() {
++ if s == nil {
++ return
++ }
++ s.epoch.Add(1)
++}
++
++func (s *Store) Dirty() bool {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ return s.dirtyLocked()
++}
++
++func (s *Store) State() State {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ return stateOf(s.floor, s.records)
++}
++
++func (s *Store) HighWater() uint64 {
++ s.mu.Lock()
++ defer s.mu.Unlock()
++ return highWater(s.floor, s.records)
++}
diff --git a/pkg/speedcap/lease_test.go b/pkg/speedcap/lease_test.go
new file mode 100644
index 00000000..2d483970
--- /dev/null
+++ b/pkg/speedcap/lease_test.go
@@ -0,0 +1,62 @@
+package speedcap
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestALeaseEndThatCannotSaveClearsNothingAndStaysArmed(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "caps")
+ s := Open(filepath.Join(dir, "speedcaps.json"))
+ core := newRecordingCore()
+ apply(t, s, core, diff(e("12", 10_000_000, 0, 7)))
+ moved := dir + ".moved"
+ if err := os.Rename(dir, moved); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(dir, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ lease := s.ArmLease()
+ expired, cleared, err := s.ExpireLease(context.Background(), lease, core.push)
+ if expired || cleared != 0 || !errors.Is(err, ErrPersist) {
+ t.Fatalf("a lease end that could not save the cleared set answered expired %v, cleared %d, err %v; want not expired, nothing cleared and the persist error", expired, cleared, err)
+ }
+ requireCap(t, s, "12", 10_000_000)
+ requireCoreMatches(t, s, core)
+
+ if err := os.Remove(dir); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(moved, dir); err != nil {
+ t.Fatal(err)
+ }
+ expired, cleared, err = s.ExpireLease(context.Background(), lease, core.push)
+ if !expired || cleared != 1 || err != nil {
+ t.Fatalf("the same lease after the save works again answered expired %v, cleared %d, err %v; want it to end now and clear the one cap", expired, cleared, err)
+ }
+ if state := s.State(); len(state.Entries) != 0 || state.Floor != 7 {
+ t.Fatalf("after the lease the node holds %+v, want no entries and the floor at the high water 7", state)
+ }
+ requireCoreMatches(t, s, core)
+ if again, _, _ := s.ExpireLease(context.Background(), lease, core.push); again {
+ t.Fatal("a lease that already ended ended a second time")
+ }
+}
+
+func TestAnEndedLeaseLeavesNothingForItsEndToClear(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("12", 10_000_000, 0, 7)))
+
+ lease := s.ArmLease()
+ s.EndLease()
+ if expired, cleared, err := s.ExpireLease(context.Background(), lease, core.push); expired || cleared != 0 || err != nil {
+ t.Fatalf("the end of a lease the panel had already ended answered expired %v, cleared %d, err %v", expired, cleared, err)
+ }
+ requireCap(t, s, "12", 10_000_000)
+ requireCoreMatches(t, s, core)
+}
diff --git a/pkg/speedcap/patch_copy_test.go b/pkg/speedcap/patch_copy_test.go
new file mode 100644
index 00000000..23e097b8
--- /dev/null
+++ b/pkg/speedcap/patch_copy_test.go
@@ -0,0 +1,52 @@
+package speedcap
+
+import (
+ "os"
+ "strings"
+ "testing"
+)
+
+func storeCopyInThePatch(t *testing.T) string {
+ t.Helper()
+ raw, err := os.ReadFile("../../patches/xray-per-user-speed-cap.patch")
+ if err != nil {
+ t.Fatal(err)
+ }
+ const header = "diff --git a/testing/speedcapnode/store.go b/testing/speedcapnode/store.go\n"
+ start := strings.Index(string(raw), header)
+ if start < 0 {
+ t.Fatal("the xray patch carries no copy of the node store for its differential test")
+ }
+ section := string(raw)[start+len(header):]
+ if next := strings.Index(section, "\ndiff --git "); next >= 0 {
+ section = section[:next+1]
+ }
+ hunk := strings.Index(section, "\n@@ ")
+ if hunk < 0 {
+ t.Fatal("the store copy in the xray patch has no hunk")
+ }
+ body := section[hunk+1:]
+ body = body[strings.Index(body, "\n")+1:]
+ var copied strings.Builder
+ for _, line := range strings.SplitAfter(body, "\n") {
+ if line == "" {
+ continue
+ }
+ if !strings.HasPrefix(line, "+") {
+ t.Fatalf("the store copy in the xray patch is not a new file: %q", line)
+ }
+ copied.WriteString(line[1:])
+ }
+ return copied.String()
+}
+
+func TestTheXrayPatchTestsThisExactStore(t *testing.T) {
+ store, err := os.ReadFile("store.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := strings.Replace(string(store), "package speedcap\n", "package speedcapnode\n", 1)
+ if got := storeCopyInThePatch(t); got != want {
+ t.Fatal("testing/speedcapnode/store.go in patches/xray-per-user-speed-cap.patch differs from pkg/speedcap/store.go; copy the store into the patch so its differential test runs against this code")
+ }
+}
diff --git a/pkg/speedcap/scope_test.go b/pkg/speedcap/scope_test.go
new file mode 100644
index 00000000..0c76abde
--- /dev/null
+++ b/pkg/speedcap/scope_test.go
@@ -0,0 +1,72 @@
+package speedcap
+
+import (
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func scopedEntry(email string, down, revision uint64, tags ...string) Entry {
+ return Entry{Email: email, Down: down, Revision: revision, InboundTags: tags}
+}
+
+func TestTheScopeIsPartOfTheStoredCap(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(scopedEntry("alice", 10_000_000, 1, "in-b", "in-a", "in-b", "")))
+ want := []Entry{scopedEntry("alice", 10_000_000, 1, "in-a", "in-b")}
+ if got := s.State().Entries; !reflect.DeepEqual(got, want) {
+ t.Fatalf("the node stored %+v, want %+v", got, want)
+ }
+ if got := core.last().Entries; !reflect.DeepEqual(got, want) {
+ t.Fatalf("the core was sent %+v, want %+v", got, want)
+ }
+ raw, err := os.ReadFile(s.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), `"inbound_tags":["in-a","in-b"]`) {
+ t.Fatalf("the store file lacks the scope: %s", raw)
+ }
+ if got := Open(s.Path()).State().Entries; !reflect.DeepEqual(got, want) {
+ t.Fatalf("a reopened store holds %+v, want %+v", got, want)
+ }
+
+ outcome := apply(t, s, core, diff(scopedEntry("alice", 10_000_000, 2, "in-c")))
+ if outcome.Changed != 1 || !reflect.DeepEqual(core.last().Entries, []Entry{scopedEntry("alice", 10_000_000, 2, "in-c")}) {
+ t.Fatalf("a change of scope alone was not applied and pushed: %+v, pushed %+v", outcome, core.last())
+ }
+ requireCoreMatches(t, s, core)
+}
+
+func TestStaleComparesTheScope(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(scopedEntry("alice", 10_000_000, 5, "in-a", "in-b")))
+ for _, c := range []struct {
+ name string
+ entry Entry
+ stale bool
+ }{
+ {"the same scope in another order with a duplicate", scopedEntry("alice", 10_000_000, 5, "in-b", "in-a", "in-a"), false},
+ {"a narrower scope at the same revision", scopedEntry("alice", 10_000_000, 5, "in-a"), true},
+ {"no scope at the same revision", scopedEntry("alice", 10_000_000, 5), true},
+ {"an older entry with the enforced scope", scopedEntry("alice", 10_000_000, 3, "in-a", "in-b"), false},
+ {"an older entry with another scope", scopedEntry("alice", 10_000_000, 3, "in-c"), true},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ outcome := apply(t, s, core, diff(c.entry))
+ if got := len(outcome.Stale) == 1; got != c.stale {
+ t.Fatalf("stale %v, want stale=%v", outcome.Stale, c.stale)
+ }
+ })
+ }
+
+ outcome := apply(t, s, core, diff(scopedEntry("alice", 0, 6, "in-a")))
+ if len(outcome.Stale) != 0 {
+ t.Fatalf("a removal that names a scope is reported stale: %v", outcome.Stale)
+ }
+ if got := s.State().Entries; !reflect.DeepEqual(got, []Entry{e("alice", 0, 0, 6)}) {
+ t.Fatalf("a tombstone keeps a scope: %+v", got)
+ }
+ requireCoreMatches(t, s, core)
+}
diff --git a/pkg/speedcap/store.go b/pkg/speedcap/store.go
new file mode 100644
index 00000000..aa85386a
--- /dev/null
+++ b/pkg/speedcap/store.go
@@ -0,0 +1,461 @@
+package speedcap
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+const stateVersion = 1
+
+var ErrPersist = errors.New("speed caps could not be persisted")
+
+type Entry struct {
+ Email string `json:"email"`
+ Down uint64 `json:"down_bps"`
+ Up uint64 `json:"up_bps"`
+ Revision uint64 `json:"revision"`
+ InboundTags []string `json:"inbound_tags,omitempty"`
+}
+
+type State struct {
+ Version int `json:"version"`
+ Floor uint64 `json:"floor"`
+ Entries []Entry `json:"entries"`
+}
+
+type Request struct {
+ Entries []Entry
+ ReplaceAll bool
+ Snapshot uint64
+}
+
+type Change struct {
+ Entries []Entry
+ ReplaceAll bool
+ Snapshot uint64
+}
+
+type Rejection struct {
+ Email string
+ Reason string
+}
+
+type Outcome struct {
+ Rejected []Rejection
+ Stale []string
+ HighWater uint64
+ Changed int
+ Pushed bool
+}
+
+type PushFunc func(context.Context, Change) error
+
+type record struct {
+ down uint64
+ up uint64
+ revision uint64
+ tags string
+}
+
+func canonicalTags(down, up uint64, tags []string) string {
+ if down == 0 && up == 0 {
+ return ""
+ }
+ kept := make([]string, 0, len(tags))
+ for _, tag := range tags {
+ if tag != "" {
+ kept = append(kept, tag)
+ }
+ }
+ sort.Strings(kept)
+ var b strings.Builder
+ for _, tag := range slices.Compact(kept) {
+ b.WriteString(strconv.Itoa(len(tag)))
+ b.WriteByte(':')
+ b.WriteString(tag)
+ }
+ return b.String()
+}
+
+func splitTags(key string) []string {
+ var tags []string
+ for key != "" {
+ colon := strings.IndexByte(key, ':')
+ size, _ := strconv.Atoi(key[:colon])
+ tags = append(tags, key[colon+1:colon+1+size])
+ key = key[colon+1+size:]
+ }
+ return tags
+}
+
+type Store struct {
+ mu sync.Mutex
+ path string
+ floor uint64
+ records map[string]record
+ failed bool
+ synced uint64
+ epoch atomic.Uint64
+ leaseGen uint64
+ leaseArmed bool
+}
+
+func Normalize(email string) string {
+ return strings.ToLower(email)
+}
+
+func NewMemoryStore() *Store {
+ s := &Store{records: make(map[string]record)}
+ s.epoch.Store(1)
+ return s
+}
+
+func (s *Store) dirtyLocked() bool {
+ return s.failed || s.epoch.Load() != s.synced
+}
+
+func (s *Store) pushLocked(ctx context.Context, change Change, push PushFunc) error {
+ epoch := s.epoch.Load()
+ if err := push(ctx, change); err != nil {
+ s.failed = true
+ return err
+ }
+ s.failed = false
+ s.synced = epoch
+ return nil
+}
+
+func Open(path string) *Store {
+ s := NewMemoryStore()
+ s.path = path
+ if path == "" {
+ return s
+ }
+ raw, err := os.ReadFile(path)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ return s
+ case err != nil:
+ log.Printf("speed caps: %s could not be read, starting without caps until the panel resends them: %v", path, err)
+ return s
+ }
+ var state State
+ if err := json.Unmarshal(raw, &state); err != nil {
+ kept := fmt.Sprintf("%s.corrupt-%d", path, time.Now().Unix())
+ if renameErr := os.Rename(path, kept); renameErr != nil {
+ log.Printf("speed caps: %s is corrupt (%v) and could not be moved aside: %v", path, err, renameErr)
+ } else {
+ log.Printf("speed caps: %s is corrupt (%v), kept as %s, starting without caps until the panel resends them", path, err, kept)
+ }
+ return s
+ }
+ s.floor = state.Floor
+ for _, entry := range state.Entries {
+ key := Normalize(entry.Email)
+ if key == "" || entry.Revision == 0 {
+ continue
+ }
+ s.records[key] = record{down: entry.Down, up: entry.Up, revision: entry.Revision, tags: canonicalTags(entry.Down, entry.Up, entry.InboundTags)}
+ }
+ return s
+}
+
+func (s *Store) Path() string {
+ if s == nil {
+ return ""
+ }
+ return s.path
+}
+
+func invalidReason(entry Entry) string {
+ switch {
+ case entry.Email == "":
+ return "email must not be empty"
+ case entry.Revision == 0:
+ return "revision must be positive"
+ }
+ return ""
+}
+
+func accepts(stored, revision, floor uint64, replaceAll bool, snapshot uint64) bool {
+ if replaceAll {
+ return stored <= snapshot || revision > stored
+ }
+ return revision > max(stored, floor)
+}
+
+type plan struct {
+ floor uint64
+ records map[string]record
+ changed []string
+ rejected []Rejection
+ stale []string
+}
+
+func (s *Store) plan(request Request) plan {
+ p := s.planChanges(request)
+ p.markStale(request.Entries)
+ return p
+}
+
+func (s *Store) planChanges(request Request) plan {
+ p := plan{floor: s.floor, records: make(map[string]record, len(s.records))}
+ for key, rec := range s.records {
+ p.records[key] = rec
+ }
+ ignored := request.ReplaceAll && request.Snapshot < s.floor
+
+ touched := make(map[string]struct{})
+ listed := make(map[string]struct{})
+ for _, entry := range request.Entries {
+ key := Normalize(entry.Email)
+ if reason := invalidReason(entry); reason != "" {
+ p.rejected = append(p.rejected, Rejection{Email: entry.Email, Reason: reason})
+ continue
+ }
+ if request.ReplaceAll {
+ listed[key] = struct{}{}
+ }
+ stored, known := p.records[key]
+ if ignored || !accepts(stored.revision, entry.Revision, p.floor, request.ReplaceAll, request.Snapshot) {
+ continue
+ }
+ revision := entry.Revision
+ if request.ReplaceAll {
+ revision = max(revision, request.Snapshot)
+ }
+ updated := record{down: entry.Down, up: entry.Up, revision: revision, tags: canonicalTags(entry.Down, entry.Up, entry.InboundTags)}
+ if known && stored == updated {
+ continue
+ }
+ p.records[key] = updated
+ touched[key] = struct{}{}
+ }
+
+ if ignored {
+ return p
+ }
+
+ if request.ReplaceAll {
+ for key, rec := range p.records {
+ if _, ok := listed[key]; ok || rec.revision > request.Snapshot {
+ continue
+ }
+ delete(p.records, key)
+ touched[key] = struct{}{}
+ }
+ if request.Snapshot != p.floor {
+ touched[""] = struct{}{}
+ }
+ p.floor = request.Snapshot
+ for key, rec := range p.records {
+ if rec.down == 0 && rec.up == 0 && rec.revision <= p.floor {
+ delete(p.records, key)
+ }
+ }
+ }
+
+ for key := range touched {
+ p.changed = append(p.changed, key)
+ }
+ sort.Strings(p.changed)
+ return p
+}
+
+func (p *plan) markStale(entries []Entry) {
+ reported := make(map[string]struct{})
+ for _, entry := range entries {
+ if invalidReason(entry) != "" {
+ continue
+ }
+ key := Normalize(entry.Email)
+ if _, seen := reported[key]; seen {
+ continue
+ }
+ if current := p.records[key]; current.down != entry.Down || current.up != entry.Up || current.tags != canonicalTags(entry.Down, entry.Up, entry.InboundTags) {
+ reported[key] = struct{}{}
+ p.stale = append(p.stale, entry.Email)
+ }
+ }
+}
+
+func stateOf(floor uint64, records map[string]record) State {
+ state := State{Version: stateVersion, Floor: floor, Entries: make([]Entry, 0, len(records))}
+ for key, rec := range records {
+ state.Entries = append(state.Entries, Entry{Email: key, Down: rec.down, Up: rec.up, Revision: rec.revision, InboundTags: splitTags(rec.tags)})
+ }
+ sort.Slice(state.Entries, func(i, j int) bool { return state.Entries[i].Email < state.Entries[j].Email })
+ return state
+}
+
+func (s *Store) persist(state State) error {
+ if s.path == "" {
+ return nil
+ }
+ raw, err := json.Marshal(state)
+ if err != nil {
+ return err
+ }
+ dir := filepath.Dir(s.path)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(dir, filepath.Base(s.path)+".tmp-*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ defer os.Remove(tmpName)
+ if _, err := tmp.Write(raw); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Chmod(0o600); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Sync(); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ if err := os.Rename(tmpName, s.path); err != nil {
+ return err
+ }
+ if d, err := os.Open(dir); err == nil {
+ _ = d.Sync()
+ _ = d.Close()
+ }
+ return nil
+}
+
+func highWater(floor uint64, records map[string]record) uint64 {
+ high := floor
+ for _, rec := range records {
+ high = max(high, rec.revision)
+ }
+ return high
+}
+
+func (s *Store) mirrorLocked() Change {
+ state := stateOf(s.floor, s.records)
+ return Change{Entries: state.Entries, ReplaceAll: true, Snapshot: s.floor}
+}
+
+func (s *Store) diffLocked(keys []string) Change {
+ change := Change{Entries: make([]Entry, 0, len(keys))}
+ for _, key := range keys {
+ rec := s.records[key]
+ change.Entries = append(change.Entries, Entry{Email: key, Down: rec.down, Up: rec.up, Revision: rec.revision, InboundTags: splitTags(rec.tags)})
+ }
+ return change
+}
+
+func (s *Store) Apply(ctx context.Context, request Request, push PushFunc) (Outcome, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if request.ReplaceAll {
+ s.leaseArmed = false
+ }
+ return s.applyLocked(ctx, request, push)
+}
+
+func (s *Store) applyLocked(ctx context.Context, request Request, push PushFunc) (Outcome, error) {
+ p := s.plan(request)
+ outcome := Outcome{Rejected: p.rejected, Stale: p.stale, Changed: len(p.changed)}
+ if len(p.changed) > 0 {
+ if err := s.persist(stateOf(p.floor, p.records)); err != nil {
+ return outcome, fmt.Errorf("%w: %v", ErrPersist, err)
+ }
+ s.floor, s.records = p.floor, p.records
+ }
+ outcome.HighWater = highWater(s.floor, s.records)
+
+ dirty := s.dirtyLocked()
+ if len(p.changed) == 0 && !dirty {
+ return outcome, nil
+ }
+ change := s.mirrorLocked()
+ if !dirty && !request.ReplaceAll {
+ change = s.diffLocked(p.changed)
+ }
+ if err := s.pushLocked(ctx, change, push); err != nil {
+ return outcome, err
+ }
+ outcome.Pushed = true
+ return outcome, nil
+}
+
+func (s *Store) ArmLease() uint64 {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.leaseGen++
+ s.leaseArmed = true
+ return s.leaseGen
+}
+
+func (s *Store) EndLease() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.leaseArmed = false
+}
+
+func (s *Store) ExpireLease(ctx context.Context, lease uint64, push PushFunc) (bool, int, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !s.leaseArmed || lease != s.leaseGen {
+ return false, 0, nil
+ }
+ cleared := len(s.records)
+ _, err := s.applyLocked(ctx, Request{ReplaceAll: true, Snapshot: highWater(s.floor, s.records)}, push)
+ if errors.Is(err, ErrPersist) {
+ return false, 0, err
+ }
+ s.leaseArmed = false
+ return true, cleared, err
+}
+
+func (s *Store) Sync(ctx context.Context, push PushFunc) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.pushLocked(ctx, s.mirrorLocked(), push)
+}
+
+func (s *Store) MarkDirty() {
+ if s == nil {
+ return
+ }
+ s.epoch.Add(1)
+}
+
+func (s *Store) Dirty() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.dirtyLocked()
+}
+
+func (s *Store) State() State {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return stateOf(s.floor, s.records)
+}
+
+func (s *Store) HighWater() uint64 {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return highWater(s.floor, s.records)
+}
diff --git a/pkg/speedcap/store_test.go b/pkg/speedcap/store_test.go
new file mode 100644
index 00000000..818fbd92
--- /dev/null
+++ b/pkg/speedcap/store_test.go
@@ -0,0 +1,482 @@
+package speedcap
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+type recordingCore struct {
+ pushes []Change
+ fail error
+ state *Store
+}
+
+func newRecordingCore() *recordingCore {
+ return &recordingCore{state: NewMemoryStore()}
+}
+
+func (c *recordingCore) push(_ context.Context, change Change) error {
+ if c.fail != nil {
+ return c.fail
+ }
+ c.pushes = append(c.pushes, change)
+ c.state.plainApply(Request(change))
+ return nil
+}
+
+func (s *Store) plainApply(request Request) {
+ p := s.plan(request)
+ s.floor, s.records = p.floor, p.records
+}
+
+func (c *recordingCore) last() Change {
+ return c.pushes[len(c.pushes)-1]
+}
+
+func e(email string, down, up, revision uint64) Entry {
+ return Entry{Email: email, Down: down, Up: up, Revision: revision}
+}
+
+func diff(entries ...Entry) Request {
+ return Request{Entries: entries}
+}
+
+func snapshot(s uint64, entries ...Entry) Request {
+ return Request{Entries: entries, ReplaceAll: true, Snapshot: s}
+}
+
+func caps(t *testing.T, s *Store, email string) (uint64, uint64) {
+ t.Helper()
+ for _, entry := range s.State().Entries {
+ if entry.Email == Normalize(email) {
+ return entry.Down, entry.Up
+ }
+ }
+ return 0, 0
+}
+
+func requireCap(t *testing.T, s *Store, email string, down uint64) {
+ t.Helper()
+ if got, _ := caps(t, s, email); got != down {
+ t.Fatalf("%s is capped at %d, want %d", email, got, down)
+ }
+}
+
+func apply(t *testing.T, s *Store, core *recordingCore, request Request) Outcome {
+ t.Helper()
+ outcome, err := s.Apply(context.Background(), request, core.push)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return outcome
+}
+
+func newSyncedStore(t *testing.T) (*Store, *recordingCore) {
+ t.Helper()
+ s := Open(filepath.Join(t.TempDir(), "speedcaps.json"))
+ core := newRecordingCore()
+ if err := s.Sync(context.Background(), core.push); err != nil {
+ t.Fatal(err)
+ }
+ return s, core
+}
+
+func requireCoreMatches(t *testing.T, s *Store, core *recordingCore) {
+ t.Helper()
+ if got, want := core.state.State(), s.State(); !reflect.DeepEqual(got, want) {
+ t.Fatalf("the core holds %+v, the node stored %+v", got, want)
+ }
+}
+
+func TestScopedDiffPushesOnlyTheListedEmail(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("alice", 10_000_000, 0, 1), e("bob", 20_000_000, 0, 2)))
+ before := len(core.pushes)
+
+ apply(t, s, core, diff(e("alice", 15_000_000, 0, 3)))
+ if len(core.pushes) != before+1 {
+ t.Fatalf("expected one push, got %d", len(core.pushes)-before)
+ }
+ pushed := core.last()
+ if pushed.ReplaceAll || len(pushed.Entries) != 1 || !reflect.DeepEqual(pushed.Entries[0], e("alice", 15_000_000, 0, 3)) {
+ t.Fatalf("a scoped change pushed %+v", pushed)
+ }
+ requireCap(t, s, "bob", 20_000_000)
+ requireCoreMatches(t, s, core)
+}
+
+func TestZeroCapsRemoveTheCapAndAStaleDiffStaysIgnored(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("alice", 10_000_000, 0, 4)))
+ apply(t, s, core, diff(e("alice", 0, 0, 5)))
+ requireCap(t, s, "alice", 0)
+
+ pushes := len(core.pushes)
+ outcome := apply(t, s, core, diff(e("alice", 10_000_000, 0, 4)))
+ if len(core.pushes) != pushes || outcome.Changed != 0 || len(outcome.Rejected) != 0 {
+ t.Fatalf("a stale diff below the tombstone was applied or reported: %+v", outcome)
+ }
+ requireCap(t, s, "alice", 0)
+ requireCoreMatches(t, s, core)
+}
+
+func TestDelayedSnapshotKeepsTheNewerDiff(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, snapshot(10, e("x", 10_000_000, 0, 10)))
+ apply(t, s, core, diff(e("x", 20_000_000, 0, 11)))
+ apply(t, s, core, snapshot(10, e("x", 10_000_000, 0, 10)))
+ requireCap(t, s, "x", 20_000_000)
+
+ outcome := apply(t, s, core, diff(e("x", 5_000_000, 0, 9)))
+ if outcome.Changed != 0 || len(outcome.Rejected) != 0 {
+ t.Fatalf("a diff at or below the snapshot changed state: %+v", outcome)
+ }
+ requireCap(t, s, "x", 20_000_000)
+ requireCoreMatches(t, s, core)
+}
+
+func TestDelayedDiffAfterASnapshotThatDroppedTheEmailIsIgnored(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("x", 10_000_000, 0, 3)))
+ apply(t, s, core, snapshot(9))
+ requireCap(t, s, "x", 0)
+
+ apply(t, s, core, diff(e("x", 30_000_000, 0, 7)))
+ requireCap(t, s, "x", 0)
+ requireCoreMatches(t, s, core)
+}
+
+func TestSnapshotBelowTheFloorIsAQuietNoOp(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, snapshot(12, e("x", 10_000_000, 0, 4)))
+ pushes := len(core.pushes)
+
+ outcome := apply(t, s, core, snapshot(11, e("y", 10_000_000, 0, 5)))
+ if outcome.Changed != 0 || len(outcome.Rejected) != 0 || len(core.pushes) != pushes {
+ t.Fatalf("a snapshot below the floor changed or pushed something: %+v", outcome)
+ }
+ if got := s.State().Floor; got != 12 {
+ t.Fatalf("floor moved to %d", got)
+ }
+ requireCap(t, s, "y", 0)
+}
+
+func TestRetryAfterAFailedCoreApplyReachesTheCore(t *testing.T) {
+ s, core := newSyncedStore(t)
+ core.fail = errors.New("core restarting")
+ if _, err := s.Apply(context.Background(), diff(e("alice", 10_000_000, 0, 1)), core.push); err == nil {
+ t.Fatal("a failed core apply reported success")
+ }
+ requireCap(t, s, "alice", 10_000_000)
+ if !s.Dirty() {
+ t.Fatal("the store did not remember that the core missed a change")
+ }
+
+ core.fail = nil
+ apply(t, s, core, diff(e("alice", 10_000_000, 0, 1)))
+ if !core.last().ReplaceAll {
+ t.Fatal("the retry did not resend the whole set to the core")
+ }
+ if s.Dirty() {
+ t.Fatal("the store still thinks the core is behind")
+ }
+ requireCoreMatches(t, s, core)
+}
+
+func TestLowerPanelCounterIsRecoveredByASnapshotAtTheHighWater(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, snapshot(40, e("x", 10_000_000, 0, 50), e("y", 30_000_000, 0, 57)))
+
+ outcome := apply(t, s, core, diff(e("x", 99_000_000, 0, 1)))
+ if outcome.Changed != 0 || outcome.HighWater != 57 {
+ t.Fatalf("a diff below the stored revisions answered %+v, want no change and high water 57", outcome)
+ }
+ requireCap(t, s, "x", 10_000_000)
+
+ outcome = apply(t, s, core, snapshot(57, e("x", 5_000_000, 0, 2), e("z", 7_000_000, 0, 3)))
+ requireCap(t, s, "x", 5_000_000)
+ requireCap(t, s, "z", 7_000_000)
+ requireCap(t, s, "y", 0)
+ if outcome.HighWater != 57 {
+ t.Fatalf("high water %d after the recovery snapshot, want 57", outcome.HighWater)
+ }
+ requireCoreMatches(t, s, core)
+}
+
+func TestSnapshotWinsWhenTheNodeHasNothingNewer(t *testing.T) {
+ const base = 1_000
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("x", 20_000_000, 0, base+10)))
+ apply(t, s, core, snapshot(base+10, e("x", 10_000_000, 0, base-5)))
+ requireCap(t, s, "x", 10_000_000)
+ requireCoreMatches(t, s, core)
+}
+
+func TestSnapshotAtRevisionZero(t *testing.T) {
+ s, core := newSyncedStore(t)
+ outcome, err := s.Apply(context.Background(), snapshot(0), core.push)
+ if err != nil || outcome.Changed != 0 || len(outcome.Rejected) != 0 {
+ t.Fatalf("an empty snapshot at revision 0 answered %+v, %v", outcome, err)
+ }
+
+ apply(t, s, core, snapshot(0, e("x", 10_000_000, 0, 1)))
+ requireCap(t, s, "x", 10_000_000)
+ requireCoreMatches(t, s, core)
+}
+
+func TestInvalidEntriesAreRejectedAndTheRestApplied(t *testing.T) {
+ s, core := newSyncedStore(t)
+ outcome := apply(t, s, core, diff(e("", 10_000_000, 0, 3), e("y", 10_000_000, 0, 0), e("z", 10_000_000, 0, 4)))
+ if len(outcome.Rejected) != 2 {
+ t.Fatalf("rejected %+v, want the empty email and the zero revision", outcome.Rejected)
+ }
+ for _, rejection := range outcome.Rejected {
+ if rejection.Reason == "" {
+ t.Fatalf("a rejection has no reason: %+v", rejection)
+ }
+ }
+ requireCap(t, s, "z", 10_000_000)
+ requireCap(t, s, "y", 0)
+}
+
+func TestDuplicateDiffIsAQuietNoOp(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("x", 10_000_000, 0, 3)))
+ pushes := len(core.pushes)
+ outcome := apply(t, s, core, diff(e("x", 10_000_000, 0, 3)))
+ if outcome.Changed != 0 || len(outcome.Rejected) != 0 || len(core.pushes) != pushes {
+ t.Fatalf("a duplicate diff changed, rejected or pushed: %+v", outcome)
+ }
+}
+
+func TestEveryAcceptedChangeIsOnDiskBeforeTheCoreSeesIt(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "speedcaps.json")
+ s := Open(path)
+ var onDisk State
+ push := func(_ context.Context, change Change) error {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ return json.Unmarshal(raw, &onDisk)
+ }
+ if _, err := s.Apply(context.Background(), diff(e("alice", 10_000_000, 2_000_000, 1), e("bob", 0, 0, 2)), push); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(onDisk, s.State()) {
+ t.Fatalf("the core was told before the state hit the disk: disk %+v, memory %+v", onDisk, s.State())
+ }
+
+ reopened := Open(path)
+ if !reflect.DeepEqual(reopened.State(), s.State()) {
+ t.Fatalf("reopened state %+v, want %+v", reopened.State(), s.State())
+ }
+ if !reopened.Dirty() {
+ t.Fatal("a reopened store must resend its state to the next core")
+ }
+ if runtime.GOOS != "windows" {
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != 0o600 {
+ t.Fatalf("the store file mode is %v", info.Mode().Perm())
+ }
+ }
+}
+
+func TestPersistFailureLeavesTheStateAndTheCoreUntouched(t *testing.T) {
+ dir := t.TempDir()
+ blocker := filepath.Join(dir, "file")
+ if err := os.WriteFile(blocker, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s := Open(filepath.Join(blocker, "speedcaps.json"))
+ core := newRecordingCore()
+ _, err := s.Apply(context.Background(), diff(e("alice", 10_000_000, 0, 1)), core.push)
+ if !errors.Is(err, ErrPersist) {
+ t.Fatalf("expected a persistence error, got %v", err)
+ }
+ if len(core.pushes) != 0 {
+ t.Fatal("the core was told about a change that is not on disk")
+ }
+ requireCap(t, s, "alice", 0)
+}
+
+func TestCorruptStoreIsMovedAsideAndTheNodeStarts(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "speedcaps.json")
+ if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s := Open(path)
+ if len(s.State().Entries) != 0 {
+ t.Fatal("caps appeared from a corrupt store")
+ }
+ names, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ kept := false
+ for _, entry := range names {
+ if strings.HasPrefix(entry.Name(), "speedcaps.json.corrupt-") {
+ kept = true
+ }
+ }
+ if !kept {
+ t.Fatal("the corrupt store was not kept for inspection")
+ }
+}
+
+func TestMarkDirtyMakesTheNextChangeResendEverything(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("alice", 10_000_000, 0, 1)))
+ s.MarkDirty()
+ apply(t, s, core, diff(e("bob", 20_000_000, 0, 2)))
+ if pushed := core.last(); !pushed.ReplaceAll || len(pushed.Entries) != 2 {
+ t.Fatalf("after a core start the next change pushed %+v instead of the whole set", pushed)
+ }
+ requireCoreMatches(t, s, core)
+}
+
+func TestStaleNamesEveryEntryWhoseCapIsNotInForce(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("x", 10_000_000, 0, 5)))
+
+ outcome := apply(t, s, core, diff(e("x", 99_000_000, 0, 5), e("y", 10_000_000, 0, 6)))
+ if !reflect.DeepEqual(outcome.Stale, []string{"x"}) {
+ t.Fatalf("an equal revision with another cap answered stale %v, want [x]", outcome.Stale)
+ }
+ outcome = apply(t, s, core, diff(e("x", 10_000_000, 0, 5)))
+ if len(outcome.Stale) != 0 {
+ t.Fatalf("an equal revision with the cap in force answered stale %v", outcome.Stale)
+ }
+
+ apply(t, s, core, snapshot(20, e("x", 10_000_000, 0, 5), e("y", 10_000_000, 0, 6)))
+ outcome = apply(t, s, core, diff(e("z", 10_000_000, 0, 19), e("w", 10_000_000, 0, 21)))
+ if !reflect.DeepEqual(outcome.Stale, []string{"z"}) {
+ t.Fatalf("a diff the floor covers answered stale %v, want [z]", outcome.Stale)
+ }
+ outcome = apply(t, s, core, diff(e("z", 0, 0, 19), e("x", 10_000_000, 0, 3)))
+ if len(outcome.Stale) != 0 {
+ t.Fatalf("older entries whose caps are already in force answered stale %v", outcome.Stale)
+ }
+
+ apply(t, s, core, diff(e("x", 30_000_000, 0, 25)))
+ outcome = apply(t, s, core, snapshot(22, e("x", 10_000_000, 0, 20), e("y", 10_000_000, 0, 6), e("w", 10_000_000, 0, 21)))
+ if !reflect.DeepEqual(outcome.Stale, []string{"x"}) {
+ t.Fatalf("a snapshot entry the node kept a newer value for answered stale %v, want [x]", outcome.Stale)
+ }
+ requireCap(t, s, "x", 30_000_000)
+
+ outcome = apply(t, s, core, snapshot(21, e("x", 30_000_000, 0, 1), e("y", 1, 0, 1), e("", 1, 0, 1)))
+ if !reflect.DeepEqual(outcome.Stale, []string{"y"}) || len(outcome.Rejected) != 1 {
+ t.Fatalf("a snapshot below the floor answered stale %v and rejected %v, want only the entry whose cap differs stale and the invalid one rejected", outcome.Stale, outcome.Rejected)
+ }
+
+ outcome = apply(t, s, core, diff(e("v", 10_000_000, 0, 40)))
+ if len(outcome.Stale) != 0 {
+ t.Fatalf("an applied entry was reported stale: %v", outcome.Stale)
+ }
+ requireCap(t, s, "v", 10_000_000)
+ requireCoreMatches(t, s, core)
+}
+
+func TestInvalidSnapshotEntriesCountAsNotListed(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("x", 10_000_000, 0, 3), e("y", 20_000_000, 0, 4)))
+ outcome := apply(t, s, core, snapshot(9, e("x", 10_000_000, 0, 0), e("y", 20_000_000, 0, 4)))
+ if len(outcome.Rejected) != 1 {
+ t.Fatalf("rejected %v, want the revision 0 entry", outcome.Rejected)
+ }
+ requireCap(t, s, "x", 0)
+ requireCap(t, s, "y", 20_000_000)
+ if got := s.State(); len(got.Entries) != 1 || got.Entries[0].Email != "y" || got.Floor != 9 {
+ t.Fatalf("an invalid entry kept an old record: %+v", got)
+ }
+ requireCoreMatches(t, s, core)
+}
+
+func TestStaleComparesTheUploadCapToo(t *testing.T) {
+ s, core := newSyncedStore(t)
+ apply(t, s, core, diff(e("x", 10_000_000, 5_000_000, 5)))
+
+ outcome := apply(t, s, core, diff(e("x", 10_000_000, 7_000_000, 5)))
+ if !reflect.DeepEqual(outcome.Stale, []string{"x"}) {
+ t.Fatalf("an equal revision whose upload cap differs answered stale %v, want [x]", outcome.Stale)
+ }
+ outcome = apply(t, s, core, diff(e("x", 10_000_000, 5_000_000, 5)))
+ if len(outcome.Stale) != 0 {
+ t.Fatalf("an equal revision with both caps in force answered stale %v", outcome.Stale)
+ }
+}
+
+func TestMarkDirtyDoesNotWaitBehindAHungPush(t *testing.T) {
+ s := NewMemoryStore()
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ pushing := make(chan struct{})
+ hung := func(ctx context.Context, _ Change) error {
+ close(pushing)
+ <-ctx.Done()
+ return ctx.Err()
+ }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ _, _ = s.Apply(ctx, diff(e("12", 1_000_000, 0, 1)), hung)
+ }()
+ <-pushing
+ marked := make(chan time.Duration, 1)
+ go func() {
+ begin := time.Now()
+ s.MarkDirty()
+ marked <- time.Since(begin)
+ }()
+ select {
+ case waited := <-marked:
+ if waited > 100*time.Millisecond {
+ t.Fatalf("MarkDirty waited %s behind a hung core push", waited)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("MarkDirty waited behind a hung core push")
+ }
+ <-done
+}
+
+func TestARestartDuringAPushLeavesTheStoreDirty(t *testing.T) {
+ s, core := newSyncedStore(t)
+ restartsMidPush := func(ctx context.Context, change Change) error {
+ s.MarkDirty()
+ return core.push(ctx, change)
+ }
+ done := make(chan error, 1)
+ go func() {
+ _, err := s.Apply(context.Background(), diff(e("12", 1_000_000, 0, 1)), restartsMidPush)
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("a core restart during a push deadlocked the store")
+ }
+ if !s.Dirty() {
+ t.Fatal("a core that restarted during the push is taken as caught up")
+ }
+ apply(t, s, core, diff(e("13", 2_000_000, 0, 2)))
+ if !core.last().ReplaceAll {
+ t.Fatal("the change after a restart during a push did not resend the whole set")
+ }
+ requireCoreMatches(t, s, core)
+}
diff --git a/scripts/singbox_http2_guard.sh b/scripts/singbox_http2_guard.sh
deleted file mode 100644
index 4f6b6652..00000000
--- a/scripts/singbox_http2_guard.sh
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/bin/sh
-set -eu
-
-tags=${1:?usage: singbox_http2_guard.sh }
-
-refuse() {
- printf 'singbox-http2-guard: %s\n' "$1" >&2
- exit 1
-}
-
-host_os=$(go env GOHOSTOS)
-host_arch=$(go env GOHOSTARCH)
-native=$(unset GOOS GOARCH; go env GOOS)/$(unset GOOS GOARCH; go env GOARCH)
-[ "$native" = "$host_os/$host_arch" ] || refuse "go without GOOS and GOARCH targets $native, not the host $host_os/$host_arch, so the tests below would not run on this host"
-files=" $(go list -tags "$tags" -f '{{join .GoFiles " "}}' golang.org/x/net/http2) "
-host_files=" $(unset GOOS GOARCH; go list -tags "$tags" -f '{{join .GoFiles " "}}' golang.org/x/net/http2) "
-module=$(go list -tags "$tags" -f '{{with .Module}}{{.Path}} {{.Version}}{{with .Replace}} => {{.Path}}{{end}}{{end}}' golang.org/x/net/http2)
-
-for file in server.go transport.go frame.go; do
- case $files in
- *" $file "*) ;;
- *) refuse "$module under tags $tags does not compile http2/$file, the implementation the tests below run" ;;
- esac
-done
-for file in server_wrap.go transport_wrap.go; do
- case $files in
- *" $file "*) refuse "$module under tags $tags compiles http2/$file, the net/http wrapper, instead of x/net's own server and transport" ;;
- esac
-done
-[ "$files" = "$host_files" ] || refuse "$module compiles other http2 files for the target than for $host_os/$host_arch, so the tests below would not run the target's code"
-
-if ! out=$(unset GOOS GOARCH; go test -count=1 -tags "$tags" -run '^(TestServerMaxHandlerGoroutines|TestServerContinuationFlood|TestServerContinuationAfterInvalidHeader)$' -v golang.org/x/net/http2 2>&1); then
- printf '%s\n' "$out" >&2
- refuse "$module failed its early-reset and CONTINUATION tests under tags $tags"
-fi
-for name in TestServerMaxHandlerGoroutines TestServerContinuationFlood TestServerContinuationAfterInvalidHeader; do
- printf '%s\n' "$out" | grep -q "^--- PASS: $name " || refuse "$module did not run and pass $name under tags $tags"
-done
-
-printf 'singbox-http2-guard: %s under tags %s compiles server.go, transport.go and frame.go and passes TestServerMaxHandlerGoroutines, TestServerContinuationFlood and TestServerContinuationAfterInvalidHeader\n' "$module" "$tags"
diff --git a/scripts/test_govulncheck_gate.sh b/scripts/test_govulncheck_gate.sh
index 92dbe15a..71d2c6c1 100644
--- a/scripts/test_govulncheck_gate.sh
+++ b/scripts/test_govulncheck_gate.sh
@@ -249,10 +249,10 @@ check n2-patch-for-other-module 1 "FAIL GO-2026-7001 golang.org/x/net@v0.60.0 is
fixture n2-patch-applied-in-other-stage
cat >"$tmp/n2-patch-applied-in-other-stage/Dockerfile" <&2; exit 2; }
-guard=$(cd "$(dirname "$guard")" && pwd)/$(basename "$guard")
-
-tmp=$(mktemp -d "${TMPDIR:-/tmp}/singbox-http2-guard-test.XXXXXX")
-trap 'rm -rf "$tmp"' EXIT
-
-export GOFLAGS=-mod=mod GOPROXY=off GOSUMDB=off GOWORK=off GOTOOLCHAIN=local
-
-pass=0
-failed=0
-
-legacy='//go:build !(go1.27 && !http2legacy)'
-wrap='//go:build go1.27 && !http2legacy'
-
-source_file() {
- if [ -n "$1" ]; then
- printf '%s\n\n' "$1"
- fi
- printf 'package http2\n'
-}
-
-test_file() {
- printf '%s\n\npackage http2\n\nimport "testing"\n\n' "$legacy"
- local name
- for name in TestServerMaxHandlerGoroutines TestServerContinuationFlood TestServerContinuationAfterInvalidHeader; do
- case " $1 " in
- *" missing:$name "*) ;;
- *" fails:$name "*) printf 'func %s(t *testing.T) { t.Fatal("limit not enforced") }\n\n' "$name" ;;
- *) printf 'func %s(t *testing.T) {}\n\n' "$name" ;;
- esac
- done
-}
-
-fixture() {
- local name=$1 tests=$2 wrap_constraint=$3
- local root=$tmp/$name
- mkdir -p "$root/xnet/http2" "$root/module"
- printf 'module golang.org/x/net\n\ngo 1.26.0\n' > "$root/xnet/go.mod"
- printf 'module guardprobe\n\ngo 1.26.0\n\nrequire golang.org/x/net v0.60.0\n\nreplace golang.org/x/net => ../xnet\n' > "$root/module/go.mod"
- source_file "$legacy" > "$root/xnet/http2/server.go"
- source_file "$legacy" > "$root/xnet/http2/transport.go"
- source_file "" > "$root/xnet/http2/frame.go"
- source_file "$wrap_constraint" > "$root/xnet/http2/server_wrap.go"
- source_file "$wrap_constraint" > "$root/xnet/http2/transport_wrap.go"
- test_file "$tests" > "$root/xnet/http2/server_test.go"
-}
-
-check() {
- local name=$1 tags=$2 want=$3 needle=$4
- local out rc
- set +e
- out=$(cd "$tmp/$name/module" && sh "$guard" "$tags" 2>&1)
- rc=$?
- set -e
- if [ "$want" = 0 ] && [ "$rc" = 0 ]; then
- pass=$((pass + 1))
- elif [ "$want" = 1 ] && [ "$rc" != 0 ] && printf '%s' "$out" | grep -qF -- "$needle"; then
- pass=$((pass + 1))
- else
- failed=$((failed + 1))
- printf 'FAIL %s: tags %s, want rc %s with "%s", got rc %s:\n%s\n' "$name" "$tags" "$want" "$needle" "$rc" "$out" >&2
- fi
-}
-
-fixture hardened "" "$wrap"
-check hardened with_quic,with_utls,with_clash_api,with_v2ray_api,http2legacy 0 ""
-if (cd "$tmp/hardened/module" && go list -tags with_quic -f '{{join .GoFiles " "}}' golang.org/x/net/http2) | grep -qw server_wrap.go; then
- check hardened with_quic,with_utls,with_clash_api,with_v2ray_api 1 "does not compile http2/server.go"
-else
- check hardened with_quic,with_utls,with_clash_api,with_v2ray_api 0 ""
-fi
-
-fixture rapid-reset-fails "fails:TestServerMaxHandlerGoroutines" "$wrap"
-check rapid-reset-fails with_quic,http2legacy 1 "--- FAIL: TestServerMaxHandlerGoroutines"
-
-fixture flood-fails "fails:TestServerContinuationFlood" "$wrap"
-check flood-fails with_quic,http2legacy 1 "--- FAIL: TestServerContinuationFlood"
-
-fixture invalid-fails "fails:TestServerContinuationAfterInvalidHeader" "$wrap"
-check invalid-fails with_quic,http2legacy 1 "--- FAIL: TestServerContinuationAfterInvalidHeader"
-
-fixture rapid-reset-missing "missing:TestServerMaxHandlerGoroutines" "$wrap"
-check rapid-reset-missing with_quic,http2legacy 1 "did not run and pass TestServerMaxHandlerGoroutines"
-
-fixture flood-missing "missing:TestServerContinuationFlood" "$wrap"
-check flood-missing with_quic,http2legacy 1 "did not run and pass TestServerContinuationFlood"
-
-fixture invalid-missing "missing:TestServerContinuationAfterInvalidHeader" "$wrap"
-check invalid-missing with_quic,http2legacy 1 "did not run and pass TestServerContinuationAfterInvalidHeader"
-
-fixture wrap-always "" '//go:build go1.20'
-check wrap-always with_quic,http2legacy 1 "compiles http2/server_wrap.go"
-
-rm "$tmp/hardened/xnet/http2/transport.go"
-check hardened with_quic,http2legacy 1 "does not compile http2/transport.go"
-
-printf 'test-singbox-http2-guard: %d passed, %d failed\n' "$pass" "$failed"
-[ "$failed" = 0 ]
diff --git a/scripts/test_toolchain_floor.sh b/scripts/test_toolchain_floor.sh
index 7312cb35..00654484 100644
--- a/scripts/test_toolchain_floor.sh
+++ b/scripts/test_toolchain_floor.sh
@@ -63,9 +63,6 @@ ARG XRAY_VERSION=v26.3.27
FROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@$digest AS builder
RUN make build
-FROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@$digest AS singbox-builder
-RUN go build ./cmd/sing-box
-
FROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@$digest AS xray-builder
COPY patches/xray-grpc-1.83.2.patch /patches/xray-grpc-1.83.2.patch
COPY patches/xray-session-revoke.patch /patches/xray-session-revoke.patch
@@ -81,7 +78,6 @@ RUN go build -o /out/xray ./main
FROM alpine:3.24.2@$alpine
COPY --from=builder /src/main /app/main
COPY --from=xray-builder /out/xray /usr/local/bin/xray
-COPY --from=singbox-builder /out/sing-box /usr/local/bin/sing-box
EOF
printf "FROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@%s AS builder\nRUN go build ./...\n\nFROM alpine:3.24.2@%s\n" "$digest" "$alpine" >"$r/Dockerfile.wireguard"
gomod_patch v0.52.0 v0.58.0 >"$r/patches/xray-grpc-1.83.2.patch"
@@ -122,7 +118,7 @@ check() {
}
fixture clean
-check clean 0 "11 pins checked, all at or above Go 1.27.4 and golang.org/x/net v0.60.0, and every golang image at or above the go.mod toolchain line 1.27.4"
+check clean 0 "10 pins checked, all at or above Go 1.27.4 and golang.org/x/net v0.60.0, and every golang image at or above the go.mod toolchain line 1.27.4"
fixture toolchain-below
edit go.mod 's/^toolchain go1.27.4$/toolchain go1.27.3/'
@@ -153,7 +149,7 @@ check toolchain-release-candidate 1 "which is not an exact release"
fixture toolchain-dropped
edit go.mod '/^toolchain /d'
-check toolchain-dropped 0 "10 pins checked, all at or above Go 1.27.4 and golang.org/x/net v0.60.0, and every golang image at or above the go.mod go line 1.27.3"
+check toolchain-dropped 0 "9 pins checked, all at or above Go 1.27.4 and golang.org/x/net v0.60.0, and every golang image at or above the go.mod go line 1.27.3"
fixture toolchain-dropped-go-line-raised
edit go.mod '/^toolchain /d; s/^go 1.27.3$/go 1.27.4/'
@@ -166,12 +162,12 @@ check toolchain-twice 1 "more than one toolchain line"
fixture toolchain-above-images
edit go.mod 's/^toolchain go1.27.4$/toolchain go1.27.5/'
check toolchain-above-images 1 "Dockerfile.wireguard image golang:1.27.4-alpine names Go 1.27.4, below the go.mod toolchain line 1.27.5"
-check toolchain-above-images 1 "4 problems in 11 pins"
+check toolchain-above-images 1 "3 problems in 10 pins"
fixture go-line-above-images
edit go.mod '/^toolchain /d; s/^go 1.27.3$/go 1.27.5/'
check go-line-above-images 1 "Dockerfile image golang:1.27.4-alpine names Go 1.27.4, below the go.mod go line 1.27.5"
-check go-line-above-images 1 "4 problems in 10 pins"
+check go-line-above-images 1 "3 problems in 9 pins"
fixture go-line-above-toolchain
edit go.mod 's/^go 1.27.3$/go 1.27.5/'
@@ -275,7 +271,7 @@ edit Dockerfile 's/golang:1.27.4-alpine(@[^ ]+) AS xray-builder/golang:1.27.3-al
check image-one-stage-below 1 "Dockerfile image golang:1.27.3-alpine names Go 1.27.3, below the security floor 1.27.4"
fixture image-without-digest
-edit Dockerfile 's/golang:1.27.4-alpine@[^ ]+ AS singbox-builder/golang:1.27.4-alpine AS singbox-builder/'
+edit Dockerfile 's/golang:1.27.4-alpine@[^ ]+ AS builder/golang:1.27.4-alpine AS builder/'
check image-without-digest 1 "Dockerfile builds from golang:1.27.4-alpine without an @sha256 digest"
fixture image-floating-tag
@@ -311,7 +307,7 @@ fixture image-at-go-line-below-floor
edit go.mod '/^toolchain /d'
edit Dockerfile 's/golang:1.27.4-alpine(@[^ ]+) AS xray-builder/golang:1.27.3-alpine\1 AS xray-builder/'
check image-at-go-line-below-floor 1 "Dockerfile image golang:1.27.3-alpine names Go 1.27.3, below the security floor 1.27.4"
-check image-at-go-line-below-floor 1 "1 problems in 10 pins"
+check image-at-go-line-below-floor 1 "1 problems in 9 pins"
fixture image-dash-name-below
printf 'FROM golang:1.26.10-alpine@%s AS dev\n' "$digest" >"$tmp/image-dash-name-below/Dockerfile-dev"
@@ -335,7 +331,7 @@ check image-symlinked-name-below 1 "build/Dockerfile image golang:1.26.10-alpine
fixture image-git-dir-ignored
mkdir -p "$tmp/image-git-dir-ignored/.git"
printf 'FROM golang:1.26.10-alpine@%s AS dev\n' "$digest" >"$tmp/image-git-dir-ignored/.git/Dockerfile"
-check image-git-dir-ignored 0 "11 pins checked"
+check image-git-dir-ignored 0 "10 pins checked"
fixture image-continued-from-below
printf 'FROM --platform=$BUILDPLATFORM \\\n golang:1.26.10-alpine@%s AS builder\nRUN go build ./...\n' "$digest" >"$tmp/image-continued-from-below/Dockerfile.wireguard"
@@ -371,7 +367,7 @@ check image-bare-name 1 "Dockerfile.wireguard builds from golang without an @sha
fixture image-lookalike-ignored
printf 'FROM golang-tools:1.0@%s AS tools\nFROM example.com/golang/tools:1.0@%s AS more\n' "$digest" "$digest" >"$tmp/image-lookalike-ignored/Dockerfile.tools"
-check image-lookalike-ignored 0 "11 pins checked"
+check image-lookalike-ignored 0 "10 pins checked"
fixture escape-directive-other-dockerfile
printf '# escape=`\nFROM --platform=$BUILDPLATFORM `\n golang:1.26.10-alpine@%s AS builder\n' "$digest" >"$tmp/escape-directive-other-dockerfile/Dockerfile.wireguard"
@@ -402,14 +398,14 @@ mkdir -p "$tmp/git-tree-ignored-dir/xray-core"
printf 'FROM golang:1.26.10-alpine@%s AS dev\n' "$digest" >"$tmp/git-tree-ignored-dir/xray-core/Dockerfile"
printf 'xray-core/\n' >"$tmp/git-tree-ignored-dir/.gitignore"
git -C "$tmp/git-tree-ignored-dir" init -q
-check git-tree-ignored-dir 0 "11 pins checked"
+check git-tree-ignored-dir 0 "10 pins checked"
fixture git-tree-nested-repo
mkdir -p "$tmp/git-tree-nested-repo/nested"
printf 'FROM golang:1.26.10-alpine@%s AS dev\n' "$digest" >"$tmp/git-tree-nested-repo/nested/Dockerfile"
git -C "$tmp/git-tree-nested-repo/nested" init -q
git -C "$tmp/git-tree-nested-repo" init -q
-check git-tree-nested-repo 0 "11 pins checked"
+check git-tree-nested-repo 0 "10 pins checked"
fixture git-tree-untracked-below
printf 'FROM golang:1.26.10-alpine@%s AS dev\n' "$digest" >"$tmp/git-tree-untracked-below/Dockerfile-dev"
@@ -472,7 +468,7 @@ check nbsp-directive-other-dockerfile 1 "Dockerfile.wireguard sets an escape or
fixture image-continued-after-tag-counted-once
printf 'FROM --platform=$BUILDPLATFORM golang:1.26.10-alpine@%s \\\n AS builder\n' "$digest" >"$tmp/image-continued-after-tag-counted-once/Dockerfile.wireguard"
-check image-continued-after-tag-counted-once 1 "2 problems in 11 pins"
+check image-continued-after-tag-counted-once 1 "2 problems in 10 pins"
fixture go-line-extra-field
edit go.mod 's/^go 1.27.3$/go 1.27.3 extra/'
@@ -552,7 +548,7 @@ check apply-in-other-stage-not-counted 1 "neither a patch applied by the Dockerf
fixture apply-after-stage-ignored
printf 'FROM alpine:3.24.2@%s AS later\nRUN git apply --verbose /patches/other-lower.patch\n\nFROM alpine:3.24.2@%s\nCOPY --from=xray-builder /out/xray /usr/local/bin/xray\n' "$alpine" "$alpine" >>"$tmp/apply-after-stage-ignored/Dockerfile"
gomod_patch v0.60.0 v0.58.0 >"$tmp/apply-after-stage-ignored/patches/other-lower.patch"
-check apply-after-stage-ignored 0 "11 pins checked"
+check apply-after-stage-ignored 0 "10 pins checked"
upstream_fixture() {
fixture "$1"
@@ -563,9 +559,6 @@ ARG XRAY_VERSION=v26.10.31
FROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@$digest AS builder
RUN make build
-FROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@$digest AS singbox-builder
-RUN go build ./cmd/sing-box
-
FROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@$digest AS xray-builder
ARG XRAY_COMMIT=556767e40baa142641838158d6cba743c879e5c3
COPY patches/xray-session-revoke.patch /patches/xray-session-revoke.patch
@@ -581,17 +574,16 @@ RUN go build -o /out/xray ./main
FROM alpine:3.24.2@$alpine
COPY --from=builder /src/main /app/main
COPY --from=xray-builder /out/xray /usr/local/bin/xray
-COPY --from=singbox-builder /out/sing-box /usr/local/bin/sing-box
EOF
printf "XRAY_COMMIT ?= \$(shell sed -n 's/^ARG XRAY_COMMIT=//p' Dockerfile)\n" >"$r/Makefile"
}
upstream_fixture upstream-gomod-meets-floor
-check upstream-gomod-meets-floor 0 "11 pins checked, all at or above Go 1.27.4 and golang.org/x/net v0.60.0"
+check upstream-gomod-meets-floor 0 "10 pins checked, all at or above Go 1.27.4 and golang.org/x/net v0.60.0"
upstream_fixture upstream-gomod-meets-floor-indirect
edit Dockerfile 's/golang.org\/x\/net v0.62.0\$" go.mod/golang.org\/x\/net v0.62.0 \/\/ indirect$" go.mod/g'
-check upstream-gomod-meets-floor-indirect 0 "11 pins checked"
+check upstream-gomod-meets-floor-indirect 0 "10 pins checked"
upstream_fixture upstream-gomod-below-floor
edit Dockerfile 's/golang.org\/x\/net v0.62.0/golang.org\/x\/net v0.59.0/g'
@@ -665,7 +657,7 @@ check upstream-check-in-quoted-backquotes 1 "neither a patch applied by the Dock
upstream_fixture upstream-quoted-substitution-with-inner-quotes
edit Dockerfile 's/^ && git apply --verbose \/patches\/xray-session-revoke.patch \\$/ \&\& test "$(grep -c "golang.org\/x\/net v" go.mod)" = "1" \&\& git apply --verbose \/patches\/xray-session-revoke.patch \\/'
-check upstream-quoted-substitution-with-inner-quotes 0 "11 pins checked"
+check upstream-quoted-substitution-with-inner-quotes 0 "10 pins checked"
upstream_fixture upstream-later-go-get-same-run
edit Dockerfile 's/^ && grep -q "golang.org\/x\/net v0.62.0\$" go.mod$/ \&\& grep -q "golang.org\/x\/net v0.62.0$" go.mod \&\& go get golang.org\/x\/net@v0.50.0/'
@@ -733,7 +725,7 @@ check upstream-workdir-changed-before-check 1 "so the go.mod check need not read
upstream_fixture upstream-one-workdir-before-check
edit Dockerfile 's@^COPY patches/xray-session-revoke.patch /patches/xray-session-revoke.patch$@WORKDIR /xray-src\nCOPY patches/xray-session-revoke.patch /patches/xray-session-revoke.patch@'
-check upstream-one-workdir-before-check 0 "11 pins checked"
+check upstream-one-workdir-before-check 0 "10 pins checked"
upstream_fixture upstream-shell-instruction
edit Dockerfile 's@^RUN go build -o /out/xray ./main$@SHELL ["/bin/sh", "-c", "cd /other \&\& sh -c \\"$0\\""]\nRUN go build -o /out/xray ./main@'
@@ -769,7 +761,7 @@ gomod_patch v0.59.0 v0.61.0 >"$tmp/upstream-later-patch-raises/patches/xray-zz-r
edit Dockerfile 's/^ && grep -q "golang.org\/x\/net v0.62.0\$" go.mod \\$/ \&\& grep -q "golang.org\/x\/net v0.59.0$" go.mod \\/'
edit Dockerfile 's@^ && git apply --verbose /patches/xray-session-revoke.patch \\$@ \&\& git apply --verbose /patches/xray-session-revoke.patch \&\& git apply --verbose /patches/xray-zz-raise.patch \\@'
edit Dockerfile 's/^ && grep -q "golang.org\/x\/net v0.62.0\$" go.mod$/ \&\& grep -q "golang.org\/x\/net v0.61.0$" go.mod/'
-check upstream-later-patch-raises 0 "11 pins checked"
+check upstream-later-patch-raises 0 "10 pins checked"
upstream_fixture upstream-check-contradicts-patch-order
edit Dockerfile 's/^ && grep -q "golang.org\/x\/net v0.62.0\$" go.mod$/ \&\& grep -q "golang.org\/x\/net v0.63.0$" go.mod/'
@@ -825,7 +817,7 @@ check goenv-env 1 "which sets GOTOOLCHAIN to something other than local or sets
fixture gotoolchain-local-accepted
edit Dockerfile 's@^RUN go build -o /out/xray ./main$@ENV GOTOOLCHAIN=local\nRUN go build -o /out/xray ./main@'
-check gotoolchain-local-accepted 0 "11 pins checked"
+check gotoolchain-local-accepted 0 "10 pins checked"
fixture stage-xray-builder-twice
printf "\nFROM --platform=\$BUILDPLATFORM golang:1.27.4-alpine@%s AS Xray-Builder\nRUN go build -o /out/xray ./main\n" "$digest" >>"$tmp/stage-xray-builder-twice/Dockerfile"
@@ -837,7 +829,7 @@ check xray-copied-from-other-stage 1 "the Dockerfile copies /usr/local/bin/xray
fixture xray-copied-from-xray-builder
printf 'COPY --from=xray-builder /out/xray /usr/local/bin/xray\n' >>"$tmp/xray-copied-from-xray-builder/Dockerfile"
-check xray-copied-from-xray-builder 0 "11 pins checked"
+check xray-copied-from-xray-builder 0 "10 pins checked"
inject_before() {
upstream_fixture "$1"
@@ -989,14 +981,14 @@ check xray-path-env-xray-builder 1 "which sets XRAY_EXECUTABLE_PATH"
fixture_before goflags-env-builder 'RUN make build' 'ENV GOFLAGS=-mod=mod'
check goflags-env-builder 1 "which sets GOFLAGS"
-fixture_before goflags-arg-singbox-builder 'RUN go build ./cmd/sing-box' 'ARG GOFLAGS=-mod=mod'
-check goflags-arg-singbox-builder 1 "which sets GOFLAGS"
+fixture_before goflags-arg-builder 'RUN make build' 'ARG GOFLAGS=-mod=mod'
+check goflags-arg-builder 1 "which sets GOFLAGS"
fixture_before goflags-run-export-builder 'RUN make build' 'RUN export GOFLAGS=-mod=mod && make build'
check goflags-run-export-builder 1 "which sets GOFLAGS"
-fixture_before goflags-run-assignment-singbox-builder 'RUN go build ./cmd/sing-box' 'RUN GOFLAGS=-mod=mod go build ./cmd/sing-box'
-check goflags-run-assignment-singbox-builder 1 "which sets GOFLAGS"
+fixture_before goflags-run-assignment-builder 'RUN make build' 'RUN GOFLAGS=-mod=mod make build'
+check goflags-run-assignment-builder 1 "which sets GOFLAGS"
later_run comment-continuation-build $'# note \\\nRUN go build -toolexec=/tmp/t -o /out/xray ./main'
check comment-continuation-build 1 "$not_allowed"
@@ -1138,17 +1130,17 @@ fixture builder-goenv
edit Dockerfile 's@^RUN make build$@ENV GOENV=/tmp/x\nRUN make build@'
check builder-goenv 1 "the Dockerfile builder stage runs 'ENV GOENV=/tmp/x', $toolchain_env"
-fixture singbox-gotoolchain-auto
-edit Dockerfile 's@^RUN go build ./cmd/sing-box$@ENV GOTOOLCHAIN=auto\nRUN go build ./cmd/sing-box@'
-check singbox-gotoolchain-auto 1 "the Dockerfile singbox-builder stage runs 'ENV GOTOOLCHAIN=auto', $toolchain_env"
+fixture builder-gotoolchain-auto
+edit Dockerfile 's@^RUN make build$@ENV GOTOOLCHAIN=auto\nRUN make build@'
+check builder-gotoolchain-auto 1 "the Dockerfile builder stage runs 'ENV GOTOOLCHAIN=auto', $toolchain_env"
-fixture singbox-go-env-write-toolchain
-edit Dockerfile 's@^RUN go build ./cmd/sing-box$@RUN go env -w GOTOOLCHAIN=go1.27.0\nRUN go build ./cmd/sing-box@'
-check singbox-go-env-write-toolchain 1 "the Dockerfile singbox-builder stage runs 'go env -w GOTOOLCHAIN=go1.27.0', $toolchain_env"
+fixture builder-go-env-write-toolchain
+edit Dockerfile 's@^RUN make build$@RUN go env -w GOTOOLCHAIN=go1.27.0\nRUN make build@'
+check builder-go-env-write-toolchain 1 "the Dockerfile builder stage runs 'go env -w GOTOOLCHAIN=go1.27.0', $toolchain_env"
fixture builder-gotoolchain-local-accepted
edit Dockerfile 's@^RUN make build$@ENV GOTOOLCHAIN=local\nRUN make build@'
-check builder-gotoolchain-local-accepted 0 "11 pins checked"
+check builder-gotoolchain-local-accepted 0 "10 pins checked"
into_bin="so it can create /usr/local/bin/xray without the xray-builder stage"
@@ -1217,14 +1209,14 @@ final-copy-dotenv|COPY .env.example /app/.env
final-copy-dotenv-relative|COPY --from=filter-assets /assets/pgfilter_index.json .env
final-copy-app-other|COPY --from=builder /src/main /app/main2
final-copy-dot-segment-app|COPY --from=builder /src/main /app/./.env
-final-copy-flag|COPY --chmod=755 --from=singbox-builder /out/sing-box /usr/local/bin/sing-box
+final-copy-flag|COPY --chmod=755 --from=builder /src/main /app/main
final-copy-share-other|COPY --from=builder /src/main /usr/local/share/xray/xray
EOF
fixture final-copy-real-set
printf '%s\n' 'WORKDIR /app' 'COPY --from=builder /src/main /app/main' 'COPY --from=xray-builder /out/xray /usr/local/bin/xray' \
'COPY --from=geo-assets /geo/geoip.dat /usr/local/share/xray/geoip.dat' 'COPY --from=geo-assets /geo/geosite.dat /usr/local/share/xray/geosite.dat' \
- 'COPY --from=singbox-builder /out/sing-box /usr/local/bin/sing-box' 'COPY --from=filter-assets /assets/pgfilter.dat /usr/local/share/xray/pgfilter.dat' \
+ 'COPY --from=filter-assets /assets/pgfilter.dat /usr/local/share/xray/pgfilter.dat' \
'COPY --from=filter-assets /assets/pgfilter_index.json /usr/local/share/xray/pgfilter_index.json' >>"$tmp/final-copy-real-set/Dockerfile"
check final-copy-real-set 0 "pins checked"
@@ -1261,7 +1253,7 @@ edit .github/workflows/publish-release.yml 's/1.27.4/1.26.6/'
edit Dockerfile 's/golang:1.27.4-alpine/golang:1.26.6-alpine/'
edit Dockerfile.wireguard 's/golang:1.27.4-alpine/golang:1.26.6-alpine/'
gomod_patch v0.58.0 v0.59.0 >"$tmp/base-tree-shape/patches/xray-x-net-0.60.0.patch"
-check base-tree-shape 1 "12 problems in 12 pins"
+check base-tree-shape 1 "11 problems in 11 pins"
printf 'test-toolchain-floor: %d passed, %d failed\n' "$pass" "$failed"
[ "$failed" = 0 ]
diff --git a/scripts/test_workflow_policy.sh b/scripts/test_workflow_policy.sh
index 884ea71c..a319aaa7 100644
--- a/scripts/test_workflow_policy.sh
+++ b/scripts/test_workflow_policy.sh
@@ -167,15 +167,15 @@ must_refuse "test suite narrowed to one package tree" run-tests.yml \
must_refuse "regular test suite replaced by a no-op" run-tests.yml \
$' TEST_INTEGRATION=true go test -v -p 1 "${packages[@]}"\n' $' echo skipped\n'
must_refuse "race detector step removed" run-tests.yml \
- $' - name: Run the controller and backend tests under the race detector\n run: |\n TEST_INTEGRATION=true CGO_ENABLED=1 SINGBOX_EXECUTABLE_PATH="$RUNNER_TEMP/sing-box" \\\n go test -race -timeout 20m -v -p 1 ./controller/...\n TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./backend/...\n' ''
+ $' - name: Run the controller and backend tests under the race detector\n run: |\n TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./controller/...\n TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./backend/...\n' ''
must_refuse "race detector dropped from the controller run" run-tests.yml \
- $' go test -race -timeout 20m -v -p 1 ./controller/...\n' $' go test -timeout 20m -v -p 1 ./controller/...\n'
+ $' TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./controller/...\n' $' TEST_INTEGRATION=true CGO_ENABLED=1 go test -timeout 20m -v -p 1 ./controller/...\n'
must_refuse "race detector dropped from the backend run" run-tests.yml \
$' TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./backend/...\n' $' TEST_INTEGRATION=true CGO_ENABLED=1 go test -timeout 20m -v -p 1 ./backend/...\n'
must_refuse "backend dropped from the race run" run-tests.yml \
$' TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./backend/...\n' ''
-must_refuse "sing-box binary dropped from the controller race run" run-tests.yml \
- $' SINGBOX_EXECUTABLE_PATH="$RUNNER_TEMP/sing-box" \\\n' $' \\\n'
+must_refuse "controller dropped from the race run" run-tests.yml \
+ $' TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./controller/...\n' ''
must_refuse "Xray patch tests run without the race detector" run-tests.yml \
$' CGO_ENABLED=1 GOFLAGS=-race make test_xray_patches\n' $' make test_xray_patches\n'
must_refuse "Xray patch guard replay removed" run-tests.yml \
diff --git a/scripts/toolchain_floor.sh b/scripts/toolchain_floor.sh
index 25ad0e7b..b1edf01a 100644
--- a/scripts/toolchain_floor.sh
+++ b/scripts/toolchain_floor.sh
@@ -344,7 +344,6 @@ final_copies='--from=builder /src/main /app/main
--from=xray-builder /out/xray /usr/local/bin/xray
--from=geo-assets /geo/geoip.dat /usr/local/share/xray/geoip.dat
--from=geo-assets /geo/geosite.dat /usr/local/share/xray/geosite.dat
---from=singbox-builder /out/sing-box /usr/local/bin/sing-box
--from=filter-assets /assets/pgfilter.dat /usr/local/share/xray/pgfilter.dat
--from=filter-assets /assets/pgfilter_index.json /usr/local/share/xray/pgfilter_index.json'
git_move_re='(^|[^[:alnum:]_.-])git[[:space:]]+(-[^[:space:]]+[[:space:]]+)*(checkout|reset|switch|restore|pull|merge|rebase|cherry-pick|am|fetch|stash|clone|read-tree|update-index|worktree|submodule)([[:space:]]|$)'
@@ -766,7 +765,7 @@ while IFS=$'\t' read -r safety element; do
fi
if [ "$final_stage" = 1 ] && [ "$keyword" = COPY ] && ! final_copy_allowed "$element"; then
checked=$((checked + 1))
- refuse "the Dockerfile final stage runs '${element:0:120}', which is not one of the image's own copies (/app/main from builder, /usr/local/bin/xray from xray-builder, /usr/local/bin/sing-box from singbox-builder and the four /usr/local/share/xray files from geo-assets and filter-assets), so it can replace /usr/local/bin/xray or write a .env that ./main loads"
+ refuse "the Dockerfile final stage runs '${element:0:120}', which is not one of the image's own copies (/app/main from builder, /usr/local/bin/xray from xray-builder and the four /usr/local/share/xray files from geo-assets and filter-assets), so it can replace /usr/local/bin/xray or write a .env that ./main loads"
fi
if [ "$final_stage" = 1 ] && ! final_stage_inst_allowed "$keyword" "$element"; then
checked=$((checked + 1))
diff --git a/scripts/upstream_drift.sh b/scripts/upstream_drift.sh
index b71f03ff..9b0b3b68 100755
--- a/scripts/upstream_drift.sh
+++ b/scripts/upstream_drift.sh
@@ -6,8 +6,8 @@ upstream_url=${UPSTREAM_URL:-https://github.com/PasarGuard/node.git}
upstream_slug=${UPSTREAM_SLUG:-PasarGuard/node}
target=${DRIFT_TARGET:-HEAD}
fetch=${UPSTREAM_FETCH:-1}
-components=${DRIFT_COMPONENTS:-node xray sing-box sing-quic}
-all_components='node xray sing-box sing-quic'
+components=${DRIFT_COMPONENTS:-node xray}
+all_components='node xray'
api_url=${GITHUB_API_URL:-https://api.github.com}
max_api_pages=${DRIFT_MAX_API_PAGES:-50}
categories='rejected|superseded|pending|not-applicable|allowed-merge'
@@ -958,22 +958,10 @@ dockerfile_arg() {
die "Dockerfile stage $2 gets ARG $1 from more than one declaration with a value, so the build may use another value than the check reads"
}
-gomod_version() {
- awk -v module="$1" '{ sub(/^require[[:space:]]+/, "") } $1 == module && $2 != "=>" { print $2; exit }'
-}
-
gomod_replace() {
awk -v module="$1" '{ for (i = 1; i < NF; i++) if ($i == module && $(i + 1) == "=>") { print $(i + 2), $(i + 3); exit } }'
}
-module_rev() {
- if printf '%s\n' "$1" | grep -Eq '[.-][0-9]{14}-[0-9a-f]{12}$'; then
- printf '%s\n' "${1##*-}"
- else
- printf 'refs/tags/%s\n' "${1%+incompatible}"
- fi
-}
-
module_git_url() {
printf '%s\n' "$1" | awk -F/ '$1 == "github.com" && NF >= 3 { print "https://github.com/" $2 "/" $3 ".git"; ok = 1 } END { exit !ok }' ||
die "cannot derive a GitHub repository from module $1"
@@ -1199,34 +1187,6 @@ if enabled xray; then
fi
fi
-if enabled sing-box; then
- singbox_version=$(dockerfile_arg SINGBOX_VERSION singbox-builder)
- [ -n "$singbox_version" ] || die "Dockerfile has no ARG SINGBOX_VERSION"
- check_thirdparty sing-box SagerNet/sing-box github.com/sagernet/sing-box oldstable \
- "refs/tags/$singbox_version" "Dockerfile ARG SINGBOX_VERSION $singbox_version" "" ""
-fi
-
-if enabled sing-quic; then
- singbox_repo=$(dockerfile_arg SINGBOX_REPO singbox-builder)
- singbox_commit=$(dockerfile_arg SINGBOX_COMMIT singbox-builder)
- printf '%s\n' "$singbox_commit" | grep -Eqx '[0-9a-f]{40}' ||
- die "Dockerfile ARG SINGBOX_COMMIT is not a full commit sha: '$singbox_commit'"
- fork_gd=$store/sing-box-fork.git
- if [ "$fetch" = 1 ]; then
- [ -d "$fork_gd" ] || git init --quiet --bare "$fork_gd"
- git --git-dir="$fork_gd" config remote.fork.url "$singbox_repo"
- git --git-dir="$fork_gd" config remote.fork.promisor true
- git --git-dir="$fork_gd" config remote.fork.partialclonefilter blob:none
- git --git-dir="$fork_gd" fetch --quiet --depth=1 --no-tags --filter=blob:none fork "$singbox_commit" ||
- die "fetching $singbox_commit from $singbox_repo failed"
- fi
- singquic_version=$(git --git-dir="$fork_gd" show "$singbox_commit:go.mod" | gomod_version github.com/sagernet/sing-quic) ||
- die "cannot read go.mod of $singbox_repo at $singbox_commit"
- [ -n "$singquic_version" ] || die "the sing-box fork go.mod does not require github.com/sagernet/sing-quic"
- check_thirdparty sing-quic SagerNet/sing-quic github.com/sagernet/sing-quic main \
- "$(module_rev "$singquic_version")" "sing-box fork go.mod requires $singquic_version" "" ""
-fi
-
if [ "$components" = "$all_components" ]; then
while read -r id _ <&7; do
if ! grep -qx "$id" "$work/used"; then
diff --git a/scripts/upstream_drift_bypass_test.sh b/scripts/upstream_drift_bypass_test.sh
index 6dec5ada..b08837b6 100755
--- a/scripts/upstream_drift_bypass_test.sh
+++ b/scripts/upstream_drift_bypass_test.sh
@@ -135,10 +135,9 @@ xray_fixture() {
git -C "$f" fetch -q "$s/upw" "$(sha_of "$s/upw" U1)"
git -C "$f" cherry-pick -x "$(sha_of "$s/upw" U1)" >/dev/null
third_party "$1" xray X main
- third_party "$1" sing-box B oldstable
case $4 in
X*) carried=$(sha_of "$s/xray-up" "$4") ;;
- *) carried=$(sha_of "$s/sing-box-up" "$4") ;;
+ *) carried=$4 ;;
esac
mkdir -p "$f/patches"
{
@@ -148,7 +147,6 @@ xray_fixture() {
printf '%s\n' "$3" >"$f/Makefile"
{
printf 'FROM scratch AS builder\nRUN true\n\n'
- printf 'FROM scratch AS singbox-builder\nARG SINGBOX_VERSION=v1.0.0\n\n'
printf 'FROM scratch AS xray-builder\nARG XRAY_COMMIT=%s\n' "$(sha_of "$s/xray-up" X0)"
printf '%s\n' "$2"
printf '%s\n' "${5-$xray_tail}"
@@ -258,7 +256,7 @@ git -C "$tmp/bypass-builder-on-an-unpinned-external-image/fork" add -A
commit "$tmp/bypass-builder-on-an-unpinned-external-image/fork" -m "build xray on an external image"
check bypass-builder-on-an-unpinned-external-image 1 DRIFT_COMPONENTS="node xray"
-xray_fixture bypass-pin-read-from-a-global-arg "$xray_applied" "$xray_makefile" B1
+xray_fixture bypass-pin-read-from-a-global-arg "$xray_applied" "$xray_makefile" "$(printf 'b%.0s' $(seq 1 40))"
perl -pi -e 's/^ARG XRAY_COMMIT=(\w+)$/ARG XRAY_VERSION=v1.0.0 \\\n XRAY_COMMIT=$1/' \
"$tmp/bypass-pin-read-from-a-global-arg/fork/Dockerfile"
xray_prepend bypass-pin-read-from-a-global-arg "ARG XRAY_COMMIT=$(sha_of "$tmp/bypass-pin-read-from-a-global-arg/xray-up" X1)"
diff --git a/scripts/upstream_drift_test.sh b/scripts/upstream_drift_test.sh
index 79d18a98..a8268389 100755
--- a/scripts/upstream_drift_test.sh
+++ b/scripts/upstream_drift_test.sh
@@ -311,10 +311,9 @@ xray_fixture() {
git -C "$f" fetch -q "$s/upw" "$(sha_of "$s/upw" U1)"
git -C "$f" cherry-pick -x "$(sha_of "$s/upw" U1)" >/dev/null
third_party "$1" xray X main
- third_party "$1" sing-box B oldstable
case $4 in
X*) carried=$(sha_of "$s/xray-up" "$4") ;;
- *) carried=$(sha_of "$s/sing-box-up" "$4") ;;
+ *) carried=$4 ;;
esac
mkdir -p "$f/patches"
{
@@ -324,7 +323,6 @@ xray_fixture() {
printf '%s\n' "$3" >"$f/Makefile"
{
printf 'FROM scratch AS builder\nRUN true\n\n'
- printf 'FROM scratch AS singbox-builder\nARG SINGBOX_VERSION=v1.0.0\n\n'
printf 'FROM scratch AS xray-builder\nARG XRAY_COMMIT=%s\n' "$(sha_of "$s/xray-up" X0)"
printf '%s\n' "$2"
printf '%s\n' "${5-$xray_tail}"
@@ -416,10 +414,6 @@ RUN git apply --verbose /patches/xray-fix.patch" 'build_xray:
for patch in $(CURDIR)/patches/xray-*.patch; do git -C "$(XRAY_SRC)" apply --verbose "$$patch" || true; done' X1
check xray-patch-makefile-failure-ignored 1 DRIFT_COMPONENTS="node xray"
-xray_fixture xray-patch-names-another-component "$xray_copy
-RUN git apply --verbose /patches/xray-fix.patch" "$xray_makefile" B1
-check xray-patch-names-another-component 1 DRIFT_COMPONENTS="node sing-box"
-
xray_fixture xray-patch-shell-comment "$xray_copy
RUN true # && git apply --verbose /patches/xray-fix.patch" "$xray_makefile" X1
check xray-patch-shell-comment 1 DRIFT_COMPONENTS="node xray"
@@ -871,7 +865,7 @@ check xray-branch-scope-after-merge 1 DRIFT_COMPONENTS="node xray"
xray_fixture xray-build-crlf-hides-the-builder-stage "$xray_copy
RUN git init -q . && git apply --verbose /patches/xray-fix.patch" "$xray_makefile" X1
-xray_rewrite xray-build-crlf-hides-the-builder-stage 's/^ARG SINGBOX_VERSION=v1\.0\.0\n/ARG SINGBOX_VERSION=v1.0.0 \\\r\n/'
+xray_rewrite xray-build-crlf-hides-the-builder-stage 's/^RUN true\n/RUN true \\\r\n/'
check xray-build-crlf-hides-the-builder-stage 2 DRIFT_COMPONENTS="node xray"
if ! grep -q 'has no stage named xray-builder' "$tmp/xray-build-crlf-hides-the-builder-stage/out"; then
printf 'FAIL %-28s does not say that the CRLF hid the xray-builder stage\n' xray-build-crlf-hides-the-builder-stage
@@ -1165,22 +1159,6 @@ if ! grep -q '^DEVONLY xray commit [0-9a-f]* \[side\] XD fix a panic on side$'
failed=$((failed + 1))
fi
-xray_fixture singbox-commit-off-the-pinned-release-line "$tp_applied" "$xray_makefile" X1
-s=$tmp/singbox-commit-off-the-pinned-release-line
-printf '%s rejected: fixture, the pinned oldstable fix stays out of the fork on purpose\n' \
- "$(sha_of "$s/sing-box-up" B1)" >>"$s/waivers"
-git -C "$s/sing-box-up" checkout -q -b stable
-printf 'package core\n\nvar nextline = true\n' >"$s/sing-box-up/nextline.go"
-git -C "$s/sing-box-up" add -A
-commit "$s/sing-box-up" -m "BS fix a panic on stable"
-git -C "$s/sing-box-up" checkout -q oldstable
-tp_refetch singbox-commit-off-the-pinned-release-line sing-box
-check singbox-commit-off-the-pinned-release-line 0 DRIFT_COMPONENTS="node sing-box"
-if ! grep -q '^DEVONLY sing-box commit [0-9a-f]* \[stable\] BS fix a panic on stable$' "$tmp/singbox-commit-off-the-pinned-release-line/out"; then
- printf 'FAIL %-28s does not report a commit off the pinned release line as DEVONLY\n' singbox-commit-off-the-pinned-release-line
- failed=$((failed + 1))
-fi
-
xray_fixture xray-released-side-branch-commit-still-blocks "$tp_applied" "$xray_makefile" X1
s=$tmp/xray-released-side-branch-commit-still-blocks
git -C "$s/xray-up" checkout -q -b side
@@ -1215,7 +1193,7 @@ fi
xray_fixture xray-pin-declared-in-another-stage "$xray_copy
RUN git init -q . && git apply --verbose /patches/xray-fix.patch" "$xray_makefile" X1
-xray_rewrite xray-pin-declared-in-another-stage "s/^ARG SINGBOX_VERSION=v1\.0\.0\$/ARG SINGBOX_VERSION=v1.0.0\nARG XRAY_COMMIT=$(sha_of "$tmp/xray-pin-declared-in-another-stage/xray-up" X1)/"
+xray_rewrite xray-pin-declared-in-another-stage "s/^RUN true\$/RUN true\nARG XRAY_COMMIT=$(sha_of "$tmp/xray-pin-declared-in-another-stage/xray-up" X1)/"
check xray-pin-declared-in-another-stage 0 DRIFT_COMPONENTS="node xray"
xray_fixture xray-pin-only-global-without-a-stage-declaration "$xray_copy
diff --git a/scripts/workflow_gates.lock b/scripts/workflow_gates.lock
index 5a5769fb..22dde47b 100644
--- a/scripts/workflow_gates.lock
+++ b/scripts/workflow_gates.lock
@@ -2,7 +2,7 @@ run-tests.yml * 21ff15a504e7403cf1038c2401b70f0337c4e6ef8b3eb9089877667dbedb0b1b
run-tests.yml govulncheck 0a5b0c53d492609d6a51d3b7d96db2251b609c1368c4562765e9e9ec924ad812
run-tests.yml private-target-harness 03288ce9b7e51c00e438c63bbac794f7865a83c52dcbdf5d717710f51b2b0a79
run-tests.yml repo-hygiene 7808ccabd4952013a46d04bf355897cce186e78ae7ae83fb606020ca51968a09
-run-tests.yml test 9fa9b3b26372c1cce29c294bf809a01e639c9b43a2574e7f8906f6a3f96e1ca4
+run-tests.yml test ea85299aadd01a614c37d8ce030324baf42c7a5ef290519e3768bae758b4ae0f
run-tests.yml wireguard-integration 6cd021bd34e56427ffa28521e9f73e36d69dbbb03b3412e21d1119bf5b94e7e6
run-tests.yml workflow-policy b8c391b01fd781ae333301f173c05e89498ea26275815dc1abf0ffe7bc4f3289
upstream-drift.yml * 21ff15a504e7403cf1038c2401b70f0337c4e6ef8b3eb9089877667dbedb0b1b
]