Compare commits

...

2 Commits

35 changed files with 1511 additions and 359 deletions
+294
View File
@@ -761,5 +761,299 @@
], ],
"SourceOnly": true, "SourceOnly": true,
"Version": "0.3.3" "Version": "0.3.3"
},
"Windows034ConnectionResilienceDelta": {
"CandidateSha256": "270c5c8d804fc1c2c930a4d86667b6fbf0f7bab9875f359a076342ee5a96cb78",
"ExampleEndpointChanges": [
{
"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/release/RELEASE-NOTES-0.3.4.md"
},
{
"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": 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": 1,
"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"
}
],
"FrozenSha256": "63580db09d867fb14853c17a8d7f7be8c420b0eb389457adf5f910fe1ab5ce6c",
"Omitted": [
"windows/assets/login-cloud-scene-v1.jpg"
],
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "343499b680a3f91e01349123a8d9ce449db2bb8184aaf7d4c7f15934cd02383f",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "aff1a50d35c22507bf4e72d44827038d7f8454e9",
"PublicDownloadDomainsRetained": [
"pro.ucvl.cn"
],
"SourceOnly": true,
"Version": "0.3.4"
},
"Windows035TrafficTrendsDelta": {
"CandidateSha256": "cd804728119ed9919898d14cd0fc0f0e36e027fa0afcac0e1f6ef6eff6afc41f",
"ExampleEndpointChanges": [
{
"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": 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": 1,
"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"
}
],
"FrozenSha256": "436f20672b19ec5ef64629ccfe41101515f110ff5bd218f279841b4718e7fdc9",
"Omitted": [
"windows/assets/login-cloud-scene-v1.jpg"
],
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "574f523befd28991f8f98da25cbb3efbcd035080953b286d40958683593afdcb",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "991b029b371ce42804bd4d7c689a6f756128e8ac",
"PublicDownloadDomainsRetained": [
"pro.ucvl.cn"
],
"SourceOnly": true,
"Version": "0.3.5"
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
# 纵横家开源源码 # 纵横家开源源码
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.3、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。 此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.5、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
| 目录 | 内容与状态 | | 目录 | 内容与状态 |
| --- | --- | | --- | --- |
+60 -25
View File
@@ -4,7 +4,7 @@
"ExportDiffersFromOriginalCandidates": true, "ExportDiffersFromOriginalCandidates": true,
"FilesBeforeProvenanceAndAudit": { "FilesBeforeProvenanceAndAudit": {
"LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", "LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
"README.md": "a64ccb0297d56ab12f3859d8a4559ec1d8ad7ac564c5805cd141f38bbb7eab3f", "README.md": "0a94bef78ae64402abf281075d68dcba5aafca466d284bb5dd88c492f9924834",
"SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c", "SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c",
"THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c", "android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c",
@@ -186,18 +186,20 @@
"windows/ClientShutdownScope.cs": "f5944b57ccb4616dbd32ee2952b56dd0c9feccb7c556d8954092c88354a78d41", "windows/ClientShutdownScope.cs": "f5944b57ccb4616dbd32ee2952b56dd0c9feccb7c556d8954092c88354a78d41",
"windows/ClientUpdater.cs": "b218513dc57b8513eb749aeab093e39911428a07f05363ae349555d22e53e4b8", "windows/ClientUpdater.cs": "b218513dc57b8513eb749aeab093e39911428a07f05363ae349555d22e53e4b8",
"windows/ConnectionAcceptanceTrace.cs": "c9efd15e19672a5ac3b4b807c96a3de3db3ff2fd373e13494a548df51fecdd9a", "windows/ConnectionAcceptanceTrace.cs": "c9efd15e19672a5ac3b4b807c96a3de3db3ff2fd373e13494a548df51fecdd9a",
"windows/ConnectionHealthPolicy.cs": "c17cf49eab51b691163ee8105f32bcaec121707ead862a773dbc372bf01e2a11", "windows/ConnectionAuthorizationLease.cs": "3edbd5123c051c797c488b49bcd7204d8c1a0c5a0743bfec95ffa4ab0bdd9bfc",
"windows/ConnectionHealthSelfTest.cs": "5a483194f754ad51366acd9df00554c8ceecaa5dadba73972c4922b72dc7e2fe", "windows/ConnectionAuthorizationSelfTest.cs": "d747ac77ef353a991fd50ae3f2229e063d27ede7b6e588d2e17a41a06b7abe90",
"windows/ConnectionRecoveryPolicy.cs": "860bd4cedf393f157fc1dd68e407776e1fe0fa1cc6cef7e99cd5581b64c6f5f6", "windows/ConnectionHealthPolicy.cs": "69f5dd230631f4b10a091f53a5000df46d19561b7c65c82a2b97eddfef7f82dd",
"windows/ConnectionHealthSelfTest.cs": "3715ea4ed2a6d44a41a3f8d5c4c4bfc65f8f20cf9dd5b3dda2a47e7503bf4813",
"windows/ConnectionRecoveryPolicy.cs": "814f4fa370f445c40ac4cc79d8e07663975f5ad20d9ef77df2affb342609ac17",
"windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc", "windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc",
"windows/ConnectionSelectionSelfTest.cs": "1ed673268d6e443ec84ef39dbf5e5562132e5ea31fc87977a54d9805b0fef3a8", "windows/ConnectionSelectionSelfTest.cs": "1ed673268d6e443ec84ef39dbf5e5562132e5ea31fc87977a54d9805b0fef3a8",
"windows/ConnectionSelfTest.cs": "6ad3f227cec3e26514d833ec1cb996818597a0cb27901053362faa45e3c1c9b3", "windows/ConnectionSelfTest.cs": "6ad3f227cec3e26514d833ec1cb996818597a0cb27901053362faa45e3c1c9b3",
"windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716", "windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716",
"windows/DashboardComboSelfTest.cs": "f1149225e373936f0e90f3f2a5b4fa29179398bba641051fceba1b1cda78b998", "windows/DashboardComboSelfTest.cs": "f1149225e373936f0e90f3f2a5b4fa29179398bba641051fceba1b1cda78b998",
"windows/DashboardControls.cs": "091ee2f42de1ecd56f5ffbe506a60af95c98ce917ee782d95b8ab7be3e064a6b", "windows/DashboardControls.cs": "55af71aac386053d05a14cb3205083654aff4f00d49b2fa3427e0c81eb57a97b",
"windows/DashboardInteractionSelfTest.cs": "401ca89225426627e10a8d0559daf7aa5f530fbb9e7485feda6affab64ddb255", "windows/DashboardInteractionSelfTest.cs": "4fc5d158ad7ec85b9327439c37a7a720a86d6b96ff9aaafe764d31eb035392ea",
"windows/DashboardLayout.cs": "5625a220a49bff18f843aebe5e4540b4df8e7dc75ba9b8aaf464ea1fb5215c23", "windows/DashboardLayout.cs": "9f49a378af4f81424c0ce3f75e684691ab06f6e1a004fc6c9ab6d982e345c6ef",
"windows/DashboardTailnetLayoutSelfTest.cs": "bc4f51bae884e135a183caa7f389a0065d523a52078d7c69b33201996606bd43", "windows/DashboardTailnetLayoutSelfTest.cs": "4a84f4954a0d3075217958f884a45178cff893938a9d3cec0d5d0479a471655f",
"windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f", "windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f",
"windows/GitReleasePolicySelfTest.cs": "9e49ba957ab15a5c23d889004b171856c3d523f98cecf10088df4fcd8b577c61", "windows/GitReleasePolicySelfTest.cs": "9e49ba957ab15a5c23d889004b171856c3d523f98cecf10088df4fcd8b577c61",
"windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b", "windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b",
@@ -221,14 +223,14 @@
"windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c", "windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c",
"windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7", "windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7",
"windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a", "windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a",
"windows/MainForm.Compact.cs": "c4f4e4af89804bb8dc2c2d5d285f388c38e6382bdb79b28a38bd6cfb9a98c396", "windows/MainForm.Compact.cs": "2e2835ce952be24fdbe711032aebfe7f046e7c0d1967204d2e9981d9e694d6e1",
"windows/MainForm.Dashboard.cs": "bc9593cfcf3564807e523c34c120d92502e54855de714b6162f434a5e47faa95", "windows/MainForm.Dashboard.cs": "46edae6d3412cee5369287ce67e1951867f728ee0a8f469879287e4c5ebd064b",
"windows/MainForm.Handover.cs": "4a914f4de335331f1f9d2397407328f17ae372e9119329e534af218555dc92e6", "windows/MainForm.Handover.cs": "4a914f4de335331f1f9d2397407328f17ae372e9119329e534af218555dc92e6",
"windows/MainForm.NextGeneration.cs": "2b34a4191e9a3c3b07507c4975f4dcbce04b0045af7a27d64190741d8639e678", "windows/MainForm.NextGeneration.cs": "5a1c21e02e304a5135b66160855aba5961d5da7da68041ff1b79be9de4a41916",
"windows/MainForm.Selection.cs": "71d3884eb6535b1c8095379585a7479c5d7dd35d00e59da4dabfa673557f17fa", "windows/MainForm.Selection.cs": "71d3884eb6535b1c8095379585a7479c5d7dd35d00e59da4dabfa673557f17fa",
"windows/MainForm.TailnetTraffic.cs": "432ea16a7f5fe66006530b5b90af6eab59362a2b02685ec2130dadfd43c1652b", "windows/MainForm.TailnetTraffic.cs": "bc48728563f163cc8553b288bcccd71e7d756f8beb11c13cb486652024c4b8d4",
"windows/MainForm.TransportSelection.cs": "7e7bf74f16cb902b71da5a13117db06e9cdf4ea6121511a5ebceaf017bd1f919", "windows/MainForm.TransportSelection.cs": "7e7bf74f16cb902b71da5a13117db06e9cdf4ea6121511a5ebceaf017bd1f919",
"windows/MainForm.cs": "326a8dbabc89d58534c718ceb967a18ec7caf6809ad0c390ba8c40f66b19a321", "windows/MainForm.cs": "d515ae6f05f992789b63132a91141dbb6ea50e3d794b86c8174da1396b746687",
"windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46", "windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46",
"windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73", "windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73",
@@ -239,12 +241,15 @@
"windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc", "windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc",
"windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3", "windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3",
"windows/NextGenerationSelfTest.cs": "a92cbbf4c8ba0cde0ec12faf2e1cdbcd2c86f758d440d677471968569030f8f1", "windows/NextGenerationSelfTest.cs": "a92cbbf4c8ba0cde0ec12faf2e1cdbcd2c86f758d440d677471968569030f8f1",
"windows/NodeHealthProbe.cs": "5c501094402010d2f8ecdc4145f1084ef084b749c2b47794fca0c0f60c4441fb", "windows/NodeHealthProbe.cs": "c9e5aded50d6091065258c2a882d914683ed95075e66650e177f29df36fe31f2",
"windows/NodeHealthProbeSelfTest.cs": "85d645160ed53f2646b58ba29d2ec17d6ff8fa54b658dc15e15c9609514c16ea", "windows/NodeHealthProbeSelfTest.cs": "512dd9f91ef8c1d645908300b3f1a08c18905caaf7a1174b230b17e963603c62",
"windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d", "windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d",
"windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0", "windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0",
"windows/NodeTrafficMonitor.cs": "03bdbb748fee521a6e0d9b08edbf60c5699ae1ebf98ae719d9c45a5cf0962a5a", "windows/NodeTrafficBackendFixtures.cs": "e2e2c72e64716f0b6d2e464b6746b33fee8675d05159eb46a377c83cf312403b",
"windows/NodeTrafficSelfTest.cs": "fc9a3e318c7b560c96b6e829990cc4b97c25d8283876a0239085db23c17ae34b", "windows/NodeTrafficMonitor.cs": "8ad43107d2f27d6308500456ecdbc22dc79be08b5f23191044f23591f05783ad",
"windows/NodeTrafficOneSecondSelfTest.cs": "640dc4091dbd0ac3d0b900b49e44d2876b8b1250461a652f50dbfbe4e007f78d",
"windows/NodeTrafficRepaintSelfTest.cs": "06f359e55cc35c73cf53443ff452d57c585c7214ced8f84a9b9e385c2e699bf3",
"windows/NodeTrafficSelfTest.cs": "284086275fbb7f81dbcbff2c7267379402c84cb2e4325658946520cf9b9b518d",
"windows/NodeTransportConnector.cs": "91d53471f35470fc9a4578e2819863e56a790cda62a7dbfe891a71149d2386e1", "windows/NodeTransportConnector.cs": "91d53471f35470fc9a4578e2819863e56a790cda62a7dbfe891a71149d2386e1",
"windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63", "windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63",
"windows/PlatformBootstrapTransport.cs": "0eef4a4272449c0e2adfac2e4652bd9cff9c1b2bc11011ca2049dde2f97e4e2b", "windows/PlatformBootstrapTransport.cs": "0eef4a4272449c0e2adfac2e4652bd9cff9c1b2bc11011ca2049dde2f97e4e2b",
@@ -258,7 +263,7 @@
"windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec", "windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec",
"windows/PublicTailnetSelection.cs": "68b6dd3d5c77c3253046f9b90e22742c1f2852e07d07157daa296512370fada7", "windows/PublicTailnetSelection.cs": "68b6dd3d5c77c3253046f9b90e22742c1f2852e07d07157daa296512370fada7",
"windows/PublicTailnetSelectionSelfTest.cs": "7b5e7352fe4529e01ce537d488a5cfcc8f5259f98bbe307846cb36a7144cacac", "windows/PublicTailnetSelectionSelfTest.cs": "7b5e7352fe4529e01ce537d488a5cfcc8f5259f98bbe307846cb36a7144cacac",
"windows/README.md": "9bfa24ddb2f1d3af4845c3a25c275ec6efd1819552735c6178f8e07e3d29722f", "windows/README.md": "336e690f3b013f36baaca67bcbb70e4eab1c72b38e6084941230e582d7c58be2",
"windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1", "windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1",
"windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9", "windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9",
"windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e", "windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e",
@@ -272,13 +277,15 @@
"windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe", "windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe",
"windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916", "windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916",
"windows/THIRD_PARTY_NOTICES.md": "c7141fe279b2c364c868888db37bd995feba1552025e2259dc4662a01e5122bb", "windows/THIRD_PARTY_NOTICES.md": "c7141fe279b2c364c868888db37bd995feba1552025e2259dc4662a01e5122bb",
"windows/TailnetReadinessPolicy.cs": "50c21754e9ca700963de34ef1f4abf9107b4f29920403ea22c19c17e120a07dd", "windows/TailnetPingConfirmation.cs": "19fad61844b5e3cb4a994b8f4558a332a9f5b39285ca8549b19cb76064bc805a",
"windows/TailnetReadinessSelfTest.cs": "80fc579bd477a03a4cc29d6a350f9b052afa719c1fffe1dba7488e30e35dc091", "windows/TailnetPingConfirmationSelfTest.cs": "5fa8f0d932a1b3fba825aff0b8301a61723cbe9ad1ac140c00a936194393be14",
"windows/TailnetReadinessPolicy.cs": "32385fd2de8762f947c9cbf6d0fb3fc934b33a2a17c0e2375d60ceb619cbff71",
"windows/TailnetReadinessSelfTest.cs": "92ba7abec5fa3f98550dd9460fb2c87b58cbdc4a55efd9f4b58ca8c5c16f67e7",
"windows/TailnetTransport.cs": "c93769b845090f244eeedef2b49afa4bea500af809a995ffdcaf8c314ffb84eb", "windows/TailnetTransport.cs": "c93769b845090f244eeedef2b49afa4bea500af809a995ffdcaf8c314ffb84eb",
"windows/TailnetTransportProbe.cs": "c71a0d946cbefb2713e0b564ea95ae99cbd70f0ec19c8cfc416a12e16589f99a", "windows/TailnetTransportProbe.cs": "c71a0d946cbefb2713e0b564ea95ae99cbd70f0ec19c8cfc416a12e16589f99a",
"windows/TailnetTransportSelfTest.cs": "8ace8cc2f443c1ce576bbb9471cb46f107ac28f999090baa30431412d8a263f3", "windows/TailnetTransportSelfTest.cs": "8ace8cc2f443c1ce576bbb9471cb46f107ac28f999090baa30431412d8a263f3",
"windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb", "windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb",
"windows/TrafficChart.cs": "3876ab1095a2b0d37542383ef580e69e716ce6b1f517955320b12143bd241bc4", "windows/TrafficChart.cs": "0412f5d45d33ee95f0d0c80ea57a53e4708ff549e20373596035a47c7a0d1eb0",
"windows/TransportPlan.cs": "f49b780fd5095cd494c040582d3cf1607548d1eb0572490bfe588dc55521a772", "windows/TransportPlan.cs": "f49b780fd5095cd494c040582d3cf1607548d1eb0572490bfe588dc55521a772",
"windows/TransportPlanSelfTest.cs": "21ba43f220cf2d36d66c5ecab149ecefa5a1e9be62813582db6274897b25093e", "windows/TransportPlanSelfTest.cs": "21ba43f220cf2d36d66c5ecab149ecefa5a1e9be62813582db6274897b25093e",
"windows/TunConfigBuilder.cs": "35a17b9da204e338dde5ed6cd4f2e979d94ad73c4c01cc0001fc582e94b67194", "windows/TunConfigBuilder.cs": "35a17b9da204e338dde5ed6cd4f2e979d94ad73c4c01cc0001fc582e94b67194",
@@ -288,11 +295,11 @@
"windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771", "windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771",
"windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1", "windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1",
"windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069", "windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069",
"windows/VPNPlus.csproj": "5ac3d22f53cd3e6af8b700a69f7ead4c8cebad355e527a5418a3a82632aae058", "windows/VPNPlus.csproj": "c81156e80e7d5ceac088c8e167ce3e3f33cc8cdf61a125b905a6761ef2e43221",
"windows/VpnApiClient.cs": "187829698d9f26b896dbfef596bc71b12a9ed4e014261abde0497e6763e40ae3", "windows/VpnApiClient.cs": "5bb824cd89d4d8fa251f10a66f4c284c58118b773f877aa07c9700fe271216a8",
"windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c", "windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c",
"windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be", "windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be",
"windows/XrayManager.cs": "1d8fc21dad18faccb6e0d9c571164603f5b7e4916f24d22b31d527bbd6da585c", "windows/XrayManager.cs": "8c87c1d84e42f00528da52ecbe9a0a4ecded445ac50e83442c187536af9555a5",
"windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5", "windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5",
"windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6", "windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6",
"windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163", "windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163",
@@ -334,7 +341,9 @@
"windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2", "windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2",
"windows/release/RELEASE-NOTES-0.3.1.md": "e28a99d049842adc34f593e39bbc33484dd4dfc9e31568cbcb1aef1f3bcd4132", "windows/release/RELEASE-NOTES-0.3.1.md": "e28a99d049842adc34f593e39bbc33484dd4dfc9e31568cbcb1aef1f3bcd4132",
"windows/release/RELEASE-NOTES-0.3.2.md": "29f2030b0be583a541dc0289ee9916d42156cf3bbd823bd5cf7867f097fb2abd", "windows/release/RELEASE-NOTES-0.3.2.md": "29f2030b0be583a541dc0289ee9916d42156cf3bbd823bd5cf7867f097fb2abd",
"windows/release/RELEASE-NOTES-0.3.3.md": "18e1f04a925b82668813cb7bde18d29790fa6218d6726887b0ad3cabec253dea" "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"
}, },
"IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6", "IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6",
"Kind": "clean-history-free-open-source-export", "Kind": "clean-history-free-open-source-export",
@@ -595,5 +604,31 @@
"SourceOnly": true, "SourceOnly": true,
"Version": "0.3.3" "Version": "0.3.3"
}, },
"Windows034ConnectionResilienceDelta": {
"CandidateSha256": "270c5c8d804fc1c2c930a4d86667b6fbf0f7bab9875f359a076342ee5a96cb78",
"FrozenSha256": "63580db09d867fb14853c17a8d7f7be8c420b0eb389457adf5f910fe1ab5ce6c",
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "343499b680a3f91e01349123a8d9ce449db2bb8184aaf7d4c7f15934cd02383f",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "aff1a50d35c22507bf4e72d44827038d7f8454e9",
"SourceOnly": true,
"Version": "0.3.4"
},
"Windows035TrafficTrendsDelta": {
"CandidateSha256": "cd804728119ed9919898d14cd0fc0f0e36e027fa0afcac0e1f6ef6eff6afc41f",
"FrozenSha256": "436f20672b19ec5ef64629ccfe41101515f110ff5bd218f279841b4718e7fdc9",
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "574f523befd28991f8f98da25cbb3efbcd035080953b286d40958683593afdcb",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "991b029b371ce42804bd4d7c689a6f756128e8ac",
"SourceOnly": true,
"Version": "0.3.5"
},
"WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38" "WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38"
} }
+42
View File
@@ -0,0 +1,42 @@
namespace UCVL.VPNPlus;
// Memory-only bounds from authenticated responses. This permits retention of
// an already-running core; it never grants offline login or a new connection.
internal sealed class ConnectionAuthorizationLease
{
private bool _known, _active;
private DateTimeOffset? _sessionExpiry, _profileExpiry;
private long? _sessionDeadline, _profileDeadline;
internal void Reset(DateTimeOffset? sessionExpiry, DateTimeOffset now, long ticks)
{
_known = _active = false;
_sessionExpiry = sessionExpiry;
_sessionDeadline = Deadline(sessionExpiry, now, ticks);
_profileExpiry = null; _profileDeadline = null;
}
internal void AcceptProfile(string status, DateTimeOffset? expiry, DateTimeOffset now, long ticks)
{
_known = !string.IsNullOrWhiteSpace(status); _active = status == "active";
var deadline = Deadline(expiry, now, ticks);
if (_profileExpiry == expiry && _profileDeadline.HasValue && deadline.HasValue)
deadline = Math.Min(_profileDeadline.Value, deadline.Value);
_profileExpiry = expiry;
_profileDeadline = deadline;
}
internal bool AccountIsValid(DateTimeOffset now, long ticks) => (!_known || _active)
&& (_sessionExpiry is null || now < _sessionExpiry) && (_profileExpiry is null || now < _profileExpiry)
&& (_sessionDeadline is null || ticks < _sessionDeadline) && (_profileDeadline is null || ticks < _profileDeadline);
internal bool CanRetain(DateTimeOffset now, long ticks, bool privateAuxiliary, long privateDeadline)
=> AccountIsValid(now, ticks) && (!privateAuxiliary || privateDeadline > ticks);
private static long? Deadline(DateTimeOffset? expiry, DateTimeOffset now, long ticks)
{
if (expiry is null) return null;
var remaining = Math.Max(0, (expiry.Value - now).TotalMilliseconds);
return ticks + (long)Math.Min(remaining, long.MaxValue - Math.Max(0, ticks));
}
}
@@ -0,0 +1,44 @@
namespace UCVL.VPNPlus;
internal static class ConnectionAuthorizationSelfTest
{
internal static Dictionary<string, bool> Check()
{
var checks = new Dictionary<string, bool>();
var now = DateTimeOffset.Parse("2026-11-05T00:00:00Z");
var lease = new ConnectionAuthorizationLease();
lease.Reset(null, now, 1000);
checks["unknown_deadline_does_not_expire_existing_core"] = lease.AccountIsValid(now.AddDays(1), 86_401_000);
lease.AcceptProfile("active", null, now, 1000);
checks["explicit_long_term_profile_has_no_invented_expiry"] = lease.CanRetain(now.AddDays(100), 8_640_001_000, false, 0);
checks["valid_private_lease_can_be_retained_during_api_outage"] = lease.CanRetain(now, 1000, true, 2000);
checks["expired_private_lease_cannot_be_retained"] = !lease.CanRetain(now, 2000, true, 2000);
checks["private_expiry_does_not_mark_account_expired_or_shadow_renewal"] = lease.AccountIsValid(now, 2000);
lease.AcceptProfile("active", now.AddSeconds(10), now, 1000);
checks["known_subscription_expiry_is_enforced"] = lease.AccountIsValid(now.AddSeconds(9), 10_000)
&& !lease.AccountIsValid(now.AddSeconds(10), 11_000);
checks["clock_rollback_cannot_extend_known_subscription"] = !lease.AccountIsValid(now.AddDays(-1), 11_000);
lease.AcceptProfile("active", now.AddSeconds(10), now.AddDays(-1), 11_000);
checks["same_profile_refresh_cannot_extend_deadline_after_clock_rollback"] = !lease.AccountIsValid(now.AddDays(-1), 11_000);
lease.AcceptProfile("active", now.AddDays(1), now.AddSeconds(10), 11_000);
checks["fresh_authenticated_profile_can_renew_subscription"] = lease.AccountIsValid(now.AddHours(1), 3_601_000);
lease.Reset(now.AddSeconds(5), now, 1000);
lease.AcceptProfile("active", now.AddDays(1), now, 1000);
checks["profile_cannot_extend_known_login_session_expiry"] = !lease.AccountIsValid(now.AddSeconds(5), 6000);
lease.Reset(null, now, 1000);
lease.AcceptProfile("suspended", null, now, 1000);
checks["explicit_inactive_status_is_not_retained"] = !lease.AccountIsValid(now, 1000);
lease.Reset(null, now, 1000);
lease.AcceptProfile("", null, now, 1000);
checks["legacy_fixture_without_status_or_deadline_is_not_expired"] = lease.AccountIsValid(now, 1000);
foreach (var failure in new Exception[] { new TimeoutException(), new HttpRequestException(), new ApiException(500, "fixture outage"), new ApiException(503, "fixture outage") })
checks["fresh_grant_failure_keeps_running_authorized_core_" + failure.GetType().Name + checks.Count]
= ConnectionRecoveryPolicy.KeepExisting(true, false, true, failure, true);
checks["expiry_prevents_control_plane_retention"] = !ConnectionRecoveryPolicy.KeepExisting(true, false, true, new TimeoutException(), false);
checks["revocation_still_ends_existing_session"] = !ConnectionRecoveryPolicy.KeepExisting(true, false, true, new ApiException(401, "revoked"), true)
&& !ConnectionRecoveryPolicy.KeepExisting(true, false, true, new ApiException(403, "revoked"), true);
checks["no_offline_new_login_or_connection_granted"] = !ConnectionRecoveryPolicy.KeepExisting(false, false, false, new TimeoutException(), true);
checks["already_replaced_core_is_not_falsely_retained"] = !ConnectionRecoveryPolicy.KeepExisting(true, true, true, new TimeoutException(), true);
return checks;
}
}
+9 -2
View File
@@ -4,7 +4,7 @@ namespace UCVL.VPNPlus;
// A delayed probe must not undo a user's disconnect or judge a different core. // A delayed probe must not undo a user's disconnect or judge a different core.
internal sealed class ConnectionHealthPolicy internal sealed class ConnectionHealthPolicy
{ {
internal enum Decision { Ignore, Keep, Repair, Switch } internal enum Decision { Ignore, Keep, Repair, Degraded, Switch }
internal long Revision { get; private set; } internal long Revision { get; private set; }
internal int Failures { get; private set; } internal int Failures { get; private set; }
internal bool HasBeenHealthy { get; private set; } internal bool HasBeenHealthy { get; private set; }
@@ -18,7 +18,8 @@ internal sealed class ConnectionHealthPolicy
internal void ResetFailures() => Failures = 0; internal void ResetFailures() => Failures = 0;
internal bool IsDue(long now, bool running) => !running || now >= _nextProbe; internal bool IsDue(long now, bool running) => !running || now >= _nextProbe;
internal Decision Observe(long revision, int? testedCore, int? currentCore, internal Decision Observe(long revision, int? testedCore, int? currentCore,
bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false) bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false,
bool activeTailnet = false, bool businessUnavailable = false)
{ {
if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting) if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting)
return Decision.Ignore; return Decision.Ignore;
@@ -26,6 +27,12 @@ internal sealed class ConnectionHealthPolicy
HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000; HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000;
return Decision.Keep; return Decision.Keep;
} }
if (currentCore is not null && (businessUnavailable && proxyHealthy || activeTailnet && !proxyHealthy)) {
// Third-party HTTP diagnostics cannot identify an active Tailnet
// transport failure. The bounded periodic ICMP policy owns fallback.
Failures = 0; _nextProbe = now + 20_000;
return Decision.Degraded;
}
if (proxyHealthy && currentCore is not null) { if (proxyHealthy && currentCore is not null) {
// Do not punish/restart a working node for a local smart-rule fault. // Do not punish/restart a working node for a local smart-rule fault.
// The UI must show degraded routing, not declare the business path healthy. // The UI must show degraded routing, not declare the business path healthy.
+13
View File
@@ -52,6 +52,19 @@ internal static class ConnectionHealthSelfTest
== ConnectionHealthPolicy.Decision.Switch; == ConnectionHealthPolicy.Decision.Switch;
checks["stale_proxy_proof_cannot_affect_new_core"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,500_000,true) checks["stale_proxy_proof_cannot_affect_new_core"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,500_000,true)
== ConnectionHealthPolicy.Decision.Ignore; == ConnectionHealthPolicy.Decision.Ignore;
policy.BeginCore(600_000);
checks["website_failures_do_not_rebuild_live_tailnet_core"] = Enumerable.Range(0, 12).All(i =>
policy.Observe(policy.Revision, 10, 10, true, false, false, false, false, 605_000 + i * 20_000,
false, activeTailnet: true) == ConnectionHealthPolicy.Decision.Degraded) && policy.Failures == 0;
checks["transport_proof_with_site_outage_is_degraded_not_false_green"] = policy.Observe(policy.Revision, 10, 10,
true, false, false, false, false, 900_000, true, businessUnavailable: true) == ConnectionHealthPolicy.Decision.Degraded;
checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null,
true, false, false, false, false, 920_000, false, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch;
revision = policy.Revision;
policy.Invalidate();
checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10,
true, false, false, false, true, 940_000, true, activeTailnet: true) == ConnectionHealthPolicy.Decision.Ignore;
foreach (var check in ConnectionAuthorizationSelfTest.Check()) checks.Add(check.Key, check.Value);
var passed = checks.Values.All(v => v); var passed = checks.Values.All(v => v);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"connection-health-self-test.json"), File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"connection-health-self-test.json"),
JsonSerializer.Serialize(new { kind="advisory_connection_health_policy", network_modified=false, JsonSerializer.Serialize(new { kind="advisory_connection_health_policy", network_modified=false,
+3 -2
View File
@@ -4,8 +4,9 @@ internal static class ConnectionRecoveryPolicy
{ {
// A control-plane timeout is not evidence that the existing data-plane // A control-plane timeout is not evidence that the existing data-plane
// process needs to be destroyed. Revoked authorization still stops service. // process needs to be destroyed. Revoked authorization still stops service.
internal static bool KeepExisting(bool reconnect, bool replacementStarted, bool coreRunning, Exception failure) internal static bool KeepExisting(bool reconnect, bool replacementStarted, bool coreRunning, Exception failure,
=> reconnect && !replacementStarted && coreRunning bool authorizationValid = true)
=> reconnect && !replacementStarted && coreRunning && authorizationValid
&& failure is not ApiException { StatusCode: 401 or 403 }; && failure is not ApiException { StatusCode: 401 or 403 };
internal static bool SelfTest() internal static bool SelfTest()
+7 -4
View File
@@ -116,11 +116,14 @@ internal sealed class MetricCard : CardPanel
if(Height<S(40)) if(Height<S(40))
{ {
var speed=Glyph is DashboardIcon.Upload or DashboardIcon.Download; var speed=Glyph is DashboardIcon.Upload or DashboardIcon.Download;
using var denseFont=Brand.Font(speed?8.5f:7.5f,FontStyle.Bold); using var denseFont=Brand.Font(8f,FontStyle.Bold);
var prefix=speed?(Glyph==DashboardIcon.Download?"↓ 下载":"↑ 上传"):Heading.Replace("代理流量", ""); var prefix=speed?(Glyph==DashboardIcon.Download?"↓ 下载":"↑ 上传"):Heading.Replace("代理流量", "");
TextRenderer.DrawText(g,$"{prefix} {ValueText} {UnitText}",denseFont,ClientRectangle, var denseFlags=ChartAxis.PaintFlags|TextFormatFlags.VerticalCenter|TextFormatFlags.SingleLine|TextFormatFlags.NoPadding|TextFormatFlags.EndEllipsis;
Glyph==DashboardIcon.Download?Brand.DeepBlue:Brand.Navy, var unitLeft=Width-S(40);
ChartAxis.PaintFlags|TextFormatFlags.VerticalCenter|TextFormatFlags.HorizontalCenter|TextFormatFlags.SingleLine|TextFormatFlags.EndEllipsis); TextRenderer.DrawText(g,prefix,denseFont,new Rectangle(S(4),0,S(38),Height),Brand.Muted,denseFlags);
TextRenderer.DrawText(g,ValueText,denseFont,new Rectangle(S(44),0,Math.Max(1,unitLeft-S(48)),Height),Brand.Navy,denseFlags|TextFormatFlags.Right);
TextRenderer.DrawText(g,UnitText,denseFont,new Rectangle(unitLeft,0,S(36),Height),
Glyph==DashboardIcon.Download?Brand.Cyan:Brand.DeepBlue,denseFlags);
return; return;
} }
var narrow = Width < S(180); var narrow = Width < S(180);
+1 -1
View File
@@ -114,7 +114,7 @@ internal sealed partial class MainForm
&& !rows.Rows[0].IntersectsWith(rows.Rows[1]); && !rows.Rows[0].IntersectsWith(rows.Rows[1]);
} }
checks["monitor_stays_below_speed_without_resizing_window"] = ClientSize == monitorSize checks["monitor_stays_below_speed_without_resizing_window"] = ClientSize == monitorSize
&& _nodeTrafficPanel.Top > _dailyCard.Bottom && _nodeTrafficPanel.Bottom < _footer.Top && _nodeTrafficPanel.Top > _speedTrendCard.Bottom && _nodeTrafficPanel.Bottom < _dailyCard.Top
&& !_dashboardScrollBar.Visible && _dashboardBody.Top == 0; && !_dashboardScrollBar.Visible && _dashboardBody.Top == 0;
checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit(); checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit();
checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount); checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount);
+28 -26
View File
@@ -6,8 +6,8 @@ internal readonly record struct DashboardGeometry(
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle SpeedTrendCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer, Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle SpeedTrendCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer,
int ContentHeight, bool Compact, float VerticalScale); int ContentHeight, bool Compact, float VerticalScale);
// All measurements are logical pixels converted exactly once. Every data row // One fitted page: local proxy trend, per-server trends, then numeric totals.
// spans the canvas; the optional transport row borrows height from the plot. // Transport selection changes the local chart caption, never the page geometry.
internal static class DashboardLayout internal static class DashboardLayout
{ {
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false, bool preferCompact = false) internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false, bool preferCompact = false)
@@ -16,29 +16,30 @@ internal static class DashboardLayout
int S(int n) => (int)Math.Round(n * scale); int S(int n) => (int)Math.Round(n * scale);
var margin = S(8); var gap = S(4); var margin = S(8); var gap = S(4);
var compact = preferCompact || viewport.Width < S(720) || viewport.Height < S(442); var compact = preferCompact || viewport.Width < S(720) || viewport.Height < S(442);
var topOffset = compact ? -S(22) : 0; var topOffset = compact ? 0 : S(22);
var width = Math.Max(1, viewport.Width - margin * 2); var width = Math.Max(1, viewport.Width - margin * 2);
var welcome = new Rectangle(margin, 0, S(120), S(18)); var welcome = new Rectangle(margin, 0, S(120), S(18));
var account = new Rectangle(welcome.Right + gap, 0, Math.Min(S(160), width - S(252)), S(18)); var account = new Rectangle(welcome.Right + gap, 0, Math.Min(S(160), width - S(252)), S(18));
var identity = new Rectangle(account.Right + gap, S(1), S(50), S(16)); var identity = new Rectangle(account.Right + gap, S(1), S(50), S(16));
var logout = new Rectangle(margin + width - S(64), 0, S(64), S(19)); var logout = new Rectangle(margin + width - S(64), 0, S(64), S(19));
var status = new Rectangle(margin, S(22)+topOffset, width, S(32)); var status = new Rectangle(margin, margin+topOffset, width, S(30));
var configuration = new Rectangle(margin, S(58)+topOffset, width, S(48)); var configuration = new Rectangle(margin, status.Bottom + gap, width, S(44));
// The right hand actual-state panel is embedded in the same surface. // The right hand actual-state panel is embedded in the same surface.
var actualLeft = (int)Math.Round(width * .52); var actualLeft = width / 2 + S(4);
var actual = new Rectangle(actualLeft, S(3), width - actualLeft - S(8), S(42)); var actual = new Rectangle(actualLeft, 0, width - actualLeft - S(8), configuration.Height);
var traffic = new Rectangle(margin, S(110)+topOffset, width, S(24)); var traffic = Rectangle.Empty;
var tailnet = showTailnet ? new Rectangle(margin, traffic.Bottom + gap, width, S(24)) : Rectangle.Empty; var tailnet = Rectangle.Empty;
var daily = new Rectangle(margin, (showTailnet ? tailnet.Bottom : traffic.Bottom) + gap, width, S(28)); var footer = new Rectangle(margin, viewport.Height - margin - S(18), width, S(18));
var footer = new Rectangle(margin, viewport.Height - S(22), width, S(18)); var daily = new Rectangle(margin, footer.Top - gap - S(22), width, S(22));
var servers = showServerTraffic ? new Rectangle(margin, footer.Top - gap - S(38), width, S(38)) : Rectangle.Empty; var trendTop = configuration.Bottom + gap;
var trendTop = daily.Bottom + gap; var graphHeight = Math.Max(S(72), daily.Top - gap - trendTop);
var trend = new Rectangle(margin, trendTop, width, Math.Max(S(28), (showServerTraffic ? servers.Top : footer.Top) - gap - trendTop)); var serverHeight = showServerTraffic ? Math.Min(S(100), (int)Math.Round((graphHeight-gap)*.52)) : 0;
var headingWidth = S(112); var trend = new Rectangle(margin, trendTop, width, graphHeight - (showServerTraffic ? serverHeight+gap : 0));
var speedWidth = (width - headingWidth - S(16)) / 2; var servers = showServerTraffic ? new Rectangle(margin, trend.Bottom+gap, width, serverHeight) : Rectangle.Empty;
Rectangle Speed(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, traffic.Height - S(2)); var headingWidth = S(120);
var totalWidth = (width - S(76)) / 2; var speedWidth = (width - headingWidth - S(10)) / 2;
Rectangle Total(int column) => new(S(66) + column * totalWidth, 0, totalWidth, daily.Height - S(2)); Rectangle Speed(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, S(22));
Rectangle Total(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, daily.Height - S(2));
Rectangle[] metrics = [Total(0), Speed(0), Speed(1), Total(1)]; Rectangle[] metrics = [Total(0), Speed(0), Speed(1), Total(1)];
return new(welcome, account, identity, logout, status, configuration, actual, metrics, return new(welcome, account, identity, logout, status, configuration, actual, metrics,
traffic, tailnet, trend, daily, servers, footer, viewport.Height, true, 1f); traffic, tailnet, trend, daily, servers, footer, viewport.Height, true, 1f);
@@ -54,8 +55,7 @@ internal static class DashboardLayout
{ {
var viewport = new Size(width * dpi / 96, height * dpi / 96); var viewport = new Size(width * dpi / 96, height * dpi / 96);
var p = Calculate(viewport, dpi, showTailnet, showServers); var p = Calculate(viewport, dpi, showTailnet, showServers);
Rectangle[] cards = [p.StatusCard,p.NodeCard,p.TrafficCard,p.SpeedTrendCard,p.DailyCard,p.Footer]; Rectangle[] cards = [p.StatusCard,p.NodeCard,p.SpeedTrendCard,p.DailyCard,p.Footer];
if(showTailnet)cards=[..cards,p.TailnetTrafficCard];
if(showServers)cards=[..cards,p.ServerTrafficCard]; if(showServers)cards=[..cards,p.ServerTrafficCard];
if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0 || c.Height<=0)) return false; if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0 || c.Height<=0)) return false;
for (var i = 0; i < cards.Length; i++) for (var i = 0; i < cards.Length; i++)
@@ -66,17 +66,19 @@ internal static class DashboardLayout
if (p.Metrics[0].IntersectsWith(p.Metrics[3]) || p.Metrics[1].IntersectsWith(p.Metrics[2])) return false; if (p.Metrics[0].IntersectsWith(p.Metrics[3]) || p.Metrics[1].IntersectsWith(p.Metrics[2])) return false;
for (var i = 0; i < p.Metrics.Length; i++) for (var i = 0; i < p.Metrics.Length; i++)
{ {
var parent=i==0||i==3?p.DailyCard:p.TrafficCard; var parent=p.DailyCard;
if(!new Rectangle(Point.Empty,parent.Size).Contains(p.Metrics[i]))return false; if(!new Rectangle(Point.Empty,parent.Size).Contains(p.Metrics[i]))return false;
} }
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false; if (p.TrafficCard != Rectangle.Empty || p.TailnetTrafficCard != Rectangle.Empty) return false;
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false; if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false;
var baseline = Calculate(viewport, dpi, false, showServers); var baseline = Calculate(viewport, dpi, false, showServers);
if (p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight || p.TrafficCard != baseline.TrafficCard) return false; if (p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight || p.TrafficCard != baseline.TrafficCard) return false;
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom || p.DailyCard.Top<=p.TailnetTrafficCard.Bottom)) return false; if(p.SpeedTrendCard.Width!=p.DailyCard.Width || p.DailyCard.Height>Sized(24))return false;
if(p.TrafficCard.Width!=p.SpeedTrendCard.Width || p.DailyCard.Height>Sized(40))return false; if (p.Metrics[0].Left != p.Metrics[1].Left || p.Metrics[3].Left != p.Metrics[2].Left
|| p.Metrics[0].Width != p.Metrics[1].Width || p.Metrics[3].Width != p.Metrics[2].Width) return false;
if(p.SpeedTrendCard.Height<Sized(45))return false; if(p.SpeedTrendCard.Height<Sized(45))return false;
if (showServers && (p.ServerTrafficCard.Top <= p.SpeedTrendCard.Bottom || p.ServerTrafficCard.Bottom >= p.Footer.Top)) return false; if (p.SpeedTrendCard.Top <= p.NodeCard.Bottom || p.DailyCard.Top<=p.SpeedTrendCard.Bottom) return false;
if (showServers && (p.ServerTrafficCard.Top <= p.SpeedTrendCard.Bottom || p.ServerTrafficCard.Bottom >= p.DailyCard.Top)) return false;
int Sized(int n)=>(int)Math.Round(n*Math.Max(1f,dpi/96f)); int Sized(int n)=>(int)Math.Round(n*Math.Max(1f,dpi/96f));
} }
return true; return true;
+8 -8
View File
@@ -11,8 +11,8 @@ internal sealed partial class MainForm
SetTailnetTrafficVisibility(true); SetTailnetTrafficVisibility(true);
SetNodeTrafficPermission(true); SetNodeTrafficPermission(true);
LayoutDashboard(); LayoutDashboard();
checks["proxy_speed_row_spans_dashboard"] = _trafficCard.Left == _statusCard.Left checks["local_speed_trend_spans_dashboard"] = _speedTrendCard.Left == _statusCard.Left
&& _trafficCard.Width == _statusCard.Width; && _speedTrendCard.Width == _statusCard.Width && !_trafficCard.Visible;
checks["cumulative_strip_keeps_plot_space"] = _dailyCard.Height <= ScaleLogical(40) checks["cumulative_strip_keeps_plot_space"] = _dailyCard.Height <= ScaleLogical(40)
&& _trafficChart.Width >= ScaleLogical(340) && _speedTrendCard.Height >= ScaleLogical(45); && _trafficChart.Width >= ScaleLogical(340) && _speedTrendCard.Height >= ScaleLogical(45);
UpdateConnectedTransportPresentation(true); UpdateConnectedTransportPresentation(true);
@@ -25,12 +25,11 @@ internal sealed partial class MainForm
ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height)); ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height));
SetTailnetTrafficVisibility(false); LayoutDashboard(); SetTailnetTrafficVisibility(false); LayoutDashboard();
var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size); var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size);
checks[$"no_tailnet_single_left_{size.Width}"] = !_tailnetTrafficCard.Visible checks[$"no_tailnet_one_local_chart_{size.Width}"] = !_tailnetTrafficCard.Visible
&& _trafficCard.Width == _statusCard.Width && _speedTrendCard.Top > _dailyCard.Bottom; && _speedTrendCard.Width == _statusCard.Width && _dailyCard.Top > _speedTrendCard.Bottom;
SetTailnetTrafficVisibility(true); SetTailnetTrafficVisibility(true);
checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left checks[$"tailnet_does_not_duplicate_local_chart_{size.Width}"] = !_tailnetTrafficCard.Visible && !_trafficCard.Visible
&& _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom && _dailyCard.Top > _speedTrendCard.Bottom;
&& _dailyCard.Top > _tailnetTrafficCard.Bottom && _speedTrendCard.Top > _dailyCard.Bottom;
checks[$"tailnet_never_increases_page_{size.Width}"] = _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4 checks[$"tailnet_never_increases_page_{size.Width}"] = _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4
&& !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty; && !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty;
checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit(); checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit();
@@ -79,7 +78,8 @@ internal sealed partial class MainForm
checks["tailnet_sample_remains_in_overall_proxy_total"] = _uploadMetric.ValueText == "1.0" checks["tailnet_sample_remains_in_overall_proxy_total"] = _uploadMetric.ValueText == "1.0"
&& _downloadMetric.ValueText == "2.0" && _tailnetUploadMetric.ValueText == "1.0" && _downloadMetric.ValueText == "2.0" && _tailnetUploadMetric.ValueText == "1.0"
&& _tailnetDownloadMetric.ValueText == "2.0" && session == (_sessionUp, _sessionDown); && _tailnetDownloadMetric.ValueText == "2.0" && session == (_sessionUp, _sessionDown);
checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible; checks["actual_tailnet_transport_is_identified_without_repeated_row"] = _currentNodeUsesTailnet && _tailnetTrafficVisible
&& !_tailnetTrafficCard.Visible;
UpdateConnectedTransportPresentation(false); UpdateConnectedTransportPresentation(false);
DisplayTraffic(3072, 4096, "公网样本"); DisplayTraffic(3072, 4096, "公网样本");
checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3.0" && _downloadMetric.ValueText == "4.0"; checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3.0" && _downloadMetric.ValueText == "4.0";
+38 -26
View File
@@ -6,6 +6,7 @@ internal sealed partial class MainForm
private bool CompactPresentation => ClientSize.Width < ScaleLogical(720) || ClientSize.Height < ScaleLogical(550); private bool CompactPresentation => ClientSize.Width < ScaleLogical(720) || ClientSize.Height < ScaleLogical(550);
private readonly Font _compactStatusFont=Brand.Font(9.5f,FontStyle.Bold); private readonly Font _compactStatusFont=Brand.Font(9.5f,FontStyle.Bold);
private readonly Font _compactChartFont=Brand.Font(7.5f); private readonly Font _compactChartFont=Brand.Font(7.5f);
private readonly Font _compactRowFont=Brand.Font(8f,FontStyle.Bold);
private readonly Dictionary<Control, (Font Original, Font? Compact)> _presentationFonts = new(); private readonly Dictionary<Control, (Font Original, Font? Compact)> _presentationFonts = new();
private bool _presentationFontsDisposed; private bool _presentationFontsDisposed;
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
@@ -17,6 +18,7 @@ internal sealed partial class MainForm
_presentationFonts.Clear(); _presentationFonts.Clear();
_compactStatusFont.Dispose(); _compactStatusFont.Dispose();
_compactChartFont.Dispose(); _compactChartFont.Dispose();
_compactRowFont.Dispose();
} }
private void SetStatusTitleFont(float size) private void SetStatusTitleFont(float size)
{ {
@@ -54,9 +56,9 @@ internal sealed partial class MainForm
foreach(Control control in _brandHeader.Controls) foreach(Control control in _brandHeader.Controls)
{ {
if(control.Tag is not Rectangle)continue; if(control.Tag is not Rectangle)continue;
if(control is PictureBox)control.Bounds=new(S(10),S(5),S(34),S(37)); if(control is PictureBox)control.Bounds=new(S(8),S(6),S(34),S(36));
else if(control is Label label && label.Text=="纵横家")control.Bounds=new(S(52),S(5),S(180),S(25)); else if(control is Label label && label.Text=="纵横家")control.Bounds=new(S(48),S(6),S(176),S(26));
else control.Bounds=new(S(53),S(28),S(260),S(15)); else control.Bounds=new(S(49),S(31),S(180),S(14));
} }
_headerPoem.Visible=false; _headerPoem.Visible=false;
LayoutWindowChrome(); LayoutWindowChrome();
@@ -103,8 +105,9 @@ internal sealed partial class MainForm
{ {
_welcomeLabel.Parent=_brandHeader; _welcomeLabel.Parent=_brandHeader;
_logoutButton.Parent=_brandHeader; _logoutButton.Parent=_brandHeader;
_welcomeLabel.Bounds=new(_brandHeader.Width-S(226),S(5),S(172),S(20)); var caption = _windowChrome!.MinimizeButton.Bounds;
_logoutButton.Bounds=new(_brandHeader.Width-S(128),S(28),S(72),S(19)); _logoutButton.Bounds=new(caption.Left-S(72),caption.Top,S(64),caption.Height);
_welcomeLabel.Bounds=new(_logoutButton.Left-S(126),caption.Top,S(118),caption.Height);
_welcomeLabel.Visible=_logoutButton.Visible=_dashboardView.Visible; _welcomeLabel.Visible=_logoutButton.Visible=_dashboardView.Visible;
_accountLabel.Visible=_identityBadge.Visible=false; _accountLabel.Visible=_identityBadge.Visible=false;
} }
@@ -117,42 +120,51 @@ internal sealed partial class MainForm
_welcomeLabel.Visible=_logoutButton.Visible=_accountLabel.Visible=_identityBadge.Visible=true; _welcomeLabel.Visible=_logoutButton.Visible=_accountLabel.Visible=_identityBadge.Visible=true;
} }
_statusDot.Bounds=R(10,4,22,22); _statusDot.Bounds=R(10,4,22,22);
_connectButton.Bounds=new(_statusCard.Width-S(80),S(4),S(70),S(24)); _connectButton.Bounds=new(_statusCard.Width-S(80),S(3),S(70),S(24));
_statusTitle.Bounds=new(S(40),S(1),_statusCard.Width-S(130),S(17)); _statusTitle.Bounds=new(S(40),0,_statusCard.Width-S(130),S(16));
_statusDetail.Bounds=new(S(40),S(17),_statusCard.Width-S(130),S(14)); _statusDetail.Bounds=new(S(40),S(16),_statusCard.Width-S(130),S(13));
_nodeIcon.Visible=_modeIcon.Visible=false; _nodeIcon.Visible=_modeIcon.Visible=false;
_scheduleBadge.Visible=false; _scheduleBadge.Visible=false;
var leftWidth=_modeCard.Left-S(8); var leftWidth=_modeCard.Left-S(8);
_selectionHeading.Bounds=R(10,3,27,20); _selectionHeading.Bounds=R(10,1,27,20);
_routeHeading.Bounds=R(10,25,27,20); _routeHeading.Bounds=R(10,23,27,20);
_routeHeading.Text="模式"; _routeHeading.Text="模式";
var fieldLeft=S(38); var fieldWidth=leftWidth-fieldLeft; var fieldLeft=S(38); var fieldWidth=leftWidth-fieldLeft;
var splitWidth=Math.Max(S(84),(fieldWidth-S(4))/2); var splitWidth=Math.Max(S(84),(fieldWidth-S(4))/2);
_connectionModeCombo.Bounds=new(fieldLeft,S(3),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20)); _connectionModeCombo.Bounds=new(fieldLeft,S(1),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20));
_manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(3),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20)); _manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(1),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20));
_routeCombo.Bounds=new(fieldLeft,S(25),fieldWidth,S(20)); _routeCombo.Bounds=new(fieldLeft,S(23),fieldWidth,S(20));
_nodeHeading.Text="节点"; _nodeHeading.Text="节点";
_nodeHeading.Bounds=R(8,0,27,20); _nodeHeading.Bounds=R(8,1,27,20);
_currentNodeLabel.Bounds=new(S(39),0,_modeCard.Width-S(41),S(20)); _currentNodeLabel.Bounds=new(S(39),S(1),_modeCard.Width-S(41),S(20));
_actualModeHeading.Bounds=R(8,22,27,20); _actualModeHeading.Bounds=R(8,23,27,20);
_routeReadOnly.Bounds=new(S(39),S(22),_modeCard.Width-S(41),S(20)); _routeReadOnly.Bounds=new(S(39),S(23),_modeCard.Width-S(41),S(20));
foreach(var label in new[]{_selectionHeading,_routeHeading,_nodeHeading,_actualModeHeading,_currentNodeLabel})
{ label.TextAlign=ContentAlignment.MiddleLeft; label.Padding=Padding.Empty; }
_trafficCard.Visible=_tailnetTrafficCard.Visible=false;
_trafficIcon.Visible=_dailyIcon.Visible=_tailnetTrafficIcon.Visible=false; _trafficIcon.Visible=_dailyIcon.Visible=_tailnetTrafficIcon.Visible=false;
_trafficHeading.Bounds=new(S(10),0,S(96),_trafficCard.Height-S(2)); _trafficHeading.Bounds=new(S(10),0,S(106),_trafficCard.Height-S(2));
_dailyHeading.Bounds=new(S(10),0,S(56),_dailyCard.Height-S(2)); _dailyHeading.Bounds=new(S(10),0,S(106),_dailyCard.Height-S(2));
_tailnetTrafficHeading.Text="Tailscale 速度"; _tailnetTrafficHeading.Text="Tailscale 速度";
_tailnetTrafficHeading.Bounds=new(S(10),0,S(96),_tailnetTrafficCard.Height-S(2)); _tailnetTrafficHeading.Bounds=new(S(10),0,S(106),_tailnetTrafficCard.Height-S(2));
foreach(var heading in new[]{_trafficHeading,_tailnetTrafficHeading,_dailyHeading})
{ heading.Font=_compactRowFont; heading.TextAlign=ContentAlignment.MiddleLeft; }
if(_tailnetTrafficVisible) if(_tailnetTrafficVisible)
{ {
_tailnetUploadMetric.Bounds=_uploadMetric.Bounds; _tailnetUploadMetric.Bounds=_uploadMetric.Bounds;
_tailnetDownloadMetric.Bounds=_downloadMetric.Bounds; _tailnetDownloadMetric.Bounds=_downloadMetric.Bounds;
} }
var rail=CompactPresentation && _speedTrendCard.Height<S(100); _trendHeading.Text="本机代理趋势 · "+(_selectionUiConnected?(_currentNodeUsesTailnet?"Tailscale":"域名入口"):"未连接");
_trendHeading.Bounds=rail?R(10,6,90,20):new(S(10),S(1),_speedTrendCard.Width-S(210),S(20)); _trendHeading.Bounds=new(S(10),S(2),_speedTrendCard.Width-S(120),S(18));
_historyRangeCombo.Bounds=rail?R(8,30,88,20):new(_speedTrendCard.Width-S(98),S(2),S(88),S(20)); _trendHeading.TextAlign=ContentAlignment.MiddleLeft;
_historyRangeCombo.Bounds=new(_speedTrendCard.Width-S(98),S(2),S(88),S(18));
_uploadLegend.Bounds=new(S(10),S(20),(_speedTrendCard.Width-S(20))/2,S(16));
_downloadLegend.Bounds=new(_uploadLegend.Right,S(20),(_speedTrendCard.Width-S(20))/2,S(16));
_uploadLegend.TextAlign=_downloadLegend.TextAlign=ContentAlignment.MiddleLeft;
_uploadLegend.Visible=_downloadLegend.Visible=true;
_trafficChart.Font=_compactChartFont; _trafficChart.Font=_compactChartFont;
_trafficChart.Bounds=rail?new(S(104),S(1),_speedTrendCard.Width-S(108),_speedTrendCard.Height-S(3)) _trafficChart.Bounds=new(S(8),S(36),_speedTrendCard.Width-S(16),Math.Max(S(22),_speedTrendCard.Height-S(40)));
:new(S(2),S(21),_speedTrendCard.Width-S(4),Math.Max(S(22),_speedTrendCard.Height-S(23))); _historyStatus.Visible=false;
_uploadLegend.Visible=_downloadLegend.Visible=_historyStatus.Visible=false;
_sampleLabel.Visible=false; _sampleLabel.Visible=false;
_planLabel.Visible=false; _planLabel.Visible=false;
_expiryLabel.Bounds=new(0,0,S(96),S(17)); _expiryLabel.Bounds=new(0,0,S(96),S(17));
+117 -183
View File
@@ -132,7 +132,11 @@ internal sealed partial class MainForm
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1]; _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
_historyRangeCombo.SelectedIndexChanged += (_, _) => _historyRangeCombo.SelectedIndexChanged += (_, _) =>
{ {
if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period) _trafficChart.SetPeriodMinutes(period.Minutes); if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period)
{
_trafficChart.SetPeriodMinutes(period.Minutes);
_nodeTrafficPanel.SetPeriodMinutes(period.Minutes);
}
}; };
_speedTrendCard.Controls.AddRange([_historyRangeCombo, _historyStatus]); _speedTrendCard.Controls.AddRange([_historyRangeCombo, _historyStatus]);
ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted); ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted);
@@ -206,7 +210,7 @@ internal sealed partial class MainForm
Place(_trafficCard, layout.TrafficCard); Place(_speedTrendCard, layout.SpeedTrendCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer); Place(_trafficCard, layout.TrafficCard); Place(_speedTrendCard, layout.SpeedTrendCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
Place(_nodeTrafficPanel, layout.ServerTrafficCard); Place(_nodeTrafficPanel, layout.ServerTrafficCard);
_tailnetTrafficCard.Bounds=layout.TailnetTrafficCard; _tailnetTrafficCard.Bounds=layout.TailnetTrafficCard;
_tailnetTrafficCard.Visible=_tailnetTrafficVisible; _trafficCard.Visible=_tailnetTrafficCard.Visible=false;
_tailnetSampleLabel.Visible=false; _tailnetSampleLabel.Visible=false;
LayoutCompactDashboard(layout); LayoutCompactDashboard(layout);
} }
@@ -217,202 +221,132 @@ internal sealed partial class MainForm
} }
} }
// Isolated synthetic fixture: no stored account, core, system proxy, update query or installation. // Isolated synthetic presentation fixture; it never starts a proxy or reads credentials.
internal static void RenderPreview() internal static void RenderPreview()
{ {
using var form = new MainForm(preview: true) { Opacity = 0, ShowInTaskbar = false }; using var form = new MainForm(preview: true) { Opacity = 0, ShowInTaskbar = false };
form.Show(); form.Show();
form.ShowDashboard(new Profile form.ShowDashboard(new Profile
{ {
DisplayName = "示例用户", Email = "demo@example.com", IdentityType = "employee", DisplayName="示例用户",Email="demo@example.com",IdentityType="employee",
Subscription = new SubscriptionInfo { Plan = "员工福利", UsedBytes = 17480516895, DeviceLimit = 3 }, Subscription=new SubscriptionInfo {Plan="员工福利",UsedBytes=276L*1024*1024*1024,DeviceLimit=10},
Nodes = [new NodeInfo { Name = "VPN003", Slug = "preview", Status = "online" }], Nodes=[new NodeInfo {Name="VPN002",Slug="aliyun-tokyo-002",Status="online"}],
RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }], RouteModes=[new RouteModeInfo {Id="smart",Name="AI 智能代理"}]
UsageHistory = Enumerable.Range(0, 7).Select(i => new DailyUsage { Day = DateTime.Today.AddDays(i - 6).ToString("yyyy-MM-dd"), UploadBytes = new long[] { 14000000, 0, 0, 0, 3000000, 35000000, 196000000 }[i], DownloadBytes = new long[] { 28000000, 0, 0, 0, 26000000, 158000000, 126000000 }[i] }).ToList()
}); });
form._refreshTimer.Stop(); form._refreshTimer.Stop();
var fixtureRanges = UsageHistoryPeriod.All.ToDictionary(p => p.Key, p => new UsageHistorySeries form.ClientSize=new Size(form.ScaleLogical(480),form.ScaleLogical(360));
form._currentNodeBaseName="VPN002";
form.UpdateConnectedTransportPresentation(true);
form.SetConnectionState(true,"已安全连接","VPN002 + Tailscale · AI 智能代理");
form.DisplayTraffic(1_153_433,64_614,"演示样本 · 近 5 分钟");
form._sessionMetric.SetBytes(1_883_750_912,hint:"本次连接累计");
var now=DateTimeOffset.UtcNow;
var serverClock=now;
using var previewServers=new NodeTrafficPanel(()=>serverClock) {Visible=false};
form._dashboardBody.Controls.Add(previewServers);
var showServerFixture=false;
for(var i=0;i<61;i++) form._trafficChart.Add((1500+Math.Sin(i*.8)*500)*1024,
(i%9==0?1900:80+Math.Sin(i*.4)*35)*1024,now.AddSeconds((i-60)*5));
form.DisplayTraffic((1500+Math.Sin(60*.8)*500)*1024,(80+Math.Sin(60*.4)*35)*1024,"演示样本 · 近 5 分钟");
form.LayoutDashboard();
var checks=new Dictionary<string,bool>
{ {
Bucket = p.Bucket, Note = p.Bucket == "hour" ? "演示数据 · 按上报入账小时;缺口为无明细" : "演示数据 · 月筛选为近30个自然日", ["geometry_all_viewport_and_dpi_cases"]=DashboardLayout.SelfTest(),
Points = Enumerable.Range(0, p.Count).Select(i => new UsageHistoryPoint ["fixed_half_size_window"]=form.ClientSize==new Size(form.ScaleLogical(480),form.ScaleLogical(360)),
{ ["repeated_proxy_and_tailnet_rows_hidden"]=!form._trafficCard.Visible&&!form._tailnetTrafficCard.Visible,
Time = p.Bucket == "hour" ? new DateTimeOffset(2026, 9, 9, 21, 0, 0, TimeSpan.FromHours(8)).AddHours(i - p.Count + 1).ToString("O") ["local_graph_caption_identifies_tailnet"]=form._trendHeading.Text.Contains("Tailscale"),
: new DateOnly(2026, 9, 9).AddDays(i - p.Count + 1).ToString("yyyy-MM-dd"), ["local_graph_has_actual_upload_download_values"]=form._uploadLegend.Visible&&form._downloadLegend.Visible
UploadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Sin(i * .72) + 1.1) * 60_000_000), &&form._uploadLegend.Text.Contains("MB/s")&&form._downloadLegend.Text.Contains("KB/s"),
DownloadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Cos(i * .81) + 1.1) * 84_000_000) ["totals_numeric_only"]=!form._dailyCard.Controls.OfType<TrafficChart>().Any(),
}).ToList() ["configuration_actual_state_aligned"]=form._connectionModeCombo.PointToScreen(Point.Empty).Y==form._currentNodeLabel.PointToScreen(Point.Empty).Y,
}); ["no_dashboard_scroll"]=!form._dashboardScrollBar.Visible&&form._dashboardBody.Location==Point.Empty,
form._currentNodeLabel.Text = "VPN003"; ["controls_fit"]=form.DashboardControlsFit(),
form.SetConnectionState(true, "已安全连接", "VPN003 · AI 智能代理"); ["half_transparent_surfaces"]=CardPanel.SurfaceAlpha==128
form.DisplayTraffic(91975, 23357, "21:13:00 · 近 5 分钟"); };
form._sessionMetric.SetBytes(130180710, hint: "本次连接累计");
for (var i = 0; i < 60; i++) form._trafficChart.Add((i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024,
(i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024, DateTimeOffset.Now.AddSeconds((i - 59) * 5));
form.LayoutBrandHeader(); form.LayoutDashboard();
var checks = new Dictionary<string, bool> { ["geometry_112_viewport_dpi_cases"] = DashboardLayout.SelfTest() };
foreach (var check in UsageHistorySeries.SelfTest()) checks[check.Key] = check.Value;
void Capture(string suffix) void Capture(string suffix)
{ {
form.PerformLayout(); form.LayoutDashboard(); Application.DoEvents(); form.PerformLayout();form.LayoutDashboard();Application.DoEvents();
using var image = new Bitmap(form.Width, form.Height); if(showServerFixture)
form.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size));
image.Save(Path.Combine(AppContext.BaseDirectory, $"preview-{GetDisplayVersion()}-{form.DeviceDpi}dpi-{suffix}.png"));
}
Capture("dashboard");
checks["default_window_width_and_height_halved"] = form.ClientSize==new Size(form.ScaleLogical(480),form.ScaleLogical(360));
checks["cumulative_card_has_only_numeric_metrics"] = !form._dailyCard.Controls.OfType<TrafficChart>().Any()
&& form._usageMetric.Parent==form._dailyCard && form._sessionMetric.Parent==form._dailyCard;
checks["proxy_speed_has_independent_trend_card"] = form._trafficChart.Parent==form._speedTrendCard
&& form._speedTrendCard.Left==form._trafficCard.Left && form._speedTrendCard.Top>form._trafficCard.Bottom;
form._currentNodeName = NodePresentation.JinanName;
form._currentNodeLabel.Text = form._currentNodeName;
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
Capture("zero3-connected");
checks["zero3_connected_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
checks["dashboard_controls_within_cards"] = form.DashboardControlsFit();
checks["footer_slogan_displays_without_company_brand"] = !form._brandHeader.Controls.Contains(form._footerCompanyLogo)
&& form._footerCompanyLogo.Parent == form._footer && !form._footerCompanyLogo.Visible;
checks["footer_slogan_text_has_no_url"] = form._footerCompanySite.Visible && form._footerCompanySite.Text == "智能连接 · 高效办公"
&& !form._footerCompanySite.Text.Contains("vpn.", StringComparison.OrdinalIgnoreCase)
&& !form._footerCompanySite.Text.Contains("://", StringComparison.OrdinalIgnoreCase);
checks["official_header_logo_preserved"] = form._brandHeader.Controls.OfType<PictureBox>().Any(logo => logo.Visible && logo.Image is not null
&& logo.SizeMode == PictureBoxSizeMode.Zoom && form._brandHeader.ClientRectangle.Contains(logo.Bounds)
&& logo.Width >= form.ScaleLogical(30) && logo.Right < form._windowChrome!.MinimizeButton.Left);
checks["product_header_named_zonghengjia"] = form.Text == "纵横家" && form._brandHeader.Controls.OfType<Label>().Any(label => label.Text == "纵横家");
checks["powered_by_removed_from_login_and_footer"] = !form._footer.Controls.OfType<Label>().Concat(form._loginView.Controls.OfType<Label>())
.Any(label => label.Text.Contains("Powered by", StringComparison.OrdinalIgnoreCase) || label.Text == "优创未来");
checks["content_uses_local_buffers_not_composited_subtree"] = !form._content.ComposeChildren;
checks["dashboard_reuses_login_backdrop"] = form._dashboardView.LoginArtwork && form._dashboardBody.ParentArtwork;
checks["header_only_has_minimize_button"] = form._brandHeader.Controls.OfType<CaptionButton>().Count() == 1;
checks["scenic_asset_is_decoration_only"] = form._brandHeader.BackgroundImage is null && form._trafficChart.Parent == form._speedTrendCard;
checks["scenic_artwork_packaged_in_exe"] = ScenicTheme.ArtworkAvailable;
checks["footer_poem_does_not_overlap_plan"] = !form._footerPoem.Visible || form._footerPoem.Left > form._expiryLabel.Right;
checks["internal_use_notice_visible"] = form._footerHint.Text == "仅限内部使用,不作商业使用。" && form._footerHint.Visible;
checks["proxy_metrics_values"] = form._usageMetric.UnitText == "GB" && form._uploadMetric.UnitText == "KB/s" && form._sessionMetric.UnitText == "MB";
checks["speed_figures_left_curve_and_totals_right"] = form._usageMetric.Parent == form._sessionMetric.Parent
&& form._usageMetric.Parent == form._dailyCard && form._trafficChart.Parent == form._speedTrendCard && form._uploadMetric.Parent == form._trafficCard
&& form._downloadMetric.Parent == form._trafficCard;
form._historyRangeCombo.SelectedIndex = 0;
Capture("history-legacy-unavailable");
checks["daily_accounting_curve_no_longer_displayed"] = form._dailyChart.Parent is null && !form._dailyChart.Visible;
form._dailyChart.SetHistory([], fixtureRanges);
var retainedSampleCount = form._trafficChart.PointCount;
foreach (var period in SpeedHistoryPeriod.All)
{
form._historyRangeCombo.SelectedItem = period;
Capture("speed-" + period.Minutes + "m");
checks["speed_filter_" + period.Minutes] = form._trafficChart.PeriodMinutes == period.Minutes
&& form._trafficChart.PointCount == retainedSampleCount;
}
form._dailyChart.SetHistory([], fixtureRanges);
checks["profile_refresh_preserves_speed_filter"] = form._trafficChart.PeriodMinutes == 60;
form._historyRangeCombo.SelectedIndex = 1;
form.Size = form.MinimumSize;
Capture("compact");
checks["zero3_compact_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
checks["compact_controls_within_cards"] = form.DashboardControlsFit();
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
Application.DoEvents();
form.LayoutDashboard();
checks["compact_footer_fits_without_scroll"] = !form._dashboardScrollBar.Visible
&& form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
checks["compact_no_horizontal_scrollbar"] = !form._dashboardView.HorizontalScroll.Visible;
Capture("compact-scrolled");
form._dashboardScrollBar.Value = 0;
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form._currentNodeName = "VPN002";
form._currentNodeLabel.Text = form._currentNodeName;
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · 已回退到公共节点");
Capture("public-fallback");
checks["fallback_does_not_show_zero3"] = !form._statusDetail.Text.Contains("Zero3") && form._currentNodeLabel.Text == "VPN002";
form.SetConnectionState(false, "未连接", "点击连接,自动选择工作节点");
form._currentNodeLabel.Text = "未连接";
form._trafficChart.Reset(); form._dailyChart.SetHistory([]);
Capture("disconnected");
checks["disconnected_speed_not_stale"] = form._uploadMetric.ValueText == "—" && form._downloadMetric.ValueText == "—";
form._connectionModeCombo.SelectedIndex = 1;
form._manualNodeCombo.SelectedIndex = 0;
Capture("manual-selection");
checks["manual_selection_controls_within_card"] = form.DashboardControlsFit();
checks["manual_selection_visible_when_disconnected"] = form._manualNodeCombo.Visible && form._manualNodeCombo.Enabled;
form.SetConnectionState(true, "已安全连接", "手动指定节点 · AI 智能代理");
Capture("manual-connected");
checks["manual_connected_selection_locked"] = !form._connectionModeCombo.Enabled && !form._manualNodeCombo.Visible;
// Same window dimensions with or without Tailnet: only the left speed
// region is subdivided. Synthetic samples do not claim live acceptance.
form._connectionModeCombo.SelectedIndex = 0;
form._currentNodeBaseName = "VPN003";
form.UpdateConnectedTransportPresentation(true);
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
form._currentNodeLabel.Text = form._currentNodeName;
form._dailyChart.SetHistory([], fixtureRanges);
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form._trafficChart.Reset();
form.ResetTailnetTraffic();
for (var i = 0; i < 60; i++)
{
var up = (i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024;
var down = (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024;
var sampledAt = DateTimeOffset.Now.AddSeconds((i - 59) * 5);
form._trafficChart.Add(up, down, sampledAt);
}
form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟");
form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟");
Capture("tailnet-dashboard");
checks["tailnet_preview_has_full_width_rows_and_compact_totals"] = form._dailyCard.Width == form._trafficCard.Width
&& form._dailyCard.Top > form._tailnetTrafficCard.Bottom && form._dailyCard.Height <= form.ScaleLogical(40);
form.Size = form.MinimumSize;
Capture("tailnet-compact");
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
Capture("tailnet-compact-scrolled");
checks["tailnet_compact_preview_footer_reachable"] = form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom
<= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
form.ClientSize=new Size(form.ScaleLogical(480),form.ScaleLogical(360));
form.SetNodeTrafficPermission(true);
var serverSampledAt=DateTimeOffset.UtcNow;
form._nodeTrafficPanel.SetSnapshot(new NodeTrafficSnapshot
{
Contract=1, Scope="server_host_interface", Source="linux_host_interface", Direction="interface_perspective",
CounterSince="boot_or_interface_reset", GeneratedAt=serverSampledAt,
Nodes=NodeTrafficPresentation.Slugs.Select((slug,index)=>new NodeTrafficReading
{ {
Slug=slug, UploadRate=index==0?1_572_864:625_664, DownloadRate=index==0?23_842:8_388_608, previewServers.Bounds=form._nodeTrafficPanel.Bounds;
TotalUpload=index==0?137_813_120_000:921_845_760_000, TotalDownload=index==0?774_618_173_440:1_320_000_000_000, previewServers.Visible=form._canViewNodeTraffic;
SampledAt=serverSampledAt, IntervalSeconds=5, CounterEpoch="synthetic-preview" form._nodeTrafficPanel.Visible=false;
}).ToList() previewServers.BringToFront();
}); }
form.LayoutDashboard(); Capture("half-size-tailnet-servers"); using var image=new Bitmap(form.Width,form.Height);
checks["half_size_tailnet_servers_fit"] = form.DashboardControlsFit() && !form._dashboardScrollBar.Visible form.DrawToBitmap(image,new Rectangle(Point.Empty,image.Size));
&& form._nodeTrafficPanel.Bottom<form._footer.Top; image.Save(Path.Combine(AppContext.BaseDirectory,$"preview-{GetDisplayVersion()}-{form.DeviceDpi}dpi-{suffix}.png"));
form.SetNodeTrafficPermission(false); }
Capture("local-trend-tailnet");
var originalBounds=(form._speedTrendCard.Bounds,form._dailyCard.Bounds,form._footer.Bounds);
form.UpdateConnectedTransportPresentation(false); form.UpdateConnectedTransportPresentation(false);
form.SetConnectionState(false, "未连接", "连接后显示当前工作节点与代理模式"); checks["domain_caption_changes_without_resizing"]=form._trendHeading.Text.Contains("域名入口")
Capture("half-size-disconnected-auto"); &&originalBounds==(form._speedTrendCard.Bounds,form._dailyCard.Bounds,form._footer.Bounds);
form._connectionModeCombo.SelectedIndex=1; Capture("local-trend-domain");
form._manualNodeCombo.SelectedIndex=0; form.UpdateConnectedTransportPresentation(true);
Capture("half-size-disconnected-manual"); form.SetNodeTrafficPermission(true);
checks["configuration_choices_left_actual_state_right"] = form._routeCombo.Right < form._modeCard.Left showServerFixture=true;
&& form._connectionModeCombo.Right < form._modeCard.Left NodeTrafficSnapshot? lastServerFixture=null;
&& form._currentNodeLabel.Text=="未连接" && form._routeReadOnly.Text=="未生效"; for(var i=0;i<301;i++)
checks["configuration_rows_do_not_overlap"] = !form._connectionModeCombo.Bounds.IntersectsWith(form._routeCombo.Bounds)
&& !form._manualNodeCombo.Bounds.IntersectsWith(form._routeCombo.Bounds);
form.SetConnectionState(true,"已安全连接","VPN003 · AI 智能代理");
Capture("half-size-connected-manual");
form._connectionModeCombo.SelectedIndex=0;
Capture("half-size-connected-auto");
form.ShowLogin(); Capture("half-size-login");
checks["half_size_login_visible"] = form.LoginFieldsVisibleForTest && form.LoginRegistrationAlignedForTest;
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form.ShowLogin(); Capture("login");
checks["login_fields_visible"] = form.LoginFieldsVisibleForTest;
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "dashboard-ui-self-test.json"), JsonSerializer.Serialize(new
{ {
version = GetDisplayVersion(), passed = checks.Values.All(v => v), checks, var sampled=now.AddSeconds(i-300);
dpi = form.DeviceDpi, synthetic_data = true, network_modified = false, installed_client_modified = false serverClock=sampled;
}, new JsonSerializerOptions { WriteIndented = true })); lastServerFixture=new NodeTrafficSnapshot
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",SamplePeriodSeconds=1,GeneratedAt=sampled,
Nodes=new[]{("VPN002 东京","aliyun-tokyo-002"),("VPN003 美国","aliyun-siliconvalley-003"),
("济南 博翠明湖","jinan-phone"),("VPN004 纽约","racknerd-newyork-004")}.Select((node,index)=>new NodeTrafficReading
{
Name=node.Item1,Slug=node.Item2,SampledAt=sampled,IntervalSeconds=1,CounterEpoch="synthetic-preview",
UploadRate=(long)((20+(index+1)*12+Math.Sin(i*.035+index)*15)*1024),
DownloadRate=(long)((150+(index+1)*45+Math.Sin(i*.07+index)*120)*1024)
}).ToList()
};
previewServers.SetSnapshot(lastServerFixture);
}
form.LayoutDashboard();Capture("local-and-four-server-trends");
checks["four_server_rows_received"]=previewServers.ServerCount==4;
checks["graphs_order_local_then_servers_then_totals"]=form._speedTrendCard.Bottom<form._nodeTrafficPanel.Top
&&form._nodeTrafficPanel.Bottom<form._dailyCard.Top&&form._dailyCard.Bottom<form._footer.Top;
checks["four_servers_have_distinct_samples"]=previewServers.History("racknerd-newyork-004").Last().Up
!=previewServers.History("aliyun-tokyo-002").Last().Up;
checks["no_personal_accounting_changes_from_server_samples"]=form._sessionUp==0&&form._sessionDown==0;
checks["server_graphs_keep_window_and_controls_fitted"]=form.DashboardControlsFit()&&!form._dashboardScrollBar.Visible;
foreach(var period in SpeedHistoryPeriod.All)
{
form._historyRangeCombo.SelectedItem=period;
previewServers.SetPeriodMinutes(period.Minutes);
checks["local_and_server_range_"+period.Minutes]=form._trafficChart.PeriodMinutes==period.Minutes
&&previewServers.HistoryCount("racknerd-newyork-004")==301;
}
form._historyRangeCombo.SelectedItem=SpeedHistoryPeriod.All[1];
previewServers.SetPeriodMinutes(5);
previewServers.SetSnapshot(new NodeTrafficSnapshot
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",SamplePeriodSeconds=1,GeneratedAt=now,
Nodes=lastServerFixture!.Nodes.Where(row=>row.Slug!="jinan-phone").ToList()
});
Capture("local-and-three-server-trends");
checks["three_live_server_fixture_fits_without_height_change"]=previewServers.ServerCount==3
&&form.DashboardControlsFit()&&!form._dashboardScrollBar.Visible;
previewServers.Unavailable("后台尚未提供服务器监控",clear:true);
Capture("server-monitor-unavailable");
checks["missing_server_data_does_not_invent_rows"]=previewServers.ServerCount==0;
form.SetNodeTrafficPermission(false);
form.SetConnectionState(false,"未连接","连接后显示代理速度趋势");
form._trafficChart.Reset();Capture("disconnected");
checks["disconnected_values_not_stale"]=form._uploadLegend.Text.Contains("—")&&form._downloadLegend.Text.Contains("—");
form.ShowLogin();Capture("login");
checks["login_still_fits"]=form.LoginFieldsVisibleForTest&&form.LoginRegistrationAlignedForTest;
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"dashboard-ui-self-test.json"),JsonSerializer.Serialize(new
{
version=GetDisplayVersion(),passed=checks.Values.All(value=>value),checks,dpi=form.DeviceDpi,
synthetic_data=true,network_modified=false,installed_client_modified=false,production_sample_observed=false
},new JsonSerializerOptions {WriteIndented=true}));
form.RequestExit(); form.RequestExit();
if (checks.Values.Any(v => !v)) throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json"); if(checks.Values.Any(value=>!value))throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json");
} }
private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _speedTrendCard, _dailyCard, _footer } private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _speedTrendCard, _dailyCard, _footer }
+9 -3
View File
@@ -7,10 +7,12 @@ internal sealed partial class MainForm
private readonly TailnetReadinessPolicy _tailnetReadiness = new(); private readonly TailnetReadinessPolicy _tailnetReadiness = new();
private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false }; private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false };
private void SetSessionToken(string? token) private void SetSessionToken(string? token, DateTimeOffset? expiresAt = null)
{ {
_connectionAttemptCancellation?.Cancel(); _connectionAttemptCancellation?.Cancel();
_accessToken = token; _accessToken = token;
_connectionAuthorization.Reset(expiresAt, DateTimeOffset.UtcNow, Environment.TickCount64);
_connectionHealth.Invalidate();
_sessionRevision++; _sessionRevision++;
_nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true); _nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true);
_nextNodeTrafficAttempt = DateTimeOffset.MinValue; _nextNodeTrafficAttempt = DateTimeOffset.MinValue;
@@ -36,6 +38,9 @@ internal sealed partial class MainForm
_busy || _healthChecking || _uplinkChecking || _handoverOperating || _handover.Pending || _handover.Settling || _xray.IsTransitioning || _exiting, _busy || _healthChecking || _uplinkChecking || _handoverOperating || _handover.Pending || _handover.Settling || _xray.IsTransitioning || _exiting,
_xray.IsRunning, _xray.UsesTailnet, !_currentNodeIsPrivateAuxiliary && _xray.TailnetProbeEndpoint is not null); _xray.IsRunning, _xray.UsesTailnet, !_currentNodeIsPrivateAuxiliary && _xray.TailnetProbeEndpoint is not null);
private bool CanRetainAuthorizedCore() => _connectionAuthorization.CanRetain(DateTimeOffset.UtcNow,
Environment.TickCount64, _currentNodeIsPrivateAuxiliary, _privateLeaseDeadlineTicks);
// The initial connection already tested this address. At ten-minute // The initial connection already tested this address. At ten-minute
// intervals repeat only the authorized IP ping; failure on the active path // intervals repeat only the authorized IP ping; failure on the active path
// retries the same node's domain through the normal fresh-grant connector. // retries the same node's domain through the normal fresh-grant connector.
@@ -51,9 +56,10 @@ internal sealed partial class MainForm
try try
{ {
if (_xray.TailnetProbeEndpoint is { } endpoint) if (_xray.TailnetProbeEndpoint is { } endpoint)
reachable = await TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, _lifetime.Token); reachable = await TailnetPingConfirmation.ProbeAsync(
pingToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, pingToken), _lifetime.Token);
} }
catch (OperationCanceledException) { } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; }
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ } catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable); var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable);
if (_exiting || IsDisposed || Disposing) return; if (_exiting || IsDisposed || Disposing) return;
+3 -1
View File
@@ -30,7 +30,9 @@ internal sealed partial class MainForm
{ {
if (_tailnetTrafficVisible == show) return; if (_tailnetTrafficVisible == show) return;
_tailnetTrafficVisible = show; _tailnetTrafficVisible = show;
_tailnetTrafficCard.Visible = show; // The transport has a caption in the single local chart; its counters
// remain available without drawing the same stream as a second row.
_tailnetTrafficCard.Visible = false;
if (!show) ResetTailnetTraffic(); if (!show) ResetTailnetTraffic();
LayoutDashboard(); LayoutDashboard();
} }
+35 -6
View File
@@ -15,6 +15,7 @@ internal sealed partial class MainForm : Form
private readonly System.Windows.Forms.Timer _trafficTimer = new() { Interval = 5_000 }; private readonly System.Windows.Forms.Timer _trafficTimer = new() { Interval = 5_000 };
private readonly System.Windows.Forms.Timer _healthTimer = new() { Interval = 5_000 }; private readonly System.Windows.Forms.Timer _healthTimer = new() { Interval = 5_000 };
private readonly ConnectionHealthPolicy _connectionHealth = new(); private readonly ConnectionHealthPolicy _connectionHealth = new();
private readonly ConnectionAuthorizationLease _connectionAuthorization = new();
private readonly Label _currentNodeLabel = new(); private readonly Label _currentNodeLabel = new();
private readonly TrafficChart _trafficChart = new(); private readonly TrafficChart _trafficChart = new();
private readonly DailyTrafficChart _dailyChart = new(); private readonly DailyTrafficChart _dailyChart = new();
@@ -439,7 +440,7 @@ internal sealed partial class MainForm : Form
try try
{ {
var response = await _api.LoginAsync(login, password, _lifetime.Token); var response = await _api.LoginAsync(login, password, _lifetime.Token);
SetSessionToken(response.AccessToken); SetSessionToken(response.AccessToken, response.ExpiresAt);
TokenStore.Save(_accessToken); TokenStore.Save(_accessToken);
_passwordText.Clear(); _passwordText.Clear();
ShowDashboard(response.Profile); ShowDashboard(response.Profile);
@@ -515,6 +516,13 @@ internal sealed partial class MainForm : Form
var replacementStarted = false; var replacementStarted = false;
try try
{ {
if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64))
{
var refreshed = await _api.GetProfileAsync(_accessToken, connectionToken);
UpdateProfile(refreshed, preserveSelections: true);
if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64))
throw new ApiException(403, "账号或订阅授权已到期,请重新登录验证。");
}
var failures = new List<string>(); var failures = new List<string>();
ConfigResponse? response = null; ConfigResponse? response = null;
var privateGrants = _privateAuxiliaryNodes.Where(n => n.ExpiresAt > DateTimeOffset.UtcNow).ToArray(); var privateGrants = _privateAuxiliaryNodes.Where(n => n.ExpiresAt > DateTimeOffset.UtcNow).ToArray();
@@ -597,7 +605,7 @@ internal sealed partial class MainForm : Form
} }
catch (ApiException exception) when (exception.StatusCode is not (401 or 403)) catch (ApiException exception) when (exception.StatusCode is not (401 or 403))
{ {
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw; if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw;
failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}"); failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}");
await _xray.StopAsync(); await _xray.StopAsync();
if (candidate is null) break; if (candidate is null) break;
@@ -606,7 +614,7 @@ internal sealed partial class MainForm : Form
} }
catch (Exception exception) when (exception is not OperationCanceledException && exception is not ApiException { StatusCode: 401 or 403 }) catch (Exception exception) when (exception is not OperationCanceledException && exception is not ApiException { StatusCode: 401 or 403 })
{ {
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw; if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw;
failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}"); failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}");
await _xray.StopAsync(); await _xray.StopAsync();
if (candidate is not null) _failedNodes[candidate.Slug] = DateTimeOffset.UtcNow.AddMinutes(5); if (candidate is not null) _failedNodes[candidate.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
@@ -642,7 +650,7 @@ internal sealed partial class MainForm : Form
{ {
if (!_exiting) await DisconnectAsync(); if (!_exiting) await DisconnectAsync();
} }
catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore()))
{ {
AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name); AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
_wantConnected = true; _wantConnected = true;
@@ -761,6 +769,13 @@ internal sealed partial class MainForm : Form
private async Task MaintainConnectionAsync() private async Task MaintainConnectionAsync()
{ {
if (_wantConnected && !_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64)
&& !_busy && !_healthChecking && !_handoverOperating && !_exiting)
{
await DisconnectAsync();
_statusDetail.Text = "已知账号或订阅授权已到期,请联网重新验证。";
return;
}
if (_currentNodeIsPrivateAuxiliary && _privateLeaseDeadlineTicks > 0 if (_currentNodeIsPrivateAuxiliary && _privateLeaseDeadlineTicks > 0
&& Environment.TickCount64 >= _privateLeaseDeadlineTicks && !_busy && !_healthChecking && !_handoverOperating && !_exiting) && Environment.TickCount64 >= _privateLeaseDeadlineTicks && !_busy && !_healthChecking && !_handoverOperating && !_exiting)
{ {
@@ -788,7 +803,8 @@ internal sealed partial class MainForm : Form
var health = await _xray.CheckHealthWithRepairAsync(_lifetime.Token); var health = await _xray.CheckHealthWithRepairAsync(_lifetime.Token);
var healthy = health.Healthy; var healthy = health.Healthy;
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId, var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy); _wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
_xray.UsesTailnet, health.BusinessUnavailable);
if (decision == ConnectionHealthPolicy.Decision.Ignore) return; if (decision == ConnectionHealthPolicy.Decision.Ignore) return;
if (healthy && _xray.IsRunning) { if (healthy && _xray.IsRunning) {
if (_localRoutingFault) { if (_localRoutingFault) {
@@ -800,6 +816,15 @@ internal sealed partial class MainForm : Form
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId); ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
return; return;
} }
if (decision == ConnectionHealthPolicy.Decision.Degraded) {
_localRoutingFault = true;
SetConnectionState(true, "网站探测异常,连接保留", $"{_currentNodeName ?? _currentNodeSlug} · 目标网站可用性尚未确认,保留当前线路");
_statusTitle.ForeColor = Color.FromArgb(155, 88, 12);
_statusDot.ForeColor = _statusTitle.ForeColor;
_notifyIcon.Text = "纵横家 · 网站探测异常";
AppPaths.WriteLog("健康诊断:网站探测异常,保留当前内核和已授权线路;未将网站状态判为节点传输失败。");
return;
}
if (decision == ConnectionHealthPolicy.Decision.Repair) { if (decision == ConnectionHealthPolicy.Decision.Repair) {
_localRoutingFault = true; _localRoutingFault = true;
SetConnectionState(true, "分流异常,正在修复", $"{_currentNodeName ?? _currentNodeSlug} · 代理出口可达,保留现有连接并重试规则验证"); SetConnectionState(true, "分流异常,正在修复", $"{_currentNodeName ?? _currentNodeSlug} · 代理出口可达,保留现有连接并重试规则验证");
@@ -949,7 +974,9 @@ internal sealed partial class MainForm : Form
var accepted = await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token); var accepted = await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token);
if (!IsCurrent() || _xray.CoreId != privateCore) return; if (!IsCurrent() || _xray.CoreId != privateCore) return;
if (accepted) if (accepted)
{
_privateLeaseDeadlineTicks = Environment.TickCount64 + Math.Max(0, (long)(renewed.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds); _privateLeaseDeadlineTicks = Environment.TickCount64 + Math.Max(0, (long)(renewed.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds);
}
else else
{ {
await DisconnectAsync(); await DisconnectAsync();
@@ -1058,8 +1085,10 @@ internal sealed partial class MainForm : Form
private void UpdateProfile(Profile profile, bool preserveSelections) private void UpdateProfile(Profile profile, bool preserveSelections)
{ {
if (_exiting || IsDisposed || Disposing) return; if (_exiting || IsDisposed || Disposing) return;
_connectionAuthorization.AcceptProfile(profile.Subscription.Status, profile.Subscription.ExpiresAt,
DateTimeOffset.UtcNow, Environment.TickCount64);
_knownTailnetAllowed = true; _knownTailnetAllowed = true;
SetNodeTrafficPermission(profile.CanViewNodeTraffic); ConfigureNodeTrafficMonitor(profile);
var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null; var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null;
_welcomeLabel.Text = $"你好,{profile.DisplayName}"; _welcomeLabel.Text = $"你好,{profile.DisplayName}";
_accountLabel.Text = profile.Email; _accountLabel.Text = profile.Email;
+61 -6
View File
@@ -6,6 +6,8 @@ namespace UCVL.VPNPlus;
// It is NOT part of 0.2.5's connection transaction and never changes routes. // It is NOT part of 0.2.5's connection transaction and never changes routes.
internal static class NodeHealthProbe internal static class NodeHealthProbe
{ {
internal readonly record struct Observation(bool BusinessHealthy, bool TransportReachable);
internal readonly record struct Report(bool BusinessHealthy, bool TransportReachable);
internal static bool Accepts(int target, int status) => target == 0 internal static bool Accepts(int target, int status) => target == 0
? status is 200 or 204 ? status is 200 or 204
: status is >= 200 and < 500; : status is >= 200 and < 500;
@@ -13,6 +15,51 @@ internal static class NodeHealthProbe
internal static bool OverallHealthy(IReadOnlyList<bool> results) => internal static bool OverallHealthy(IReadOnlyList<bool> results) =>
results.Count >= 3 && results[2] && (results[0] || results[1]); results.Count >= 3 && results[2] && (results[0] || results[1]);
internal static bool AcceptsTransportStatus(int status) => status is >= 100 and <= 599;
private static async Task<Observation> Observed(Task<Observation> probe)
{
try { return await probe.ConfigureAwait(false); }
catch { return default; }
}
internal static async Task<bool> AggregateTransportAsync(IReadOnlyList<Task<Observation>> probes,
CancellationToken token, Action cancelRemaining)
{
var pending = probes.Select(Observed).ToList();
try
{
token.ThrowIfCancellationRequested();
while (pending.Count > 0)
{
var finished = await Task.WhenAny(pending).WaitAsync(token).ConfigureAwait(false);
pending.Remove(finished);
var observation = await finished.ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (observation.TransportReachable) return true;
}
return false;
}
finally { cancelRemaining(); }
}
internal static async Task<Report> AggregateReportAsync(IReadOnlyList<Task<Observation>> probes,
CancellationToken token, Action cancelRemaining)
{
var observations = probes.Select(Observed).ToArray();
async Task<bool> BusinessAsync(Task<Observation> probe) => (await probe.ConfigureAwait(false)).BusinessHealthy;
try
{
token.ThrowIfCancellationRequested();
var business = AggregateAsync(observations.Select(BusinessAsync).ToArray(), token, () => { });
var transport = AggregateTransportAsync(observations, token, () => { });
await Task.WhenAll(business, transport).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
return new(await business.ConfigureAwait(false), await transport.ConfigureAwait(false));
}
finally { cancelRemaining(); }
}
internal static async Task<bool> AggregateAsync(IReadOnlyList<Task<bool>> probes, internal static async Task<bool> AggregateAsync(IReadOnlyList<Task<bool>> probes,
CancellationToken token, Action cancelRemaining) CancellationToken token, Action cancelRemaining)
{ {
@@ -52,6 +99,12 @@ internal static class NodeHealthProbe
} }
internal static async Task<bool> CheckAsync(CancellationToken token, int proxyPort = 0) internal static async Task<bool> CheckAsync(CancellationToken token, int proxyPort = 0)
=> (await CheckReportAsync(token, proxyPort).ConfigureAwait(false)).BusinessHealthy;
internal static async Task<bool> CheckTransportAsync(CancellationToken token, int proxyPort)
=> (await CheckReportAsync(token, proxyPort, transportOnly: true).ConfigureAwait(false)).TransportReachable;
internal static async Task<Report> CheckReportAsync(CancellationToken token, int proxyPort = 0, bool transportOnly = false)
{ {
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
timeout.CancelAfter(TimeSpan.FromSeconds(15)); timeout.CancelAfter(TimeSpan.FromSeconds(15));
@@ -64,14 +117,16 @@ internal static class NodeHealthProbe
var probes = urls.Select(async (url, index) => { var probes = urls.Select(async (url, index) => {
try { try {
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, timeout.Token); using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
return Accepts(index, (int)response.StatusCode); return new Observation(Accepts(index, (int)response.StatusCode), AcceptsTransportStatus((int)response.StatusCode));
} }
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
catch { return false; } catch { return default(Observation); }
}).ToArray(); }).ToArray();
// This client exists primarily for ChatGPT/Codex. Google or the OpenAI // Retain the stricter business-site diagnostic separately. A valid
// REST API remaining reachable must not mask a broken Codex transport. // TLS/HTTP response through the forced proxy, including 5xx, proves
// Require the Codex endpoint plus one independent Internet target. // transport reachability without claiming the target service is healthy.
return await AggregateAsync(probes, token, timeout.Cancel); if (transportOnly)
return new(false, await AggregateTransportAsync(probes, token, timeout.Cancel).ConfigureAwait(false));
return await AggregateReportAsync(probes, token, timeout.Cancel);
} }
} }
+37
View File
@@ -133,6 +133,43 @@ internal static class NodeHealthProbeSelfTest
Require(await result, "Unused-probe cancellation changed the health verdict"); Require(await result, "Unused-probe cancellation changed the health verdict");
}); });
await Check("http_5xx_response_proves_transport_but_not_business_health", () => {
Require(NodeHealthProbe.AcceptsTransportStatus(503) && !NodeHealthProbe.Accepts(2, 503), "HTTP outage confused with proxy transport");
return Task.CompletedTask;
});
await Check("single_codex_outage_keeps_independent_transport_proof", async () => {
var report = await NodeHealthProbe.AggregateReportAsync(new[] {
Task.FromResult(new NodeHealthProbe.Observation(true, true)),
Task.FromResult(new NodeHealthProbe.Observation(true, true)),
Task.FromResult(new NodeHealthProbe.Observation(false, false)) }, CancellationToken.None, () => { });
Require(!report.BusinessHealthy && report.TransportReachable, "Site failure must remain distinct from transport failure");
});
await Check("all_sites_return_5xx_still_is_not_transport_death", async () => {
var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3)
.Select(_ => Task.FromResult(new NodeHealthProbe.Observation(false, true))).ToArray(), CancellationToken.None, () => { });
Require(!report.BusinessHealthy && report.TransportReachable, "HTTP responses lost transport proof");
});
await Check("transport_proof_does_not_wait_for_failed_codex", async () => {
var pending = new TaskCompletionSource<NodeHealthProbe.Observation>(TaskCreationOptions.RunContinuationsAsynchronously);
var cancelled = false;
var reached = await NodeHealthProbe.AggregateTransportAsync(new[] {
Task.FromResult(new NodeHealthProbe.Observation(true, true)), pending.Task, pending.Task }, CancellationToken.None, () => cancelled = true)
.WaitAsync(TimeSpan.FromSeconds(1));
Require(reached && cancelled, "Transport startup unnecessarily waited for a site diagnostic");
pending.SetException(new IOException("late site fixture"));
});
await Check("all_transport_failures_remain_unavailable", async () => {
var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3)
.Select(_ => Task.FromResult(default(NodeHealthProbe.Observation))).ToArray(), CancellationToken.None, () => { });
Require(!report.BusinessHealthy && !report.TransportReachable, "Failed transport became false healthy");
});
await Check("transport_caller_cancellation_propagates", async () => {
using var caller = new CancellationTokenSource(); caller.Cancel();
var cancelled = false;
try { await NodeHealthProbe.AggregateTransportAsync([], caller.Token, () => { }); }
catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; }
Require(cancelled, "Transport cancellation was converted to false health");
});
var passed = checks.Values.All(value => value); var passed = checks.Values.All(value => value);
var report = JsonSerializer.Serialize(new { kind = "node_health_early_completion", network_used = false, var report = JsonSerializer.Serialize(new { kind = "node_health_early_completion", network_used = false,
checks, errors, passed }, new JsonSerializerOptions { WriteIndented = true }); checks, errors, passed }, new JsonSerializerOptions { WriteIndented = true });
+169
View File
@@ -0,0 +1,169 @@
namespace UCVL.VPNPlus;
// Captured from the isolated backend/schema and real sampler round-trip fixtures.
// These contain synthetic nodes only; they are not production measurements.
internal static class NodeTrafficBackendFixtures
{
internal const string Baseline = """
{
"contract": 1,
"scope": "server_host_interface",
"source": "linux_host_interface",
"direction": "interface_perspective",
"counter_since": "boot_or_interface_reset",
"refresh_seconds": 5,
"sample_period_seconds": 1,
"freshness_seconds": 15,
"history_seconds": 9,
"available_storage_history_seconds": 3600,
"requested_history_seconds": 300,
"history_point_limit_per_node": 300,
"history_truncated": false,
"history_since": "2026-11-06T07:55:00+00:00",
"generated_at": "2026-11-06T08:00:00+00:00",
"nodes": [
{
"slug": "fixture-node",
"name": "VPN",
"region": "fixture",
"current_upload_bytes_per_second": 2000,
"current_download_bytes_per_second": 1000,
"total_upload_bytes": 4000,
"total_download_bytes": 2000,
"sampled_at": "2026-11-06T07:59:52+00:00",
"interval_seconds": 1.0,
"interface": "eth0",
"counter_epoch": "22222222-2222-4222-8222-222222222222",
"stale": false,
"history_truncated": false,
"returned_history_since": "2026-11-06T07:59:51+00:00",
"history": [
{
"sampled_at": "2026-11-06T07:59:51+00:00",
"interval_seconds": 0.0,
"sequence": 1,
"upload_bytes_per_second": null,
"download_bytes_per_second": null,
"counter_epoch": "22222222-2222-4222-8222-222222222222",
"interface": "eth0",
"quality": "baseline",
"gap_before": true,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T07:59:52+00:00",
"interval_seconds": 1.0,
"sequence": 2,
"upload_bytes_per_second": 2000,
"download_bytes_per_second": 1000,
"counter_epoch": "22222222-2222-4222-8222-222222222222",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
}
]
}
]
}
""";
internal const string Roundtrip = """
{
"contract": 1,
"scope": "server_host_interface",
"source": "linux_host_interface",
"direction": "interface_perspective",
"counter_since": "boot_or_interface_reset",
"refresh_seconds": 5,
"sample_period_seconds": 1,
"freshness_seconds": 15,
"history_seconds": 5,
"available_storage_history_seconds": 3600,
"requested_history_seconds": 300,
"history_point_limit_per_node": 300,
"history_truncated": false,
"history_since": "2026-11-06T05:55:06+00:00",
"generated_at": "2026-11-06T06:00:06+00:00",
"nodes": [
{
"slug": "node-example",
"name": "VPN",
"region": "fixture",
"current_upload_bytes_per_second": 40,
"current_download_bytes_per_second": 80,
"total_upload_bytes": 50,
"total_download_bytes": 100,
"sampled_at": "2026-11-06T06:00:05+00:00",
"interval_seconds": 1.0,
"interface": "eth0",
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"stale": false,
"history_truncated": false,
"returned_history_since": "2026-11-06T06:00:01+00:00",
"history": [
{
"sampled_at": "2026-11-06T06:00:01+00:00",
"interval_seconds": 0.0,
"sequence": 1,
"upload_bytes_per_second": null,
"download_bytes_per_second": null,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interface": "eth0",
"quality": "baseline",
"gap_before": true,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:02+00:00",
"interval_seconds": 1.0,
"sequence": 2,
"upload_bytes_per_second": 100,
"download_bytes_per_second": 200,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:03+00:00",
"interval_seconds": 1.0,
"sequence": 3,
"upload_bytes_per_second": 300,
"download_bytes_per_second": 800,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:04+00:00",
"interval_seconds": 1.0,
"sequence": 4,
"upload_bytes_per_second": null,
"download_bytes_per_second": null,
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"interface": "eth0",
"quality": "reset",
"gap_before": true,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:05+00:00",
"interval_seconds": 1.0,
"sequence": 5,
"upload_bytes_per_second": 40,
"download_bytes_per_second": 80,
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
}
]
}
]
}
""";
}
+209 -35
View File
@@ -10,6 +10,8 @@ internal sealed class NodeTrafficSnapshot
[JsonPropertyName("direction")] public string Direction { get; init; } = ""; [JsonPropertyName("direction")] public string Direction { get; init; } = "";
[JsonPropertyName("counter_since")] public string CounterSince { get; init; } = ""; [JsonPropertyName("counter_since")] public string CounterSince { get; init; } = "";
[JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; } [JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; }
[JsonPropertyName("sample_period_seconds")] public int SamplePeriodSeconds { get; init; }
[JsonPropertyName("history_since")] public DateTimeOffset? HistorySince { get; init; }
[JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = []; [JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = [];
} }
@@ -26,26 +28,57 @@ internal sealed class NodeTrafficReading
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; } [JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
[JsonPropertyName("stale")] public bool Stale { get; init; } [JsonPropertyName("stale")] public bool Stale { get; init; }
[JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; } [JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; }
[JsonPropertyName("history")] public List<NodeTrafficHistoryReading> History { get; init; }=[];
}
internal sealed class NodeTrafficHistoryReading
{
[JsonPropertyName("sampled_at")] public DateTimeOffset SampledAt { get; init; }
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
[JsonPropertyName("upload_bytes_per_second")] public long? Upload { get; init; }
[JsonPropertyName("download_bytes_per_second")] public long? Download { get; init; }
[JsonPropertyName("counter_epoch")] public string CounterEpoch { get; init; }="";
[JsonPropertyName("interface")] public string Interface { get; init; }="";
[JsonPropertyName("quality")] public string Quality { get; init; }="";
[JsonPropertyName("gap_before")] public bool GapBefore { get; init; }
} }
// Read-only display contract: no personal accounting or route/core mutations. // Read-only display contract: no personal accounting or route/core mutations.
internal static class NodeTrafficPresentation internal static class NodeTrafficPresentation
{ {
internal static readonly string[] Slugs = ["aliyun-tokyo-002", "aliyun-siliconvalley-003"];
internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1 internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1
&& value.Scope == "server_host_interface" && value.Source == "linux_host_interface" && value.Scope == "server_host_interface" && value.Source == "linux_host_interface"
&& value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset" && value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset"
&& value.SamplePeriodSeconds is 0 or 1
&& value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15) && value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15)
&& value.Nodes is { Count: <= 2 } && value.Nodes.All(n => n is not null) && value.Nodes is { Count: <= 32 } && value.Nodes.All(n => n is not null)
&& value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count && value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count
&& value.Nodes.All(n => Slugs.Contains(n.Slug, StringComparer.Ordinal) && value.Nodes.All(n => n.Slug is { Length: > 0 and <= 80 }
&& n.Slug.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_')
&& n.Name is { Length: <= 120 } && n.Region is { Length: <= 160 }
&& n.UploadRate is not < 0 && n.DownloadRate is not < 0 && n.UploadRate is not < 0 && n.DownloadRate is not < 0
&& n.TotalUpload is not < 0 && n.TotalDownload is not < 0 && n.TotalUpload is not < 0 && n.TotalDownload is not < 0
&& (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value) && n.IntervalSeconds > 0 && n.IntervalSeconds <= 30)); && (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value)
&&(n.IntervalSeconds>0||n.IntervalSeconds==0&&n.UploadRate is null&&n.DownloadRate is null)
&& n.IntervalSeconds <=(n.UploadRate is null&&n.DownloadRate is null?86400:30))
&& n.History is {Count:<=3600}
&& n.History.All(point=>point is not null&&ValidHistory(point,value.GeneratedAt))
&& n.History.Zip(n.History.Skip(1),(first,second)=>second.SampledAt>first.SampledAt
||second.SampledAt==first.SampledAt&&second.CounterEpoch!=first.CounterEpoch).All(ordered=>ordered));
private static bool ValidHistory(NodeTrafficHistoryReading point,DateTimeOffset generated) =>
point.SampledAt>=generated.AddHours(-1).AddSeconds(-5)&&point.SampledAt<=generated.AddSeconds(5)
&&point.CounterEpoch is {Length:>0 and <=128}&&point.Interface is {Length:<=80}
&&point.Quality is "ok" or "baseline" or "reset" or "gap" or "interface_changed" or "boot_changed"
&&(point.IntervalSeconds is null||double.IsFinite(point.IntervalSeconds.Value)&&point.IntervalSeconds>=(point.Quality=="ok"?double.Epsilon:0)
&&point.IntervalSeconds<=(point.Quality=="ok"?30:86400))
&&(point.Quality=="ok"?point.Upload is >=0&&point.Download is >=0&&point.IntervalSeconds is >0
:point.Upload is null&&point.Download is null);
internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale
&& row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15) && row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15)
&& row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch); && row.IntervalSeconds is > 0 and <=30 && row.UploadRate is >=0 && row.DownloadRate is >=0
&& !string.IsNullOrWhiteSpace(row.CounterEpoch);
internal static string Bytes(long? bytes, bool speed = false) internal static string Bytes(long? bytes, bool speed = false)
{ {
if (speed) return SpeedDisplay.Format(bytes); if (speed) return SpeedDisplay.Format(bytes);
@@ -79,16 +112,80 @@ internal readonly record struct NodeTrafficBarRates(long? Ingress, long? Egress)
internal sealed class NodeTrafficPanel : CardPanel internal sealed class NodeTrafficPanel : CardPanel
{ {
private readonly Func<DateTimeOffset> _clock; private readonly Func<DateTimeOffset> _clock;
private readonly Font _plotFont=Brand.Font(7.5f);
private readonly ToolTip _details = new() { InitialDelay = 350, ReshowDelay = 100, AutoPopDelay = 15_000 }; private readonly ToolTip _details = new() { InitialDelay = 350, ReshowDelay = 100, AutoPopDelay = 15_000 };
private NodeTrafficSnapshot? _snapshot; private NodeTrafficSnapshot? _snapshot;
private string _status = "等待服务器采样"; private string _status = "等待服务器采样";
private string _detailText = "等待服务器采样"; private string _detailText = "等待服务器采样";
internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); } private readonly Dictionary<string, TrafficChartTimeline> _histories = new(StringComparer.Ordinal);
internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); } private readonly Dictionary<string,SortedDictionary<(DateTimeOffset At,string Epoch),NodeTrafficHistoryReading>> _historyRecords=new(StringComparer.Ordinal);
private int _periodMinutes = 5;
private string? _historySource;
internal int ServerCount => _snapshot?.Nodes.Count ?? 0;
internal int HistoryCount(string slug) => _histories.TryGetValue(slug, out var history) ? history.PointCount : 0;
internal TrafficChartTimeline.Sample[] History(string slug) => _histories.TryGetValue(slug, out var history)
? history.Visible(TimeSpan.FromMinutes(_periodMinutes)) : [];
internal void SetPeriodMinutes(int minutes)
{
if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes));
_periodMinutes=minutes;
Invalidate();
}
internal void SetSnapshot(NodeTrafficSnapshot value)
{
var now=_clock();
if(!NodeTrafficPresentation.Valid(value,now)) { Unavailable("服务器采样契约无效"); return; }
if(_snapshot is not null && value.GeneratedAt<_snapshot.GeneratedAt)return;
if(_historySource!=value.Scope) { _histories.Clear();_historyRecords.Clear();_historySource=value.Scope; }
var allowed=value.Nodes.Select(row=>row.Slug).ToHashSet(StringComparer.Ordinal);
foreach(var slug in _histories.Keys.Where(slug=>!allowed.Contains(slug)).ToArray())
{ _histories.Remove(slug); _historyRecords.Remove(slug); }
_snapshot=value; _status="每 5 秒更新";
foreach(var row in value.Nodes)
{
if(!_histories.TryGetValue(row.Slug,out var timeline))
_histories[row.Slug]=timeline=new TrafficChartTimeline(_clock);
if(!_historyRecords.TryGetValue(row.Slug,out var records))
_historyRecords[row.Slug]=records=new SortedDictionary<(DateTimeOffset At,string Epoch),NodeTrafficHistoryReading>();
var changed=false;
foreach(var point in row.History)changed|=records.TryAdd((point.SampledAt,point.CounterEpoch),point);
if(NodeTrafficPresentation.Fresh(row,now))
changed|=records.TryAdd((row.SampledAt!.Value,row.CounterEpoch!),new NodeTrafficHistoryReading
{
SampledAt=row.SampledAt.Value,CounterEpoch=row.CounterEpoch!,IntervalSeconds=row.IntervalSeconds,
Upload=row.UploadRate,Download=row.DownloadRate,Quality="ok"
});
while(records.Count>3600||records.Count>0&&records.First().Key.At<now.AddHours(-1))
{records.Remove(records.First().Key);changed=true;}
if(changed)
{
timeline.Reset();
string? epoch=null;
foreach(var point in records.Values)
{
if(point.GapBefore||epoch is not null&&epoch!=point.CounterEpoch)timeline.MarkUnavailable(point.SampledAt);
epoch=point.CounterEpoch;
if(point.Quality=="ok"&&point.Upload is { } up&&point.Download is { } down)
timeline.Add(up,down,point.SampledAt);
else timeline.MarkUnavailable(point.SampledAt);
}
}
if(!NodeTrafficPresentation.Fresh(row,now) || row.UploadRate is null || row.DownloadRate is null)
{ timeline.MarkUnavailable(now); continue; }
timeline.AdvanceClock(now);
}
Invalidate();
}
internal void Unavailable(string status, bool clear = false)
{
if(clear) { _snapshot=null; _histories.Clear(); _historyRecords.Clear(); _historySource=null; }
else foreach(var timeline in _histories.Values) timeline.MarkUnavailable(_clock());
_status=status; Invalidate();
}
internal NodeTrafficPanel(Func<DateTimeOffset>? clock = null) internal NodeTrafficPanel(Func<DateTimeOffset>? clock = null)
{ {
_clock = clock ?? (() => DateTimeOffset.UtcNow); _clock = clock ?? (() => DateTimeOffset.UtcNow);
AccessibleName = "VPN 服务器流入流出实时速度与累计流量,上入下出细柱"; AccessibleName = "各 VPN 服务器流入流出速度趋势,青色为流入,蓝色为流出";
} }
internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight) internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight)
{ {
@@ -139,44 +236,84 @@ internal sealed class NodeTrafficPanel : CardPanel
} }
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing) _details.Dispose(); if (disposing) { _details.Dispose(); _plotFont.Dispose(); }
base.Dispose(disposing); base.Dispose(disposing);
} }
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
base.OnPaint(e); base.OnPaint(e);
var now = _clock(); var now = _clock();
var compact=Width<720*DeviceDpi/96; // Keep one owned font: allocating a Font on every repaint continually
using var font = Brand.Font(7.5f); // fills TextRenderer's native HFONT cache during live sample updates.
var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height); var font = _plotFont;
var scale=Math.Max(1f,DeviceDpi/96f);
int S(int n)=>(int)Math.Round(n*scale);
var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis; var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis;
if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 细柱上入下出 · 累计自网卡启动 / 重置", font, var title=new Rectangle(S(10),S(2),Width-S(20),S(17));
layout.Title, Brand.Muted, flags); var heading=_snapshot?.SamplePeriodSeconds==1?"服务器出入 · 1秒采样"+(_periodMinutes>5?" · 仅已获取":""):"服务器出入速度趋势";
var rows = NodeTrafficPresentation.Slugs.Select(slug => _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug)).ToArray(); TextRenderer.DrawText(e.Graphics,heading,font,title,Brand.Text,flags);
var rates = rows.Select(row => NodeTrafficPresentation.BarRates(_snapshot, row, now, _status == "每 5 秒更新")).ToArray(); var legendWidth=S(65);
var maximum = NodeTrafficPresentation.BarMaximum(rates); TextRenderer.DrawText(e.Graphics,"● 流入",font,new Rectangle(Width-S(140),S(2),legendWidth,S(17)),Brand.Cyan,flags);
TextRenderer.DrawText(e.Graphics,"● 流出",font,new Rectangle(Width-S(72),S(2),legendWidth,S(17)),Brand.RoyalBlue,flags);
var rows=_snapshot?.Nodes??[];
var envelopeValid=_snapshot is not null&&NodeTrafficPresentation.Valid(_snapshot,now);
var remaining=new Rectangle(S(8),S(21),Width-S(16),Math.Max(0,Height-S(25)));
if(rows.Count==0)
{
TextRenderer.DrawText(e.Graphics,_status=="每 5 秒更新"?"暂无服务器采样":_status,font,remaining,Brand.Muted,
flags|TextFormatFlags.HorizontalCenter);
AccessibleDescription="服务器整机网卡速率;"+_status+";暂无数据,不使用本机个人代理流量代替服务器采样。";
if(_detailText!=AccessibleDescription)
{ _detailText=AccessibleDescription; _details.SetToolTip(this,_detailText); }
return;
}
var details = new List<string>(); var details = new List<string>();
for (var i = 0; i < 2; i++) for (var i = 0; i < rows.Count; i++)
{ {
var row = rows[i]; var row = rows[i];
var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now) var fresh = envelopeValid
&& NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新"; && NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新";
var name = i == 0 ? "VPN002 东京" : "VPN003 美国"; var name = !string.IsNullOrWhiteSpace(row.Name)?row.Name:row.Slug switch
var up = fresh ? row!.UploadRate : null; { "aliyun-tokyo-002"=>"VPN002 东京", "aliyun-siliconvalley-003"=>"VPN003 美国", _=>row.Slug };
var down = fresh ? row!.DownloadRate : null; var up = fresh ? row.UploadRate : null;
var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss") var down = fresh ? row.DownloadRate : null;
: row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报"; var status = fresh ? row.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss")
: row.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "暂无数据";
var text = $"{name} {status} 入{NodeTrafficPresentation.Bytes(down, true)} 出{NodeTrafficPresentation.Bytes(up, true)}" var text = $"{name} {status} 入{NodeTrafficPresentation.Bytes(down, true)} 出{NodeTrafficPresentation.Bytes(up, true)}"
+ $" 累计入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}"; + $" 累计入{NodeTrafficPresentation.Bytes(row.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row.TotalUpload)}";
details.Add(text); details.Add(text);
if(compact)text=$"{(i==0?"VPN002东京":"VPN003美国")} {(fresh?status:row?.SampledAt is { } age?$"过期{age.LocalDateTime:HH:mm}":"待上报")} 入{NodeTrafficPresentation.Bytes(down,true)} 出{NodeTrafficPresentation.Bytes(up,true)} Σ入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}"; var lineTop=remaining.Top+remaining.Height*i/rows.Count;
var rowLayout = RowLayout(layout.Rows[i], DeviceDpi); var lineBottom=remaining.Top+remaining.Height*(i+1)/rows.Count;
TextRenderer.DrawText(e.Graphics, text, font, var bounds=new Rectangle(remaining.Left,lineTop,remaining.Width,lineBottom-lineTop);
rowLayout.Text, Brand.Text, flags); var nameWidth=Math.Min(S(85),bounds.Width/5);
PaintBars(e.Graphics, rowLayout.Ingress, rowLayout.Egress, rates[i], maximum); var rateWidth=Math.Min(S(154),bounds.Width*2/5);
TextRenderer.DrawText(e.Graphics,name,font,new Rectangle(bounds.Left,bounds.Top,nameWidth,bounds.Height),Brand.Text,flags);
var rateLeft=bounds.Right-rateWidth;
var chart=new RectangleF(bounds.Left+nameWidth+S(4),bounds.Top+S(3),Math.Max(1,rateLeft-S(8)-bounds.Left-nameWidth),Math.Max(1,bounds.Height-S(7)));
using(var grid=new Pen(Color.FromArgb(100,Brand.Muted),Math.Max(1,scale*.5f)))
e.Graphics.DrawLine(grid,chart.Left,chart.Bottom,chart.Right,chart.Bottom);
if(_histories.TryGetValue(row.Slug,out var timeline))
{
timeline.AdvanceClock(now);
var points=timeline.Visible(TimeSpan.FromMinutes(_periodMinutes));
var maximum=ChartAxisY.Create(points.Select(p=>Math.Max(p.Up,p.Down)).DefaultIfEmpty(1024).Max(),true).MaximumBytes;
foreach(var segment in points.GroupBy(point=>point.Segment))
{
var samples=segment.ToArray();
PointF[] Line(bool inbound)=>samples.Select(point=>new PointF(
chart.Left+(float)Math.Clamp(1-(timeline.End-point.Time).TotalMinutes/_periodMinutes,0,1)*chart.Width,
chart.Bottom-(float)((inbound?point.Down:point.Up)/maximum)*chart.Height)).ToArray();
ChartAxis.Curve(e.Graphics,Line(true),Brand.Cyan,DeviceDpi,dots:samples.Length==1);
ChartAxis.Curve(e.Graphics,Line(false),Brand.RoyalBlue,DeviceDpi,dots:samples.Length==1);
}
}
if(!fresh) TextRenderer.DrawText(e.Graphics,"暂无数据",font,Rectangle.Round(chart),Brand.Muted,flags|TextFormatFlags.HorizontalCenter);
var columnWidth=rateWidth/2;
TextRenderer.DrawText(e.Graphics,"入 "+SpeedDisplay.Format(down),font,new Rectangle(rateLeft,bounds.Top,columnWidth,bounds.Height),Brand.Cyan,flags);
TextRenderer.DrawText(e.Graphics,"出 "+SpeedDisplay.Format(up),font,new Rectangle(rateLeft+columnWidth,bounds.Top,rateWidth-columnWidth,bounds.Height),Brand.RoyalBlue,flags);
} }
AccessibleDescription = _status + ";细柱上方为流入,下方为流出,两台使用同一量程,上限 " AccessibleDescription = _status + ";每台服务器各自一张流入、流出趋势图;青色流入,蓝色流出。近 "+_periodMinutes+" 分钟。"
+ SpeedDisplay.Format(maximum) + "。速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。" +"服务器真实1秒网卡采样,客户端每5秒获取批次。青色流入(RX),蓝色流出(TX)。包含系统及隧道开销,不是本账号代理用量;过期累计保留采样时间。"
+ Environment.NewLine + string.Join(Environment.NewLine, details); + Environment.NewLine + string.Join(Environment.NewLine, details);
if (_detailText != AccessibleDescription) if (_detailText != AccessibleDescription)
{ {
@@ -191,6 +328,10 @@ internal sealed partial class MainForm
private readonly NodeTrafficPanel _nodeTrafficPanel = new(); private readonly NodeTrafficPanel _nodeTrafficPanel = new();
private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 }; private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 };
private bool _canViewNodeTraffic, _nodeTrafficReading; private bool _canViewNodeTraffic, _nodeTrafficReading;
private bool _nodeTrafficDiscovery;
private long _nodeTrafficDiscoveryRevision=long.MinValue;
private DateTimeOffset? _nodeTrafficSince;
private string? _nodeTrafficSlugs;
private DateTimeOffset _nextNodeTrafficAttempt; private DateTimeOffset _nextNodeTrafficAttempt;
private void BuildNodeTrafficMonitor() private void BuildNodeTrafficMonitor()
{ {
@@ -201,6 +342,8 @@ internal sealed partial class MainForm
} }
private void SetNodeTrafficPermission(bool allowed) private void SetNodeTrafficPermission(bool allowed)
{ {
_nodeTrafficDiscovery=false;
if(!allowed) { _nodeTrafficSince=null; _nodeTrafficSlugs=null; }
if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true); if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true);
_canViewNodeTraffic = allowed; _canViewNodeTraffic = allowed;
_nodeTrafficPanel.Visible = allowed; _nodeTrafficPanel.Visible = allowed;
@@ -208,21 +351,48 @@ internal sealed partial class MainForm
else _nodeTrafficTimer.Stop(); else _nodeTrafficTimer.Stop();
LayoutDashboard(); LayoutDashboard();
} }
private void ConfigureNodeTrafficMonitor(Profile profile)
{
if(_preview||_uiOnly) { SetNodeTrafficPermission(profile.CanViewNodeTraffic); return; }
// Legacy profiles have no staff/monitor flag. Probe the read-only staff
// endpoint once per login; only a successful server authorization shows
// the panel. A 403 hides it and stops polling for that session.
if(_nodeTrafficDiscoveryRevision!=_sessionRevision)
{ _nodeTrafficDiscoveryRevision=_sessionRevision; _nodeTrafficDiscovery=true; _nextNodeTrafficAttempt=DateTimeOffset.MinValue; }
if((_canViewNodeTraffic||_nodeTrafficDiscovery)&&!_exiting)
{ _nodeTrafficTimer.Start(); _=RefreshNodeTrafficAsync(); }
}
private async Task RefreshNodeTrafficAsync() private async Task RefreshNodeTrafficAsync()
{ {
_nodeTrafficPanel.Invalidate(); _nodeTrafficPanel.Invalidate();
if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting if (!(_canViewNodeTraffic||_nodeTrafficDiscovery) || _nodeTrafficReading || _preview || _uiOnly || _exiting
|| string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return; || string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return;
var token = _accessToken; var token = _accessToken;
var revision = _sessionRevision; var revision = _sessionRevision;
bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token; bool Current() => !_exiting && !IsDisposed && (_canViewNodeTraffic||_nodeTrafficDiscovery) && _sessionRevision == revision && _accessToken == token;
_nodeTrafficReading = true; _nodeTrafficReading = true;
try try
{ {
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token); var since=_nodeTrafficSince;
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token,since);
if (!Current()) return; if (!Current()) return;
if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。"); if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。");
if(!_canViewNodeTraffic)SetNodeTrafficPermission(true);
_nodeTrafficPanel.SetSnapshot(result); _nodeTrafficPanel.SetSnapshot(result);
var slugs=string.Join(",",result.Nodes.Select(row=>row.Slug).OrderBy(slug=>slug,StringComparer.Ordinal));
if(_nodeTrafficSlugs is not null&&_nodeTrafficSlugs!=slugs)_nodeTrafficSince=null;
else
{
var latest=result.Nodes.Select(row=>row.History.LastOrDefault()?.SampledAt??row.SampledAt)
.Where(at=>at is { } sampled&&sampled>=DateTimeOffset.UtcNow.AddSeconds(-15)&&sampled<=DateTimeOffset.UtcNow.AddSeconds(5))
.Select(at=>at!.Value).ToArray();
if(latest.Length>0)
{
var cursor=latest.Min().AddSeconds(-2);
if(_nodeTrafficSince is null||cursor>_nodeTrafficSince)_nodeTrafficSince=cursor;
}
}
_nodeTrafficSlugs=slugs;
} }
catch (ApiException error) when (error.StatusCode is 401 or 403) catch (ApiException error) when (error.StatusCode is 401 or 403)
{ {
@@ -233,6 +403,10 @@ internal sealed partial class MainForm
{ {
if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); } if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); }
} }
catch(ApiException error) when(error.StatusCode==400)
{
if(Current()) { _nodeTrafficSince=null; _nodeTrafficPanel.Unavailable("正在重新获取服务器采样"); }
}
catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); } catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); }
catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); } catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); }
finally { _nodeTrafficReading = false; } finally { _nodeTrafficReading = false; }
+84
View File
@@ -0,0 +1,84 @@
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class NodeTrafficOneSecondSelfTest
{
internal static Dictionary<string,bool> Check(DateTimeOffset at)
{
var checks=new Dictionary<string,bool>();
NodeTrafficHistoryReading Point(int seconds,string quality="ok",string epoch="epoch-1",bool gap=false)=>new()
{
SampledAt=at.AddSeconds(seconds),IntervalSeconds=quality=="baseline"?null:1,
Upload=quality=="ok"?1024+seconds:null,Download=quality=="ok"?2048+seconds:null,
CounterEpoch=epoch,Interface="eth0",Quality=quality,GapBefore=gap
};
NodeTrafficSnapshot Snapshot(List<NodeTrafficHistoryReading> history,bool stale=false)=>new()
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",GeneratedAt=at,SamplePeriodSeconds=1,
Nodes=[new NodeTrafficReading
{
Slug="racknerd-newyork-004",Name="VPN004",Region="纽约",SampledAt=at,IntervalSeconds=1,
UploadRate=stale?null:1024,DownloadRate=stale?null:2048,TotalUpload=300_000,TotalDownload=400_000,
CounterEpoch=history.LastOrDefault()?.CounterEpoch??"epoch-1",Stale=stale,History=history
}]
};
var points=new List<NodeTrafficHistoryReading> {Point(-5,"baseline"),Point(-4),Point(-3),Point(-2,"gap",gap:true),Point(-1),Point(0)};
var snapshot=Snapshot(points);
checks["one_second_wire_contract_preserves_host_scope"]=NodeTrafficPresentation.Valid(snapshot,at);
var serialized=JsonSerializer.Serialize(snapshot);
var parsed=JsonSerializer.Deserialize<NodeTrafficSnapshot>(serialized)!;
checks["real_wire_history_fields_deserialize"]=parsed.Nodes.Single().History.Count==6
&&parsed.Nodes[0].History[1].Upload==1020&&parsed.SamplePeriodSeconds==1;
using var panel=new NodeTrafficPanel(()=>at);
panel.SetSnapshot(parsed);panel.SetSnapshot(parsed);
var samples=panel.History("racknerd-newyork-004");
checks["five_second_poll_keeps_actual_one_second_points"]=samples.Length==4
&&samples.Select(point=>point.Time).SequenceEqual(new[]{at.AddSeconds(-4),at.AddSeconds(-3),at.AddSeconds(-1),at});
checks["duplicate_batches_do_not_repeat_samples"]=panel.HistoryCount("racknerd-newyork-004")==4;
checks["missing_and_baseline_points_do_not_become_zero"]=samples.All(point=>point.Up>0&&point.Down>0);
checks["gap_marker_breaks_the_curve"]=samples[1].Segment!=samples[2].Segment;
checks["host_rx_is_ingress_tx_is_egress"]=NodeTrafficPresentation.BarRates(parsed,parsed.Nodes[0],at)==new NodeTrafficBarRates(2048,1024);
checks["unordered_history_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(0),Point(-1)]),at);
checks["duplicate_history_identity_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(0),Point(0)]),at);
checks["history_too_old_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(-3606)]),at);
checks["history_future_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(6)]),at);
checks["more_than_one_hour_of_one_second_points_rejected"]=!NodeTrafficPresentation.Valid(Snapshot(Enumerable.Range(0,3601).Select(i=>Point(i-3600)).ToList()),at);
checks["unknown_quality_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(0,"unknown")]),at);
var reset=Snapshot([Point(-3),Point(-2,"reset","epoch-2",true),Point(-1,epoch:"epoch-2"),Point(0,epoch:"epoch-2")]);
using var resetPanel=new NodeTrafficPanel(()=>at);
resetPanel.SetSnapshot(reset);
var resetSamples=resetPanel.History("racknerd-newyork-004");
checks["counter_epoch_change_breaks_history_without_counter_spike"]=resetSamples.Length==3
&&resetSamples[0].Segment!=resetSamples[1].Segment&&resetSamples.All(point=>point.Up<2048);
var delta=Snapshot([Point(-1),Point(0)]);
panel.SetSnapshot(delta);
checks["incremental_history_keeps_older_received_points"]=panel.HistoryCount("racknerd-newyork-004")==4;
using var latePanel=new NodeTrafficPanel(()=>at);
latePanel.SetSnapshot(Snapshot([Point(-4),Point(-2),Point(0)]));
latePanel.SetSnapshot(Snapshot([Point(-3)]));
checks["late_batch_inserts_older_real_timestamp_without_loss"]=latePanel.History("racknerd-newyork-004").Select(point=>point.Time)
.SequenceEqual(new[]{at.AddSeconds(-4),at.AddSeconds(-3),at.AddSeconds(-2),at});
panel.SetSnapshot(Snapshot([],stale:true));
checks["stale_current_does_not_erase_history_or_add_zeros"]=panel.HistoryCount("racknerd-newyork-004")==4;
panel.SetPeriodMinutes(1);
checks["time_range_filters_without_recounting"]=panel.History("racknerd-newyork-004").Length==4;
panel.Unavailable("监控权限不可用",clear:true);
checks["permission_loss_clears_all_server_history"]=panel.HistoryCount("racknerd-newyork-004")==0&&panel.ServerCount==0;
foreach(var (name,json) in new[]{("backend_baseline",NodeTrafficBackendFixtures.Baseline),("sampler_roundtrip",NodeTrafficBackendFixtures.Roundtrip)})
{
var fixture=JsonSerializer.Deserialize<NodeTrafficSnapshot>(json)!;
checks[name+"_wire_decodes_and_validates"]=NodeTrafficPresentation.Valid(fixture,fixture.GeneratedAt);
using var fixturePanel=new NodeTrafficPanel(()=>fixture.GeneratedAt);
fixturePanel.SetSnapshot(fixture);
var fixtureRow=fixture.Nodes.Single();
var good=fixtureRow.History.Count(point=>point.Quality=="ok");
checks[name+"_zero_interval_baseline_not_fake_zero"]=fixtureRow.History[0].IntervalSeconds==0
&&fixturePanel.HistoryCount(fixtureRow.Slug)==good;
if(name=="sampler_roundtrip")checks["sampler_reset_marker_splits_real_curve"]=fixturePanel.History(fixtureRow.Slug)
.Select(point=>point.Segment).Distinct().Count()==2;
}
return checks;
}
}
+76
View File
@@ -0,0 +1,76 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class NodeTrafficRepaintSelfTest
{
[DllImport("user32.dll")] private static extern int GetGuiResources(IntPtr process,int flag);
internal static Dictionary<string,bool> Check()
{
var checks=new Dictionary<string,bool>();
const int iterations=160;
var clock=DateTimeOffset.UtcNow;
using var surface=new ScenicPanel {Size=new Size(1100,400),LoginArtwork=true};
using var panel=new NodeTrafficPanel(()=>clock) {Location=new Point(10,10)};
surface.Controls.Add(panel);panel.CreateControl();
var dpi=panel.DeviceDpi;
panel.Size=new Size(464*dpi/96,100*dpi/96);
using var actual=new Bitmap(panel.Width,panel.Height);
using var expected=new Bitmap(panel.Width,panel.Height);
NodeTrafficSnapshot Snapshot(int index)=>new()
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",SamplePeriodSeconds=1,GeneratedAt=clock,
Nodes=Enumerable.Range(2,3).Select(node=>new NodeTrafficReading
{
Slug="fixture-"+node,Name="VPN00"+node,SampledAt=clock,IntervalSeconds=1,CounterEpoch="paint-epoch",
UploadRate=index%37==0?null:(index%2==0?1_000_000+index:1024+index),
DownloadRate=index%37==0?null:2048+index,TotalUpload=1_000_000_000L+index,TotalDownload=3_000_000_000L+index,
Stale=index%37==0,
History=[new NodeTrafficHistoryReading
{
SampledAt=clock,IntervalSeconds=1,CounterEpoch="paint-epoch",Interface="eth0",
Upload=index%37==0?null:(index%2==0?1_000_000+index:1024+index),Download=index%37==0?null:2048+index,
Quality=index%37==0?"gap":"ok",GapBefore=index%37==0
}]
}).ToList()
};
panel.SetSnapshot(Snapshot(1));panel.DrawToBitmap(actual,panel.ClientRectangle);
GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();
using var process=Process.GetCurrentProcess();
var beforeGdi=GetGuiResources(process.Handle,0);var beforeUser=GetGuiResources(process.Handle,1);
process.Refresh();var beforeBytes=process.PrivateMemorySize64;
var timer=Stopwatch.StartNew();
for(var i=1;i<=iterations;i++)
{
clock=clock.AddSeconds(1);
panel.SetSnapshot(Snapshot(i));
using(var graphics=Graphics.FromImage(actual))graphics.Clear(Color.Magenta);
panel.DrawToBitmap(actual,panel.ClientRectangle);
}
using(var graphics=Graphics.FromImage(expected))graphics.Clear(Color.Cyan);
panel.DrawToBitmap(expected,panel.ClientRectangle);
var identical=true;
for(var y=0;y<actual.Height&&identical;y++)
for(var x=0;x<actual.Width;x++)if(actual.GetPixel(x,y)!=expected.GetPixel(x,y)) {identical=false;break;}
GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();process.Refresh();
var afterGdi=GetGuiResources(process.Handle,0);var afterUser=GetGuiResources(process.Handle,1);
var afterBytes=process.PrivateMemorySize64;
checks["owned_repaint_sample_replacement_160_iterations_completed"]=panel.ServerCount==3;
checks["dirty_surface_repaint_matches_clean_surface_exactly"]=identical;
checks["repaint_gdi_handles_bounded"]=afterGdi<=beforeGdi+16;
checks["repaint_user_handles_bounded"]=afterUser<=beforeUser+16;
checks["repaint_private_memory_growth_bounded_96MiB"]=afterBytes<=beforeBytes+96*1024*1024;
checks["repaint_cached_samples_bounded"]=Enumerable.Range(2,3).All(node=>panel.HistoryCount("fixture-"+node)<=iterations+1);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"node-traffic-repaint-stress.json"),JsonSerializer.Serialize(new
{
passed=checks.Values.All(value=>value),checks,iterations,dpi,seconds=timer.Elapsed.TotalSeconds,
beforeGdi,afterGdi,beforeUser,afterUser,beforeBytes,afterBytes,
scope="owned buffered WinForms surface; synthetic 1-second samples; no production acceptance",
network_modified=false,installed_client_modified=false
},new JsonSerializerOptions {WriteIndented=true}));
return checks;
}
}
+28 -9
View File
@@ -4,6 +4,7 @@ namespace UCVL.VPNPlus;
internal static class NodeTrafficSelfTest internal static class NodeTrafficSelfTest
{ {
private const string SecondFixtureSlug="aliyun-siliconvalley-003";
internal static int Run() internal static int Run()
{ {
var checks = new Dictionary<string, bool>(); var checks = new Dictionary<string, bool>();
@@ -18,11 +19,13 @@ internal static class NodeTrafficSelfTest
NodeTrafficSnapshot Snapshot(List<NodeTrafficReading>? rows = null, string scope = "server_host_interface", NodeTrafficSnapshot Snapshot(List<NodeTrafficReading>? rows = null, string scope = "server_host_interface",
string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new() string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new()
{ Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset", { Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset",
GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(NodeTrafficPresentation.Slugs[1])] }; GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(SecondFixtureSlug)] };
bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now); bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now);
checks["exact_two_authorized_server_contract"] = Valid(Snapshot()); checks["exact_two_authorized_server_contract"] = Valid(Snapshot());
checks["four_authorized_nodes_supported_without_static_whitelist"] = Valid(Snapshot([Row(), Row("aliyun-siliconvalley-003"), Row("jinan-phone"), Row("racknerd-newyork-004")]));
checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([])); checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([]));
checks["other_nodes_rejected"] = !Valid(Snapshot([Row("phone")])); checks["additional_authorized_nodes_accepted"] = Valid(Snapshot([Row("phone")]));
checks["unsafe_node_slug_rejected"] = !Valid(Snapshot([Row("../phone")]));
checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()])); checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()]));
checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()])); checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()]));
checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate")); checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate"));
@@ -52,7 +55,7 @@ internal static class NodeTrafficSelfTest
checks["expired_envelope_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(generated: now.AddSeconds(-16)), Row(), now) == new NodeTrafficBarRates(null, null); checks["expired_envelope_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(generated: now.AddSeconds(-16)), Row(), now) == new NodeTrafficBarRates(null, null);
checks["unavailable_sampling_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(), now, false) == new NodeTrafficBarRates(null, null); checks["unavailable_sampling_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(), now, false) == new NodeTrafficBarRates(null, null);
checks["measured_zero_bars_remain_available"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: 0, down: 0), now) == new NodeTrafficBarRates(0, 0); checks["measured_zero_bars_remain_available"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: 0, down: 0), now) == new NodeTrafficBarRates(0, 0);
checks["individual_missing_rate_is_not_fabricated"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: null, down: 20), now) == new NodeTrafficBarRates(20, null); checks["individual_missing_rate_is_not_fabricated"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: null, down: 20), now) == new NodeTrafficBarRates(null, null);
var commonMaximum = NodeTrafficPresentation.BarMaximum([new(100 * 1024, 200 * 1024), new(20 * 1024, null)]); var commonMaximum = NodeTrafficPresentation.BarMaximum([new(100 * 1024, 200 * 1024), new(20 * 1024, null)]);
checks["two_servers_share_one_common_scale"] = commonMaximum > 200 * 1024 checks["two_servers_share_one_common_scale"] = commonMaximum > 200 * 1024
&& NodeTrafficPresentation.BarWidth(100 * 1024, commonMaximum, 100) < NodeTrafficPresentation.BarWidth(200 * 1024, commonMaximum, 100); && NodeTrafficPresentation.BarWidth(100 * 1024, commonMaximum, 100) < NodeTrafficPresentation.BarWidth(200 * 1024, commonMaximum, 100);
@@ -104,12 +107,12 @@ internal static class NodeTrafficSelfTest
using (var panel = new NodeTrafficPanel(() => now) { BackColor = Color.White }) using (var panel = new NodeTrafficPanel(() => now) { BackColor = Color.White })
{ {
panel.CreateControl(); panel.CreateControl();
panel.Size = new Size(464 * panel.DeviceDpi / 96, 38 * panel.DeviceDpi / 96); panel.Size = new Size(464 * panel.DeviceDpi / 96, 100 * panel.DeviceDpi / 96);
using var preview = new Bitmap(panel.Width, panel.Height); using var preview = new Bitmap(panel.Width, panel.Height);
panel.SetSnapshot(Snapshot([Row(up: 100 * 1024, down: 200 * 1024, totalUp: 2_000_000_000, totalDown: 3_000_000_000), panel.SetSnapshot(Snapshot([Row(up: 100 * 1024, down: 200 * 1024, totalUp: 2_000_000_000, totalDown: 3_000_000_000),
Row(NodeTrafficPresentation.Slugs[1], up: 20 * 1024, down: 40 * 1024, totalUp: 5_000_000_000, totalDown: 6_000_000_000)])); Row(SecondFixtureSlug, up: 20 * 1024, down: 40 * 1024, totalUp: 5_000_000_000, totalDown: 6_000_000_000)]));
panel.DrawToBitmap(preview, panel.ClientRectangle); panel.DrawToBitmap(preview, panel.ClientRectangle);
checks["actual_panel_describes_ingress_egress_order"] = panel.AccessibleDescription?.Contains("上方为流入,下方为流出") == true; checks["actual_panel_describes_distinct_server_curves"] = panel.AccessibleDescription?.Contains("每台服务器各自一张流入、流出趋势图") == true;
checks["actual_panel_retains_rates_totals_and_sample_time"] = panel.AccessibleDescription?.Contains("200.0 KB/s") == true checks["actual_panel_retains_rates_totals_and_sample_time"] = panel.AccessibleDescription?.Contains("200.0 KB/s") == true
&& panel.AccessibleDescription.Contains("累计入") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss")); && panel.AccessibleDescription.Contains("累计入") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss"));
preview.Save(Path.Combine(AppContext.BaseDirectory, "node-traffic-bars-preview.png")); preview.Save(Path.Combine(AppContext.BaseDirectory, "node-traffic-bars-preview.png"));
@@ -117,19 +120,34 @@ internal static class NodeTrafficSelfTest
panel.DrawToBitmap(preview, panel.ClientRectangle); panel.DrawToBitmap(preview, panel.ClientRectangle);
checks["actual_unavailable_panel_preserves_totals_and_time_without_live_rate"] = panel.AccessibleDescription?.Contains("入— 出—") == true checks["actual_unavailable_panel_preserves_totals_and_time_without_live_rate"] = panel.AccessibleDescription?.Contains("入— 出—") == true
&& panel.AccessibleDescription.Contains("累计入2.79 GB") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss")); && panel.AccessibleDescription.Contains("累计入2.79 GB") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss"));
checks["unavailable_never_fabricates_history_zero"] = panel.HistoryCount("aliyun-tokyo-002")==1;
panel.SetSnapshot(Snapshot());
checks["duplicate_backend_timestamp_not_added_twice"] = panel.HistoryCount("aliyun-tokyo-002")==1;
var next=now.AddSeconds(5);
panel.SetSnapshot(Snapshot([Row(sampled:next,epoch:"new-counter"), Row(SecondFixtureSlug,sampled:next)]));
var history=panel.History("aliyun-tokyo-002");
checks["counter_epoch_change_breaks_curve_segment"] = history.Length==2 && history[0].Segment!=history[1].Segment;
panel.SetPeriodMinutes(1);
checks["server_time_range_does_not_recreate_samples"] = panel.HistoryCount("aliyun-tokyo-002")==2;
panel.SetSnapshot(Snapshot([Row(), Row("aliyun-siliconvalley-003"), Row("jinan-phone"), Row("racknerd-newyork-004")]));
checks["four_distinct_servers_receive_separate_histories"] = panel.ServerCount==4 && panel.HistoryCount("racknerd-newyork-004")==1;
panel.SetSnapshot(Snapshot([]));
checks["revoked_server_rows_clear_old_history"] = panel.ServerCount==0 && panel.HistoryCount("racknerd-newyork-004")==0;
} }
foreach (var tailnet in new[] { false, true }) foreach (var tailnet in new[] { false, true })
{ {
var view = new Size(960, 612); var view = new Size(960, 612);
var layout = DashboardLayout.Calculate(view, 96, tailnet, true); var layout = DashboardLayout.Calculate(view, 96, tailnet, true);
checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.DailyCard.Bottom checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.SpeedTrendCard.Bottom
&& layout.ServerTrafficCard.Top > layout.TrafficCard.Bottom && layout.DailyCard.Top > layout.ServerTrafficCard.Bottom
&& (!tailnet || layout.ServerTrafficCard.Top > layout.TailnetTrafficCard.Bottom); && layout.TrafficCard.IsEmpty && layout.TailnetTrafficCard.IsEmpty;
checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height
&& layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top; && layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top;
} }
var oldProfile = JsonSerializer.Deserialize<Profile>("{\"email\":\"fixture@example.invalid\"}")!; var oldProfile = JsonSerializer.Deserialize<Profile>("{\"email\":\"fixture@example.invalid\"}")!;
checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic; checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic;
foreach(var check in NodeTrafficOneSecondSelfTest.Check(now))checks[check.Key]=check.Value;
foreach(var check in NodeTrafficRepaintSelfTest.Check())checks[check.Key]=check.Value;
} }
catch (Exception exception) { error = exception.GetType().Name; } catch (Exception exception) { error = exception.GetType().Name; }
var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value); var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value);
@@ -139,4 +157,5 @@ internal static class NodeTrafficSelfTest
new JsonSerializerOptions { WriteIndented = true })); new JsonSerializerOptions { WriteIndented = true }));
return passed ? 0 : 84; return passed ? 0 : 84;
} }
} }
+3 -5
View File
@@ -1,6 +1,6 @@
# 纵横家 Windows 0.3.3 开源源码 # 纵横家 Windows 0.3.5 开源源码
基于已冻结的 0.3.3 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。 基于已冻结的 0.3.5 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
## 构建 ## 构建
@@ -17,6 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。 公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
0.3.3:重排紧凑主界面;左侧选择调度及代理模式,右侧显示实际工作状态;全宽代理速度与按实际传输显示的Tailscale速度行,紧凑累计数值与代理速度趋势。删除公网入口速度,速率最低为KB/s并保留一位小数;修复下拉重排选择、无障碍值及密集图表上限标注。此清洁源码保留原授权、连接与统计口径;离线和合成界面测试不代表生产网络或安装验收。 0.3.5:为本机代理及各服务器显示独立流量趋势,清晰区分上传、下载及累计数值,保持固定紧凑主界面。保留0.3.4连接容错与授权有效期处理;本次只更新界面,不改变调度、节点优先级或网络路由,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
0.3.3追加:授权内网候选遵循后台新会话分配并确认节点预留;连接后每十分钟复测内网,不可达时先尝试同节点域名。服务器监控上入下出细柱沿用真实样本及过期失效。现有连接保持粘性,不拆分单个TCP流,不宣称启用跨节点带宽叠加。
+29
View File
@@ -0,0 +1,29 @@
namespace UCVL.VPNPlus;
// A bounded round tolerates isolated ICMP loss. This is address reachability,
// never a substitute for an authenticated proxy grant or a business-site test.
internal static class TailnetPingConfirmation
{
internal const int Attempts = 3;
internal static async Task<bool> ProbeAsync(Func<CancellationToken, Task<bool>> ping,
CancellationToken token, TimeSpan? budget = null)
{
token.ThrowIfCancellationRequested();
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(budget ?? TimeSpan.FromSeconds(4));
for (var attempt = 0; attempt < Attempts; attempt++)
{
try
{
var reachable = await ping(deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (reachable) return true;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested && deadline.IsCancellationRequested) { return false; }
catch (OperationCanceledException) { throw; }
catch (Exception) { /* One failed ICMP attempt is inconclusive. */ }
token.ThrowIfCancellationRequested();
}
return false;
}
}
@@ -0,0 +1,36 @@
namespace UCVL.VPNPlus;
internal static class TailnetPingConfirmationSelfTest
{
internal static async Task<Dictionary<string, bool>> CheckAsync()
{
var checks = new Dictionary<string, bool>();
var calls = 0;
var reachable = await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 2), CancellationToken.None);
checks["single_lost_ping_followed_by_success_is_reachable"] = reachable && calls == 2;
calls = 0;
reachable = await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 3), CancellationToken.None);
checks["two_lost_pings_followed_by_success_do_not_switch"] = reachable && calls == 3;
calls = 0;
reachable = await TailnetPingConfirmation.ProbeAsync(_ => { calls++; return Task.FromResult(false); }, CancellationToken.None);
checks["three_failed_icmp_attempts_are_one_failed_round"] = !reachable && calls == 3;
calls = 0;
reachable = await TailnetPingConfirmation.ProbeAsync(_ => ++calls == 1
? Task.FromException<bool>(new IOException("fixture ping failure")) : Task.FromResult(true), CancellationToken.None);
checks["one_ping_exception_does_not_force_fallback"] = reachable && calls == 2;
var pending = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
reachable = await TailnetPingConfirmation.ProbeAsync(_ => pending.Task, CancellationToken.None, TimeSpan.FromMilliseconds(30));
checks["uncooperative_ping_callback_has_bounded_deadline"] = !reachable;
using var caller = new CancellationTokenSource(); caller.Cancel();
var cancelled = false;
try { await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(true), caller.Token); }
catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; }
checks["caller_cancellation_is_not_a_failed_ping"] = cancelled;
using var race = new CancellationTokenSource();
cancelled = false;
try { await TailnetPingConfirmation.ProbeAsync(_ => { race.Cancel(); return Task.FromResult(true); }, race.Token); }
catch (OperationCanceledException error) { cancelled = error.CancellationToken == race.Token; }
checks["cancelled_successful_ping_cannot_publish_old_result"] = cancelled;
return checks;
}
}
+12 -2
View File
@@ -11,7 +11,9 @@ internal sealed class TailnetReadinessPolicy
internal enum Result { Ignore, NotReady, Confirming, BecameReady, Ready, Fallback } internal enum Result { Ignore, NotReady, Confirming, BecameReady, Ready, Fallback }
internal const long IntervalMilliseconds = 10 * 60_000; internal const long IntervalMilliseconds = 10 * 60_000;
internal const long ConfirmationMilliseconds = 5_000;
private bool _bound, _inFlight, _usesTailnet; private bool _bound, _inFlight, _usesTailnet;
private int _failedRounds;
private long _generation, _sequence, _epoch, _nextDue; private long _generation, _sequence, _epoch, _nextDue;
private int? _core; private int? _core;
internal bool IsReady { get; private set; } internal bool IsReady { get; private set; }
@@ -23,6 +25,7 @@ internal sealed class TailnetReadinessPolicy
_bound = _inFlight = IsReady = false; _bound = _inFlight = IsReady = false;
_core = null; _core = null;
_nextDue = 0; _nextDue = 0;
_failedRounds = 0;
} }
private static bool Eligible(Context context) => context.Wanted && context.Running private static bool Eligible(Context context) => context.Wanted && context.Running
@@ -64,12 +67,19 @@ internal sealed class TailnetReadinessPolicy
_nextDue = now + IntervalMilliseconds; _nextDue = now + IntervalMilliseconds;
// Do not publish a result obtained while connection/authorization state // Do not publish a result obtained while connection/authorization state
// is being changed. A new ticket can retry after the normal cadence. // is being changed. A new ticket can retry after the normal cadence.
if (context.Busy) return Result.Ignore; if (context.Busy) { _failedRounds = 0; return Result.Ignore; }
if (!reachable) if (!reachable)
{ {
IsReady = false; IsReady = false;
return context.UsesTailnet ? Result.Fallback : Result.NotReady; if (!context.UsesTailnet) { _failedRounds = 0; return Result.NotReady; }
if (++_failedRounds < 2)
{
_nextDue = now + ConfirmationMilliseconds;
return Result.Confirming;
}
return Result.Fallback;
} }
_failedRounds = 0;
if (context.UsesTailnet) return Result.Ready; if (context.UsesTailnet) return Result.Ready;
if (IsReady) return Result.Ready; if (IsReady) return Result.Ready;
IsReady = true; IsReady = true;
+11 -1
View File
@@ -25,7 +25,16 @@ internal static class TailnetReadinessSelfTest
policy.Reset(); current = current with { UsesTailnet = true }; policy.Reset(); current = current with { UsesTailnet = true };
checks["active_tailnet_waits_ten_minutes"] = !Begin(4_000_000, out _) && policy.NextDue == 4_600_000; checks["active_tailnet_waits_ten_minutes"] = !Begin(4_000_000, out _) && policy.NextDue == 4_600_000;
checks["active_tailnet_success_retains_transport"] = Begin(4_600_000, out first) && Complete(first, 4_600_100, true) == TailnetReadinessPolicy.Result.Ready && !policy.IsReady; checks["active_tailnet_success_retains_transport"] = Begin(4_600_000, out first) && Complete(first, 4_600_100, true) == TailnetReadinessPolicy.Result.Ready && !policy.IsReady;
checks["active_tailnet_failure_requests_domain_fallback"] = Begin(5_200_100, out first) && Complete(first, 5_200_200, false).ToString() == "Fallback"; checks["single_failed_round_does_not_switch_active_tailnet"] = Begin(5_200_100, out first)
&& Complete(first, 5_200_200, false) == TailnetReadinessPolicy.Result.Confirming;
checks["confirmation_wait_is_bounded_five_seconds"] = !Begin(5_205_199, out _)
&& Begin(5_205_200, out second);
checks["second_failed_round_confirms_domain_fallback"] = Complete(second, 5_205_300, false) == TailnetReadinessPolicy.Result.Fallback;
policy.Reset();
checks["new_active_path_schedules_after_reset"] = !Begin(5_300_000, out _) && Begin(5_900_000, out first);
checks["loss_then_recovery_clears_confirmation"] = Complete(first, 5_900_100, false) == TailnetReadinessPolicy.Result.Confirming
&& Begin(5_905_100, out second) && Complete(second, 5_905_200, true) == TailnetReadinessPolicy.Result.Ready
&& policy.NextDue == 6_505_200;
policy.Reset(); policy.Reset();
checks["reset_clears_schedule"] = !policy.IsReady && policy.NextDue == 0; checks["reset_clears_schedule"] = !policy.IsReady && policy.NextDue == 0;
checks["new_session_has_no_duplicate_immediate_probe"] = !Begin(6_000_000, out _) && Begin(6_600_000, out first); checks["new_session_has_no_duplicate_immediate_probe"] = !Begin(6_000_000, out _) && Begin(6_600_000, out first);
@@ -44,6 +53,7 @@ internal static class TailnetReadinessSelfTest
checks["busy_completion_is_not_a_failure"] = Begin(10_600_000, out first) && policy.Observe(first, current with { Busy = true }, 10_600_100, false) == TailnetReadinessPolicy.Result.Ignore; checks["busy_completion_is_not_a_failure"] = Begin(10_600_000, out first) && policy.Observe(first, current with { Busy = true }, 10_600_100, false) == TailnetReadinessPolicy.Result.Ignore;
foreach (var state in new[] { current with { Wanted = false }, current with { CoreId = null }, current with { Running = false }, current with { HasAuthorizedCandidate = false } }) foreach (var state in new[] { current with { Wanted = false }, current with { CoreId = null }, current with { Running = false }, current with { HasAuthorizedCandidate = false } })
checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 12_000_000, out _); checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 12_000_000, out _);
foreach (var check in TailnetPingConfirmationSelfTest.CheckAsync().GetAwaiter().GetResult()) checks.Add(check.Key, check.Value);
var passed = checks.Values.All(v => v); var passed = checks.Values.All(v => v);
foreach (var check in checks.Where(c => !c.Value)) Console.WriteLine("FAIL " + check.Key); foreach (var check in checks.Where(c => !c.Value)) Console.WriteLine("FAIL " + check.Key);
Console.WriteLine($"{(passed ? "PASS" : "FAIL")} ten-minute Tailnet recheck; {checks.Count} checks"); Console.WriteLine($"{(passed ? "PASS" : "FAIL")} ten-minute Tailnet recheck; {checks.Count} checks");
+5 -1
View File
@@ -193,7 +193,11 @@ internal static class ChartAxis
{ {
var y = plot.Bottom - plot.Height * i / 2; var y = plot.Bottom - plot.Height * i / 2;
g.DrawLine(grid, plot.Left, y, plot.Right, y); g.DrawLine(grid, plot.Left, y, plot.Right, y);
if (denseSpeed ? i == 0 : !compactAxis || i == 0) TextRenderer.DrawText(g, axis.Tick(maximum * i / 2), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding); // A fitted chart can be only a few text lines tall. Keep its
// explicit upper-limit metadata legible instead of drawing a
// redundant zero label across that second line in the gutter.
var drawTick = denseSpeed ? i == 0 && y - fontHeight / 2 >= fontHeight * 2 + 2 * scale : !compactAxis || i == 0;
if (drawTick) TextRenderer.DrawText(g, axis.Tick(maximum * i / 2), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding);
} }
for (var i = 0; i <= 6; i++) for (var i = 0; i <= 6; i++)
{ {
+4 -4
View File
@@ -10,10 +10,10 @@
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon> <ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest> <ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<Version>0.3.3</Version> <Version>0.3.5</Version>
<AssemblyVersion>0.3.3.0</AssemblyVersion> <AssemblyVersion>0.3.5.0</AssemblyVersion>
<FileVersion>0.3.3.0</FileVersion> <FileVersion>0.3.5.0</FileVersion>
<InformationalVersion>0.3.3</InformationalVersion> <InformationalVersion>0.3.5</InformationalVersion>
<Product>纵横家</Product> <Product>纵横家</Product>
<Company>优创未来(UCVL)</Company> <Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description> <Description>纵横家 Windows 智能网络客户端</Description>
+5 -4
View File
@@ -65,12 +65,13 @@ internal sealed class VpnApiClient : IDisposable
return await GitReleaseUpdater.GetLatestAsync(cancellationToken); return await GitReleaseUpdater.GetLatestAsync(cancellationToken);
} }
internal async Task<NodeTrafficSnapshot> GetNodeTrafficAsync(string token, CancellationToken cancellationToken) internal async Task<NodeTrafficSnapshot> GetNodeTrafficAsync(string token, CancellationToken cancellationToken,DateTimeOffset? since=null)
{ {
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(TimeSpan.FromSeconds(3)); deadline.CancelAfter(TimeSpan.FromSeconds(since.HasValue?3:8));
using var request = AuthorizedRequest(HttpMethod.Get, "api/v1/client/node-traffic/", token); var path="api/v1/client/node-traffic/"+(since is { } cursor?"?since="+Uri.EscapeDataString(cursor.ToString("O")):"");
return await SendAsync<NodeTrafficSnapshot>(request, deadline.Token, maximumBodyBytes: 32 * 1024); using var request = AuthorizedRequest(HttpMethod.Get, path, token);
return await SendAsync<NodeTrafficSnapshot>(request, deadline.Token, maximumBodyBytes: 1024 * 1024);
} }
internal async Task<ConfigResponse> GetConfigAsync(string token, string nodeSlug, string routeMode, CancellationToken cancellationToken, IEnumerable<string>? excluded = null) internal async Task<ConfigResponse> GetConfigAsync(string token, string nodeSlug, string routeMode, CancellationToken cancellationToken, IEnumerable<string>? excluded = null)
+9 -4
View File
@@ -140,14 +140,14 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
internal Task<bool> CheckProxyHealthAsync(CancellationToken token) internal Task<bool> CheckProxyHealthAsync(CancellationToken token)
=> !IsRunning || _learningProbePort == 0 ? Task.FromResult(false) => !IsRunning || _learningProbePort == 0 ? Task.FromResult(false)
: NodeHealthProbe.CheckAsync(token, _learningProbePort); : NodeHealthProbe.CheckTransportAsync(token, _learningProbePort);
internal sealed record HealthResult(bool Healthy, bool ProxyHealthy, bool RepairAttempted); internal sealed record HealthResult(bool Healthy, bool ProxyHealthy, bool RepairAttempted, bool BusinessUnavailable = false);
internal async Task<HealthResult> CheckHealthWithRepairAsync(CancellationToken token) internal async Task<HealthResult> CheckHealthWithRepairAsync(CancellationToken token)
{ {
var expectedCore = CoreId; var expectedCore = CoreId;
if (await CheckHealthAsync(token)) return new(true, false, false); if (await CheckHealthAsync(token)) return new(true, false, false);
if (_routeMode != "smart" || expectedCore is null || CoreId != expectedCore || _learningProbePort == 0) if (expectedCore is null || CoreId != expectedCore || _learningProbePort == 0)
return new(false, false, false); return new(false, false, false);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token, _learningEpoch.Token); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token, _learningEpoch.Token);
deadline.CancelAfter(TimeSpan.FromSeconds(45)); deadline.CancelAfter(TimeSpan.FromSeconds(45));
@@ -155,9 +155,14 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
try try
{ {
// A failing ordinary route is not proof that the proxy node is down. // A failing ordinary route is not proof that the proxy node is down.
if (!await NodeHealthProbe.CheckAsync(deadline.Token, _learningProbePort)) return new(false, false, false); var proxy = await NodeHealthProbe.CheckReportAsync(deadline.Token, _learningProbePort);
if (!proxy.TransportReachable) return new(false, false, false);
proxyHealthy = true; proxyHealthy = true;
if (CoreId != expectedCore) return new(false, true, false); if (CoreId != expectedCore) return new(false, true, false);
// The forced proxy authenticated the same transport and received
// TLS/HTTP from at least one site. A site's outage is a business
// diagnostic, not evidence that this node needs to be replaced.
if (_routeMode != "smart" || !proxy.BusinessHealthy) return new(false, true, false, true);
AppPaths.WriteLog("普通智能路径异常,代理比较路径正常;先重新验证并热修复规则,不重启内核。"); AppPaths.WriteLog("普通智能路径异常,代理比较路径正常;先重新验证并热修复规则,不重启内核。");
await Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target => await Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
ScheduleLearningAsync(new LearningObservation { Target = target, Port = 443, AccessKind = "http", ScheduleLearningAsync(new LearningObservation { Target = target, Port = 443, AccessKind = "http",
+10
View File
@@ -0,0 +1,10 @@
# 纵横家 Windows 0.3.4 · 连接容错与固定网格候选版
本版修复网站探测、内网丢包和后台暂时不可用引发的连接恢复问题,并统一紧凑主界面网格。实际验证结果以同一候选包的 evidence 报告为准,不能以本文代替验收。
- 将网站业务可用性与代理传输可达性区分。第三方网站异常时显示琥珀色“网站探测异常,连接保留”,不会将其假报为已恢复或据此拆掉运行中的 Tailscale 连接。核心进程退出仍触发正常恢复。
- 首次连接沿用内网优先检测;连接后每十分钟复测。定期检查使用有界多次 ICMP,首轮失败先确认,约五秒后的确认仍失败才要求同节点域名回退。过期探测不能影响新会话或新核心。
- 后台超时或服务端暂时故障时,保留尚在明确授权期限内的既有核心;新建连接仍需要后台新授权。401/403、已知账号或订阅到期仍终止;私有节点续租和到期回退沿用专属逻辑。不新增离线登录。
- 默认 480 × 360 logical 的主界面使用统一外边距、行高、标题列及数值/单位槽。配置两行、当前工作状态、代理/Tailscale/累计数值和趋势表头对齐;Tailscale 及服务器区域显隐不加高窗口,不启用滚动。累计仍只显示数值,代理速度保留趋势,最小速度单位为 KB/s。
这是待部署候选版。中央后台 192.0.2.1 尚待云控制台诊断,本文不表示后台已恢复、真实连接提速、生产覆盖升级或实际网络验收通过。准备过程不修改当前安装、Tailscale 配置、手机或电视。安装包未做 Authenticode 签名,安装升级需要管理员权限。
+11
View File
@@ -0,0 +1,11 @@
# 纵横家 Windows 0.3.5
流量区改为上下排列的趋势图:顶部显示本机代理上传、下载和实际使用的连接入口;下方为每台获授权服务器各自的流入、流出曲线。移除重复的代理与 Tailscale 速度行,累计用量仅用紧凑数字表示。
服务器数据采用独立的物理公网接口采样,每秒读取一次原始字节计数,按实际间隔计算速度;每五秒传输一批逐秒样本并刷新界面。首次采样、计数器复位、接口切换、过期或缺失数据不伪造零速率。服务器曲线覆盖该服务器网口流量,与本机代理流量的统计范围不同。
保留紧凑窗口、半透明山水背景和固定对齐,窗口不因服务器数量或 Tailscale 连接而增高,不新增页面滚动。速率最低显示 KB/s。服务器监控继续受后台管理权限控制,普通账户不会因此获得额外监控权限。
保留 0.3.4 的连接容错。本次图表调整不修改节点调度、Tailscale/域名选择、代理规则或账户限速,不宣称改变网络带宽。
安装包为 Windows x64 自包含程序,沿用现有管理员安装与非强制自动更新方式,尚未配置 Authenticode 签名。发布验证以本版冻结产物的构建、自检、隔离升级、数据接口与采样证据为准;不将隔离验证描述为所有终端已安装或本机真实联网升级验收。