Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c4f43cca5c |
@@ -1219,169 +1219,5 @@
|
||||
],
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.6"
|
||||
},
|
||||
"Windows037ExitReliabilityDelta": {
|
||||
"CandidateSha256": "ee3751c05cec1a2ac0b5f53e8c9cb9d644dc8d5aa1b28b9879f03bfd8e4af7a4",
|
||||
"ExampleEndpointChanges": [
|
||||
{
|
||||
"Count": 2,
|
||||
"Path": "windows/ClientRuntimeSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 4,
|
||||
"Path": "windows/KnownTailnetEndpoints.cs"
|
||||
},
|
||||
{
|
||||
"Count": 3,
|
||||
"Path": "windows/LearningSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/LearningTransportSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/NetworkHandoverSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/PlatformBootstrapTransport.cs"
|
||||
},
|
||||
{
|
||||
"Count": 5,
|
||||
"Path": "windows/PlatformBootstrapTransportSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 4,
|
||||
"Path": "windows/PrivateAuxiliaryRouting.cs"
|
||||
},
|
||||
{
|
||||
"Count": 25,
|
||||
"Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/PublicTailnetSelectionSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 65,
|
||||
"Path": "windows/TailnetTransportSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/TransportPlanSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/ConnectionSelfTest.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/GitReleasePolicySelfTest.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/InstallationIntegration.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/KnownTailnetEndpoints.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 2,
|
||||
"Path": "windows/LearningSelfTest.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/MainForm.Dashboard.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 2,
|
||||
"Path": "windows/MainForm.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/PlatformBootstrapTransport.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 6,
|
||||
"Path": "windows/PlatformBootstrapTransportSelfTest.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/PrivateAuxiliaryRouting.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 7,
|
||||
"Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 2,
|
||||
"Path": "windows/TailnetTransportProbe.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 3,
|
||||
"Path": "windows/TailnetTransportSelfTest.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 2,
|
||||
"Path": "windows/TunConfigBuilder.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/VpnApiClient.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/XrayManager.cs",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/installer/VPNPlus.nsi",
|
||||
"RuleSet": "windows-monitor-20261027"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/KnownTailnetEndpoints.cs",
|
||||
"RuleSet": "windows-runtime-repair-20261106"
|
||||
},
|
||||
{
|
||||
"Count": 3,
|
||||
"Path": "windows/TailnetTransportSelfTest.cs",
|
||||
"RuleSet": "windows-runtime-repair-20261106"
|
||||
}
|
||||
],
|
||||
"FrozenSha256": "d2c0af09f08657bcd365c342cfbad681d83be8a468ad086036830fae81c63a7b",
|
||||
"Omitted": [
|
||||
"windows/assets/login-cloud-scene-v1.jpg"
|
||||
],
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "fe0fa2a01f6e1eb541ff85fc96f5ef978cb6716846c27eea0a8e8eccbfa10288",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "ac40dd3a6ceb1391596dd55265e299c03d7419ee",
|
||||
"PublicDownloadDomainsRetained": [
|
||||
"pro.ucvl.cn"
|
||||
],
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 纵横家开源源码
|
||||
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.7、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.6、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
|
||||
| 目录 | 内容与状态 |
|
||||
| --- | --- |
|
||||
|
||||
+8
-27
@@ -4,7 +4,7 @@
|
||||
"ExportDiffersFromOriginalCandidates": true,
|
||||
"FilesBeforeProvenanceAndAudit": {
|
||||
"LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"README.md": "3b3602a1b7eabfe504125f6293b5bd27dcb42cb47f9516cdce5949fdd868ccfb",
|
||||
"README.md": "1e974eb4f09d4bf219b8840ae7826a0d34423ddcfe1ed87932327ad35f29071b",
|
||||
"SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c",
|
||||
"THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
|
||||
"android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c",
|
||||
@@ -204,14 +204,9 @@
|
||||
"windows/AppPaths.cs": "2bac68512acfb68b4f3dad0d30c9ee17eb6f576eeb73c6a453501d4ea184488e",
|
||||
"windows/Brand.cs": "621a1c5b75880cbf4f88b482dc58bdd3c98e0f4d156bf816d23d63d48e199bca",
|
||||
"windows/ChartFreshnessSelfTest.cs": "4af3f37b14296fc34097f5708f8f0f78fb1683c1b091459091c425a11c500a62",
|
||||
"windows/ClientExitRecoveryFixture.cs": "577b11849cd8ca52a6f5af8f21c2e79411dd6a84d9f0c972d4738610fd6e02dc",
|
||||
"windows/ClientRuntime.cs": "6b1babd9cbe4cafe463205905d90a83ce9180b8e43e278b9b47fb9ec7eecd03b",
|
||||
"windows/ClientRuntimeSelfTest.cs": "9677ffbb300f5b73b64290339d5a8abb29c2c0edfb586e3da6cea03f97ad713f",
|
||||
"windows/ClientShutdownChildSelfTest.cs": "4cb5f65087a45bc5360e2a4d8a5a8d792b9c7f3628b55a2051a07b6e452a9a14",
|
||||
"windows/ClientShutdownScope.cs": "7adef7ac0ebff04453433d6e460ca4590d9e5dc7be3e45567d14c0a6660973fe",
|
||||
"windows/ClientShutdownSelfTest.cs": "8a7a670f4e7446f46143e69424c9d1ea95671c1a72d8e054493125339a3fca76",
|
||||
"windows/ClientShutdownUiSelfTest.cs": "a99b00e14f4eae28f7da3b02ad3ed93544ad8d81f1b7d8e99b7011eec163076b",
|
||||
"windows/ClientUpdateFlow.cs": "9f9b1490487171e67c3e78d18652808a0f6fbb64f38c8f2dbaa96c7d7476d69a",
|
||||
"windows/ClientShutdownScope.cs": "f5944b57ccb4616dbd32ee2952b56dd0c9feccb7c556d8954092c88354a78d41",
|
||||
"windows/ClientUpdater.cs": "6c6265bf7946e4d1323d6ff94596409b3281ed396376263aaff22cf223c53a42",
|
||||
"windows/ConnectionAcceptanceTrace.cs": "c9efd15e19672a5ac3b4b807c96a3de3db3ff2fd373e13494a548df51fecdd9a",
|
||||
"windows/ConnectionAuthorizationLease.cs": "3edbd5123c051c797c488b49bcd7204d8c1a0c5a0743bfec95ffa4ab0bdd9bfc",
|
||||
@@ -258,7 +253,7 @@
|
||||
"windows/MainForm.Selection.cs": "71d3884eb6535b1c8095379585a7479c5d7dd35d00e59da4dabfa673557f17fa",
|
||||
"windows/MainForm.TailnetTraffic.cs": "bc48728563f163cc8553b288bcccd71e7d756f8beb11c13cb486652024c4b8d4",
|
||||
"windows/MainForm.TransportSelection.cs": "7e7bf74f16cb902b71da5a13117db06e9cdf4ea6121511a5ebceaf017bd1f919",
|
||||
"windows/MainForm.cs": "e781334e1c13c5513d589a94c02522c1a5601f06fd39f909811a1130b4ecee2d",
|
||||
"windows/MainForm.cs": "924c7989a962b66555de1bff3727b0d0aaa9c21770b7d491c333b32b4c874dc5",
|
||||
"windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
|
||||
"windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46",
|
||||
"windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73",
|
||||
@@ -286,12 +281,12 @@
|
||||
"windows/PrivateAuxiliaryRoutingSelfTest.cs": "8b2e867f562017e680def8f74c7fba972404442816abae7bf54fcab5d47339df",
|
||||
"windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf",
|
||||
"windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3",
|
||||
"windows/Program.cs": "93ac54d0c1656d4eceb4c9e95372572e693af5933e7614e6e875acf0a5ab8e7f",
|
||||
"windows/Program.cs": "c530738bc80c6da198dcf51615773793a71eb780b1c7f3389eb8a0f6fadf08a0",
|
||||
"windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0",
|
||||
"windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec",
|
||||
"windows/PublicTailnetSelection.cs": "68b6dd3d5c77c3253046f9b90e22742c1f2852e07d07157daa296512370fada7",
|
||||
"windows/PublicTailnetSelectionSelfTest.cs": "7b5e7352fe4529e01ce537d488a5cfcc8f5259f98bbe307846cb36a7144cacac",
|
||||
"windows/README.md": "20cf8d77eee9f07e2cfaef393bfbb986af0eec7de45a5aaa915309bff8ea4baf",
|
||||
"windows/README.md": "18c4125a27f5d63fbee3dab9bab099ad4b9cd863e639bb01ee6ec2fedc42c3bc",
|
||||
"windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1",
|
||||
"windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9",
|
||||
"windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e",
|
||||
@@ -323,11 +318,11 @@
|
||||
"windows/UpdateSelfTest.cs": "fcb73067484cad50618f0ce93e087fa36a1cc3b40a10173d26a2b0230b0b77e1",
|
||||
"windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1",
|
||||
"windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069",
|
||||
"windows/VPNPlus.csproj": "b1f1e3d2663e08b32feaaca50f5a5888a57eb49c73f05f7d9f59ea8bf34367a7",
|
||||
"windows/VPNPlus.csproj": "e4d0b0715a809053b0b1c8a35d6994ab05784334fbf65f4dfacf087697134812",
|
||||
"windows/VpnApiClient.cs": "5bb824cd89d4d8fa251f10a66f4c284c58118b773f877aa07c9700fe271216a8",
|
||||
"windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c",
|
||||
"windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be",
|
||||
"windows/XrayManager.cs": "8befd495ca283b529d3c0a44f243b4e6b07b1387ecf281e2fc82afaf2f6bbe9b",
|
||||
"windows/XrayManager.cs": "38d9582cd30d430aa2f1cc42494f4cbdb2cb6190e96721fa3493ec6f828b6b36",
|
||||
"windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5",
|
||||
"windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6",
|
||||
"windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163",
|
||||
@@ -372,8 +367,7 @@
|
||||
"windows/release/RELEASE-NOTES-0.3.3.md": "18e1f04a925b82668813cb7bde18d29790fa6218d6726887b0ad3cabec253dea",
|
||||
"windows/release/RELEASE-NOTES-0.3.4.md": "10f0a3edd111932ea92e25581208ac527990b515ee1c73bbd7bd4acba734936f",
|
||||
"windows/release/RELEASE-NOTES-0.3.5.md": "4b92799fbd145660732a1748828d03f0defe179709bc77b7e13e9de693ccc304",
|
||||
"windows/release/RELEASE-NOTES-0.3.6.md": "b5ce5826c244a9159783fc408e09cfd923140dc4ac8c716d8dff2e4c268776b1",
|
||||
"windows/release/RELEASE-NOTES-0.3.7.md": "74abb193dea9ff6ae076e3919947fee98590b57b97e96d89b55fab8e30e66da5"
|
||||
"windows/release/RELEASE-NOTES-0.3.6.md": "b5ce5826c244a9159783fc408e09cfd923140dc4ac8c716d8dff2e4c268776b1"
|
||||
},
|
||||
"IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6",
|
||||
"Kind": "clean-history-free-open-source-export",
|
||||
@@ -673,18 +667,5 @@
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.6"
|
||||
},
|
||||
"Windows037ExitReliabilityDelta": {
|
||||
"CandidateSha256": "ee3751c05cec1a2ac0b5f53e8c9cb9d644dc8d5aa1b28b9879f03bfd8e4af7a4",
|
||||
"FrozenSha256": "d2c0af09f08657bcd365c342cfbad681d83be8a468ad086036830fae81c63a7b",
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "fe0fa2a01f6e1eb541ff85fc96f5ef978cb6716846c27eea0a8e8eccbfa10288",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "ac40dd3a6ceb1391596dd55265e299c03d7419ee",
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.7"
|
||||
},
|
||||
"WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 UCVL (Youchuang Future)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Account bandwidth policy source supplement
|
||||
|
||||
MIT source only; not an operational deployment or an enforcement claim.
|
||||
Add these six overlay files to a compatible legacy Django platform in an
|
||||
independent review branch. Existing platform modules and licenses remain intact.
|
||||
Ordinary account policy defaults are 500 KiB/s in each direction. Administrator
|
||||
values may range from 1 to 10240 KiB/s. The existing operator-approved exemption
|
||||
is bound to a fixed account identity and is not transferred by email changes.
|
||||
|
||||
The additive migration changes only shared_budget policy configuration. It
|
||||
preserves the existing exempt owner's policy and exemption, fills missing ordinary
|
||||
policies, and locks accounts before policy DDL to follow the registration order.
|
||||
It does not activate a limiter. Both budget switches must remain disabled until
|
||||
the separate executor supports the configured rate and real traffic is accepted.
|
||||
Old executors may still reject rates above 204800 bytes/s.
|
||||
|
||||
The included real-Django checks require your compatible legacy platform fixture
|
||||
at the sibling directory legacy-platform-fixture. Run tests/run_policy_checks.py
|
||||
with --stage red or green and a fresh --run-id. Tests build an isolated database;
|
||||
they do not connect to a deployed server. clone_validation.py exposes an explicit
|
||||
validate(before) entry and rolls back synthetic writes. Local SQLite checks do
|
||||
not substitute for PostgreSQL clone migration and concurrency acceptance.
|
||||
|
||||
No production database, credentials, real endpoint map, deployment driver,
|
||||
production binding, virtual environment or operational evidence is published.
|
||||
SOURCE-PROVENANCE.json records original and sanitized-source hashes, not private
|
||||
source history. No existing root module is replaced by this supplement.
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"DeploymentPerformed": false,
|
||||
"Feature": "account-rate-policy-default-500",
|
||||
"License": "MIT",
|
||||
"OriginalManifestSha256": "6bde5e669c1b1222b919a575083a6d53e266a27fc3f6ccd484b6a8b53d6ef5dc",
|
||||
"OriginalSourceSha256": {
|
||||
"overlay/shared_budget/allocator.py": "e8f4219ec616edc2c370c98986b3dd47ea86d8b2181aec385d504c3f3e218a87",
|
||||
"overlay/shared_budget/migrations/0002_account_rate_500.py": "78d6bf29212e91c172ced7d17ec051ce7accf741c0b3a087a61123366d992daa",
|
||||
"overlay/shared_budget/models.py": "375950395f3e1366cf0004c1e49bdc6de5b8b27aa82f5ca3ca293a4ca847bdbf",
|
||||
"overlay/shared_budget/policy.py": "40ef4d6deb764e6a301dd4fcd73b2fc2539da3ed44c3840351887b4da066f79b",
|
||||
"overlay/shared_budget/web_context.py": "70d4aaf2fa80c1dac19b54f0abf0d630a1acbcf27199e3af40da1433d0c8e5e3",
|
||||
"overlay/templates/includes/admin_budget.html": "2d78a88ffdeae943d4d08bde2d2bad55481d2d2c502ab44981dff2fef7a59b0d",
|
||||
"tests/clone_validation.py": "52d319ecca7cc9e562fb552f42735894f75abbf1f82ffcd0d562a8aa165ba720",
|
||||
"tests/run_policy_checks.py": "eb3bb110cf1062f7b707efadf9501e8463ccb291709b034c0a3c0c8f3e947509"
|
||||
},
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAcceptanceAsserted": false,
|
||||
"SanitizedSourceSha256": {
|
||||
"backend/account-rate-500-20261106/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/account-rate-500-20261106/README.md": "ee2b398587b860afa93b4e4901f8d52616d2bd2e15b86ee75df2456bce12a1f8",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/allocator.py": "e8f4219ec616edc2c370c98986b3dd47ea86d8b2181aec385d504c3f3e218a87",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/migrations/0002_account_rate_500.py": "78d6bf29212e91c172ced7d17ec051ce7accf741c0b3a087a61123366d992daa",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/models.py": "375950395f3e1366cf0004c1e49bdc6de5b8b27aa82f5ca3ca293a4ca847bdbf",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/policy.py": "40ef4d6deb764e6a301dd4fcd73b2fc2539da3ed44c3840351887b4da066f79b",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/web_context.py": "70d4aaf2fa80c1dac19b54f0abf0d630a1acbcf27199e3af40da1433d0c8e5e3",
|
||||
"backend/account-rate-500-20261106/overlay/templates/includes/admin_budget.html": "2d78a88ffdeae943d4d08bde2d2bad55481d2d2c502ab44981dff2fef7a59b0d",
|
||||
"backend/account-rate-500-20261106/tests/clone_validation.py": "52d319ecca7cc9e562fb552f42735894f75abbf1f82ffcd0d562a8aa165ba720",
|
||||
"backend/account-rate-500-20261106/tests/run_policy_checks.py": "d99e54ddd1a293944b309df218c0846ae7ab933451aa7802cd0eafb4e3eb7592"
|
||||
},
|
||||
"Schema": 1,
|
||||
"SourceOnly": true
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
"""Opt-in v2 primary allocator with bounded replay state and explicit leases.
|
||||
|
||||
Credit issuance is not proof of deployed enforcement. At rate R and bucket B,
|
||||
issuance during T is bounded by B+R*T. Pre-issued credit has TTL <= 1 second;
|
||||
gate admission can therefore have an extra B+R*TTL release allowance, not an
|
||||
instantaneous strict configured-rate wire guarantee. Kernel/transport buffering is
|
||||
outside this account payload contract. Unused credits are burned, not refunded.
|
||||
|
||||
One durable node epoch fences restarted executors. One persisted response and
|
||||
sequence high-water per node/subscription/direction replaces a per-RPC ledger.
|
||||
Do not delete/reset same-epoch lane state, or reset node epochs. UUID request_id
|
||||
is correlation; the replay identity is (node, epoch, lane, sequence). Same seq
|
||||
retries retain their first monotonic request-start deadline at the executor.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import DatabaseError, IntegrityError, connections, transaction
|
||||
from django.http import JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .models import ACCOUNT_BANDWIDTH_EXCEPTION_KEY, AccountBandwidthExemption, AccountBandwidthPolicy
|
||||
from .policy import _limit_in_bytes
|
||||
from .helpers import (
|
||||
BURST_MS, DB, MAX_REQUEST_BYTES, MICRO, BudgetRejected, _database_now,
|
||||
_node_allowed, _require_primary_backend, _unique_json_pairs,
|
||||
)
|
||||
from .models import AccountBandwidthBucket, AccountBandwidthExecutor, AccountBandwidthLane
|
||||
from control.models import Node, Subscription
|
||||
|
||||
CONTRACT = 2
|
||||
POLICY_VERSION = "shared-account-budget-v2"
|
||||
MAX_SEQUENCE = 2**63 - 1
|
||||
MAX_TTL_MS = 1000
|
||||
MAX_RESPONSE_BYTES = 2048
|
||||
|
||||
|
||||
def _reply(payload, status=200):
|
||||
response = JsonResponse(payload, status=status)
|
||||
response["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
|
||||
def _integer(value, minimum, maximum=MAX_SEQUENCE):
|
||||
return type(value) is int and minimum <= value <= maximum
|
||||
|
||||
|
||||
def _uuid(value):
|
||||
return (isinstance(value, str) and len(value) == 36 and str(uuid.UUID(value)) == value
|
||||
and uuid.UUID(value).int != 0)
|
||||
|
||||
|
||||
def _contract(payload, fields):
|
||||
if (not isinstance(payload, dict) or set(payload) != fields
|
||||
or type(payload["contract"]) is not int or payload["contract"] != CONTRACT
|
||||
or payload["policy_version"] != POLICY_VERSION):
|
||||
raise ValueError("unsupported budget v2 contract")
|
||||
|
||||
|
||||
def _parse_open(payload):
|
||||
_contract(payload, {"contract", "policy_version", "expected_epoch", "boot_id", "registration_id"})
|
||||
if not _integer(payload["expected_epoch"], 0) or not all(_uuid(payload[key]) for key in ("boot_id", "registration_id")):
|
||||
raise ValueError("invalid executor registration")
|
||||
return payload
|
||||
|
||||
|
||||
def _parse_credit(payload):
|
||||
_contract(payload, {"contract", "policy_version", "subscription_id", "credential_uuid", "direction",
|
||||
"requested_bytes", "request_id", "boot_id", "session_id", "ttl_ms", "executor_epoch", "sequence"})
|
||||
if (not all(_integer(payload[key], 1) for key in ("subscription_id", "executor_epoch", "sequence"))
|
||||
or not _integer(payload["requested_bytes"], 1, MAX_REQUEST_BYTES)
|
||||
or not _integer(payload["ttl_ms"], 50, MAX_TTL_MS)
|
||||
or payload["direction"] not in ("upload", "download")
|
||||
or not all(_uuid(payload[key]) for key in ("credential_uuid", "request_id", "boot_id", "session_id"))):
|
||||
raise ValueError("invalid budget v2 request")
|
||||
return payload
|
||||
|
||||
|
||||
def _timeouts():
|
||||
if connections[DB].vendor == "postgresql":
|
||||
with connections[DB].cursor() as cursor:
|
||||
cursor.execute("SET LOCAL lock_timeout = '100ms'")
|
||||
cursor.execute("SET LOCAL statement_timeout = '250ms'")
|
||||
|
||||
|
||||
def _current_node(node, lock=False):
|
||||
query = Node.objects.using(DB)
|
||||
if lock:
|
||||
query = query.select_for_update(nowait=True)
|
||||
current = query.filter(pk=node.pk).first()
|
||||
if not _node_allowed(current) or current.agent_token_digest != node.agent_token_digest:
|
||||
raise BudgetRejected("node_not_authorized", 401)
|
||||
return current
|
||||
|
||||
|
||||
def _check_clock(now, *floors):
|
||||
if any(floor is not None and now < floor for floor in floors):
|
||||
raise BudgetRejected("budget_clock_regressed", 503)
|
||||
|
||||
|
||||
def read_executor(node):
|
||||
_require_primary_backend()
|
||||
current = _current_node(node)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
_check_clock(_database_now(), state.clock_floor if state else None)
|
||||
return {"contract": CONTRACT, "policy_version": POLICY_VERSION, "node_slug": current.slug,
|
||||
"executor_epoch": state.epoch if state else 0}
|
||||
|
||||
|
||||
def _registration_response(state, node):
|
||||
return {"contract": CONTRACT, "policy_version": POLICY_VERSION, "node_slug": node.slug,
|
||||
"executor_epoch": state.epoch, "boot_id": str(state.boot_id), "registration_id": str(state.registration_id)}
|
||||
|
||||
|
||||
def open_executor(node, payload):
|
||||
payload = _parse_open(payload)
|
||||
_require_primary_backend()
|
||||
with transaction.atomic(using=DB):
|
||||
_timeouts()
|
||||
current = _current_node(node, lock=True)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
now = _database_now()
|
||||
_check_clock(now, state.clock_floor if state else None)
|
||||
if state:
|
||||
same_registration = (str(state.boot_id) == payload["boot_id"] and str(state.registration_id) == payload["registration_id"])
|
||||
if same_registration and payload["expected_epoch"] == state.epoch - 1:
|
||||
return _registration_response(state, current)
|
||||
if (payload["expected_epoch"] != state.epoch or state.epoch == MAX_SEQUENCE
|
||||
or str(state.boot_id) == payload["boot_id"] or str(state.registration_id) == payload["registration_id"]):
|
||||
raise BudgetRejected("fenced", 409)
|
||||
state.epoch += 1
|
||||
state.boot_id, state.registration_id = payload["boot_id"], payload["registration_id"]
|
||||
state.opened_at = state.clock_floor = now
|
||||
state.save(using=DB)
|
||||
else:
|
||||
if payload["expected_epoch"] != 0:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).create(node=current, epoch=1,
|
||||
boot_id=payload["boot_id"], registration_id=payload["registration_id"], opened_at=now, clock_floor=now)
|
||||
return _registration_response(state, current)
|
||||
|
||||
|
||||
def _authorize_subscription(node, payload):
|
||||
owner_id = Subscription.objects.using(DB).filter(pk=payload["subscription_id"]).values_list("user_id", flat=True).first()
|
||||
if owner_id is None:
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
user = get_user_model().objects.using(DB).select_for_update().filter(pk=owner_id).first()
|
||||
subscription = Subscription.objects.using(DB).select_for_update(of=("self",)).select_related("plan").filter(pk=payload["subscription_id"]).first()
|
||||
if user is None or subscription is None or subscription.user_id != user.pk:
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
# Same lock order as v1: account/subscription first, node NOWAIT afterwards.
|
||||
current = _current_node(node, lock=True)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
if state is None or state.epoch != payload["executor_epoch"] or str(state.boot_id) != payload["boot_id"]:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
now = _database_now()
|
||||
_check_clock(now, state.clock_floor)
|
||||
subscription.user = user
|
||||
if (not user.service_enabled or subscription.status != Subscription.Status.ACTIVE
|
||||
or subscription.provisioning_state != Subscription.ProvisioningState.ACTIVE
|
||||
or str(subscription.credential_uuid) != payload["credential_uuid"]
|
||||
or subscription.route_mode not in Subscription.RouteMode.values or subscription.online_payment_pending
|
||||
or (subscription.starts_at and subscription.starts_at > now)
|
||||
or (subscription.expires_at and subscription.expires_at <= now)
|
||||
or (subscription.traffic_limit_bytes and subscription.used_bytes >= subscription.traffic_limit_bytes)
|
||||
or not subscription.nodes_for_subscription().using(DB).filter(pk=current.pk).exists()):
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
return user, subscription, current, state, now
|
||||
|
||||
|
||||
def issue_credit_v2(node, payload):
|
||||
payload = _parse_credit(payload)
|
||||
_require_primary_backend()
|
||||
fingerprint = hashlib.sha256(json.dumps({"node_id": node.pk, **payload}, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
||||
with transaction.atomic(using=DB):
|
||||
_timeouts()
|
||||
user, subscription, current, executor, now = _authorize_subscription(node, payload)
|
||||
lane = AccountBandwidthLane.objects.using(DB).filter(node=current, subscription=subscription, direction=payload["direction"]).first()
|
||||
same_epoch = lane is not None and lane.executor_epoch == executor.epoch
|
||||
if same_epoch:
|
||||
if str(lane.session_id) != payload["session_id"] or str(lane.credential_uuid) != payload["credential_uuid"] or lane.user_id != user.pk:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
_check_clock(now, lane.issued_at)
|
||||
if payload["sequence"] == lane.sequence:
|
||||
if fingerprint != lane.fingerprint:
|
||||
raise BudgetRejected("sequence_conflict", 409)
|
||||
return json.loads(lane.response)
|
||||
if payload["sequence"] != lane.sequence + 1:
|
||||
raise BudgetRejected("sequence_out_of_order", 409)
|
||||
elif payload["sequence"] != 1:
|
||||
raise BudgetRejected("sequence_out_of_order", 409)
|
||||
if lane is not None and lane.executor_epoch > executor.epoch:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
# The stable User row is already locked: serialize policy creation and all lanes.
|
||||
policy, _ = AccountBandwidthPolicy.objects.using(DB).get_or_create(user=user)
|
||||
rate = _limit_in_bytes(getattr(policy, payload["direction"] + "_limit_kib_per_second"))
|
||||
exempt = AccountBandwidthExemption.objects.using(DB).filter(policy_key=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, user_id=user.pk).exists()
|
||||
capacity = rate * BURST_MS * 1000
|
||||
bucket, _ = AccountBandwidthBucket.objects.using(DB).get_or_create(user=user, direction=payload["direction"],
|
||||
defaults={"available_microbytes": 0 if exempt else capacity, "rate_bytes_per_second": rate, "exempt": exempt, "refilled_at": now})
|
||||
_check_clock(now, bucket.refilled_at)
|
||||
if bucket.rate_bytes_per_second != rate or bucket.exempt != exempt:
|
||||
available = 0
|
||||
else:
|
||||
elapsed = now - bucket.refilled_at
|
||||
elapsed_us = (elapsed.days * 86400 + elapsed.seconds) * MICRO + elapsed.microseconds
|
||||
available = min(capacity, bucket.available_microbytes + elapsed_us * rate)
|
||||
granted = 0 if exempt else min(payload["requested_bytes"], available // MICRO)
|
||||
bucket.available_microbytes = 0 if exempt else available - granted * MICRO
|
||||
bucket.rate_bytes_per_second, bucket.exempt, bucket.refilled_at = rate, exempt, now
|
||||
bucket.save(using=DB)
|
||||
expiry = now + timedelta(milliseconds=payload["ttl_ms"])
|
||||
if subscription.expires_at:
|
||||
expiry = min(expiry, subscription.expires_at)
|
||||
response = {"contract": CONTRACT, "policy_version": POLICY_VERSION, "request_id": payload["request_id"],
|
||||
"node_slug": current.slug, "boot_id": payload["boot_id"], "session_id": payload["session_id"],
|
||||
"account_id": user.pk, "subscription_id": subscription.pk, "credential_uuid": str(subscription.credential_uuid),
|
||||
"direction": payload["direction"], "requested_bytes": payload["requested_bytes"], "ttl_ms": payload["ttl_ms"],
|
||||
"issued_at": now.isoformat(), "expires_at": expiry.isoformat(), "executor_epoch": executor.epoch,
|
||||
"sequence": payload["sequence"], "enforced": False, "exempt": exempt,
|
||||
"kind": "bandwidth_exemption_lease" if exempt else "byte_credit"}
|
||||
if exempt:
|
||||
response["exemption_policy_key"] = ACCOUNT_BANDWIDTH_EXCEPTION_KEY
|
||||
else:
|
||||
response.update(granted_bytes=granted, rate_bytes_per_second=rate, burst_bytes=capacity // MICRO)
|
||||
encoded = json.dumps(response, sort_keys=True, separators=(",", ":"))
|
||||
if len(encoded.encode()) > MAX_RESPONSE_BYTES:
|
||||
raise BudgetRejected("budget_unavailable", 503)
|
||||
values = dict(user=user, executor_epoch=executor.epoch, credential_uuid=subscription.credential_uuid,
|
||||
session_id=payload["session_id"], sequence=payload["sequence"], fingerprint=fingerprint,
|
||||
response=encoded, issued_at=now)
|
||||
if lane is None:
|
||||
AccountBandwidthLane.objects.using(DB).create(node=current, subscription=subscription, direction=payload["direction"], **values)
|
||||
else:
|
||||
for key, value in values.items():
|
||||
setattr(lane, key, value)
|
||||
lane.save(using=DB)
|
||||
executor.clock_floor = now
|
||||
executor.save(using=DB, update_fields=["clock_floor"])
|
||||
return response
|
||||
|
||||
|
||||
def _http(request, action):
|
||||
if getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is not True:
|
||||
return _reply({"error_code": "budget_disabled"}, 503)
|
||||
from control.views import _authenticate_node
|
||||
try:
|
||||
_require_primary_backend()
|
||||
node = _authenticate_node(request)
|
||||
if not _node_allowed(node):
|
||||
raise BudgetRejected("node_not_authorized", 401)
|
||||
if action == "read":
|
||||
return _reply(read_executor(node))
|
||||
if len(request.body) > 4096:
|
||||
raise ValueError("budget payload too large")
|
||||
payload = json.loads(request.body, object_pairs_hook=_unique_json_pairs)
|
||||
return _reply(open_executor(node, payload) if action == "open" else issue_credit_v2(node, payload))
|
||||
except BudgetRejected as exc:
|
||||
return _reply({"error_code": exc.code}, exc.status)
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return _reply({"error_code": "invalid_budget_request"}, 400)
|
||||
except (DatabaseError, IntegrityError):
|
||||
return _reply({"error_code": "budget_unavailable"}, 503)
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_http_methods(["GET", "POST"])
|
||||
def node_budget_executor(request):
|
||||
return _http(request, "read" if request.method == "GET" else "open")
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_http_methods(["POST"])
|
||||
def node_bandwidth_budget_v2(request):
|
||||
return _http(request, "credit")
|
||||
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"""Account configuration only; does not activate the disabled budget executor."""
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def lock_accounts_before_policy_ddl(apps, schema_editor):
|
||||
User = apps.get_model("accounts", "User")
|
||||
Policy = apps.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
if schema_editor.connection.vendor == "postgresql":
|
||||
# Serialize registration and policy edits for complete coverage. The
|
||||
# existing fixed-ID exemption and every owner policy byte stay intact.
|
||||
quote = schema_editor.connection.ops.quote_name
|
||||
with schema_editor.connection.cursor() as cursor:
|
||||
cursor.execute("LOCK TABLE " + quote(User._meta.db_table) + " IN SHARE MODE")
|
||||
cursor.execute("LOCK TABLE " + quote(Policy._meta.db_table) + " IN SHARE ROW EXCLUSIVE MODE")
|
||||
|
||||
|
||||
def set_ordinary_account_defaults(apps, schema_editor):
|
||||
User = apps.get_model("accounts", "User")
|
||||
Policy = apps.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
database = schema_editor.connection.alias
|
||||
ordinary = User.objects.using(database).exclude(pk=5)
|
||||
policies = Policy.objects.using(database)
|
||||
policies.exclude(user_id=5).update(upload_limit_kib_per_second=500, download_limit_kib_per_second=500)
|
||||
missing = ordinary.exclude(pk__in=policies.values("user_id")).values_list("pk", flat=True)
|
||||
policies.bulk_create([Policy(user_id=pk, upload_limit_kib_per_second=500, download_limit_kib_per_second=500)
|
||||
for pk in missing], batch_size=1000)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("shared_budget", "0001_initial")]
|
||||
operations = [
|
||||
# Must precede every DDL table lock: registration holds User first and
|
||||
# its post_save signal writes Policy. Acquiring Policy DDL first could
|
||||
# deadlock that transaction when we subsequently lock User.
|
||||
migrations.RunPython(lock_accounts_before_policy_ddl, migrations.RunPython.noop),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthpolicy", name="sb_policy_upload_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthpolicy", name="sb_policy_download_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthbucket", name="bandwidth_bucket_rate_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthbucket", name="bandwidth_bucket_credit_bounded"),
|
||||
migrations.AlterField(model_name="accountbandwidthpolicy", name="upload_limit_kib_per_second",
|
||||
field=models.PositiveSmallIntegerField("账号上传上限(KiB/s)", default=500, db_default=500,
|
||||
validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10240)])),
|
||||
migrations.AlterField(model_name="accountbandwidthpolicy", name="download_limit_kib_per_second",
|
||||
field=models.PositiveSmallIntegerField("账号下载上限(KiB/s)", default=500, db_default=500,
|
||||
validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10240)])),
|
||||
migrations.AddConstraint(model_name="accountbandwidthpolicy", constraint=models.CheckConstraint(
|
||||
condition=models.Q(upload_limit_kib_per_second__gte=1, upload_limit_kib_per_second__lte=10240), name="sb_policy_upload_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthpolicy", constraint=models.CheckConstraint(
|
||||
condition=models.Q(download_limit_kib_per_second__gte=1, download_limit_kib_per_second__lte=10240), name="sb_policy_download_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthbucket", constraint=models.CheckConstraint(
|
||||
condition=models.Q(rate_bytes_per_second__gte=1, rate_bytes_per_second__lte=10485760), name="bandwidth_bucket_rate_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthbucket", constraint=models.CheckConstraint(
|
||||
condition=models.Q(available_microbytes__lte=2097152000000), name="bandwidth_bucket_credit_bounded")),
|
||||
# Irreversible data policy: an automatic downgrade must not overwrite
|
||||
# later administrator choices or silently recreate 200 KiB/s limits.
|
||||
migrations.RunPython(set_ordinary_account_defaults),
|
||||
]
|
||||
@@ -0,0 +1,149 @@
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from control.models import Node, Subscription
|
||||
|
||||
from .policy import DEFAULT_KIB_PER_SECOND, MAX_KIB_PER_SECOND, MAX_BYTES_PER_SECOND, MAX_BUCKET_MICROBYTES
|
||||
|
||||
ACCOUNT_BANDWIDTH_EXCEPTION_KEY = "owner-approved-20261022"
|
||||
APPROVED_EXEMPT_USER_ID = 5
|
||||
|
||||
|
||||
class AccountBandwidthPolicy(models.Model):
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
|
||||
primary_key=True, related_name="shared_bandwidth_policy")
|
||||
upload_limit_kib_per_second = models.PositiveSmallIntegerField(
|
||||
"账号上传上限(KiB/s)", default=DEFAULT_KIB_PER_SECOND, db_default=DEFAULT_KIB_PER_SECOND,
|
||||
validators=[MinValueValidator(1), MaxValueValidator(MAX_KIB_PER_SECOND)])
|
||||
download_limit_kib_per_second = models.PositiveSmallIntegerField(
|
||||
"账号下载上限(KiB/s)", default=DEFAULT_KIB_PER_SECOND, db_default=DEFAULT_KIB_PER_SECOND,
|
||||
validators=[MinValueValidator(1), MaxValueValidator(MAX_KIB_PER_SECOND)])
|
||||
|
||||
class Meta:
|
||||
verbose_name = "账户带宽策略"
|
||||
verbose_name_plural = "账户带宽策略"
|
||||
constraints = [
|
||||
models.CheckConstraint(condition=models.Q(upload_limit_kib_per_second__gte=1,
|
||||
upload_limit_kib_per_second__lte=MAX_KIB_PER_SECOND), name="sb_policy_upload_bounded"),
|
||||
models.CheckConstraint(condition=models.Q(download_limit_kib_per_second__gte=1,
|
||||
download_limit_kib_per_second__lte=MAX_KIB_PER_SECOND), name="sb_policy_download_bounded"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return str(self.user)
|
||||
|
||||
|
||||
class ProtectedExemptionQuerySet(models.QuerySet):
|
||||
def update(self, **kwargs):
|
||||
raise ValidationError("受控豁免不能通过普通查询修改。")
|
||||
|
||||
def delete(self):
|
||||
raise ValidationError("受控豁免不能通过普通查询删除。")
|
||||
|
||||
def bulk_create(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免仅可通过审核后的数据迁移建立。")
|
||||
|
||||
def bulk_update(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免不能通过普通查询修改。")
|
||||
|
||||
|
||||
class AccountBandwidthExemption(models.Model):
|
||||
policy_key = models.CharField(primary_key=True, max_length=64,
|
||||
default=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, editable=False)
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
|
||||
related_name="shared_bandwidth_exemption", editable=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
objects = ProtectedExemptionQuerySet.as_manager()
|
||||
|
||||
class Meta:
|
||||
verbose_name = "受控账号免限速绑定"
|
||||
verbose_name_plural = "受控账号免限速绑定"
|
||||
default_permissions = ("view",)
|
||||
constraints = [models.CheckConstraint(
|
||||
condition=models.Q(policy_key=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, user_id=APPROVED_EXEMPT_USER_ID),
|
||||
name="sb_single_approved_exemption")]
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免仅可通过审核后的数据迁移建立。")
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免不能由普通后台操作删除。")
|
||||
|
||||
|
||||
class AccountBandwidthBucket(models.Model):
|
||||
"""Primary-DB account/direction credit, shared by every subscription/node.
|
||||
|
||||
Microbytes preserve sub-byte refill fractions without floating point. These
|
||||
rows and the grant ledger are authorizations, not traffic measurements.
|
||||
"""
|
||||
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
|
||||
related_name="bandwidth_budget_buckets")
|
||||
direction = models.CharField(max_length=8, choices=[("upload", "upload"), ("download", "download")])
|
||||
available_microbytes = models.PositiveBigIntegerField(default=0)
|
||||
rate_bytes_per_second = models.PositiveIntegerField()
|
||||
exempt = models.BooleanField(default=False)
|
||||
refilled_at = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["user", "direction"], name="unique_account_bandwidth_bucket"),
|
||||
models.CheckConstraint(condition=models.Q(direction__in=["upload", "download"]),
|
||||
name="bandwidth_bucket_direction"),
|
||||
models.CheckConstraint(condition=models.Q(rate_bytes_per_second__gte=1,
|
||||
rate_bytes_per_second__lte=MAX_BYTES_PER_SECOND),
|
||||
name="bandwidth_bucket_rate_bounded"),
|
||||
models.CheckConstraint(condition=models.Q(available_microbytes__lte=MAX_BUCKET_MICROBYTES),
|
||||
name="bandwidth_bucket_credit_bounded"),
|
||||
]
|
||||
|
||||
|
||||
class AccountBandwidthExecutor(models.Model):
|
||||
"""One durable fencing generation per node; never reset/delete on restart."""
|
||||
|
||||
node = models.OneToOneField(Node, on_delete=models.PROTECT, primary_key=True,
|
||||
related_name="bandwidth_budget_executor")
|
||||
epoch = models.PositiveBigIntegerField()
|
||||
boot_id = models.UUIDField()
|
||||
registration_id = models.UUIDField()
|
||||
opened_at = models.DateTimeField()
|
||||
clock_floor = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [models.CheckConstraint(condition=models.Q(epoch__gte=1, epoch__lte=9223372036854775807),
|
||||
name="bandwidth_executor_epoch_bounded")]
|
||||
|
||||
|
||||
class AccountBandwidthLane(models.Model):
|
||||
"""Fixed one-response replay slot, not a per-RPC ledger.
|
||||
|
||||
Same-epoch sequence/session state must never be reset. Older-epoch rows may
|
||||
be reused only while holding the durable node executor fence.
|
||||
"""
|
||||
|
||||
node = models.ForeignKey(Node, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
subscription = models.ForeignKey(Subscription, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
direction = models.CharField(max_length=8, choices=[("upload", "upload"), ("download", "download")])
|
||||
executor_epoch = models.PositiveBigIntegerField()
|
||||
credential_uuid = models.UUIDField()
|
||||
session_id = models.UUIDField()
|
||||
sequence = models.PositiveBigIntegerField()
|
||||
fingerprint = models.CharField(max_length=64)
|
||||
response = models.CharField(max_length=2048)
|
||||
issued_at = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["node", "subscription", "direction"], name="unique_account_bandwidth_lane"),
|
||||
models.CheckConstraint(condition=models.Q(direction__in=["upload", "download"]), name="bandwidth_lane_direction"),
|
||||
models.CheckConstraint(condition=models.Q(executor_epoch__gte=1, executor_epoch__lte=9223372036854775807,
|
||||
sequence__gte=1, sequence__lte=9223372036854775807),
|
||||
name="bandwidth_lane_identity_bounded"),
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
DEFAULT_KIB_PER_SECOND = 500
|
||||
MAX_KIB_PER_SECOND = 10240
|
||||
MAX_BYTES_PER_SECOND = MAX_KIB_PER_SECOND * 1024
|
||||
# Keep the DB credit bound aligned with the allocator's existing 200 ms burst.
|
||||
MAX_BUCKET_MICROBYTES = MAX_BYTES_PER_SECOND * 200 * 1000
|
||||
|
||||
|
||||
def _limit_in_bytes(value):
|
||||
if type(value) is not int or not 1 <= value <= MAX_KIB_PER_SECOND:
|
||||
raise ValueError(f"Account proxy speed request must be an integer in 1–{MAX_KIB_PER_SECOND} KiB/s.")
|
||||
return value * 1024
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Read-only, request-scoped portal guidance; never infers a live VPN connection."""
|
||||
from django.conf import settings
|
||||
from django.urls import reverse
|
||||
|
||||
from control.models import PlanApplication, Subscription
|
||||
from .models import AccountBandwidthExemption, AccountBandwidthExecutor
|
||||
from .policy import DEFAULT_KIB_PER_SECOND, MAX_KIB_PER_SECOND
|
||||
|
||||
|
||||
def portal_context(request):
|
||||
context = {"PLATFORM_NAME": "纵横家"}
|
||||
user = getattr(request, "user", None)
|
||||
if not user or not user.is_authenticated:
|
||||
return context
|
||||
|
||||
can_manage = bool(user.is_active and user.is_staff and (
|
||||
user.has_perm("shared_budget.view_accountbandwidthpolicy")
|
||||
or user.has_perm("shared_budget.change_accountbandwidthpolicy")))
|
||||
if can_manage:
|
||||
admin_budget = {
|
||||
"default_upload": DEFAULT_KIB_PER_SECOND, "default_download": DEFAULT_KIB_PER_SECOND,
|
||||
"maximum_limit": MAX_KIB_PER_SECOND,
|
||||
"allocator_enabled": getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is True,
|
||||
"policy_url": reverse("admin:shared_budget_accountbandwidthpolicy_changelist"),
|
||||
"execution_label": "待现场验收",
|
||||
}
|
||||
if user.has_perm("shared_budget.view_accountbandwidthexemption"):
|
||||
admin_budget["exemption_count"] = AccountBandwidthExemption.objects.count()
|
||||
admin_budget["exemption_url"] = reverse("admin:shared_budget_accountbandwidthexemption_changelist")
|
||||
admin_budget["registered_executors"] = AccountBandwidthExecutor.objects.count()
|
||||
context["admin_budget"] = admin_budget
|
||||
|
||||
match = getattr(request, "resolver_match", None)
|
||||
if not match or match.url_name != "portal-dashboard":
|
||||
return context
|
||||
# Every query is scoped to the signed-in user; no account ID is accepted
|
||||
# from query strings, form fields, or a selected client node.
|
||||
subscriptions = user.subscriptions.select_related("plan", "routing_policy").all()
|
||||
subscription = subscriptions.exclude(status__in=["cancelled", "expired"]).first() or subscriptions.first()
|
||||
pending = user.plan_applications.filter(status=PlanApplication.Status.PENDING).exists()
|
||||
journey = {"pending": pending, "ready": False, "step": 1,
|
||||
"primary_url": reverse("apply-plan"), "primary_label": "选择套餐并申请"}
|
||||
if not user.is_active or user.account_status in ("suspended", "departed"):
|
||||
journey.update(state="restricted", step=2, title="服务暂不可用",
|
||||
body="账号已暂停或停止服务,请联系管理员核实。当前页面不会提供订阅凭据。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看申请记录")
|
||||
elif subscription and subscription.is_usable:
|
||||
journey.update(state="ready", ready=True, step=3, title="订阅已准备好",
|
||||
body="下载 Windows 客户端后,用同一账号登录;也可展开个人订阅地址供兼容客户端使用。",
|
||||
primary_url=reverse("client-download-latest"), primary_label="下载 Windows 客户端")
|
||||
elif pending:
|
||||
journey.update(state="review", step=2, title="申请已提交,等待审核",
|
||||
body="不用重复提交。管理员核实身份并审核后,开通进度与订阅会显示在这里;暂未开放付款的套餐不会扣款。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看审核进度")
|
||||
elif subscription and subscription.online_payment_pending:
|
||||
journey.update(state="payment_pending", step=2, title="套餐暂未开放付款",
|
||||
body="申请只作登记,尚未扣款或开通付费服务。请等待管理员通知,不要向个人账号转账。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看申请记录")
|
||||
elif subscription and subscription.status == "active" and user.service_enabled:
|
||||
journey.update(state="provisioning", step=2, title="审核已通过,等待订阅就绪",
|
||||
body="节点配置仍在处理。请稍后刷新本页;实际连接状态只在客户端查看。",
|
||||
primary_url=reverse("portal-dashboard"), primary_label="刷新开通进度")
|
||||
elif subscription:
|
||||
journey.update(state="renew", step=2, title="订阅当前不可用",
|
||||
body="请核对下方有效期、流量和处理状态。需要续期或更换套餐时再提交申请。",
|
||||
primary_url=reverse("apply-plan"), primary_label="查看可申请套餐")
|
||||
else:
|
||||
journey.update(state="apply", title="先选择套餐,提交开通申请",
|
||||
body="注册只需一次。提交套餐申请后由管理员审核,通过后在这里获取订阅与客户端下载入口。")
|
||||
context["portal_journey"] = journey
|
||||
return context
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{% if admin_budget %}
|
||||
<section class="admin-budget-panel" aria-labelledby="budget-heading">
|
||||
<div><span class="budget-eyebrow">账户共享带宽</span><h2 id="budget-heading">默认每方向 {{ admin_budget.default_upload }} KiB/s</h2>
|
||||
<p>同一账户的设备与节点共用上传、下载预算;单账户每方向可设 1–{{ admin_budget.maximum_limit|stringformat:"d" }} KiB/s。</p>
|
||||
<p>中央预算 API:{% if admin_budget.allocator_enabled %}<strong>已开启</strong>{% else %}<strong>未开启</strong>{% endif %} · 执行状态:<strong>{{ admin_budget.execution_label }}</strong></p>
|
||||
<p class="budget-detail">已注册执行器 {{ admin_budget.registered_executors }} 个。注册或开启 API 不代表真实限速已验收。{% if admin_budget.exemption_count != None %}受控豁免 {{ admin_budget.exemption_count }} 个,绑定固定账号 ID,不随邮箱转移。{% endif %}</p>
|
||||
</div>
|
||||
<div class="budget-links"><a class="budget-primary" href="{{ admin_budget.policy_url }}">管理账户限速</a>{% if admin_budget.exemption_url %}<a href="{{ admin_budget.exemption_url }}">查看只读豁免</a>{% endif %}</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Real Django policy checks; all exercise writes are rolled back.
|
||||
|
||||
The deployment driver execs this source in a separate namespace and explicitly
|
||||
calls protected_snapshot()/validate(before); Django shell is not __main__.
|
||||
For a direct script entry, RATE500_BEFORE_JSON can supply the prior snapshot.
|
||||
No node process, network, user credential or limiter flag is changed here.
|
||||
"""
|
||||
import io
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.management import call_command
|
||||
from django.db import IntegrityError, connection, transaction
|
||||
from django.db import migrations
|
||||
from django.db.migrations.executor import MigrationExecutor
|
||||
from django.test import RequestFactory
|
||||
from django.template.loader import render_to_string
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
def protected_snapshot():
|
||||
from shared_budget.models import AccountBandwidthExemption, AccountBandwidthPolicy
|
||||
return {
|
||||
"owner_policy": list(AccountBandwidthPolicy.objects.filter(user_id=5).values()),
|
||||
"exemptions": list(AccountBandwidthExemption.objects.order_by("policy_key").values()),
|
||||
"user_count": get_user_model().objects.count(),
|
||||
}
|
||||
|
||||
|
||||
def validate(before=None):
|
||||
from shared_budget import policy
|
||||
from shared_budget.allocator import node_bandwidth_budget_v2, node_budget_executor
|
||||
from shared_budget.models import AccountBandwidthBucket, AccountBandwidthExemption, AccountBandwidthPolicy
|
||||
from shared_budget.web_context import portal_context
|
||||
|
||||
checks, errors = {}, {}
|
||||
|
||||
def check(name, action):
|
||||
try:
|
||||
action()
|
||||
checks[name] = True
|
||||
except Exception as error:
|
||||
checks[name] = False
|
||||
errors[name] = f"{type(error).__name__}: {error}"
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise AssertionError(message)
|
||||
|
||||
def rejected(action, exception):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
action()
|
||||
except exception:
|
||||
return
|
||||
raise AssertionError(f"expected {exception.__name__}")
|
||||
|
||||
check("all_ordinary_users_have_policy", lambda: require(
|
||||
get_user_model().objects.exclude(pk=5).exclude(
|
||||
pk__in=AccountBandwidthPolicy.objects.values("user_id")).count() == 0, "missing ordinary policy"))
|
||||
check("all_ordinary_accounts_500_each_direction", lambda: require(
|
||||
not AccountBandwidthPolicy.objects.exclude(user_id=5).exclude(
|
||||
upload_limit_kib_per_second=500, download_limit_kib_per_second=500).exists(), "ordinary policy is not 500/500"))
|
||||
check("owner_fixed_id5_exemption_unchanged", lambda: require(
|
||||
list(AccountBandwidthExemption.objects.values_list("policy_key", "user_id")) == [("owner-approved-20261022", 5)],
|
||||
"expected existing fixed-ID owner exemption"))
|
||||
if before is not None:
|
||||
after = protected_snapshot()
|
||||
for key in ("owner_policy", "exemptions", "user_count"):
|
||||
check("migration_preserves_" + key, lambda key=key: require(
|
||||
json.dumps(after[key], sort_keys=True, default=str) == json.dumps(before[key], sort_keys=True, default=str), key + " changed"))
|
||||
check("default_is_500", lambda: require(
|
||||
AccountBandwidthPolicy._meta.get_field("upload_limit_kib_per_second").default == 500
|
||||
and AccountBandwidthPolicy._meta.get_field("download_limit_kib_per_second").default == 500, "default != 500"))
|
||||
check("admin_max_10240", lambda: require(policy.MAX_KIB_PER_SECOND == 10240, "max != 10240"))
|
||||
def migration_lock_order():
|
||||
module = importlib.import_module("shared_budget.migrations.0002_account_rate_500")
|
||||
first = module.Migration.operations[0]
|
||||
require(isinstance(first, migrations.RunPython) and first.code is module.lock_accounts_before_policy_ddl,
|
||||
"account lock must be first operation, before policy DDL")
|
||||
statements = []
|
||||
class Cursor:
|
||||
def __enter__(self):
|
||||
return self
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
def execute(self, sql):
|
||||
statements.append(sql)
|
||||
state = MigrationExecutor(connection).loader.project_state([("shared_budget", "0001_initial")]).apps
|
||||
first.code(state, SimpleNamespace(connection=SimpleNamespace(vendor="postgresql", ops=connection.ops, cursor=Cursor)))
|
||||
require(len(statements) == 2 and '"accounts_user" IN SHARE MODE' in statements[0]
|
||||
and '"shared_budget_accountbandwidthpolicy" IN SHARE ROW EXCLUSIVE MODE' in statements[1], "User must lock before Policy")
|
||||
check("migration_locks_user_before_any_policy_ddl", migration_lock_order)
|
||||
check("policy_501_converts_without_200_clamp", lambda: require(policy._limit_in_bytes(501) == 513024, "501 conversion"))
|
||||
check("policy_max_converts", lambda: require(policy._limit_in_bytes(10240) == 10485760, "10240 conversion"))
|
||||
for value in (0, -1, 10241, True, "500"):
|
||||
check("policy_rejects_" + type(value).__name__ + "_" + str(value), lambda value=value: rejected(lambda: policy._limit_in_bytes(value), ValueError))
|
||||
check("allocator_stays_disabled", lambda: require(
|
||||
getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is False
|
||||
and getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_ENABLED", False) is False, "allocator enabled"))
|
||||
factory = RequestFactory()
|
||||
for label, endpoint in (("credit", node_bandwidth_budget_v2), ("executor", node_budget_executor)):
|
||||
def disabled(endpoint=endpoint):
|
||||
response = endpoint(factory.post("/", "{}", content_type="application/json"))
|
||||
require(response.status_code == 503 and json.loads(response.content)["error_code"] == "budget_disabled", "API not disabled")
|
||||
check("disabled_" + label + "_api", disabled)
|
||||
|
||||
with transaction.atomic():
|
||||
user = get_user_model().objects.create_user(username="rate500-test-" + uuid.uuid4().hex,
|
||||
email=uuid.uuid4().hex + "@example.invalid", display_name="Isolated policy verification")
|
||||
row = AccountBandwidthPolicy.objects.get(user=user)
|
||||
check("new_user_signal_500_each_direction", lambda: require(
|
||||
(row.upload_limit_kib_per_second, row.download_limit_kib_per_second) == (500, 500), "new user defaults"))
|
||||
request = factory.get("/")
|
||||
request.user = get_user_model()(is_active=True, is_staff=True, is_superuser=True)
|
||||
form_type = admin.site._registry[AccountBandwidthPolicy].get_form(request, row)
|
||||
for value in (501, 10240):
|
||||
def form_valid(value=value):
|
||||
form = form_type(data={"upload_limit_kib_per_second": value, "download_limit_kib_per_second": value}, instance=row)
|
||||
require(form.is_valid(), str(form.errors))
|
||||
check("real_admin_form_accepts_" + str(value), form_valid)
|
||||
def model_valid(value=value):
|
||||
with transaction.atomic():
|
||||
row.upload_limit_kib_per_second = row.download_limit_kib_per_second = value
|
||||
row.full_clean()
|
||||
row.save()
|
||||
row.refresh_from_db()
|
||||
require(row.upload_limit_kib_per_second == value and row.download_limit_kib_per_second == value, "not stored")
|
||||
check("model_and_db_accept_" + str(value), model_valid)
|
||||
for value in (0, 10241):
|
||||
def invalid(value=value):
|
||||
row.upload_limit_kib_per_second = value
|
||||
rejected(row.full_clean, ValidationError)
|
||||
rejected(lambda: AccountBandwidthPolicy.objects.filter(user=user).update(download_limit_kib_per_second=value), IntegrityError)
|
||||
check("python_and_db_reject_" + str(value), invalid)
|
||||
def bucket_at_max():
|
||||
with transaction.atomic():
|
||||
AccountBandwidthBucket.objects.create(user=user, direction="upload", rate_bytes_per_second=10485760,
|
||||
available_microbytes=2097152000000, refilled_at=timezone.now())
|
||||
check("bucket_db_accepts_admin_max_rate_and_credit", bucket_at_max)
|
||||
check("bucket_db_rejects_above_max", lambda: rejected(lambda: AccountBandwidthBucket.objects.create(
|
||||
user=user, direction="download", rate_bytes_per_second=10485761, available_microbytes=0,
|
||||
refilled_at=timezone.now()), IntegrityError))
|
||||
check("bucket_db_rejects_above_credit_max", lambda: rejected(lambda: AccountBandwidthBucket.objects.create(
|
||||
user=user, direction="download", rate_bytes_per_second=512000, available_microbytes=2097152000001,
|
||||
refilled_at=timezone.now()), IntegrityError))
|
||||
check("portal_context_matches_500_and_max", lambda: require(
|
||||
portal_context(request)["admin_budget"]["default_upload"] == 500
|
||||
and portal_context(request)["admin_budget"]["default_download"] == 500
|
||||
and portal_context(request)["admin_budget"]["maximum_limit"] == 10240, "portal values"))
|
||||
def portal_template():
|
||||
rendered = render_to_string("includes/admin_budget.html", portal_context(request))
|
||||
require("500 KiB/s" in rendered and "10,240" not in rendered and "10240 KiB/s" in rendered
|
||||
and "1–200" not in rendered and "未开启" in rendered, "template range/default/state")
|
||||
check("actual_portal_template_500_and_max", portal_template)
|
||||
def database_defaults():
|
||||
AccountBandwidthPolicy.objects.filter(user=user).delete()
|
||||
table = connection.ops.quote_name(AccountBandwidthPolicy._meta.db_table)
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("INSERT INTO " + table + " (user_id) VALUES (%s)", [user.pk])
|
||||
saved = AccountBandwidthPolicy.objects.get(user=user)
|
||||
require((saved.upload_limit_kib_per_second, saved.download_limit_kib_per_second) == (500, 500), "DB defaults")
|
||||
check("raw_insert_db_defaults_500", database_defaults)
|
||||
transaction.set_rollback(True)
|
||||
|
||||
def no_pending_migrations():
|
||||
call_command("makemigrations", "shared_budget", check=True, dry_run=True, stdout=io.StringIO())
|
||||
check("real_models_have_no_pending_migration", no_pending_migrations)
|
||||
check("all_real_apps_have_no_pending_migration", lambda: call_command(
|
||||
"makemigrations", check=True, dry_run=True, stdout=io.StringIO()))
|
||||
check("policy_retains_positive_small_integer_type", lambda: require(all(
|
||||
AccountBandwidthPolicy._meta.get_field(field).get_internal_type() == "PositiveSmallIntegerField"
|
||||
for field in ("upload_limit_kib_per_second", "download_limit_kib_per_second")), "policy field type changed"))
|
||||
return {"passed": all(checks.values()), "checks": checks, "errors": errors,
|
||||
"ordinary_account_count": get_user_model().objects.exclude(pk=5).count(),
|
||||
"allocator_enabled": False, "wire_enforcement_verified": False,
|
||||
"exercise_writes_rolled_back": True, "production_modified": False,
|
||||
"known_executor_max_bytes_per_second": 204800,
|
||||
"scope": "legacy shared_budget policy configuration only; no deployed 500 KiB/s enforcement claim"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
snapshot_file = os.environ.get("RATE500_BEFORE_JSON")
|
||||
before = json.load(open(snapshot_file, encoding="utf-8")) if snapshot_file else None
|
||||
result = validate(before)
|
||||
print("RATE500_CLONE_VALIDATION=" + json.dumps(result, ensure_ascii=False, sort_keys=True, default=str))
|
||||
if not result["passed"]:
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Build an isolated legacy project and run real Django/DB checks, never live DB."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--stage", choices=("red", "green"), required=True)
|
||||
parser.add_argument("--run-id")
|
||||
args = parser.parse_args()
|
||||
candidate = Path(__file__).resolve().parents[1]
|
||||
def candidate_inputs():
|
||||
return {str(path.relative_to(candidate)).replace("\\", "/"): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for directory in (candidate / "overlay", candidate / "tests") for path in directory.rglob("*")
|
||||
if path.is_file() and path.suffix in (".py", ".html")}
|
||||
inputs_before = candidate_inputs()
|
||||
baseline = candidate.parent / "legacy-platform-fixture"
|
||||
run = candidate / "evidence" / (args.run_id or args.stage)
|
||||
run.mkdir(parents=True, exist_ok=False)
|
||||
project = run / "project"
|
||||
shutil.copytree(baseline, project, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
||||
if args.stage == "green":
|
||||
for source in (candidate / "overlay").rglob("*"):
|
||||
if source.is_file():
|
||||
target = project / source.relative_to(candidate / "overlay")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
os.environ.update(DJANGO_SETTINGS_MODULE="rate500_test_settings", DJANGO_SECRET_KEY="isolated-not-production",
|
||||
DJANGO_DEBUG="false", DJANGO_ALLOWED_HOSTS="localhost,127.0.0.1,testserver",
|
||||
ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED="false", ACCOUNT_BANDWIDTH_BUDGET_ENABLED="false")
|
||||
(project / "rate500_test_settings.py").write_text(
|
||||
"from toplc_vpn.test_settings import *\nDATABASES['default']['NAME'] = " + repr(str(run / "test.sqlite3")) + "\n", encoding="utf-8")
|
||||
sys.path.insert(0, str(project))
|
||||
import django
|
||||
django.setup()
|
||||
from django.core.management import call_command
|
||||
from django.db import connection
|
||||
from django.db.migrations.executor import MigrationExecutor
|
||||
call_command("migrate", "shared_budget", "0001", verbosity=0)
|
||||
state = MigrationExecutor(connection).loader.project_state([("shared_budget", "0001_initial")]).apps
|
||||
User = state.get_model("accounts", "User")
|
||||
Policy = state.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
Exemption = state.get_model("shared_budget", "AccountBandwidthExemption")
|
||||
for key in (1, 2, 5, 7):
|
||||
User.objects.create(id=key, username="fixture-" + str(key), email="owner@example.invalid" if key == 5 else f"fixture-{key}@example.invalid")
|
||||
if key != 7:
|
||||
Policy.objects.create(user_id=key, upload_limit_kib_per_second=111 if key == 5 else 200,
|
||||
download_limit_kib_per_second=123 if key == 5 else 150)
|
||||
Exemption.objects.create(policy_key="owner-approved-20261022", user_id=5)
|
||||
spec = importlib.util.spec_from_file_location("clone_validation", candidate / "tests/clone_validation.py")
|
||||
validation = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(validation)
|
||||
before = validation.protected_snapshot()
|
||||
def business_snapshot():
|
||||
result = {}
|
||||
with connection.cursor() as cursor:
|
||||
for table in sorted(connection.introspection.table_names()):
|
||||
if table.startswith(("accounts_", "control_", "shared_budget_")) and table != "shared_budget_accountbandwidthpolicy":
|
||||
cursor.execute("SELECT * FROM " + connection.ops.quote_name(table))
|
||||
rows = sorted(json.dumps(row, default=str, sort_keys=True) for row in cursor.fetchall())
|
||||
result[table] = hashlib.sha256("\n".join(rows).encode()).hexdigest()
|
||||
return result
|
||||
business_before = business_snapshot()
|
||||
has_migration = (project / "shared_budget/migrations/0002_account_rate_500.py").exists()
|
||||
plan = []
|
||||
if has_migration:
|
||||
plan = [(migration.app_label, migration.name, backwards) for migration, backwards in MigrationExecutor(connection).migration_plan([
|
||||
("shared_budget", "0002_account_rate_500")])]
|
||||
call_command("migrate", "shared_budget", "0002_account_rate_500", verbosity=0)
|
||||
business_after = business_snapshot()
|
||||
call_command("migrate", verbosity=0)
|
||||
result = validation.validate(before)
|
||||
result["checks"]["additive_0002_migration_present"] = has_migration
|
||||
result["checks"]["migration_plan_only_shared_budget_0002"] = plan == [("shared_budget", "0002_account_rate_500", False)]
|
||||
result["checks"]["migration_preserves_all_other_business_rows"] = business_before == business_after
|
||||
result["business_before_sha256"] = business_before
|
||||
result["business_after_sha256"] = business_after
|
||||
result["migration_plan"] = plan
|
||||
result["candidate_inputs_sha256"] = inputs_before
|
||||
result["checks"]["candidate_inputs_unchanged_during_test"] = inputs_before == candidate_inputs()
|
||||
result["passed"] = all(result["checks"].values())
|
||||
result["stage"] = args.stage
|
||||
result["django_version"] = django.get_version()
|
||||
result["database_vendor"] = connection.vendor
|
||||
result["inputs_sha256"] = {str(path.relative_to(project)).replace("\\", "/"): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in project.rglob("*") if path.is_file() and path.suffix in (".py", ".html") and "__pycache__" not in path.parts}
|
||||
(run / "result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
print(json.dumps({key: value for key, value in result.items() if key != "inputs_sha256"}, ensure_ascii=False, indent=2))
|
||||
raise SystemExit(0 if result["passed"] else 1)
|
||||
@@ -1,5 +0,0 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Only uiOnly fixtures may substitute recovery. Production always uses Xray's
|
||||
// ownership-checked route/DNS journals and exact child process handle.
|
||||
internal sealed record ClientExitRecoveryFixture(Func<Task> Dispose, TimeSpan? Deadline = null);
|
||||
@@ -1,51 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
internal static class ClientShutdownChildSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
var children = new List<Process>();
|
||||
string? error = null;
|
||||
Process Start(int delay, int exitCode)
|
||||
{
|
||||
var info = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false, CreateNoWindow = true };
|
||||
if (Path.GetFileNameWithoutExtension(Environment.ProcessPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
|
||||
info.ArgumentList.Add(Assembly.GetExecutingAssembly().Location);
|
||||
info.ArgumentList.Add("--client-shutdown-test-child"); info.ArgumentList.Add(delay.ToString()); info.ArgumentList.Add(exitCode.ToString());
|
||||
var child = Process.Start(info)!;
|
||||
_ = child.Handle; // Pin the exact owned child before waiting.
|
||||
children.Add(child);
|
||||
return child;
|
||||
}
|
||||
try
|
||||
{
|
||||
var delayed = Start(1200, 0);
|
||||
checks["exact_owned_child_exits_cleanly_before_handoff"] = ClientShutdownScope.WaitForExit([delayed]) && delayed.HasExited;
|
||||
var failed = Start(10, 7);
|
||||
checks["nonzero_old_client_exit_blocks_replacement"] = !ClientShutdownScope.WaitForExit([failed]);
|
||||
var slow = Start(1200, 0);
|
||||
var timer = Stopwatch.StartNew();
|
||||
checks["timeout_blocks_replacement_without_killing_client"] = !ClientShutdownScope.WaitForExit([slow], TimeSpan.FromMilliseconds(70)) && !slow.HasExited;
|
||||
checks["wait_is_bounded"] = timer.ElapsedMilliseconds < 1000;
|
||||
checks["timed_out_child_can_finish_gracefully"] = ClientShutdownScope.WaitForExit([slow]);
|
||||
checks["all_exact_handles_reap_successfully"] = children.All(c => c.HasExited);
|
||||
}
|
||||
catch (Exception exception) { error = exception.ToString(); }
|
||||
finally
|
||||
{
|
||||
foreach (var child in children)
|
||||
{
|
||||
try { if (!child.HasExited) { child.Kill(entireProcessTree: true); child.WaitForExit(2000); } } catch { }
|
||||
child.Dispose();
|
||||
}
|
||||
}
|
||||
var passed = error is null && checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-exit-child-handoff-self-test.json"),
|
||||
JsonSerializer.Serialize(new { Passed = passed, Checks = checks, Error = error, ProductionProcessQueried = false, NetworkingModified = false }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 87;
|
||||
}
|
||||
}
|
||||
@@ -8,21 +8,6 @@ internal static class ClientShutdownScope
|
||||
internal static bool IsUnambiguous(string expected, int session, IEnumerable<Instance> processes)
|
||||
=> processes.Where(p => p.SessionId == session).All(p => !string.IsNullOrWhiteSpace(p.Executable)
|
||||
&& string.Equals(Path.GetFullPath(p.Executable), Path.GetFullPath(expected), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// Call only after path/session verification and pinning exact handles.
|
||||
// All instances consume one shared budget; a timeout never kills a client.
|
||||
internal static bool WaitForExit(IEnumerable<System.Diagnostics.Process> processes, TimeSpan? budget = null)
|
||||
{
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
var limit = budget ?? TimeSpan.FromSeconds(90);
|
||||
foreach (var process in processes)
|
||||
{
|
||||
var remaining = (int)Math.Clamp(limit.TotalMilliseconds - watch.ElapsedMilliseconds, 0, int.MaxValue);
|
||||
if (!process.HasExited && (remaining == 0 || !process.WaitForExit(remaining))) return false;
|
||||
if (process.ExitCode != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
const string expected = @"C:\fixture\installed\VPNPlus.exe";
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ClientShutdownSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var flow = RunFlowAsync().GetAwaiter().GetResult();
|
||||
var ui = flow == 0 ? ClientShutdownUiSelfTest.Run() : -1;
|
||||
var handoff = flow == 0 && ui == 0 ? ClientShutdownChildSelfTest.Run() : -1;
|
||||
var passed = flow == 0 && ui == 0 && handoff == 0;
|
||||
var checks = new Dictionary<string, bool>();
|
||||
foreach (var (prefix, file) in new[] { ("flow", "client-exit-self-test.json"),
|
||||
("ui", "client-exit-ui-self-test.json"), ("handoff", "client-exit-child-handoff-self-test.json") })
|
||||
{
|
||||
var path = Path.Combine(AppContext.BaseDirectory, file);
|
||||
if (!File.Exists(path)) { checks[prefix + ".report_exists"] = false; continue; }
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(path));
|
||||
foreach (var assertion in document.RootElement.GetProperty("Checks").EnumerateObject())
|
||||
checks[prefix + "." + assertion.Name] = assertion.Value.GetBoolean();
|
||||
}
|
||||
passed &= checks.Count > 0 && checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-shutdown-self-test.json"),
|
||||
JsonSerializer.Serialize(new { passed, checks, flow_exit_code = flow, ui_exit_code = ui, child_handoff_exit_code = handoff,
|
||||
network_modified = false, installed_client_modified = false }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 85;
|
||||
}
|
||||
|
||||
private static async Task<int> RunFlowAsync()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
try
|
||||
{
|
||||
var current = false;
|
||||
var confirms = 0; var downloads = 0; var launches = 0;
|
||||
var accepted = await ClientUpdateFlow.RunAsync(() => current,
|
||||
() => { confirms++; return true; },
|
||||
() => { downloads++; return Task.FromResult("fixture.exe"); }, _ => launches++);
|
||||
checks["closed_before_offer_has_no_side_effect"] = !accepted && confirms == 0 && downloads == 0 && launches == 0;
|
||||
|
||||
current = true; confirms = downloads = launches = 0;
|
||||
accepted = await ClientUpdateFlow.RunAsync(() => current,
|
||||
() => { confirms++; current = false; return true; },
|
||||
() => { downloads++; return Task.FromResult("fixture.exe"); }, _ => launches++);
|
||||
checks["shutdown_during_confirmation_never_opens_progress_or_installer"] = !accepted && confirms == 1 && downloads == 0 && launches == 0;
|
||||
|
||||
current = true; confirms = downloads = launches = 0;
|
||||
var downloaded = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var pending = ClientUpdateFlow.RunAsync(() => current,
|
||||
() => { confirms++; return true; },
|
||||
() => { downloads++; return downloaded.Task; }, _ => launches++);
|
||||
current = false;
|
||||
downloaded.SetResult("fixture.exe");
|
||||
accepted = await pending;
|
||||
checks["shutdown_during_download_never_launches_installer"] = !accepted && confirms == 1 && downloads == 1 && launches == 0;
|
||||
|
||||
current = true; confirms = downloads = launches = 0;
|
||||
accepted = await ClientUpdateFlow.RunAsync(() => current, () => false,
|
||||
() => { downloads++; return Task.FromResult("fixture.exe"); }, _ => launches++);
|
||||
checks["declined_offer_retains_client"] = !accepted && downloads == 0 && launches == 0;
|
||||
accepted = await ClientUpdateFlow.RunAsync(() => current, () => true,
|
||||
() => Task.FromResult("verified-fixture.exe"), path => { if (path == "verified-fixture.exe") launches++; });
|
||||
checks["active_accepted_update_launches_exact_download_once"] = accepted && launches == 1;
|
||||
}
|
||||
catch (Exception error) { checks["unexpected_error"] = false; Console.Error.WriteLine(error); }
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-exit-self-test.json"),
|
||||
JsonSerializer.Serialize(new { Passed = checks.Values.All(x => x), Checks = checks }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return checks.Values.All(x => x) ? 0 : 85;
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ClientShutdownUiSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
string? error = null;
|
||||
try
|
||||
{
|
||||
var uiThread = Environment.CurrentManagedThreadId;
|
||||
var disposals = 0;
|
||||
var background = false;
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (var form = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
async () => { Interlocked.Increment(ref disposals); background = Environment.CurrentManagedThreadId != uiThread; await release.Task; })))
|
||||
{
|
||||
form.Show(); PumpUntil(() => form.LoginReadyForTest);
|
||||
form.WindowChromeForTest!.SetLoginMode(false);
|
||||
form.Close();
|
||||
checks["ordinary_authenticated_close_is_blocked"] = form.Visible && !form.IsDisposed && disposals == 0;
|
||||
form.RequestExitForUpdate();
|
||||
PumpUntil(() => Volatile.Read(ref disposals) == 1);
|
||||
form.RequestExitForUpdate();
|
||||
checks["installer_exit_bypasses_tray_and_starts_cleanup_once"] = disposals == 1 && !form.IsDisposed && background;
|
||||
release.SetResult();
|
||||
checks["installer_closes_when_tracked_cleanup_finishes"] = PumpUntil(() => form.IsDisposed);
|
||||
}
|
||||
|
||||
using (var failed = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => Task.FromException(new IOException("isolated recovery failure")))))
|
||||
{
|
||||
failed.Show(); PumpUntil(() => failed.LoginReadyForTest);
|
||||
failed.RequestExitForUpdate();
|
||||
checks["installer_recovery_error_closes_without_blocking_modal"] = PumpUntil(() => failed.IsDisposed)
|
||||
&& failed.NetworkRecoveryFailed;
|
||||
}
|
||||
|
||||
var timedOutRecovery = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (var timedOut = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => timedOutRecovery.Task, TimeSpan.FromMilliseconds(80))))
|
||||
{
|
||||
timedOut.Show(); PumpUntil(() => timedOut.LoginReadyForTest);
|
||||
timedOut.RequestExitForUpdate();
|
||||
checks["stalled_recovery_bounds_exit_and_blocks_install_success"] = PumpUntil(() => timedOut.IsDisposed)
|
||||
&& timedOut.NetworkRecoveryFailed;
|
||||
timedOutRecovery.SetResult();
|
||||
}
|
||||
|
||||
disposals = 0;
|
||||
using (var canceled = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => { Interlocked.Increment(ref disposals); return Task.CompletedTask; })))
|
||||
{
|
||||
canceled.Show(); PumpUntil(() => canceled.LoginReadyForTest);
|
||||
Invoke(canceled, "SetBusy", true, null);
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
var query = Dispatch(canceled, 0x11, IntPtr.Zero);
|
||||
var repeat = Dispatch(canceled, 0x11, IntPtr.Zero);
|
||||
checks["repeated_session_query_returns_promptly_without_recovery"] = watch.ElapsedMilliseconds < 300
|
||||
&& query == (IntPtr)1 && repeat == (IntPtr)1 && disposals == 0
|
||||
&& !Lifetime(canceled).IsCancellationRequested && !canceled.IsDisposed;
|
||||
// Query/canceled END must not reset an active operation or its UI.
|
||||
canceled.Enabled = false; canceled.UseWaitCursor = true;
|
||||
Dispatch(canceled, 0x16, IntPtr.Zero);
|
||||
Dispatch(canceled, 0x16, IntPtr.Zero);
|
||||
checks["canceled_session_query_preserves_active_ui_state"] = !canceled.Enabled && canceled.UseWaitCursor
|
||||
&& !Lifetime(canceled).IsCancellationRequested && disposals == 0;
|
||||
canceled.Enabled = true; Invoke(canceled, "SetBusy", false, null);
|
||||
checks["operation_can_finish_after_canceled_shutdown"] = canceled.LoginReadyForTest;
|
||||
canceled.RequestExitForUpdate();
|
||||
checks["canceled_query_client_can_later_exit"] = PumpUntil(() => canceled.IsDisposed) && disposals == 1;
|
||||
}
|
||||
|
||||
disposals = 0;
|
||||
using (var queued = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => { Interlocked.Increment(ref disposals); return Task.CompletedTask; })))
|
||||
{
|
||||
queued.Show(); PumpUntil(() => queued.LoginReadyForTest);
|
||||
Dispatch(queued, 0x11, IntPtr.Zero);
|
||||
queued.RequestExitForUpdate();
|
||||
checks["installer_exit_still_works_after_session_query"] = PumpUntil(() => queued.IsDisposed) && disposals == 1;
|
||||
}
|
||||
|
||||
disposals = 0;
|
||||
using (var confirmed = new MainForm(uiOnly: true, exitRecoveryFixture: new(
|
||||
() => { Interlocked.Increment(ref disposals); return Task.CompletedTask; })))
|
||||
{
|
||||
confirmed.Show(); PumpUntil(() => confirmed.LoginReadyForTest);
|
||||
Dispatch(confirmed, 0x11, IntPtr.Zero);
|
||||
Invoke(confirmed, "CompleteSessionEnding");
|
||||
Invoke(confirmed, "CompleteSessionEnding");
|
||||
Dispatch(confirmed, 0x16, IntPtr.Zero);
|
||||
checks["confirmed_session_finalizes_once_and_cannot_resume"] = disposals == 1
|
||||
&& Lifetime(confirmed).IsCancellationRequested && !confirmed.NetworkRecoveryFailed;
|
||||
}
|
||||
}
|
||||
catch (Exception exception) { error = exception.ToString(); }
|
||||
var passed = error is null && checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-exit-ui-self-test.json"),
|
||||
JsonSerializer.Serialize(new { Passed = passed, Checks = checks, Error = error, ProductionNetworking = false, ActualWindowsShutdown = false }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 86;
|
||||
}
|
||||
|
||||
private static object? Invoke(MainForm form, string method, params object?[] args) => typeof(MainForm)
|
||||
.GetMethod(method, BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(form, args);
|
||||
private static IntPtr Dispatch(MainForm form, int message, IntPtr wparam)
|
||||
{
|
||||
object?[] args = [Message.Create(form.Handle, message, wparam, IntPtr.Zero)];
|
||||
typeof(MainForm).GetMethod("WndProc", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(form, args);
|
||||
return ((Message)args[0]!).Result;
|
||||
}
|
||||
private static CancellationTokenSource Lifetime(MainForm form) => (CancellationTokenSource)typeof(MainForm)
|
||||
.GetField("_lifetime", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(form)!;
|
||||
private static bool PumpUntil(Func<bool> condition)
|
||||
{
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
while (!condition() && watch.ElapsedMilliseconds < 2500) { Application.DoEvents(); Thread.Sleep(5); }
|
||||
return condition();
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// The confirmation dialog runs a nested message loop. Shutdown may win while
|
||||
// it is open, or while the package is downloading; never launch afterwards.
|
||||
internal static class ClientUpdateFlow
|
||||
{
|
||||
internal static async Task<bool> RunAsync(Func<bool> isCurrent, Func<bool> confirm,
|
||||
Func<Task<string>> download, Action<string> launch)
|
||||
{
|
||||
if (!isCurrent() || !confirm() || !isCurrent()) return false;
|
||||
var installer = await download();
|
||||
if (!isCurrent()) return false;
|
||||
launch(installer);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+24
-55
@@ -74,8 +74,6 @@ internal sealed partial class MainForm : Form
|
||||
private Task<Exception?>? _exitCleanupTask;
|
||||
private bool _exitResourcesDisposed;
|
||||
private bool _sessionEnding;
|
||||
private bool _installerExitRequested;
|
||||
private readonly ClientExitRecoveryFixture? _exitRecoveryFixture;
|
||||
private bool _windowExitSelfTestConnected;
|
||||
private bool _updateCheckRunning;
|
||||
private DateTimeOffset _nextUpdateCheckAt = DateTimeOffset.MinValue;
|
||||
@@ -87,11 +85,8 @@ internal sealed partial class MainForm : Form
|
||||
internal bool NetworkRecoveryFailed { get; private set; }
|
||||
|
||||
internal MainForm(bool runWindowExitSelfTest = false, bool preview = false, bool uiOnly = false,
|
||||
bool autoConnect = false, Func<CancellationToken, Task>? startupRecovery = null,
|
||||
ClientExitRecoveryFixture? exitRecoveryFixture = null)
|
||||
bool autoConnect = false, Func<CancellationToken, Task>? startupRecovery = null)
|
||||
{
|
||||
if (exitRecoveryFixture is not null && !uiOnly) throw new ArgumentException("Recovery fixtures require uiOnly isolation.");
|
||||
_exitRecoveryFixture = exitRecoveryFixture;
|
||||
_uiOnly = uiOnly;
|
||||
_preview = preview;
|
||||
_startupRecovery = startupRecovery;
|
||||
@@ -197,34 +192,33 @@ internal sealed partial class MainForm : Form
|
||||
return false;
|
||||
}
|
||||
var notes = string.IsNullOrWhiteSpace(update.Notes) ? "包含稳定性和网络恢复改进。" : update.Notes.Trim();
|
||||
return await ClientUpdateFlow.RunAsync(
|
||||
() => !_exiting && !_sessionEnding && !IsDisposed && !Disposing && !_lifetime.IsCancellationRequested,
|
||||
() => {
|
||||
var choice = MessageBox.Show(this,
|
||||
var choice = MessageBox.Show(
|
||||
$"发现新版本 {update.Version}\n\n{notes}\n\n是否现在安全升级?\n升级将覆盖原安装目录,但会保留账号、设备标识和本机配置。",
|
||||
"纵横家·发现更新",
|
||||
update.Mandatory ? MessageBoxButtons.OKCancel : MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Information);
|
||||
accepted = update.Mandatory ? choice == DialogResult.OK : choice == DialogResult.Yes;
|
||||
if (!accepted) _nextUpdateCheckAt = DateTimeOffset.UtcNow.AddHours(6);
|
||||
return accepted;
|
||||
}, async () => {
|
||||
if (!accepted)
|
||||
{
|
||||
_nextUpdateCheckAt = DateTimeOffset.UtcNow.AddHours(6);
|
||||
return false;
|
||||
}
|
||||
|
||||
UseWaitCursor = true;
|
||||
Text = $"纵横家 · 正在下载 {update.Version}…";
|
||||
using var progressWindow = new UpdateProgressForm(update.Version);
|
||||
progressWindow.Show(this);
|
||||
Enabled = false;
|
||||
try { return await ClientUpdater.DownloadAsync(update, _lifetime.Token, new Progress<int>(progressWindow.Report)); }
|
||||
finally { if (!_exiting && !IsDisposed && !Disposing) Enabled = true; }
|
||||
}, installer => {
|
||||
string installer;
|
||||
try { installer = await ClientUpdater.DownloadAsync(update, _lifetime.Token, new Progress<int>(progressWindow.Report)); }
|
||||
finally { Enabled = true; }
|
||||
// Start and authorize the installer BEFORE stopping the working client.
|
||||
// The installer stages and validates all files, then requests graceful shutdown.
|
||||
// Cancelling UAC or failing to start must leave the current connection alive.
|
||||
var installerProcess = ClientUpdater.LaunchInstaller(installer);
|
||||
_installerLaunched = true;
|
||||
_ = ObserveInstallerAsync(installerProcess);
|
||||
AppPaths.WriteLog("update.install.started version=" + update.Version);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
@@ -234,7 +228,7 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
_nextUpdateCheckAt = DateTimeOffset.UtcNow.AddMinutes(accepted ? 30 : 2);
|
||||
AppPaths.WriteError(exception);
|
||||
if (accepted && !_exiting && !_sessionEnding && !IsDisposed && !Disposing)
|
||||
if (accepted)
|
||||
{
|
||||
MessageBox.Show(
|
||||
$"更新未启动,已保留当前版本和当前连接。\n\n{exception.Message}",
|
||||
@@ -247,7 +241,8 @@ internal sealed partial class MainForm : Form
|
||||
finally
|
||||
{
|
||||
_updateCheckRunning = false;
|
||||
if (!_exiting && !IsDisposed && !Disposing) { UseWaitCursor = false; Text = "纵横家"; }
|
||||
UseWaitCursor = false;
|
||||
Text = "纵横家";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1254,7 +1249,7 @@ internal sealed partial class MainForm : Form
|
||||
eventArgs.Cancel = true;
|
||||
return;
|
||||
}
|
||||
if ((_uiOnly || _preview) && _exitRecoveryFixture is null)
|
||||
if (_uiOnly || _preview)
|
||||
{
|
||||
_ = BeginExitCleanup();
|
||||
CompleteExitResources();
|
||||
@@ -1274,21 +1269,13 @@ internal sealed partial class MainForm : Form
|
||||
SetConnectionState(false, "正在恢复本地网络", "正在恢复系统代理并关闭内核,请稍候…");
|
||||
}
|
||||
|
||||
Exception? error;
|
||||
try { error = await cleanup.WaitAsync(_exitRecoveryFixture?.Deadline ?? TimeSpan.FromSeconds(85)); }
|
||||
catch (TimeoutException timeout)
|
||||
{
|
||||
// Leave every still-owned recovery journal intact. The installer
|
||||
// observes a nonzero client exit and must not replace its files.
|
||||
error = timeout;
|
||||
AppPaths.WriteLog("exit.recovery.timeout journals_retained=true");
|
||||
}
|
||||
var error = await cleanup;
|
||||
if (_sessionEnding || IsDisposed || Disposing) return;
|
||||
if (error is not null)
|
||||
{
|
||||
// Never install over a client whose network recovery failed.
|
||||
NetworkRecoveryFailed = true;
|
||||
if (!_installerExitRequested) MessageBox.Show("网络恢复未全部完成,恢复记录已保留;本次不继续自动安装。\n" + error.GetBaseException().Message,
|
||||
MessageBox.Show("网络恢复未全部完成,恢复记录已保留;本次不继续自动安装。\n" + error.GetBaseException().Message,
|
||||
"纵横家 · 网络恢复提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
CompleteExitResources();
|
||||
@@ -1306,19 +1293,13 @@ internal sealed partial class MainForm : Form
|
||||
_refreshTimer.Stop(); _updateTimer.Stop(); _trafficTimer.Stop(); _healthTimer.Stop();
|
||||
_nodeTrafficTimer.Stop();
|
||||
_lifetime.Cancel();
|
||||
if ((_uiOnly || _preview) && _exitRecoveryFixture is null) return _exitCleanupTask = Task.FromResult<Exception?>(null);
|
||||
if (_uiOnly || _preview) return _exitCleanupTask = Task.FromResult<Exception?>(null);
|
||||
// The same tracked cleanup serves menu/installer exit and session end.
|
||||
// Run it without a UI synchronization context so WM_ENDSESSION can
|
||||
// wait within Windows' shutdown budget without blocking its continuations.
|
||||
return _exitCleanupTask = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_exitRecoveryFixture is { } fixture) await fixture.Dispose().ConfigureAwait(false);
|
||||
else await _xray.DisposeAsync().ConfigureAwait(false);
|
||||
return (Exception?)null;
|
||||
}
|
||||
catch (OperationCanceledException error) when (_sessionEnding) { return error; }
|
||||
try { await _xray.DisposeAsync().ConfigureAwait(false); return (Exception?)null; }
|
||||
catch (Exception error) { AppPaths.WriteError(error); return error; }
|
||||
});
|
||||
}
|
||||
@@ -1339,17 +1320,14 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
if (message.Msg == 0x11 /* WM_QUERYENDSESSION */)
|
||||
{
|
||||
// A query can be canceled. Return promptly without disconnecting
|
||||
// or launching any recovery helper before Windows confirms it.
|
||||
// A query may be canceled by another application. Do not cancel
|
||||
// our session or await network cleanup until Windows confirms it.
|
||||
message.Result = (IntPtr)1;
|
||||
return;
|
||||
}
|
||||
if (message.Msg == 0x16 /* WM_ENDSESSION */)
|
||||
{
|
||||
if (message.WParam == IntPtr.Zero)
|
||||
{
|
||||
message.Result = IntPtr.Zero; return;
|
||||
}
|
||||
if (message.WParam == IntPtr.Zero) { message.Result = IntPtr.Zero; return; }
|
||||
CompleteSessionEnding();
|
||||
}
|
||||
base.WndProc(ref message);
|
||||
@@ -1359,7 +1337,6 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
if (_sessionEnding) return;
|
||||
_sessionEnding = true;
|
||||
_xray.ConfirmSessionShutdown();
|
||||
var cleanup = BeginExitCleanup();
|
||||
// Windows can terminate us after its short shutdown allowance. Never
|
||||
// remove recovery journals here or display a modal recovery error.
|
||||
@@ -1459,19 +1436,11 @@ internal sealed partial class MainForm : Form
|
||||
|
||||
internal void RequestExit()
|
||||
{
|
||||
if (IsDisposed || Disposing) return;
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
_exitRequested = true;
|
||||
if (_exiting) return;
|
||||
Close();
|
||||
}
|
||||
|
||||
internal void RequestExitForUpdate()
|
||||
{
|
||||
_installerExitRequested = true;
|
||||
AppPaths.WriteLog("update.shutdown.requested");
|
||||
RequestExit();
|
||||
}
|
||||
|
||||
private static void OpenRegistrationPage()
|
||||
{
|
||||
try
|
||||
|
||||
+15
-20
@@ -11,19 +11,6 @@ internal static class Program
|
||||
[STAThread]
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (args.Length == 1 && args[0] == "--client-shutdown-self-test")
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
return ClientShutdownSelfTest.Run();
|
||||
}
|
||||
if (args.Length == 3 && args[0] == "--client-shutdown-test-child"
|
||||
&& int.TryParse(args[1], out var childDelay) && childDelay is >= 10 and <= 2000
|
||||
&& int.TryParse(args[2], out var childExit) && childExit is 0 or 7)
|
||||
{
|
||||
Thread.Sleep(childDelay);
|
||||
return childExit;
|
||||
}
|
||||
if (args.Any(a => a.StartsWith("--client-shutdown-test-child", StringComparison.OrdinalIgnoreCase))) return 87;
|
||||
if (args.Length == 5 && args[0] is "--installer-guardian-gate" or "--installer-guardian-apply")
|
||||
return InstallerGuardianGate.Run(args[1], args[2], args[3], args[4], apply: args[0] == "--installer-guardian-apply");
|
||||
// Malformed maintenance arguments must never fall through to the GUI.
|
||||
@@ -208,12 +195,9 @@ internal static class Program
|
||||
shutdownEvent,
|
||||
(_, _) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!mainForm.IsDisposed && mainForm.IsHandleCreated)
|
||||
mainForm.BeginInvoke(mainForm.RequestExitForUpdate);
|
||||
}
|
||||
catch (InvalidOperationException) { /* A concurrent close destroyed the HWND. */ }
|
||||
var form = Application.OpenForms.OfType<MainForm>().FirstOrDefault();
|
||||
if (form is null || form.IsDisposed || !form.IsHandleCreated) return;
|
||||
form.BeginInvoke(form.RequestExit);
|
||||
},
|
||||
null,
|
||||
Timeout.Infinite,
|
||||
@@ -351,7 +335,18 @@ internal static class Program
|
||||
foreach (var process in processes) process.CloseMainWindow();
|
||||
}
|
||||
|
||||
return ClientShutdownScope.WaitForExit(processes) ? 0 : 2;
|
||||
foreach (var process in processes)
|
||||
{
|
||||
using (process)
|
||||
{
|
||||
if (!process.WaitForExit(15_000))
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
if (process.ExitCode != 0) return 2;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
# 纵横家 Windows 0.3.7 开源源码
|
||||
# 纵横家 Windows 0.3.6 开源源码
|
||||
|
||||
基于已冻结的 0.3.7 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
基于已冻结的 0.3.6 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -17,4 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
|
||||
|
||||
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
|
||||
|
||||
0.3.7:修复升级确认后窗口退出竞态、旧进程退出等待期限、安装器退出的阻塞提示,并改进Windows会话结束的限时清理和恢复记录保留。保留0.3.6连接与运行组件修复。已进行隔离回归,不代表实际关机验收。可选JPG保持从开源代码中省略,许可边界保持不变。
|
||||
0.3.6:连接前检查本机Xray及必要运行文件;组件缺失时一次性明确提示修复安装,避免逐节点重复失败。延长受限速环境下完整升级包下载的总时间预算。保留0.3.5本机和服务器趋势图、连接容错、调度与路由规则,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.3.7</Version>
|
||||
<AssemblyVersion>0.3.7.0</AssemblyVersion>
|
||||
<FileVersion>0.3.7.0</FileVersion>
|
||||
<InformationalVersion>0.3.7</InformationalVersion>
|
||||
<Version>0.3.6</Version>
|
||||
<AssemblyVersion>0.3.6.0</AssemblyVersion>
|
||||
<FileVersion>0.3.6.0</FileVersion>
|
||||
<InformationalVersion>0.3.6</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
|
||||
+9
-25
@@ -22,8 +22,6 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
private bool _disposed;
|
||||
private NetworkOwnerLease? _ownerLease;
|
||||
private bool _recoveryComplete;
|
||||
private bool _stoppedCleanly;
|
||||
private readonly CancellationTokenSource _systemShutdown = new();
|
||||
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
||||
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
|
||||
private string? _baseConfigJson;
|
||||
@@ -68,8 +66,6 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
public bool CanRebindNetwork => !string.IsNullOrWhiteSpace(_baseConfigJson) && _boundNetwork is not null;
|
||||
bool IHandoverRuntime.IsRunning => IsRunning;
|
||||
|
||||
internal void ConfirmSessionShutdown() => _systemShutdown.Cancel();
|
||||
|
||||
public async Task SuspendForNetworkChangeAsync(CancellationToken token)
|
||||
{
|
||||
await _lifecycle.WaitAsync(token);
|
||||
@@ -292,7 +288,6 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
{
|
||||
ValidateRuntime();
|
||||
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
|
||||
_stoppedCleanly = false;
|
||||
PrivateAuxiliaryRuntime.ValidateLifetime(_baseConfigJson);
|
||||
var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson);
|
||||
var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost;
|
||||
@@ -440,18 +435,16 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
{
|
||||
// A rejected second instance must not delete the active owner's DNS,
|
||||
// routes, PID journal or virtual adapter through its error/Dispose path.
|
||||
if (_ownerLease is null || !_recoveryComplete || _stoppedCleanly) return;
|
||||
if (_ownerLease is null || !_recoveryComplete) return;
|
||||
_learningEpoch.Cancel();
|
||||
var proxyRestored = SystemProxy.Restore();
|
||||
Exception? restoreError = null;
|
||||
var sessionToken = _systemShutdown.Token;
|
||||
using var recovery = CancellationTokenSource.CreateLinkedTokenSource(sessionToken);
|
||||
recovery.CancelAfter(TimeSpan.FromSeconds(25));
|
||||
using var recovery = new CancellationTokenSource(TimeSpan.FromSeconds(25));
|
||||
Exception? dnsRestoreError = null;
|
||||
try { recovery.Token.ThrowIfCancellationRequested(); await ProxyDnsPolicy.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { dnsRestoreError = error; if (!sessionToken.IsCancellationRequested) AppPaths.WriteError(error); }
|
||||
try { recovery.Token.ThrowIfCancellationRequested(); await TunRouting.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { restoreError = error; if (!sessionToken.IsCancellationRequested) AppPaths.WriteError(error); }
|
||||
try { await ProxyDnsPolicy.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { dnsRestoreError = error; AppPaths.WriteError(error); }
|
||||
try { await TunRouting.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
||||
catch (Exception error) { restoreError = error; AppPaths.WriteError(error); }
|
||||
try
|
||||
{
|
||||
if (_process is { HasExited: false })
|
||||
@@ -471,30 +464,21 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
SafeDelete(AppPaths.PidFile);
|
||||
SafeDeleteConfig();
|
||||
}
|
||||
// Confirmed system shutdown forbids launching fresh helper processes.
|
||||
// Kill the already-owned core above, retain failed journals, and let
|
||||
// startup recovery finish after Windows is ready again.
|
||||
sessionToken.ThrowIfCancellationRequested();
|
||||
await TunRouting.CleanupOwnedAdapterAsync(sessionToken).ConfigureAwait(false);
|
||||
await TunRouting.CleanupOwnedAdapterAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
if (restoreError is not null)
|
||||
{
|
||||
// Removal of a failed TUN device may have removed its routes too.
|
||||
// Retry the retained journal; never erase it merely because exit was requested.
|
||||
using var retry = CancellationTokenSource.CreateLinkedTokenSource(sessionToken);
|
||||
retry.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
retry.Token.ThrowIfCancellationRequested();
|
||||
using var retry = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
await TunRouting.RestoreAsync(retry.Token).ConfigureAwait(false);
|
||||
}
|
||||
if (!proxyRestored && !SystemProxy.Restore())
|
||||
throw new IOException("系统代理恢复未完成,恢复记录已保留。请勿继续升级安装。");
|
||||
if (dnsRestoreError is not null)
|
||||
{
|
||||
using var retry = CancellationTokenSource.CreateLinkedTokenSource(sessionToken);
|
||||
retry.CancelAfter(TimeSpan.FromSeconds(25));
|
||||
retry.Token.ThrowIfCancellationRequested();
|
||||
using var retry = new CancellationTokenSource(TimeSpan.FromSeconds(25));
|
||||
await ProxyDnsPolicy.RestoreAsync(retry.Token).ConfigureAwait(false);
|
||||
}
|
||||
_stoppedCleanly = true;
|
||||
}
|
||||
|
||||
private async Task HandleCoreExitAsync(Process exited)
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# 纵横家 Windows 0.3.7
|
||||
|
||||
修复自动升级确认后旧程序偶发无法退出,以及退出过程中后台升级检查继续操作已销毁窗口的问题。
|
||||
|
||||
- 升级确认和下载完成后重新检查窗口生命周期,退出时取消升级检查,避免关闭后再次弹窗。
|
||||
- 安装器等待旧程序的期限与网络恢复流程对齐,后台升级退出不被恢复警告弹窗挡住。
|
||||
- 关闭事件与窗口销毁发生竞争时安全结束回调。
|
||||
- Windows 查询关机时立即响应,取消关机不会改变当前连接;确认结束时使用限时清理,不再启动新的外部恢复工具或交互提示,未完成的恢复记录保留供下次启动处理。
|
||||
- 保留 0.3.6 的运行组件修复、内网优先和本机与服务器独立流量趋势。
|
||||
|
||||
验证包含同包离线回归和隔离退出/会话消息测试。没有重启当前电脑,不将模拟消息测试称为真实关机验收。安装包未签名,安装时仍需 Windows 授权。
|
||||
Reference in New Issue
Block a user