From 26e9caeef146e6444aa6af2e6433105c805bc66b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=9C=E5=AE=87?= Date: Tue, 1 Dec 2026 19:40:24 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20MongoDB=20=E4=B8=8E=20?= =?UTF-8?q?Docker=20=E9=9D=A2=E6=9D=BF=E6=8F=92=E4=BB=B6=E7=9A=84=E5=AE=A1?= =?UTF-8?q?=E6=9F=A5=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Docker 面板(协议层): - X-Registry-Auth 保留 base64 填充;仓库主机名按 Docker 规则规范化 - 写回文件保留原属主与权限,经符号链接写到目标;长文件名走 PAX;可打开符号链接 - 列目录兼容 BusyBox ls 与 GNU 悬空链接;长连接流与普通请求分池(跟随日志上限 6) - 慢操作不再套 30 秒超时;GetStringAsync 检查状态码;帧解码按流解码、限长、处理 \r - LineDiff 改为剥前后缀 + Myers,大文件不再 OOM;PluginMain 关闭路径不重复释放 Docker 面板(界面层): - 日志按真实 Tty 解帧;日志重启串行化;事件只刷新关心它的当前页,消除系统页刷新环 - 连接、拉取聚合器、Compose 合并日志、采样器的重入与跨线程问题 - SSH 会话断开时停流并显示失败页;任务取消后正确结束;非 UTF-8 文件只读打开 - 紧凑行高接通;与宿主几何的偏离写进 README MongoDB: - SBE 执行计划(explainVersion 2)按 queryPlan 建阶段流 - 连接字符串形态 + SSH 跳板可用;mongodb+srv 串拒绝走跳板;URI 里的选项不被表单默认值覆盖 - 跳板会话竞态泄漏与失效重连;经隧道的 TLS 按真实主机名核对 - runCommand 只读判断改白名单;查询历史脱敏并截断;Shell 格式整数 double 与 Timestamp/MinKey 往返 - 编辑器打开时保留暂存修改;URI 口令移入密钥库;限时解锁挂到连接上;冲突对话框排队 - 遇错停止导入写入错误行之前的数据;GridFS 缩略图缓存与下载不覆盖;改自己口令同步密钥库 - 导出默认无损;索引建议不建议删 TTL、唯一与分片键索引;监控空桶画成空位 - 网格水平虚拟化、结果网格排版缓存等性能改进 测试:DockerPanel 214/214,Mongo 559/559(MongoDB 9.0 单节点副本集 + seed-shop.js)。 --- .../Docker/DiskMath.cs | 34 +- .../Docker/DockerClient.Containers.cs | 9 +- .../Docker/DockerClient.Exec.cs | 159 +++- .../Docker/DockerClient.Files.cs | 243 +++++- .../Docker/DockerClient.Images.cs | 26 +- .../Docker/DockerClient.System.cs | 8 +- .../Docker/DockerClient.VolumesNetworks.cs | 4 +- .../Docker/DockerClient.cs | 139 +++- .../Docker/DockerFrames.cs | 138 +++- .../Docker/DockerModels.cs | 28 +- .../Docker/DockerRawHttp.cs | 125 ++- .../Docker/LineDiff.cs | 240 ++++-- .../Docker/RegistryAuth.cs | 88 +- .../Docker/TarUtil.cs | 377 ++++++--- .../PluginMain.cs | 55 +- .../VelaShell.Plugin.DockerPanel/README.md | 44 +- .../Syntax/DotEnv.xshd | 7 +- .../Syntax/Yaml.xshd | 4 +- .../Ui/ConfirmGate.cs | 6 + .../Ui/Converters.cs | 9 + .../Ui/DockerPanelViewModel.Dialogs.cs | 7 +- .../Ui/DockerPanelViewModel.Events.cs | 147 +++- .../Ui/DockerPanelViewModel.cs | 263 +++++- .../Ui/LineBuffer.cs | 19 +- .../VelaShell.Plugin.DockerPanel/Ui/Mvvm.cs | 109 ++- .../Ui/PageViewModel.cs | 23 +- .../Ui/Pages/ComposePageViewModel.cs | 195 +++-- .../Ui/Pages/ContainerDetailViewModel.cs | 93 ++- .../Ui/Pages/ContainerFilesView.axaml | 2 +- .../Ui/Pages/ContainerFilesView.axaml.cs | 84 +- .../Ui/Pages/ContainerFilesViewModel.cs | 268 ++++++- .../Ui/Pages/ContainerTerminalViewModel.cs | 78 +- .../Ui/Pages/ContainersPageView.axaml | 2 +- .../Ui/Pages/ContainersPageViewModel.cs | 189 ++++- .../Ui/Pages/ImagesPageView.axaml | 2 +- .../Ui/Pages/ImagesPageViewModel.cs | 48 +- .../Ui/Pages/LogsView.axaml | 23 +- .../Ui/Pages/LogsViewModel.cs | 362 +++++++-- .../Ui/Pages/NetworksPageView.axaml | 2 +- .../Ui/Pages/OverviewPageViewModel.cs | 4 + .../Ui/Pages/PullImageViewModel.cs | 43 +- .../Ui/Pages/SystemPageViewModel.cs | 53 +- .../Ui/Pages/VolumesPageView.axaml | 2 +- .../Ui/StatsSampler.cs | 30 +- .../Ui/TaskCenter.cs | 85 +- .../Analysis/ExplainPlan.cs | 94 ++- .../Analysis/IndexAdvisor.cs | 31 +- .../VelaShell.Plugin.Mongo/Bson/BsonText.cs | 21 +- .../VelaShell.Plugin.Mongo/Bson/ShellJson.cs | 38 +- .../Core/ConnectionProbe.cs | 16 +- .../Core/GridFsService.cs | 12 +- .../Core/MongoConnection.Catalog.cs | 120 ++- .../Core/MongoConnection.cs | 68 +- .../Core/MongoConnector.cs | 17 +- .../Core/MongoProfile.cs | 102 ++- .../VelaShell.Plugin.Mongo/Core/SshTunnel.cs | 321 ++++++-- .../VelaShell.Plugin.Mongo/Core/TlsTrust.cs | 32 +- plugins/VelaShell.Plugin.Mongo/Loc.Design.cs | 13 +- plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs | 4 + plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs | 1 + plugins/VelaShell.Plugin.Mongo/Loc.Query.cs | 4 + .../VelaShell.Plugin.Mongo/Loc.Transfer.cs | 6 + plugins/VelaShell.Plugin.Mongo/Loc.Users.cs | 8 + .../VelaShell.Plugin.Mongo/MongoSettings.cs | 17 +- plugins/VelaShell.Plugin.Mongo/MongoStore.cs | 55 +- plugins/VelaShell.Plugin.Mongo/README.md | 16 +- .../Shell/CodeExport.cs | 170 +++- .../Shell/ShellExecutor.cs | 53 +- .../Shell/ShellParser.cs | 71 +- .../Transfer/CellFormatter.cs | 20 +- .../Transfer/CollectionCopier.cs | 43 +- .../Transfer/ImportRunner.cs | 39 +- .../Transfer/ImportValues.cs | 56 +- .../Transfer/SchemaSampler.cs | 5 +- .../Transfer/TransferModels.cs | 9 +- .../Transfer/XlsxWriter.cs | 25 +- .../Ui/Charts/BarChart.cs | 14 +- .../Collection/CollectionTabViewModel.Edit.cs | 96 ++- .../CollectionTabViewModel.Query.cs | 108 ++- .../CollectionTabViewModel.Views.cs | 21 +- .../Ui/Collection/CollectionTabViewModel.cs | 122 ++- .../Ui/Collection/ConflictDialogViewModel.cs | 4 + .../DocumentEditorDialogViewModel.cs | 41 +- .../Ui/Collection/GridModels.cs | 86 +- .../Ui/Collection/GridPaneView.axaml | 5 +- .../Ui/Collection/GridPaneView.axaml.cs | 137 +++- .../Ui/Collection/JsonCardViewModel.cs | 24 +- .../Ui/Collection/JsonCardsView.axaml | 16 +- .../Ui/Design/DesignModels.cs | 26 +- .../Ui/Design/DesignTabViewModel.Indexes.cs | 45 +- .../Design/DesignTabViewModel.Validation.cs | 98 ++- .../Ui/Design/DesignValidationView.axaml | 4 +- .../Ui/Dialogs/ConnectionDialogViewModel.cs | 76 +- .../Ui/Editor/CodeEditor.cs | 19 +- .../Ui/GridFs/GridFsEntry.cs | 13 +- .../Ui/GridFs/GridFsTabViewModel.Actions.cs | 116 ++- .../Ui/GridFs/GridFsTabViewModel.cs | 6 + .../Ui/GridFs/GridFsThumbnailCache.cs | 78 ++ .../Ui/Monitor/MonitorTabViewModel.cs | 118 ++- .../Ui/Objects/ObjectsTabViewModel.Details.cs | 38 +- .../Ui/Pipeline/PipelineTabViewModel.cs | 22 +- .../Ui/Profiler/ProfilerDetail.cs | 21 +- .../Ui/Profiler/ProfilerModels.cs | 84 +- .../Ui/Profiler/ProfilerTabView.axaml | 14 +- .../Ui/Profiler/ProfilerTabViewModel.cs | 202 ++++- .../Ui/Query/CodeExportDialogViewModel.cs | 17 +- .../Ui/Query/QueryTabViewModel.Editor.cs | 20 +- .../Ui/Query/QueryTabViewModel.Panels.cs | 43 +- .../Ui/Query/QueryTabViewModel.Run.cs | 21 +- .../Ui/Query/QueryTabViewModel.cs | 8 +- .../Ui/Query/ResultGrid.cs | 91 ++- .../Ui/Shell/MongoSession.cs | 6 + .../MongoWorkspaceViewModel.Connections.cs | 6 +- .../Ui/Shell/WorkspaceTab.cs | 28 + .../Ui/Shell/WriteGuard.cs | 69 +- .../Ui/Transfer/ExportWizardViewModel.cs | 43 +- .../Ui/Transfer/ImportWizardView.axaml | 9 + .../Ui/Transfer/ImportWizardViewModel.cs | 174 +++- .../Ui/Transfer/TransferRows.cs | 17 +- .../Ui/Transfer/TransferWizardViewModel.cs | 66 +- .../Ui/Transfer/XferWizardViewModel.cs | 12 +- .../Ui/Users/UserAdmin.cs | 14 +- .../Ui/Users/UserEditorViewModel.cs | 35 +- .../Ui/Users/UsersTabView.axaml | 8 +- .../Ui/Users/UsersTabViewModel.cs | 68 +- .../DockerCoreFixTests.cs | 749 ++++++++++++++++++ .../FakeDockerDaemon.cs | 358 +++++++++ .../InspectionTests.cs | 18 +- .../UiRobustnessTests.cs | 330 ++++++++ .../BsonRoundTripTests.cs | 134 ++++ .../CatalogAndCopierTests.cs | 88 ++ .../CodeExportLiteralTests.cs | 111 +++ .../CollectionTests.cs | 13 +- .../VelaShell.Plugin.Mongo.Tests/CsvTests.cs | 4 +- .../DocumentEditorTests.cs | 4 +- .../ExplainPlanSbeTests.cs | 116 +++ .../ImportRunnerTests.cs | 133 ++++ .../IndexAdvisorProtectionTests.cs | 65 ++ .../IndexAdvisorTests.cs | 4 +- .../ObjectsTests.cs | 6 +- .../ProfileStoreTests.cs | 54 ++ .../QueryHistoryRedactionTests.cs | 50 ++ .../ShellGuardTests.cs | 177 +++++ .../ToolTabFixesTests.cs | 138 ++++ .../TransferFixTests.cs | 72 ++ .../TunnelSettingsTests.cs | 323 ++++++++ .../UiReviewFixesTests.cs | 444 +++++++++++ .../UsersTests.cs | 1 + 148 files changed, 9909 insertions(+), 1255 deletions(-) create mode 100644 plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsThumbnailCache.cs create mode 100644 tests/VelaShell.Plugin.DockerPanel.Tests/DockerCoreFixTests.cs create mode 100644 tests/VelaShell.Plugin.DockerPanel.Tests/FakeDockerDaemon.cs create mode 100644 tests/VelaShell.Plugin.DockerPanel.Tests/UiRobustnessTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/BsonRoundTripTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/CatalogAndCopierTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/CodeExportLiteralTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/ExplainPlanSbeTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/ImportRunnerTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorProtectionTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/ProfileStoreTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/QueryHistoryRedactionTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/ShellGuardTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/ToolTabFixesTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/TransferFixTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/TunnelSettingsTests.cs create mode 100644 tests/VelaShell.Plugin.Mongo.Tests/UiReviewFixesTests.cs diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DiskMath.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DiskMath.cs index e6fbca8..0550362 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DiskMath.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DiskMath.cs @@ -43,10 +43,40 @@ public static ReclaimBreakdown Reclaimable(DiskUsage? usage) ImageSummary[] unusedImages = [.. (usage.Images ?? []).Where(static i => i.Containers <= 0)]; VolumeSummary[] unusedVolumes = [.. (usage.Volumes ?? []).Where(static v => v.UsageData is { RefCount: <= 0 })]; return new( - unusedImages.Sum(static i => i.Size), + ReclaimableImageBytes(usage, unusedImages), unusedVolumes.Sum(static v => v.UsageData is { Size: > 0 } u ? u.Size : 0), (usage.BuildCache ?? []).Where(static c => !c.InUse).Sum(static c => c.Size), unusedImages.Length, unusedVolumes.Length); } -} + + /// + /// 镜像这一段的可回收字节,口径同 docker CLI(system df 的 RECLAIMABLE 列): + /// LayersSize − Σ(在用镜像的 Size − SharedSize),不小于 0。 + /// + /// 不能把未使用镜像的 Size 直接相加:Size 含与其它镜像共享的层, + /// 两个基于同一个基础镜像的旧版本会把那几层算两遍,报出一个比磁盘上实际能腾出来的 + /// 还大的数。LayersSize 是去重后的层总量,减掉在用镜像独占的那部分才是能删的。 + /// + /// + /// 老 daemon 不报 LayersSize 时退回逐个相加 —— 偏大,但总比报 0 强。 + /// + /// + private static long ReclaimableImageBytes(DiskUsage usage, ImageSummary[] unusedImages) + { + if (usage.LayersSize <= 0) + { + return unusedImages.Sum(static i => i.Size); + } + long used = 0; + foreach (ImageSummary image in usage.Images ?? []) + { + // SharedSize 为 -1 表示 daemon 没算;CLI 同样跳过这种镜像。 + if (image.Containers > 0 && image.Size >= 0 && image.SharedSize >= 0) + { + used += image.Size - image.SharedSize; + } + } + return Math.Max(0, usage.LayersSize - used); + } +} \ No newline at end of file diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Containers.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Containers.cs index 0342d9d..25d3aa1 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Containers.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Containers.cs @@ -78,7 +78,8 @@ public Task TopAsync(string id, string psArgs = "-ef", Cance /// 可写层相对镜像的变更(docker diff)。 public async Task ChangesAsync(string id, CancellationToken cancellationToken = default) { - // 没有任何变更时 daemon 返回 JSON null,不是空数组。 + // 没有任何变更时 daemon 返回 JSON null,不是空数组。错误状态码已由 GetStringAsync 翻成异常, + // 不会再把 {"message":"No such container"} 静默当成"没有变更"。 string body = await GetStringAsync($"/containers/{Uri.EscapeDataString(id)}/changes", cancellationToken).ConfigureAwait(false); return DockerJson.TryDeserialize(body) ?? []; } @@ -114,13 +115,13 @@ public Task CommitContainerAsync(string id, string? repository, ("tag", string.IsNullOrWhiteSpace(tag) ? null : tag), ("comment", string.IsNullOrWhiteSpace(comment) ? null : comment), ("author", string.IsNullOrWhiteSpace(author) ? null : author), - ("pause", pause ? "1" : "0")), null, cancellationToken); + ("pause", pause ? "1" : "0")), null, NoTimeout, cancellationToken); /// - /// 等容器结束并拿退出码。用于"跑一次性容器"的场景。 + /// 等容器结束并拿退出码。用于"跑一次性容器"的场景。不设时限 —— 容器跑多久就等多久,只认取消令牌。 /// public Task WaitContainerAsync(string id, CancellationToken cancellationToken = default) => - PostJsonAsync($"/containers/{Uri.EscapeDataString(id)}/wait", null, cancellationToken); + PostJsonAsync($"/containers/{Uri.EscapeDataString(id)}/wait", null, NoTimeout, cancellationToken); } /// 等待容器结束的响应。 diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Exec.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Exec.cs index a15b405..2522692 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Exec.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Exec.cs @@ -12,6 +12,12 @@ public readonly record struct ExecCapture(string StandardOutput, string Standard /// 退出码为 0。 public bool IsSuccess => ExitCode == 0; + /// + /// 输出超过 被截断了。 + /// 截断时连接被主动断开,命令若还没跑完, 记为 -1。 + /// + public bool IsTruncated { get; init; } + /// 给人看的一行失败原因。 public string FailureText { @@ -50,15 +56,28 @@ public async Task WriteAsync(ReadOnlyMemory data, CancellationToken cancel } /// 持续读出容器的输出,直到会话结束或取消。 - public Task ReadAsync(Action onLine, CancellationToken cancellationToken) + /// + /// 取消即释放底层流(会话随之结束):隧道上的劫持流不一定理会取消令牌, + /// 不这么做的话一个没有输出的会话会让取消永远等下去。 + /// + public async Task ReadAsync(Action onLine, CancellationToken cancellationToken) { var decoder = new DockerFrameDecoder(Tty, timestamps: false); - return decoder.ReadAsync(stream, onLine, cancellationToken); + using (cancellationToken.Register(stream.Dispose)) + { + await decoder.ReadAsync(stream, onLine, cancellationToken).ConfigureAwait(false); + } } /// 把原始字节交给调用方(终端控件要的是字节,不是行)。 - public ValueTask ReadRawAsync(Memory buffer, CancellationToken cancellationToken = default) => - stream.ReadAsync(buffer, cancellationToken); + /// 与 一样:取消一次读取即结束整个会话。 + public async ValueTask ReadRawAsync(Memory buffer, CancellationToken cancellationToken = default) + { + using (cancellationToken.Register(stream.Dispose)) + { + return await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + } + } /// /// 底层的双工流,交给终端视图去泵。 @@ -85,6 +104,16 @@ public Task InspectAsync(CancellationToken cancellationToke public sealed partial class DockerClient { + /// + /// 收集输出的上限(stdout + stderr 合计,按 UTF-16 字符计)。 + /// 超过就截断并断开 —— 一条意外刷屏的命令不该把宿主进程的内存吃光 + /// (插件与宿主同进程,OOM 带走的是整个 VelaShell)。 + /// + public const int MaxExecCaptureBytes = 8 * 1024 * 1024; + + /// 的默认时限。 + public static readonly TimeSpan DefaultExecTimeout = TimeSpan.FromMinutes(2); + /// /// 在容器里开一条**交互式** exec 会话。返回的会话握着一条独立的隧道, /// 调用方负责释放它 —— 释放即结束远端进程。 @@ -106,10 +135,22 @@ public async Task StartExecAsync(string containerId, string[] try { string body = JsonSerializer.Serialize(new { Detach = false, Tty = tty }, DockerJson.Options); - (int status, string? reason, Stream? hijacked) = await DockerRawHttp - .PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, cancellationToken) - .ConfigureAwait(false); - return status is not (200 or 101) ? throw new DockerApiException((System.Net.HttpStatusCode)status, $"启动 exec 失败:HTTP {status} {reason}") : new(created.Id, hijacked, this, tty); + int status; + string reason, head; + Stream hijacked; + // 握手期间的取消同样靠释放流打断(隧道流的读不一定理会令牌)。 + using (cancellationToken.Register(stream.Dispose)) + { + (status, reason, head, hijacked) = await DockerRawHttp + .PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, cancellationToken) + .ConfigureAwait(false); + if (status is not (200 or 101)) + { + throw await StartExecFailureAsync(status, reason, head, hijacked, cancellationToken).ConfigureAwait(false); + } + } + cancellationToken.ThrowIfCancellationRequested(); + return new(created.Id, hijacked, this, tty); } catch { @@ -126,33 +167,97 @@ public async Task StartExecAsync(string containerId, string[] /// 而"命令失败了"和"命令没有输出"才区分得开。 /// /// + /// 容器 id 或名字。 + /// 要执行的命令(argv 形态,不经 shell 解析)。 + /// 以哪个用户执行;留空用镜像默认。 + /// 工作目录;留空用镜像默认。 + /// 时限;null 用 。超时抛 。 + /// 取消令牌。 public async Task ExecCaptureAsync(string containerId, string[] command, - string? user = null, string? workingDir = null, CancellationToken cancellationToken = default) + string? user = null, string? workingDir = null, TimeSpan? timeout = null, + CancellationToken cancellationToken = default) { - ExecCreateResponse created = await CreateExecAsync(containerId, command, tty: false, attachStdin: false, - user, workingDir, cancellationToken).ConfigureAwait(false); - Stream stream = await Transport.ConnectAsync(cancellationToken).ConfigureAwait(false); + TimeSpan limit = timeout ?? DefaultExecTimeout; + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + if (limit != Timeout.InfiniteTimeSpan) + { + cts.CancelAfter(limit); + } + CancellationToken token = cts.Token; var stdout = new StringBuilder(); var stderr = new StringBuilder(); - await using (stream.ConfigureAwait(false)) + bool truncated = false; + string execId; + try { - string body = JsonSerializer.Serialize(new { Detach = false, Tty = false }, DockerJson.Options); - (int status, string? reason, Stream? hijacked) = await DockerRawHttp - .PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, cancellationToken) - .ConfigureAwait(false); - if (status is not (200 or 101)) + ExecCreateResponse created = await CreateExecAsync(containerId, command, tty: false, attachStdin: false, + user, workingDir, token).ConfigureAwait(false); + execId = created.Id; + Stream stream = await Transport.ConnectAsync(token).ConfigureAwait(false); + await using (stream.ConfigureAwait(false)) + // 隧道上的劫持流不一定理会取消令牌:取消 / 超时一律以释放流来打断读取, + // 否则一条不出声的命令能让调用方永远等下去。 + using (token.Register(stream.Dispose)) { - throw new DockerApiException((System.Net.HttpStatusCode)status, $"启动 exec 失败:HTTP {status} {reason}"); + string body = JsonSerializer.Serialize(new { Detach = false, Tty = false }, DockerJson.Options); + (int status, string reason, string head, Stream hijacked) = await DockerRawHttp + .PostAsync(stream, $"/exec/{Uri.EscapeDataString(created.Id)}/start", body, upgrade: true, token) + .ConfigureAwait(false); + if (status is not (200 or 101)) + { + throw await StartExecFailureAsync(status, reason, head, hijacked, token).ConfigureAwait(false); + } + // 截断时用它停下读取循环;它不连着外面的令牌,停下来不算"被取消"。 + using var stop = CancellationTokenSource.CreateLinkedTokenSource(token); + var decoder = new DockerFrameDecoder(tty: false, timestamps: false); + try + { + await decoder.ReadAsync(hijacked, line => + { + if (truncated) + { + return; + } + if (stdout.Length + stderr.Length + line.Text.Length + 1 > MaxExecCaptureBytes) + { + truncated = true; + stop.Cancel(); + return; + } + StringBuilder target = line.Kind == DockerStreamKind.StdErr ? stderr : stdout; + _ = target.Append(line.Text).Append('\n'); + }, stop.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (truncated && !token.IsCancellationRequested) + { + // 主动截断,不是取消。 + } } - var decoder = new DockerFrameDecoder(tty: false, timestamps: false); - await decoder.ReadAsync(hijacked, line => - { - StringBuilder target = line.Kind == DockerStreamKind.StdErr ? stderr : stdout; - _ = target.Append(line.Text).Append('\n'); - }, cancellationToken).ConfigureAwait(false); + ExecInspectResponse inspect = await InspectExecAsync(execId, token).ConfigureAwait(false); + // 截断时连接已断,命令可能还在跑 —— 那时的退出码没有意义,不能报成成功。 + int exitCode = truncated && inspect.Running ? -1 : inspect.ExitCode; + return new(stdout.ToString(), stderr.ToString(), exitCode) { IsTruncated = truncated }; + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested && cts.IsCancellationRequested + && ex is OperationCanceledException or ObjectDisposedException or IOException + or DockerUnreachableException) + { + throw new TimeoutException($"命令在 {limit.TotalSeconds:0} 秒内没有结束:{string.Join(' ', command)}", ex); } - ExecInspectResponse inspect = await InspectExecAsync(created.Id, cancellationToken).ConfigureAwait(false); - return new(stdout.ToString(), stderr.ToString(), inspect.ExitCode); + catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is not OperationCanceledException) + { + // 取消是靠释放流实现的,冒上来的会是 ObjectDisposedException / IOException —— 统一成取消。 + throw new OperationCanceledException(cancellationToken); + } + } + + /// exec 启动失败:把 daemon 的原话读出来(容器没在跑、exec 不存在 ……)。 + private static async Task StartExecFailureAsync(int status, string reason, string head, + Stream body, CancellationToken cancellationToken) + { + string message = await DockerRawHttp.ReadErrorMessageAsync(status, reason, head, body, cancellationToken) + .ConfigureAwait(false); + return new((System.Net.HttpStatusCode)status, $"启动 exec 失败:{message}"); } /// 创建一个 exec 实例(还没开始跑)。 diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Files.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Files.cs index 3bf8182..40330ee 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Files.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Files.cs @@ -23,8 +23,28 @@ public readonly record struct ContainerFileEntry( string Modified, string? LinkTarget); +/// 容器内一个文件的属主与权限(取自 /archive 的 tar 头)。 +/// 权限位(含 setuid / setgid / sticky),如 0755。 +/// 属主 uid。 +/// 属组 gid。 +/// 属主名(daemon 解包时只认数字 id,这里留着给界面看)。 +/// 属组名。 +public sealed record ContainerFileMetadata(int Mode, int Uid, int Gid, string? UserName = null, string? GroupName = null) +{ + /// 新建文件的缺省值:0644、root:root。 + public static ContainerFileMetadata NewFile { get; } = new(TarUtil.DefaultFileMode, 0, 0); +} + +/// 从容器里读出来的一个文件。 +/// 顺着符号链接解析之后的真实路径(写回时要写这里,而不是写链接本身)。 +/// 内容。 +/// 属主与权限。 +public sealed record ContainerFile(string Path, byte[] Content, ContainerFileMetadata Metadata); + public sealed partial class DockerClient { + /// 读文件时最多顺着符号链接跳几次(防环)。 + public const int MaxSymlinkHops = 8; /// 面板允许在线编辑的单文件上限。超过它的文件只给下载,不进编辑器。 public const long MaxEditableFileBytes = 2 * 1024 * 1024; @@ -50,10 +70,7 @@ public async Task ListDirectoryAsync(string containerId, s CancellationToken cancellationToken = default) { string target = string.IsNullOrWhiteSpace(path) ? "/" : path; - // -A 排掉 . 与 ..,--time-style=long-iso 把时间列压成固定的两段, - // 省得为不同 locale 的 ls 输出各写一套解析。 - ExecCapture result = await ExecCaptureAsync(containerId, - ["/bin/sh", "-c", $"ls -lAL --time-style=long-iso -- {ShellQuote(target)} 2>/dev/null || ls -lA -- {ShellQuote(target)}"], + ExecCapture result = await ExecCaptureAsync(containerId, ["/bin/sh", "-c", ListCommand(target)], cancellationToken: cancellationToken).ConfigureAwait(false); if (!result.IsSuccess && result.StandardOutput.Length == 0) { @@ -71,8 +88,31 @@ public async Task ListDirectoryAsync(string containerId, s return [.. entries.OrderByDescending(static e => e.IsDirectory).ThenBy(static e => e.Name, StringComparer.OrdinalIgnoreCase)]; } + /// + /// 列目录用的 shell 命令。 + /// + /// 按能力选命令,不按失败回退。 GNU ls 用 --time-style=long-iso 把时间列压成固定的 + /// 两段(2026-08-21 09:12),省得为不同 locale 各写一套解析;BusyBox(alpine 系镜像) + /// 没有这个选项,用它默认的三段(Aug 21 09:12 / Aug 21 2025)。 + /// 以前写成 A || B:BusyBox 上 A 必败、B 必跑,而 GNU 上 -L 碰到一个悬空链接 + /// 就退出 1 —— 两份列表一起打出来,每个条目出现两次。 + /// + /// -A 排掉 . 与 ..。 + /// + internal static string ListCommand(string target) + { + string quoted = ShellQuote(target); + return $"if ls --time-style=long-iso -d / >/dev/null 2>&1; then ls -lAL --time-style=long-iso -- {quoted}; " + + $"else ls -lA -- {quoted}; fi"; + } + /// /// 解一行 ls -lA。解不动就返回 null —— 总量行("total 12")与空行都走这条路。 + /// + /// 时间列按形状认:yyyy-mm-dd HH:MM(GNU long-iso)是两段, + /// Mon dd HH:MM / Mon dd yyyy(BusyBox 与 GNU 默认)是三段。 + /// 设备文件的大小列是 主, 次 两段,也要认出来,否则名字整体错位。 + /// /// internal static ContainerFileEntry? ParseLsLine(string line, string directory) { @@ -86,17 +126,34 @@ public async Task ListDirectoryAsync(string containerId, s { return null; } - // 权限 链接数 属主 属组 大小 日期 时间 名字… + // 权限 链接数 属主 属组 大小 日期… 名字… string[] parts = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length < 8) + if (parts.Length < 7) { return null; } string owner = $"{parts[2]} {parts[3]}"; - _ = long.TryParse(parts[4], out long size); - string modified = $"{parts[5]} {parts[6]}"; - // 名字里可能有空格,所以按"前七段之后的全部"取,而不是取第八段。 - int nameStart = IndexOfNthToken(trimmed, 7); + int sizeIndex = 4; + // 字符 / 块设备:"1, 3" —— 主设备号后面带逗号,大小列占两段。 + if (parts[4].EndsWith(',') && parts.Length > 5) + { + sizeIndex = 5; + } + long size = 0; + if (sizeIndex == 4) + { + _ = long.TryParse(parts[4], out size); + } + int dateIndex = sizeIndex + 1; + int dateTokens = IsIsoDate(parts[dateIndex]) ? 2 : 3; + int nameIndex = dateIndex + dateTokens; + if (parts.Length <= nameIndex) + { + return null; + } + string modified = string.Join(' ', parts, dateIndex, dateTokens); + // 名字里可能有空格,所以按"时间列之后的全部"取,而不是取下一段。 + int nameStart = IndexOfNthToken(trimmed, nameIndex); string name = nameStart >= 0 ? trimmed[nameStart..] : parts[^1]; string? linkTarget = null; if (mode[0] == 'l') @@ -116,6 +173,12 @@ public async Task ListDirectoryAsync(string containerId, s return new(name, full, mode[0] == 'd', mode[0] == 'l', size, mode, owner, modified, linkTarget); } + /// yyyy-mm-dd 形状(GNU long-iso 的日期段)。 + private static bool IsIsoDate(string token) => + token.Length == 10 && token[4] == '-' && token[7] == '-' + && char.IsAsciiDigit(token[0]) && char.IsAsciiDigit(token[3]) + && char.IsAsciiDigit(token[5]) && char.IsAsciiDigit(token[9]); + /// 找出第 n 个空白分隔字段的起始下标(n 从 0 起)。 private static int IndexOfNthToken(string text, int n) { @@ -148,18 +211,123 @@ private static int IndexOfNthToken(string text, int n) /// /// 读容器里的一个文件。走 GET /archive 拿一段 tar 再取出唯一那个文件 —— - /// 不经过 shell,因此不受登录 shell、引用规则与 locale 的影响。 + /// 不经过 shell,因此不受登录 shell、引用规则与 locale 的影响。符号链接会被跟随 + /// (见 )。 /// public async Task ReadFileAsync(string containerId, string path, long maxBytes = MaxEditableFileBytes, CancellationToken cancellationToken = default) + { + ContainerFile file = await ReadFileWithMetadataAsync(containerId, path, maxBytes, cancellationToken) + .ConfigureAwait(false); + return file.Content; + } + + /// + /// 读容器里的一个文件,连同它的属主与权限一起返回。 + /// + /// 符号链接要自己跟。 GET /archive 只解析路径中间的链接,最后一段是链接时 + /// 交回来的是一个类型为 2(符号链接)的条目,里面没有内容 —— /etc/localtime、 + /// 各种 *.conf -> ../available/*.conf 因此一律"不是普通文件"。这里读出链接目标, + /// 相对目标按链接所在目录解析,再请求一次,最多 跳。 + /// + /// + public async Task ReadFileWithMetadataAsync(string containerId, string path, + long maxBytes = MaxEditableFileBytes, CancellationToken cancellationToken = default) + { + string current = path; + for (int hop = 0; hop <= MaxSymlinkHops; hop++) + { + TarEntryInfo? entry = await ReadArchiveHeadAsync(containerId, current, maxBytes, readContent: true, + cancellationToken).ConfigureAwait(false); + if (entry is { IsLink: true }) + { + current = ResolveLinkTarget(current, entry.LinkName); + continue; + } + if (entry is not { IsRegularFile: true, Content: { } content }) + { + throw new DockerApiException(System.Net.HttpStatusCode.NotFound, $"{path} 不是一个普通文件。"); + } + return new(current, content, ToMetadata(entry)); + } + throw new DockerApiException(System.Net.HttpStatusCode.BadRequest, + $"{path} 的符号链接超过 {MaxSymlinkHops} 层,可能成环。"); + } + + /// + /// 查一个路径(跟随符号链接)真正指向的文件与它的属主、权限;不存在返回 null。 + /// 只读 tar 头,不读内容。 + /// + internal async Task<(string Path, ContainerFileMetadata? Metadata)> ProbeFileAsync(string containerId, string path, + CancellationToken cancellationToken) + { + string current = path; + for (int hop = 0; hop <= MaxSymlinkHops; hop++) + { + TarEntryInfo? entry; + try + { + entry = await ReadArchiveHeadAsync(containerId, current, long.MaxValue, readContent: false, + cancellationToken).ConfigureAwait(false); + } + catch (DockerApiException ex) when (ex.IsNotFound) + { + // 不存在:新建文件(或者悬空链接的目标 —— 写到目标上,链接本身留着)。 + return (current, null); + } + if (entry is { IsLink: true }) + { + current = ResolveLinkTarget(current, entry.LinkName); + continue; + } + return (current, entry is { IsRegularFile: true } ? ToMetadata(entry) : null); + } + throw new DockerApiException(System.Net.HttpStatusCode.BadRequest, + $"{path} 的符号链接超过 {MaxSymlinkHops} 层,可能成环。"); + } + + /// GET /archive 一个路径,只看第一个条目。 + private async Task ReadArchiveHeadAsync(string containerId, string path, long maxBytes, + bool readContent, CancellationToken cancellationToken) { string url = $"/containers/{Uri.EscapeDataString(containerId)}/archive" + Query(("path", path)); - using HttpResponseMessage response = await OpenStreamAsync(HttpMethod.Get, url, cancellationToken).ConfigureAwait(false); + // 单个可编辑文件(≤ 2 MB)很快就读完,走短请求池,不占长连接的位子。 + using HttpResponseMessage response = await OpenStreamAsync(HttpMethod.Get, url, cancellationToken, longLived: false) + .ConfigureAwait(false); await using Stream body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - (string Name, byte[] Content)? entry = await TarUtil.ReadFirstFileAsync(body, maxBytes, cancellationToken) - .ConfigureAwait(false); - return entry?.Content - ?? throw new DockerApiException(System.Net.HttpStatusCode.NotFound, $"{path} 不是一个普通文件。"); + return await TarUtil.ReadFirstEntryAsync(body, maxBytes, readContent, cancellationToken).ConfigureAwait(false); + } + + private static ContainerFileMetadata ToMetadata(TarEntryInfo entry) => + new(entry.Mode, entry.Uid, entry.Gid, + string.IsNullOrEmpty(entry.UserName) ? null : entry.UserName, + string.IsNullOrEmpty(entry.GroupName) ? null : entry.GroupName); + + /// + /// 把符号链接目标解析成绝对路径:绝对目标原样(daemon 会把它限定在容器根内), + /// 相对目标按链接所在目录拼,再规整掉 . 与 ..。 + /// + internal static string ResolveLinkTarget(string linkPath, string target) + { + string combined = target.StartsWith('/') ? target : GetDirectory(linkPath).TrimEnd('/') + "/" + target; + List parts = []; + foreach (string segment in combined.Split('/')) + { + if (segment is "" or ".") + { + continue; + } + if (segment == "..") + { + if (parts.Count > 0) + { + parts.RemoveAt(parts.Count - 1); + } + continue; + } + parts.Add(segment); + } + return "/" + string.Join('/', parts); } /// @@ -168,13 +336,40 @@ public async Task ReadFileAsync(string containerId, string path, long ma /// 整个文件以 tar 流 PUT 回容器的可写层。这是会丢数据的操作 —— /// 原文件被整体覆盖,Docker 不做备份 —— 界面必须走"手打确认串"那一档闸门。 /// + /// + /// 属主与权限沿用原文件。 daemon 解包时按 tar 头里的 uid/gid 与 mode 落盘 —— + /// 写死 0644 root:root 的话,entrypoint.sh 存一次就丢了执行位、0600 的密钥被放宽、 + /// 应用自己的配置变成 root 的,容器下次启动才炸。所以先读一次原文件的 tar 头 + /// (只读头,不读内容;顺着符号链接写到真正的文件上,链接本身不被替换成普通文件), + /// 文件不存在才用 0644 root:root。 + /// /// public async Task WriteFileAsync(string containerId, string path, ReadOnlyMemory content, CancellationToken cancellationToken = default) { + (string target, ContainerFileMetadata? metadata) = await ProbeFileAsync(containerId, path, cancellationToken) + .ConfigureAwait(false); + await WriteFileAsync(containerId, target, content, metadata, cancellationToken).ConfigureAwait(false); + } + + /// + /// 按给定的属主与权限把内容写到 (不再跟随符号链接,也不再探测原文件)。 + /// 一般配合 用:把读到的 + /// 与 原样传回来,省掉一次探测。 + /// + /// 容器 id 或名字。 + /// 目标路径。 + /// 内容。 + /// 属主与权限;null 用 。 + /// 取消令牌。 + public async Task WriteFileAsync(string containerId, string path, ReadOnlyMemory content, + ContainerFileMetadata? metadata, CancellationToken cancellationToken = default) + { + ContainerFileMetadata meta = metadata ?? ContainerFileMetadata.NewFile; string directory = GetDirectory(path); string name = path[(path.LastIndexOf('/') + 1)..]; - byte[] tar = TarUtil.CreateSingleFile(name, content.Span); + byte[] tar = TarUtil.CreateSingleFile(name, content.Span, meta.Mode, null, meta.Uid, meta.Gid, + meta.UserName, meta.GroupName); string url = $"/containers/{Uri.EscapeDataString(containerId)}/archive" + Query(("path", directory), ("noOverwriteDirNonDir", "1")); using var request = new HttpRequestMessage(HttpMethod.Put, url) @@ -234,6 +429,11 @@ public override long Position public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => inner.ReadAsync(buffer, cancellationToken); + // 基类的数组版 ReadAsync 会退回 BeginRead/EndRead(线程池上的同步读), + // 也绕过了 inner 自己的异步实现 —— CopyToAsync 之类的调用方走的正是这一版。 + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => inner.ReadAsync(buffer, offset, count, cancellationToken); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); @@ -247,5 +447,14 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } + + // 调用方都是 await using:基类的 DisposeAsync 只会同步调 Dispose, + // 而 inner 的异步释放(排空 / 关闭连接)应该真的异步走。 + public override async ValueTask DisposeAsync() + { + await inner.DisposeAsync().ConfigureAwait(false); + response.Dispose(); + await base.DisposeAsync().ConfigureAwait(false); + } } } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Images.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Images.cs index 2b473e1..3be5287 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Images.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.Images.cs @@ -76,7 +76,7 @@ public async Task PushImageAsync(string name, string? tag, string? registryAuth, /// 取消令牌。 public Task PruneImagesAsync(bool danglingOnly, CancellationToken cancellationToken = default) => PostJsonAsync("/images/prune" + Query(("filters", Filters(("dangling", danglingOnly ? "true" : "false")))), - null, cancellationToken); + null, NoTimeout, cancellationToken); /// /// 把一个或多个镜像导出成 tar 流(docker save)。 @@ -94,15 +94,26 @@ public async Task SaveImagesAsync(IReadOnlyList names, Cancellat HttpResponseMessage response; try { - response = await _http.GetAsync(path, HttpCompletionOption.ResponseHeadersRead, cancellationToken) - .ConfigureAwait(false); + response = await _streamHttp.GetAsync(path, HttpCompletionOption.ResponseHeadersRead, cancellationToken) + .ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { throw Unreachable(ex); } - await EnsureSuccessAsync(response, path, cancellationToken).ConfigureAwait(false); - return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + try + { + await EnsureSuccessAsync(response, path, cancellationToken).ConfigureAwait(false); + // 响应的生命周期钉在交出去的流上:调用方释放流,连接才回池。 + return new ResponseOwningStream(response, + await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)); + } + catch + { + // 失败时没有人会再拿到这条响应 —— 不在这里释放,它占着的那条隧道就漏了。 + response.Dispose(); + throw; + } } /// @@ -140,8 +151,9 @@ private async Task StreamNdjsonAsync(HttpMethod method, string path, string? reg HttpResponseMessage response; try { - response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken) - .ConfigureAwait(false); + // 拉取 / 推送 / 导入能跑几分钟,走长连接池,不占短请求的位子。 + response = await _streamHttp.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken) + .ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.System.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.System.cs index 0dcfa66..1d2ac47 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.System.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.System.cs @@ -22,17 +22,17 @@ public async Task InfoRawAsync(CancellationToken cancellationToken = def /// 磁盘用量(docker system df -v)。 /// /// 这条请求在镜像多的机器上要几秒 —— daemon 得把每个卷都 du 一遍。 - /// 界面因此不把它挂在自动刷新上,只在进"系统"页与手动重算时发。 + /// 界面因此不把它挂在自动刷新上,只在进"系统"页与手动重算时发;也因此不套 30 秒时限。 /// /// public Task DiskUsageAsync(CancellationToken cancellationToken = default) => - GetJsonAsync("/system/df", cancellationToken); + GetJsonAsync("/system/df", NoTimeout, cancellationToken); /// 清理已停止的容器。 public Task PruneContainersAsync(CancellationToken cancellationToken = default) => - PostJsonAsync("/containers/prune", null, cancellationToken); + PostJsonAsync("/containers/prune", null, NoTimeout, cancellationToken); /// 清理构建缓存。 public Task PruneBuildCacheAsync(bool all = false, CancellationToken cancellationToken = default) => - PostJsonAsync("/build/prune" + Query(("all", all ? "1" : "0")), null, cancellationToken); + PostJsonAsync("/build/prune" + Query(("all", all ? "1" : "0")), null, NoTimeout, cancellationToken); } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.VolumesNetworks.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.VolumesNetworks.cs index 3ff043a..b91992d 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.VolumesNetworks.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.VolumesNetworks.cs @@ -41,7 +41,7 @@ public Task RemoveVolumeAsync(string name, bool force = false, CancellationToken /// 清理未被任何容器使用的卷。同样会丢数据。 public Task PruneVolumesAsync(CancellationToken cancellationToken = default) => - PostJsonAsync("/volumes/prune", null, cancellationToken); + PostJsonAsync("/volumes/prune", null, NoTimeout, cancellationToken); // ─────────────────────────── 网络 ─────────────────────────── @@ -97,7 +97,7 @@ public Task DisconnectNetworkAsync(string networkId, string container, bool forc /// 清理未使用的网络。 public Task PruneNetworksAsync(CancellationToken cancellationToken = default) => - PostJsonAsync("/networks/prune", null, cancellationToken); + PostJsonAsync("/networks/prune", null, NoTimeout, cancellationToken); } /// 新建网络的响应。 diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.cs index bdb5fed..2bdbf1a 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerClient.cs @@ -22,8 +22,49 @@ public sealed partial class DockerClient : IAsyncDisposable /// 一次性请求的默认时限。流式请求不受它约束。 private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30); + /// + /// "不设时限,只认取消令牌"。传给请求原语的 timeout 参数时, + /// 请求同时改走长连接池(见下面的连接预算)—— 一条要跑几分钟的 prune + /// 不该占着短请求池里的一个位子。 + /// + internal static readonly TimeSpan NoTimeout = Timeout.InfiniteTimeSpan; + + // ─────────────────────────── 连接预算 ─────────────────────────── + // + // 隧道配额是**每插件 16 条**(宿主强制,超了 ConnectAsync 直接失败)。分三块: + // + // 短请求池 RequestConnections = 4 列表、inspect、启停、统计快照 …… + // 长连接池 LongLivedConnections = 10 事件流 1 + 详情统计流 1 + // + 跟随日志 MaxFollowStreams(6) + // + 传输 2(拉取 / 推送 / 导入导出 / 整包下载、慢请求) + // 直连 16 − 4 − 10 = 2 exec 劫持连接(控制台一条 + ls / which 之类一条) + // + // 以前两类共用一个 6 条的池:事件流 + 统计流 + 几条跟随日志一占满, + // 多出来的日志源永远开不起来,普通请求排队排到 30 秒超时、被报成"daemon 连不上"。 + // 分池之后,长连接再多也只在自己那一池里排队,短请求永远有位子。 + + /// + /// 同时跟随(follow=1)的日志源上限。界面必须按它封顶 —— + /// 超出的那几条会在长连接池里排队,表现为"加了日志源但一直没有输出"。 + /// + public const int MaxFollowStreams = 6; + + /// 短请求池的连接数。 + private const int RequestConnections = 4; + + /// 长连接池的连接数:事件 1 + 统计 1 + 跟随日志 + 传输 2。 + private const int LongLivedConnections = 1 + 1 + MaxFollowStreams + 2; + + /// 每插件的隧道配额(宿主规定)。 + internal const int TunnelQuota = 16; + + /// 留给 exec 劫持连接(不经连接池)的条数。 + internal const int DirectConnections = TunnelQuota - RequestConnections - LongLivedConnections; + private readonly SocketsHttpHandler _handler; private readonly HttpClient _http; + private readonly SocketsHttpHandler _streamHandler; + private readonly HttpClient _streamHttp; private bool _disposed; /// 按端点建一个客户端。 @@ -31,27 +72,36 @@ public DockerClient(DockerEndpoint endpoint, IDockerTransport transport) { Endpoint = endpoint; Transport = transport; - _handler = new SocketsHttpHandler - { - ConnectCallback = async (_, ct) => await transport.ConnectAsync(ct).ConfigureAwait(false), - // 连接池要留出余量:隧道配额是每插件 16 条,而事件流、每条跟随中的日志与统计 - // 各自长期占一条。池子开太大,真正要紧的那几条流就开不出来了。 - MaxConnectionsPerServer = 6, - PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2), - // 隧道自己会随 SSH 会话一起断,不需要再叠一层生存期轮转。 - PooledConnectionLifetime = Timeout.InfiniteTimeSpan, - AllowAutoRedirect = false, - UseCookies = false, - UseProxy = false - }; - _http = new HttpClient(_handler, disposeHandler: false) + // 两个池子各管各的连接数(见上面的连接预算)。 + _handler = CreateHandler(transport, RequestConnections); + _http = CreateClient(_handler); + _streamHandler = CreateHandler(transport, LongLivedConnections); + _streamHttp = CreateClient(_streamHandler); + } + + private static SocketsHttpHandler CreateHandler(IDockerTransport transport, int maxConnections) => new() + { + ConnectCallback = async (_, ct) => await transport.ConnectAsync(ct).ConfigureAwait(false), + MaxConnectionsPerServer = maxConnections, + PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2), + // 隧道自己会随 SSH 会话一起断,不需要再叠一层生存期轮转。 + PooledConnectionLifetime = Timeout.InfiniteTimeSpan, + AllowAutoRedirect = false, + UseCookies = false, + UseProxy = false + }; + + private static HttpClient CreateClient(SocketsHttpHandler handler) + { + var http = new HttpClient(handler, disposeHandler: false) { // 主机名是给 Host 头凑数的:对面是一个 socket,不看它。 BaseAddress = new Uri("http://docker/"), // 总时限交给每次调用的取消令牌 —— HttpClient.Timeout 会把流式请求一并掐掉。 Timeout = Timeout.InfiniteTimeSpan }; - _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return http; } /// 这个客户端连的是哪个端点。 @@ -70,6 +120,8 @@ public ValueTask DisposeAsync() _disposed = true; _http.Dispose(); _handler.Dispose(); + _streamHttp.Dispose(); + _streamHandler.Dispose(); return ValueTask.CompletedTask; } @@ -109,16 +161,25 @@ internal static string Query(params (string Key, string? Value)[] items) } /// GET 一段 JSON 并反序列化。 - internal async Task GetJsonAsync(string path, CancellationToken cancellationToken) + internal Task GetJsonAsync(string path, CancellationToken cancellationToken) => + GetJsonAsync(path, DefaultTimeout, cancellationToken); + + /// GET 一段 JSON 并反序列化,自定时限( = 只认取消令牌)。 + internal async Task GetJsonAsync(string path, TimeSpan timeout, CancellationToken cancellationToken) { - using HttpResponseMessage response = await SendAsync(HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false); + using HttpResponseMessage response = await SendAsync(HttpMethod.Get, path, null, cancellationToken, timeout).ConfigureAwait(false); return await ReadJsonAsync(response, path, cancellationToken).ConfigureAwait(false); } /// GET 一段原始文本(inspect 的完整 JSON 直接给界面看)。 + /// + /// 非 2xx 一样翻成异常 —— 否则 {"message":"No such container"} 会被当成 + /// inspect 结果摆进详情页,统计快照会把错误体解成一份全零的统计。 + /// internal async Task GetStringAsync(string path, CancellationToken cancellationToken) { using HttpResponseMessage response = await SendAsync(HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false); + await EnsureSuccessAsync(response, path, cancellationToken).ConfigureAwait(false); return await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); } @@ -130,9 +191,13 @@ internal async Task PostAsync(string path, object? body = null, CancellationToke } /// POST 并反序列化响应。 - internal async Task PostJsonAsync(string path, object? body = null, CancellationToken cancellationToken = default) + internal Task PostJsonAsync(string path, object? body = null, CancellationToken cancellationToken = default) => + PostJsonAsync(path, body, DefaultTimeout, cancellationToken); + + /// POST 并反序列化响应,自定时限( = 只认取消令牌)。 + internal async Task PostJsonAsync(string path, object? body, TimeSpan timeout, CancellationToken cancellationToken) { - using HttpResponseMessage response = await SendAsync(HttpMethod.Post, path, JsonBody(body), cancellationToken).ConfigureAwait(false); + using HttpResponseMessage response = await SendAsync(HttpMethod.Post, path, JsonBody(body), cancellationToken, timeout).ConfigureAwait(false); return await ReadJsonAsync(response, path, cancellationToken).ConfigureAwait(false); } @@ -154,14 +219,23 @@ internal async Task DeleteJsonAsync(string path, CancellationToken cancell /// 发一条**流式**请求:响应头一到就返回,响应体留着慢慢读。 /// 调用方负责释放返回的 。 /// + /// 方法。 + /// 路径。 + /// 取消令牌。 + /// + /// 是否长连接(事件、跟随日志、统计流、大传输)。长连接走自己的池子, + /// 不占短请求的位子;读一个 2 MB 以内的文件这种"流式但很快"的请求传 false。 + /// internal async Task OpenStreamAsync(HttpMethod method, string path, - CancellationToken cancellationToken) + CancellationToken cancellationToken, bool longLived = true) { + ObjectDisposedException.ThrowIf(_disposed, this); using var request = new HttpRequestMessage(method, path); HttpResponseMessage response; try { - response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + response = await (longLived ? _streamHttp : _http) + .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { @@ -183,21 +257,36 @@ internal async Task OpenStreamAsync(HttpMethod method, stri private static JsonContent? JsonBody(object? body) => body is null ? null : JsonContent.Create(body, options: DockerJson.Options); + /// 方法。 + /// 路径。 + /// 请求体。 + /// 取消令牌。 + /// + /// 时限;null 用 。 表示只认取消令牌, + /// 并改走长连接池 —— system df、各种 prune、commit、wait 在大机器上要跑几分钟, + /// 30 秒一到就报"daemon 没有响应",而 daemon 其实还在干活。 + /// private async Task SendAsync(HttpMethod method, string path, HttpContent? content, - CancellationToken cancellationToken) + CancellationToken cancellationToken, TimeSpan? timeout = null) { ObjectDisposedException.ThrowIf(_disposed, this); + TimeSpan limit = timeout ?? DefaultTimeout; + bool unbounded = limit == NoTimeout; using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(DefaultTimeout); + if (!unbounded) + { + cts.CancelAfter(limit); + } using var request = new HttpRequestMessage(method, path) { Content = content }; try { - return await _http.SendAsync(request, HttpCompletionOption.ResponseContentRead, cts.Token).ConfigureAwait(false); + return await (unbounded ? _streamHttp : _http) + .SendAsync(request, HttpCompletionOption.ResponseContentRead, cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { throw new DockerUnreachableException( - $"请求 {path} 超过 {DefaultTimeout.TotalSeconds:0} 秒没有响应。", DockerUnreachableReason.Unknown); + $"请求 {path} 超过 {limit.TotalSeconds:0} 秒没有响应。", DockerUnreachableReason.Unknown); } catch (Exception ex) when (ex is not OperationCanceledException) { diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerFrames.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerFrames.cs index f1c6515..255ecbe 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerFrames.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerFrames.cs @@ -32,53 +32,92 @@ public enum DockerStreamKind /// /// /// 解出来的字节再按 UTF-8 解码并切行。跨帧的半个字符与半行都被缓存住, -/// 不会吐出替换字符或半行 —— 半行开头的日志比少几行更难读。 +/// 不会吐出替换字符或半行 —— 半行开头的日志比少几行更难读。stdout 与 stderr +/// 各有一份解码器与行缓冲:两条流的帧是交错到达的,共用一个解码器会把一条流里 +/// 劈开的多字节字符跟另一条流的字节拼在一起。 +/// +/// +/// 行尾:\n、\r\n 与单独的 \r 都算一次换行(进度条靠 \r 原地重画, +/// 不把它当换行的话那一"行"永远不结束)。单行超过 强制切断。 +/// +/// +/// 帧头校验:类型只能是 0–3、第 1–3 字节必须为 0、长度不超过 。 +/// 第一个帧头就不合法,几乎一定是"容器其实有 TTY"(调用方拿到的 tty 标志不对)—— +/// 这时退回裸文本模式,把这 8 个字节连同后续当正文;流中途出现不合法的帧头则是 +/// 协议错乱,抛 (调用方本来就把读流异常报成"流断开")。 +/// 类型 3(systemerr,daemon 自己的错误)并进 stderr,不混进 stdout。 /// /// public sealed class DockerFrameDecoder(bool tty, bool timestamps) { + /// 单帧长度上限。daemon 实际的帧在 32 KB 上下,1 MB 已经宽得多。 + public const int MaxFrameBytes = 1024 * 1024; + + /// 单行长度上限(字符)。超过就强制切成一行交出去,行缓冲不会无限长。 + public const int MaxLineChars = 64 * 1024; + private readonly byte[] _header = new byte[8]; - private readonly Decoder _decoder = new UTF8Encoding(false).GetDecoder(); - private readonly StringBuilder _stdout = new(); - private readonly StringBuilder _stderr = new(); + private readonly LineState _stdout = new(); + private readonly LineState _stderr = new(); private char[] _chars = new char[4096]; + /// 一条流自己的解码器、行缓冲与"上一块以 \r 结尾"的状态。 + private sealed class LineState + { + public readonly Decoder Decoder = new UTF8Encoding(false).GetDecoder(); + public readonly StringBuilder Buffer = new(); + public bool PendingCr; + } + /// /// 从流里持续解出日志行,直到流结束或取消。 /// /// 已经定位到帧起点的响应体流。 /// 逐行回调(在读流的线程上同步调用,应快速返回)。 /// 取消令牌。 + /// 流中途出现不合法的帧头。 public async Task ReadAsync(Stream stream, Action onLine, CancellationToken cancellationToken) { byte[] payload = new byte[64 * 1024]; + bool raw = tty; + bool sawFrame = false; while (!cancellationToken.IsCancellationRequested) { - DockerStreamKind kind; - int length; - if (tty) + if (raw) { // 有 TTY:没有帧头,读到多少算多少,全部归 stdout // ——(TTY 本来就把 stderr 并进了同一条流,这不是我们丢的)。 - kind = DockerStreamKind.StdOut; - length = await stream.ReadAsync(payload, cancellationToken).ConfigureAwait(false); - if (length <= 0) + int read = await stream.ReadAsync(payload, cancellationToken).ConfigureAwait(false); + if (read <= 0) { break; } - Emit(kind, payload.AsSpan(0, length), onLine); + Emit(DockerStreamKind.StdOut, payload.AsSpan(0, read), onLine); continue; } if (!await ReadExactlyAsync(stream, _header, cancellationToken).ConfigureAwait(false)) { break; } - kind = (DockerStreamKind)_header[0]; - length = BinaryPrimitives.ReadInt32BigEndian(_header.AsSpan(4, 4)); - if (length < 0) + byte type = _header[0]; + int length = BinaryPrimitives.ReadInt32BigEndian(_header.AsSpan(4, 4)); + bool valid = type <= 3 && _header[1] == 0 && _header[2] == 0 && _header[3] == 0 + && length is >= 0 and <= MaxFrameBytes; + if (!valid) { - break; + if (!sawFrame) + { + // 第一帧就不像帧头:按裸文本处理,这 8 个字节本身就是正文。 + raw = true; + Emit(DockerStreamKind.StdOut, _header, onLine); + continue; + } + throw new InvalidDataException( + $"Docker 输出流的帧头不合法(类型 {type},长度 {length}),流已错位,停止解码。"); } + sawFrame = true; + // 0 = stdin 回显,与 stdout 同列(moby 的 stdcopy 也这么处理);3 = daemon 的错误,归 stderr。 + DockerStreamKind kind = type is 2 or 3 ? DockerStreamKind.StdErr : DockerStreamKind.StdOut; if (length > payload.Length) { payload = new byte[length]; @@ -94,32 +133,80 @@ public async Task ReadAsync(Stream stream, Action onLine, Cancell FlushRemainder(DockerStreamKind.StdErr, onLine); } + private LineState StateOf(DockerStreamKind kind) => kind == DockerStreamKind.StdErr ? _stderr : _stdout; + private void Emit(DockerStreamKind kind, ReadOnlySpan bytes, Action onLine) { - int needed = _decoder.GetCharCount(bytes, flush: false); + LineState state = StateOf(kind); + int needed = state.Decoder.GetCharCount(bytes, flush: false); if (needed > _chars.Length) { _chars = new char[needed]; } - int produced = _decoder.GetChars(bytes, _chars, flush: false); - StringBuilder buffer = kind == DockerStreamKind.StdErr ? _stderr : _stdout; - for (int i = 0; i < produced; i++) + int produced = state.Decoder.GetChars(bytes, _chars, flush: false); + ReadOnlySpan chars = _chars.AsSpan(0, produced); + while (!chars.IsEmpty) { - char c = _chars[i]; - if (c == '\n') + if (state.PendingCr) { - PublishLine(kind, buffer, onLine); + // 上一块以 \r 结尾、这一块以 \n 开头:\r\n 是一次换行,不是两次。 + state.PendingCr = false; + if (chars[0] == '\n') + { + chars = chars[1..]; + continue; + } } - else if (c != '\r') + int stop = chars.IndexOfAny('\n', '\r'); + Append(kind, state, stop < 0 ? chars : chars[..stop], onLine); + if (stop < 0) { - _ = buffer.Append(c); + break; } + if (chars[stop] == '\r') + { + if (stop + 1 < chars.Length) + { + if (chars[stop + 1] == '\n') + { + stop++; + } + } + else + { + state.PendingCr = true; + } + } + PublishLine(kind, state.Buffer, onLine); + chars = chars[(stop + 1)..]; + } + } + + /// 往行缓冲里追加一段;攒满 就先交出去一行。 + private void Append(DockerStreamKind kind, LineState state, ReadOnlySpan segment, Action onLine) + { + StringBuilder buffer = state.Buffer; + while (buffer.Length + segment.Length > MaxLineChars) + { + int take = MaxLineChars - buffer.Length; + // 不把代理对劈开。 + if (take > 0 && char.IsHighSurrogate(segment[take - 1])) + { + take--; + } + if (take > 0) + { + _ = buffer.Append(segment[..take]); + segment = segment[take..]; + } + PublishLine(kind, buffer, onLine); } + _ = buffer.Append(segment); } private void FlushRemainder(DockerStreamKind kind, Action onLine) { - StringBuilder buffer = kind == DockerStreamKind.StdErr ? _stderr : _stdout; + StringBuilder buffer = StateOf(kind).Buffer; if (buffer.Length > 0) { PublishLine(kind, buffer, onLine); @@ -138,7 +225,6 @@ private void PublishLine(DockerStreamKind kind, StringBuilder buffer, Action /// 带 timestamps=1 时,daemon 会在每行前面拼一个 RFC3339 时间戳加一个空格。 /// 把它拆出来交给界面,而不是让时间戳混在正文里被搜索命中。 diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerModels.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerModels.cs index 52a0126..a332df5 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerModels.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerModels.cs @@ -25,7 +25,16 @@ public static class DockerJson NumberHandling = JsonNumberHandling.AllowReadingFromString }; - private static readonly JsonSerializerOptions HumanJson = new() { WriteIndented = true }; + /// + /// 只给人看的缩进 JSON。用宽松转义:默认编码器会把中文写成 \uXXXX、 + /// 把 & + < 也转义掉 —— 那是为嵌进 HTML 准备的, + /// 而这里的输出只进只读文本框,永远不会被当成标记解析。 + /// + private static readonly JsonSerializerOptions HumanJson = new() + { + WriteIndented = true, + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; /// 把一段 JSON 反序列化成 ;失败返回 。 /// @@ -297,6 +306,12 @@ public sealed record ContainerConfig /// 用户。 public string? User { get; init; } + /// + /// 有没有分配 TTY。决定日志与 attach 流是裸字节还是 8 字节多路复用帧 —— + /// 这是容器**创建时**定下的属性,与它现在跑没跑无关。 + /// + public bool Tty { get; init; } + /// 标签。 public Dictionary? Labels { get; init; } @@ -992,7 +1007,7 @@ public double CpuPercent /// /// 不扣缓存的话,一个只是读过大文件的容器会显示成"内存快满了" —— /// docker stats 自己也是这么扣的。cgroup v2 的字段叫 inactive_file, - /// v1 叫 cache;两个都试,取到哪个算哪个。 + /// v1 叫 total_inactive_file(更老的内核只有 cache);按这个顺序试,取到哪个算哪个。 /// /// public ulong MemoryUsed @@ -1006,7 +1021,14 @@ public ulong MemoryUsed ulong cache = 0; if (MemoryStats.Stats is { } stats) { - if (stats.TryGetValue("inactive_file", out ulong inactive)) + // 与 docker CLI 的 calculateMemUsageUnixNoCache 同一顺序: + // v1 先认 total_inactive_file(层级合计),v2 认 inactive_file, + // 都没有才退回 v1 的 cache(老内核上 total_inactive_file 不存在)。 + if (stats.TryGetValue("total_inactive_file", out ulong totalInactive)) + { + cache = totalInactive; + } + else if (stats.TryGetValue("inactive_file", out ulong inactive)) { cache = inactive; } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerRawHttp.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerRawHttp.cs index 6b6e6d1..1bb217d 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerRawHttp.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/DockerRawHttp.cs @@ -23,8 +23,8 @@ internal static class DockerRawHttp /// 请求体;为 null 表示没有体。 /// 是否带 Upgrade: tcp(exec/attach 要)。 /// 取消令牌。 - /// 状态码与"已经把头读完"的流(头之后多读到的字节已经补回流首)。 - public static async Task<(int StatusCode, string ReasonPhrase, Stream Body)> PostAsync( + /// 状态码、响应头原文与"已经把头读完"的流(流正好停在响应体的第一个字节)。 + public static async Task<(int StatusCode, string ReasonPhrase, string Head, Stream Body)> PostAsync( Stream stream, string path, string? jsonBody, bool upgrade, CancellationToken cancellationToken) { byte[] body = jsonBody is null ? [] : Encoding.UTF8.GetBytes(jsonBody); @@ -55,7 +55,7 @@ internal static class DockerRawHttp /// 刻意不做块读:响应头之后紧跟着的就是要交给调用方的裸数据,多读一个字节 /// 就得自己补回去。头很短(几百字节),这点系统调用换来的是零缓冲复杂度。 /// - private static async Task<(int, string, Stream)> ReadResponseHeadAsync(Stream stream, CancellationToken cancellationToken) + private static async Task<(int, string, string, Stream)> ReadResponseHeadAsync(Stream stream, CancellationToken cancellationToken) { var head = new List(512); byte[] one = new byte[1]; @@ -76,6 +76,123 @@ internal static class DockerRawHttp string[] parts = statusLine.Split(' ', 3); int status = parts.Length > 1 && int.TryParse(parts[1], out int code) ? code : 0; string reason = parts.Length > 2 ? parts[2] : ""; - return (status, reason, stream); + return (status, reason, text, stream); + } + + /// 错误响应体最多读这么多 —— 只为拿到 daemon 那句 message。 + private const int MaxErrorBodyBytes = 64 * 1024; + + /// + /// 非 2xx 时把响应体读出来,翻成 daemon 的原话。 + /// + /// 只报 "HTTP 409 Conflict" 等于把最有用的那句 "container ... is not running" 扔了。 + /// 按 Content-Length / chunked 读,最多 64 KB;读不出来就退回状态行。 + /// + /// + public static async Task ReadErrorMessageAsync(int status, string reason, string head, Stream body, + CancellationToken cancellationToken) + { + string text = ""; + // 错误体很短;给它几秒,读不完就算了。超时靠释放流来打断 —— 隧道流的 ReadAsync + // 不一定理会取消令牌,而这条流在出错路径上本来就要被扔掉。 + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(5)); + using (cts.Token.Register(body.Dispose)) + { + try + { + byte[] bytes = await ReadBodyAsync(head, body, cts.Token).ConfigureAwait(false); + text = Encoding.UTF8.GetString(bytes); + } + catch (Exception) when (!cancellationToken.IsCancellationRequested) + { + // 连错误体都读不回来时,至少还有状态行可报。 + } + } + return DockerJson.TryDeserialize(text)?.Message + ?? (text.Trim() is { Length: > 0 } trimmed ? trimmed : $"HTTP {status} {reason}"); + } + + private static async Task ReadBodyAsync(string head, Stream body, CancellationToken cancellationToken) + { + string? contentLength = HeaderValue(head, "Content-Length"); + if (contentLength is not null && long.TryParse(contentLength, out long length)) + { + byte[] buffer = new byte[(int)Math.Clamp(length, 0, MaxErrorBodyBytes)]; + int read = await body.ReadAtLeastAsync(buffer, buffer.Length, throwOnEndOfStream: false, cancellationToken) + .ConfigureAwait(false); + return buffer[..read]; + } + if (HeaderValue(head, "Transfer-Encoding") is { } encoding + && encoding.Contains("chunked", StringComparison.OrdinalIgnoreCase)) + { + using var output = new MemoryStream(); + while (output.Length < MaxErrorBodyBytes) + { + string? sizeLine = await ReadLineAsync(body, cancellationToken).ConfigureAwait(false); + if (sizeLine is null) + { + break; + } + int semicolon = sizeLine.IndexOf(';'); + string hex = (semicolon >= 0 ? sizeLine[..semicolon] : sizeLine).Trim(); + if (!int.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out int size) || size <= 0) + { + break; + } + byte[] chunk = new byte[Math.Min(size, MaxErrorBodyBytes)]; + int read = await body.ReadAtLeastAsync(chunk, chunk.Length, throwOnEndOfStream: false, cancellationToken) + .ConfigureAwait(false); + output.Write(chunk, 0, read); + if (read < chunk.Length || size > chunk.Length) + { + break; + } + _ = await ReadLineAsync(body, cancellationToken).ConfigureAwait(false); + } + return output.ToArray(); + } + // 既无长度也非分块:按 HTTP/1.1 是读到连接关闭。错误响应很短,封顶读就行。 + byte[] rest = new byte[MaxErrorBodyBytes]; + int got = await body.ReadAtLeastAsync(rest, rest.Length, throwOnEndOfStream: false, cancellationToken) + .ConfigureAwait(false); + return rest[..got]; + } + + /// 从响应头原文里取一个头的值(不区分大小写);没有返回 null。 + internal static string? HeaderValue(string head, string name) + { + foreach (string line in head.Split("\r\n")) + { + int colon = line.IndexOf(':'); + if (colon > 0 && line.AsSpan(0, colon).Trim().Equals(name, StringComparison.OrdinalIgnoreCase)) + { + return line[(colon + 1)..].Trim(); + } + } + return null; + } + + private static async Task ReadLineAsync(Stream stream, CancellationToken cancellationToken) + { + var line = new List(16); + byte[] one = new byte[1]; + while (line.Count < 1024) + { + int read = await stream.ReadAsync(one.AsMemory(0, 1), cancellationToken).ConfigureAwait(false); + if (read <= 0) + { + return line.Count == 0 ? null : Encoding.ASCII.GetString([.. line]); + } + if (one[0] == (byte)'\n') + { + break; + } + if (one[0] != (byte)'\r') + { + line.Add(one[0]); + } + } + return Encoding.ASCII.GetString([.. line]); } } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/LineDiff.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/LineDiff.cs index b2eda5c..37361d3 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/LineDiff.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/LineDiff.cs @@ -23,85 +23,243 @@ public enum DiffMarker /// 行内容。 public readonly record struct DiffLine(DiffMarker Marker, int OldNumber, int NewNumber, string Text); +/// +/// 的结果:按顺序的差异行,外加"是不是近似结果"。 +/// +public sealed class LineDiffResult(List lines, bool isApproximate) : IReadOnlyList +{ + /// + /// 改动太散(编辑距离超过 ),中间那段没有逐行对齐, + /// 而是整段标成"删掉旧的、加上新的"。行数统计因此偏大,界面可以据此说明。 + /// + public bool IsApproximate { get; } = isApproximate; + + /// + public DiffLine this[int index] => lines[index]; + + /// + public int Count => lines.Count; + + /// + public IEnumerator GetEnumerator() => lines.GetEnumerator(); + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); +} + /// /// 按行比对两段文本。 /// -/// 用最长公共子序列,不是逐行对齐:在一个配置文件顶部插一行,逐行对齐会把 -/// **之后的每一行**都标成改过,那样的差异视图等于没有。 +/// 求的是最短编辑脚本(等价于最长公共子序列),不是逐行对齐:在一个配置文件顶部插一行, +/// 逐行对齐会把**之后的每一行**都标成改过,那样的差异视图等于没有。 /// /// -/// 面板要比的是配置文件(几十到几千行),LCS 的 O(n·m) 在这个量级上无所谓; -/// 真碰上超大文件,上层的 2 MB 在线编辑上限先一步挡住了。 +/// 算法:先剥掉公共前缀与后缀(编辑一个文件,绝大部分行都在这两段里), +/// 中间剩下的用 Myers 的 O((N+M)·D) 贪心算法 —— D 是编辑距离,改几行就是几。 +/// 以前用的是 O(N·M) 的 LCS 表:5 千行的文件每敲一个键分配约 100 MB,3 万行直接 OOM, +/// 而插件与宿主同进程,OOM 带走的是整个 VelaShell。 +/// D 超过 时不再找最优对齐,退化为整段替换并标记 +/// —— 内存与时间都有硬上限。 /// /// public static class LineDiff { - /// 相邻的一删一增合并成"改过";超过这个规模就不合并了。 + /// 相邻的一删一增合并成"改过";改动行超过这个规模的 4 倍就不合并了。 private const int MaxPairedChange = 200; + /// + /// 精确对齐的编辑距离上限。回溯要保存每一步的 V 数组,内存约 D² 个 int: + /// 1000 对应约 4 MB,时间约 (N+M)·1000 次比较。 + /// + public const int MaxEditDistance = 1000; + /// 比出差异。 - public static IReadOnlyList Compute(string oldText, string newText) + public static LineDiffResult Compute(string oldText, string newText) { string[] a = Split(oldText); string[] b = Split(newText); - int[,] lcs = BuildLcs(a, b); - List result = []; - int i = 0; - int j = 0; - while (i < a.Length && j < b.Length) + // 公共前缀 / 后缀:不进核心算法。 + int prefix = 0; + int limit = Math.Min(a.Length, b.Length); + while (prefix < limit && a[prefix] == b[prefix]) + { + prefix++; + } + int suffix = 0; + while (suffix < limit - prefix && a[a.Length - 1 - suffix] == b[b.Length - 1 - suffix]) + { + suffix++; + } + int n = a.Length - prefix - suffix; + int m = b.Length - prefix - suffix; + + List result = new(Math.Max(a.Length, b.Length) + 1); + for (int k = 0; k < prefix; k++) + { + result.Add(new(DiffMarker.None, k + 1, k + 1, a[k])); + } + bool approximate = false; + if (n > 0 || m > 0) + { + approximate = !TryMyers(a, b, prefix, n, m, result); + } + for (int k = 0; k < suffix; k++) + { + int i = a.Length - suffix + k; + int j = b.Length - suffix + k; + result.Add(new(DiffMarker.None, i + 1, j + 1, a[i])); + } + return new(Pair(result), approximate); + } + + /// 新文里有多少行与原文不同(底部那句"已修改 N 行")。 + public static int CountChanged(IReadOnlyList lines) => + lines.Count(static l => l.Marker != DiffMarker.None); + + /// + /// 对 a[offset..offset+n) 与 b[offset..offset+m) 跑 Myers,把结果追加进 。 + /// 编辑距离超限时改为整段替换并返回 false。 + /// + private static bool TryMyers(string[] a, string[] b, int offset, int n, int m, List output) + { + if (n == 0 || m == 0) + { + AppendReplacement(a, b, offset, n, m, output); + return true; + } + // 先把行映射成整数 id:核心循环里比的是 int,不是字符串。 + var ids = new Dictionary(StringComparer.Ordinal); + int[] x = new int[n]; + int[] y = new int[m]; + for (int i = 0; i < n; i++) + { + x[i] = IdOf(ids, a[offset + i]); + } + for (int j = 0; j < m; j++) + { + y[j] = IdOf(ids, b[offset + j]); + } + + int cap = Math.Min(MaxEditDistance, n + m); + int center = cap + 1; + int[] v = new int[(2 * cap) + 3]; + // trace[d] = 第 d 步开始前 V 在 [-d-1, d+1] 上的快照,回溯时用。 + List trace = []; + int found = -1; + for (int d = 0; d <= cap && found < 0; d++) + { + int[] snapshot = new int[(2 * d) + 3]; + Array.Copy(v, center - d - 1, snapshot, 0, snapshot.Length); + trace.Add(snapshot); + for (int k = -d; k <= d; k += 2) + { + int px = k == -d || (k != d && v[center + k - 1] < v[center + k + 1]) + ? v[center + k + 1] // 从 k+1 往下走:插入 b 的一行 + : v[center + k - 1] + 1; // 从 k-1 往右走:删掉 a 的一行 + int py = px - k; + while (px < n && py < m && x[px] == y[py]) + { + px++; + py++; + } + v[center + k] = px; + if (px >= n && py >= m) + { + found = d; + break; + } + } + } + if (found < 0) + { + AppendReplacement(a, b, offset, n, m, output); + return false; + } + + // 倒着回溯,攒好再翻转。 + List reversed = new(n + m); + int cx = n; + int cy = m; + for (int d = found; d > 0; d--) { - if (a[i] == b[j]) + int[] prev = trace[d]; + int k = cx - cy; + int prevK = k == -d || (k != d && prev[k - 1 + d + 1] < prev[k + 1 + d + 1]) ? k + 1 : k - 1; + int prevX = prev[prevK + d + 1]; + int prevY = prevX - prevK; + while (cx > prevX && cy > prevY) { - result.Add(new(DiffMarker.None, i + 1, j + 1, a[i])); - i++; - j++; + cx--; + cy--; + reversed.Add(new(DiffMarker.None, offset + cx + 1, offset + cy + 1, a[offset + cx])); } - else if (lcs[i + 1, j] >= lcs[i, j + 1]) + if (cx == prevX) { - result.Add(new(DiffMarker.Removed, i + 1, 0, a[i])); - i++; + reversed.Add(new(DiffMarker.Added, 0, offset + prevY + 1, b[offset + prevY])); } else { - result.Add(new(DiffMarker.Added, 0, j + 1, b[j])); - j++; + reversed.Add(new(DiffMarker.Removed, offset + prevX + 1, 0, a[offset + prevX])); } + cx = prevX; + cy = prevY; } - while (i < a.Length) + while (cx > 0 && cy > 0) { - result.Add(new(DiffMarker.Removed, i + 1, 0, a[i])); - i++; + cx--; + cy--; + reversed.Add(new(DiffMarker.None, offset + cx + 1, offset + cy + 1, a[offset + cx])); } - while (j < b.Length) + reversed.Reverse(); + output.AddRange(reversed); + return true; + } + + private static int IdOf(Dictionary ids, string line) + { + ref int slot = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault(ids, line, out bool exists); + if (!exists) { - result.Add(new(DiffMarker.Added, 0, j + 1, b[j])); - j++; + slot = ids.Count; } - return Pair(result); + return slot; } - /// 新文里有多少行与原文不同(底部那句"已修改 N 行")。 - public static int CountChanged(IReadOnlyList lines) => - lines.Count(static l => l.Marker != DiffMarker.None); + /// 整段替换:先列出全部删除,再列出全部新增。 + private static void AppendReplacement(string[] a, string[] b, int offset, int n, int m, List output) + { + for (int i = 0; i < n; i++) + { + output.Add(new(DiffMarker.Removed, offset + i + 1, 0, a[offset + i])); + } + for (int j = 0; j < m; j++) + { + output.Add(new(DiffMarker.Added, 0, offset + j + 1, b[offset + j])); + } + } /// /// 把"紧挨着的一删一增"合并成一条"改过"。 /// /// 改一行的值(listen 80; → listen 8080;)在 LCS 里天然是一删一增, /// 但人看到的是**一行改了**。不合并的话,一个改了三处的文件会显示成六行差异。 + /// 门槛看的是**改动行数**而不是文件总行数 —— 大文件里改一行,也该显示成一行改动。 /// /// private static List Pair(List lines) { + int changes = CountChanged(lines); + if (changes > MaxPairedChange * 4) + { + return lines; + } List paired = [with(lines.Count)]; for (int k = 0; k < lines.Count; k++) { DiffLine current = lines[k]; if (current.Marker == DiffMarker.Removed && k + 1 < lines.Count - && lines[k + 1].Marker == DiffMarker.Added - && lines.Count <= MaxPairedChange * 4) + && lines[k + 1].Marker == DiffMarker.Added) { DiffLine next = lines[k + 1]; paired.Add(new(DiffMarker.Changed, current.OldNumber, next.NewNumber, next.Text)); @@ -115,20 +273,4 @@ private static List Pair(List lines) private static string[] Split(string text) => text.Length == 0 ? [] : text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'); - - private static int[,] BuildLcs(string[] a, string[] b) - { - // lcs[i, j] = a[i..] 与 b[j..] 的最长公共子序列长度。倒着填,回溯时正着走。 - int[,] lcs = new int[a.Length + 1, b.Length + 1]; - for (int i = a.Length - 1; i >= 0; i--) - { - for (int j = b.Length - 1; j >= 0; j--) - { - lcs[i, j] = a[i] == b[j] - ? lcs[i + 1, j + 1] + 1 - : Math.Max(lcs[i + 1, j], lcs[i, j + 1]); - } - } - return lcs; - } -} +} \ No newline at end of file diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/RegistryAuth.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/RegistryAuth.cs index 82c055e..482b2b7 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/RegistryAuth.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/RegistryAuth.cs @@ -51,6 +51,8 @@ public sealed class RegistryAuthProvider(IRemoteFsApi remoteFs, DockerEndpoint e /// /// 规则与 Docker 自己一致:第一段里带 . 或 : 或等于 localhost /// 才算仓库主机,否则整串都是 Docker Hub 上的仓库名。 + /// 显式写出的 docker.io / index.docker.io / registry-1.docker.io + /// 也是 Docker Hub —— config.json 里它们统一记在 这个键下。 /// public static string ResolveRegistry(string imageReference) { @@ -64,7 +66,71 @@ public static string ResolveRegistry(string imageReference) bool isHost = first.Contains('.', StringComparison.Ordinal) || first.Contains(':', StringComparison.Ordinal) || first == "localhost"; - return isHost ? first : DockerHub; + return !isHost || IsDockerHubHost(first) ? DockerHub : first; + } + + /// + /// 把 config.json 里的键或仓库地址归一成主机名,口径同 Docker CLI 的 + /// ConvertToHostname:去掉 http:// / https://,截到第一个 /。 + /// Docker Hub 的几个别名统一归成 docker.io。 + /// + /// + /// 不归一的话,docker login ghcr.io 之外的写法(老版本 CLI 存的 + /// https://ghcr.io、手写的 https://registry.example.com/v2/) + /// 一律匹配不上,表现为"命令行能拉、面板说没有凭据"。 + /// + internal static string NormalizeRegistryHost(string registry) + { + string host = registry.Trim(); + if (host.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) + { + host = host["http://".Length..]; + } + else if (host.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + host = host["https://".Length..]; + } + int slash = host.IndexOf('/'); + if (slash >= 0) + { + host = host[..slash]; + } + host = host.ToLowerInvariant(); + return IsDockerHubHost(host) ? "docker.io" : host; + } + + private static bool IsDockerHubHost(string host) => + host.Equals("docker.io", StringComparison.OrdinalIgnoreCase) + || host.Equals("index.docker.io", StringComparison.OrdinalIgnoreCase) + || host.Equals("registry-1.docker.io", StringComparison.OrdinalIgnoreCase); + + /// + /// 在 config.json 的某张表里找这个仓库:先按原键精确找,再按归一后的主机名找 + /// (与 Docker CLI 的 GetAuthConfig 同一顺序)。 + /// + internal static bool TryFindRegistryEntry(Dictionary? map, string registry, + [System.Diagnostics.CodeAnalysis.MaybeNullWhen(false)] out T value) + { + value = default; + if (map is null) + { + return false; + } + if (map.TryGetValue(registry, out value!)) + { + return true; + } + string wanted = NormalizeRegistryHost(registry); + foreach ((string key, T candidate) in map) + { + if (NormalizeRegistryHost(key) == wanted) + { + value = candidate; + return true; + } + } + value = default; + return false; } /// 查这个镜像所属仓库的登录状态(给表单显示用,不返回凭据本身)。 @@ -77,14 +143,14 @@ public async Task GetStatusAsync(string imageReference, Canc return new(registry, registry == DockerHub ? RegistryAuthState.NotRequired : RegistryAuthState.Missing, "远端没有 ~/.docker/config.json —— 公开仓库不受影响。"); } - if (config.CredHelpers?.ContainsKey(registry) == true || - (!string.IsNullOrEmpty(config.CredsStore) && config.Auths?.ContainsKey(registry) == true && - string.IsNullOrEmpty(config.Auths[registry].Auth))) + bool hasEntry = TryFindRegistryEntry(config.Auths, registry, out DockerAuthEntry? entry); + if (TryFindRegistryEntry(config.CredHelpers, registry, out _) || + (!string.IsNullOrEmpty(config.CredsStore) && hasEntry && string.IsNullOrEmpty(entry!.Auth))) { return new(registry, RegistryAuthState.HelperOnly, "凭据由 credential helper 保管,面板读不到。私有镜像请在终端里 docker pull。"); } - if (config.Auths?.TryGetValue(registry, out DockerAuthEntry? entry) == true && !string.IsNullOrEmpty(entry.Auth)) + if (hasEntry && !string.IsNullOrEmpty(entry!.Auth)) { return new(registry, RegistryAuthState.Available, "凭据来自远端 ~/.docker/config.json"); } @@ -100,10 +166,16 @@ public async Task GetStatusAsync(string imageReference, Canc { string registry = ResolveRegistry(imageReference); DockerConfigFile? config = await ReadConfigAsync(cancellationToken).ConfigureAwait(false); - if (config?.Auths is null || !config.Auths.TryGetValue(registry, out DockerAuthEntry? entry)) + if (config is null || !TryFindRegistryEntry(config.Auths, registry, out DockerAuthEntry? entry)) { return null; } + return BuildAuthHeader(entry, registry); + } + + /// 由一条 config.json 凭据项造 X-Registry-Auth 的值;凭据不全返回 null。 + internal static string? BuildAuthHeader(DockerAuthEntry entry, string registry) + { string? username = entry.Username; string? password = entry.Password; if (!string.IsNullOrEmpty(entry.Auth)) @@ -136,8 +208,10 @@ public async Task GetStatusAsync(string imageReference, Canc }, DockerJson.Options); // Docker 要的是 base64url(RFC 4648 §5)—— 用标准 base64 的话, // 带 + 或 / 的凭据会在头里被截断,表现为一个莫名其妙的 401。 + // 但**补齐的 = 必须留着**:daemon 用 Go 的 base64.URLEncoding(带填充)解码, + // 去掉 = 之后,长度不是 3 的倍数的那三分之二凭据会解出 "unexpected EOF"。 return Convert.ToBase64String(Encoding.UTF8.GetBytes(json)) - .Replace('+', '-').Replace('/', '_').TrimEnd('='); + .Replace('+', '-').Replace('/', '_'); } private async Task ReadConfigAsync(CancellationToken cancellationToken) diff --git a/plugins/VelaShell.Plugin.DockerPanel/Docker/TarUtil.cs b/plugins/VelaShell.Plugin.DockerPanel/Docker/TarUtil.cs index 5399ee5..eb9673f 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Docker/TarUtil.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Docker/TarUtil.cs @@ -1,40 +1,149 @@ +using System.Formats.Tar; using System.Text; namespace VelaShell.Plugin.DockerPanel.Docker; +/// tar 里一个条目的头信息(可带内容)。 +/// 条目名。 +/// 条目类型。 +/// 符号链接 / 硬链接的目标;其它类型为空串。 +/// 权限位(含 setuid / setgid / sticky),如 0755。 +/// 属主 uid。 +/// 属组 gid。 +/// 属主名(ustar / PAX 才有)。 +/// 属组名(ustar / PAX 才有)。 +/// 内容字节数。 +/// 内容;只读头时、或条目不是普通文件时为 。 +internal sealed record TarEntryInfo( + string Name, + TarEntryType Kind, + string LinkName, + int Mode, + int Uid, + int Gid, + string? UserName, + string? GroupName, + long Size, + byte[]? Content) +{ + /// 普通文件。 + public bool IsRegularFile => Kind is TarEntryType.RegularFile or TarEntryType.V7RegularFile or TarEntryType.ContiguousFile; + + /// 符号链接或硬链接 —— 要顺着 再取一次。 + public bool IsLink => Kind is TarEntryType.SymbolicLink or TarEntryType.HardLink; +} + /// /// 只够用的 tar 读写。 /// -/// /containers/{id}/archive 收发的是 tar 流,而 .NET 自带的 -/// System.Formats.Tar 完全能用 —— 这里仍然手写,是因为面板只做**单文件**的 -/// 读与写,手写这一小段换来的是零额外依赖,以及对 Docker 那几个怪癖 -/// (目录项以 / 结尾、长度补齐到 512、两个全零块收尾)的完全掌控。 +/// 写仍然手写:面板只往容器里放**单个文件**,一个 ustar 头加内容就够, +/// 手写这一小段换来的是对 Docker 那几个怪癖(长度补齐到 512、两个全零块收尾)的完全掌控。 +/// 名字、属主名超出 ustar 字段宽度或 id 超出八进制字段范围时,前面加一个 PAX 扩展头 +/// (path / uname / gname / uid / gid)—— +/// 以前是静默截断,超过 99 字节的名字会被写成另一个文件,还可能劈开一个 UTF-8 字符。 +/// +/// +/// 读交给 BCL 的 (System.Formats.Tar,框架自带,不是额外依赖): +/// daemon 吐出来的 tar 由 Go 的 archive/tar 生成,长名字、非 ASCII 名字会带 PAX 头, +/// 老版本还有 GNU 的 L / K 长名条目 —— 这些手写解析要么漏要么错。 /// /// internal static class TarUtil { private const int BlockSize = 512; - /// 把一个文件打成一个最小的 tar(ustar 格式)。 + /// 默认权限 0644(新建文件用)。 + public const int DefaultFileMode = 0b110_100_100; + + /// ustar 八进制 id 字段(7 位八进制)能放下的最大值。 + private const int MaxOctalId = 0x1FFFFF; + + /// 把一个文件打成一个最小的 tar(ustar 格式,必要时带 PAX 扩展头)。 /// tar 内的文件名(不带路径分隔前缀)。 /// 文件内容。 /// 权限位,默认 0644。 /// 修改时间;默认取当前时间。 - public static byte[] CreateSingleFile(string name, ReadOnlySpan content, int mode = 0b110_100_100, - DateTimeOffset? modified = null) + /// 属主 uid,默认 0。 + /// 属组 gid,默认 0。 + /// 属主名;可空。 + /// 属组名;可空。 + public static byte[] CreateSingleFile(string name, ReadOnlySpan content, int mode = DefaultFileMode, + DateTimeOffset? modified = null, int uid = 0, int gid = 0, string? userName = null, string? groupName = null) { ArgumentException.ThrowIfNullOrWhiteSpace(name); + long mtime = (modified ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(); + + // 字段放不下的值走 PAX 扩展头;ustar 头里留一个截短的、不劈字符的近似值。 + List<(string Key, string Value)> pax = []; + if (Encoding.UTF8.GetByteCount(name) > 99) + { + pax.Add(("path", name)); + } + if (userName is not null && Encoding.UTF8.GetByteCount(userName) > 31) + { + pax.Add(("uname", userName)); + } + if (groupName is not null && Encoding.UTF8.GetByteCount(groupName) > 31) + { + pax.Add(("gname", groupName)); + } + if (uid is < 0 or > MaxOctalId) + { + pax.Add(("uid", uid.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + if (gid is < 0 or > MaxOctalId) + { + pax.Add(("gid", gid.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + + byte[]? paxBlock = null; + if (pax.Count > 0) + { + byte[] records = BuildPaxRecords(pax); + int paxPadded = (records.Length + BlockSize - 1) / BlockSize * BlockSize; + paxBlock = new byte[BlockSize + paxPadded]; + byte[] paxHeader = BuildHeader(TruncateUtf8("PaxHeaders/" + name, 99), records.Length, 0b110_100_100, + mtime, 0, 0, null, null, (byte)'x'); + paxHeader.CopyTo(paxBlock, 0); + records.CopyTo(paxBlock, BlockSize); + } + + byte[] header = BuildHeader(TruncateUtf8(name, 99), content.Length, mode, mtime, + uid is < 0 or > MaxOctalId ? 0 : uid, gid is < 0 or > MaxOctalId ? 0 : gid, + userName is null ? null : TruncateUtf8(userName, 31), groupName is null ? null : TruncateUtf8(groupName, 31), + (byte)'0'); + + int padded = (content.Length + BlockSize - 1) / BlockSize * BlockSize; + int prefix = paxBlock?.Length ?? 0; + byte[] result = new byte[prefix + BlockSize + padded + BlockSize * 2]; + paxBlock?.CopyTo(result, 0); + header.CopyTo(result, prefix); + content.CopyTo(result.AsSpan(prefix + BlockSize)); + return result; + } + + private static byte[] BuildHeader(string name, long size, int mode, long mtime, int uid, int gid, + string? userName, string? groupName, byte typeflag) + { byte[] header = new byte[BlockSize]; WriteString(header, 0, 100, name); - WriteOctal(header, 100, 8, (ulong)mode); - WriteOctal(header, 108, 8, 0); // uid - WriteOctal(header, 116, 8, 0); // gid - WriteOctal(header, 124, 12, (ulong)content.Length); // size - WriteOctal(header, 136, 12, (ulong)(modified ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds()); - header[156] = (byte)'0'; // typeflag: 普通文件 + WriteOctal(header, 100, 8, (ulong)(mode & 0xFFF)); + WriteOctal(header, 108, 8, (ulong)uid); + WriteOctal(header, 116, 8, (ulong)gid); + WriteOctal(header, 124, 12, (ulong)size); + WriteOctal(header, 136, 12, (ulong)Math.Max(0, mtime)); + header[156] = typeflag; WriteString(header, 257, 6, "ustar"); header[263] = (byte)'0'; header[264] = (byte)'0'; + if (userName is not null) + { + WriteString(header, 265, 32, userName); + } + if (groupName is not null) + { + WriteString(header, 297, 32, groupName); + } // 校验和的算法要求先把校验和字段当成 8 个空格再求和 —— 顺序反了 tar 会说文件损坏。 for (int i = 148; i < 156; i++) { @@ -47,56 +156,121 @@ public static byte[] CreateSingleFile(string name, ReadOnlySpan content, i } WriteOctal(header, 148, 7, checksum); header[155] = (byte)' '; + return header; + } - int padded = (content.Length + BlockSize - 1) / BlockSize * BlockSize; - byte[] result = new byte[BlockSize + padded + BlockSize * 2]; - header.CopyTo(result, 0); - content.CopyTo(result.AsSpan(BlockSize)); - return result; + /// PAX 记录:"%d %s=%s\n",开头的长度包含它自己的位数。 + private static byte[] BuildPaxRecords(List<(string Key, string Value)> records) + { + using var output = new MemoryStream(); + foreach ((string key, string value) in records) + { + int body = Encoding.UTF8.GetByteCount(key) + Encoding.UTF8.GetByteCount(value) + 3; // ' ' '=' '\n' + int length = body + 1; + while (length != body + length.ToString(System.Globalization.CultureInfo.InvariantCulture).Length) + { + length = body + length.ToString(System.Globalization.CultureInfo.InvariantCulture).Length; + } + byte[] record = Encoding.UTF8.GetBytes($"{length} {key}={value}\n"); + output.Write(record); + } + return output.ToArray(); + } + + /// 截到不超过 个 UTF-8 字节,且不劈开任何字符。 + private static string TruncateUtf8(string value, int maxBytes) + { + if (Encoding.UTF8.GetByteCount(value) <= maxBytes) + { + return value; + } + int bytes = 0; + int index = 0; + while (index < value.Length) + { + int step = char.IsSurrogatePair(value, index) ? 2 : 1; + int size = Encoding.UTF8.GetByteCount(value.AsSpan(index, step)); + if (bytes + size > maxBytes) + { + break; + } + bytes += size; + index += step; + } + return value[..index]; } /// - /// 从一条 tar 流里取出第一个普通文件的内容。 - /// 找不到普通文件返回 (比如路径指的是目录)。 + /// 读 tar 流里的第一个条目(PAX / GNU 扩展头由 合进条目)。 + /// 空归档或流在头部就断了返回 。 /// - public static async Task<(string Name, byte[] Content)?> ReadFirstFileAsync(Stream tar, long maxBytes, + /// tar 流。 + /// 普通文件内容的上限;超过抛 。 + /// 是否把普通文件的内容读出来;为假时只读头。 + /// 取消令牌。 + public static async Task ReadFirstEntryAsync(Stream tar, long maxBytes, bool readContent, CancellationToken cancellationToken) { - byte[] header = new byte[BlockSize]; - while (true) + TarReader reader = new(tar, leaveOpen: true); + await using (reader.ConfigureAwait(false)) { - if (!await ReadExactlyAsync(tar, header, cancellationToken).ConfigureAwait(false)) + TarEntry? entry; + try + { + entry = await reader.GetNextEntryAsync(copyData: false, cancellationToken).ConfigureAwait(false); + } + catch (EndOfStreamException) { return null; } - // 两个全零块 = 归档结束。 - if (header.All(static b => b == 0)) + if (entry is null) { return null; } - string name = ReadString(header, 0, 100); - long size = (long)ReadOctal(header, 124, 12); - char type = (char)header[156]; - int padded = (int)((size + BlockSize - 1) / BlockSize * BlockSize); - if (type is '0' or '\0') + var posix = entry as PosixTarEntry; + byte[]? content = null; + bool regular = entry.EntryType is TarEntryType.RegularFile or TarEntryType.V7RegularFile + or TarEntryType.ContiguousFile; + if (regular && readContent) { - if (size > maxBytes) + if (entry.Length > maxBytes) { throw new InvalidOperationException( - $"文件 {name} 有 {size:N0} 字节,超过了面板允许在线编辑的上限 {maxBytes:N0} 字节。"); + $"文件 {entry.Name} 有 {entry.Length:N0} 字节,超过了面板允许在线编辑的上限 {maxBytes:N0} 字节。"); + } + content = new byte[entry.Length]; + if (entry.DataStream is { } data) + { + int read = await data.ReadAtLeastAsync(content, content.Length, throwOnEndOfStream: false, + cancellationToken).ConfigureAwait(false); + if (read < content.Length) + { + // 内容不完整:不把半个文件交给编辑器,一保存就是数据损坏。 + return null; + } } - byte[] content = new byte[size]; - if (!await ReadExactlyAsync(tar, content, cancellationToken).ConfigureAwait(false)) + else if (content.Length > 0) { return null; } - await SkipAsync(tar, padded - size, cancellationToken).ConfigureAwait(false); - return (name, content); } - await SkipAsync(tar, padded, cancellationToken).ConfigureAwait(false); + return new(entry.Name, entry.EntryType, entry.LinkName ?? "", (int)entry.Mode, entry.Uid, entry.Gid, + posix?.UserName, posix?.GroupName, entry.Length, content); } } + /// + /// 从一条 tar 流里取出第一个条目的内容 —— 它得是普通文件,否则返回 + /// (比如路径指的是目录或符号链接)。 + /// + public static async Task<(string Name, byte[] Content)?> ReadFirstFileAsync(Stream tar, long maxBytes, + CancellationToken cancellationToken) + { + TarEntryInfo? entry = await ReadFirstEntryAsync(tar, maxBytes, readContent: true, cancellationToken) + .ConfigureAwait(false); + return entry is { IsRegularFile: true, Content: { } content } ? (entry.Name, content) : null; + } + /// /// 把 tar 流里第一个普通文件边读边写到目标流,返回写出的字节数; /// 没有普通文件返回 0。 @@ -109,40 +283,51 @@ public static byte[] CreateSingleFile(string name, ReadOnlySpan content, i public static async Task ExtractFirstFileAsync(Stream tar, Stream destination, CancellationToken cancellationToken) { - byte[] header = new byte[BlockSize]; byte[] buffer = new byte[64 * 1024]; - while (true) + TarReader reader = new(tar, leaveOpen: true); + await using (reader.ConfigureAwait(false)) { - if (!await ReadExactlyAsync(tar, header, cancellationToken).ConfigureAwait(false) - || header.All(static b => b == 0)) - { - return 0; - } - long size = (long)ReadOctal(header, 124, 12); - char type = (char)header[156]; - long padded = (size + BlockSize - 1) / BlockSize * BlockSize; - if (type is not ('0' or '\0')) + while (true) { - await SkipAsync(tar, padded, cancellationToken).ConfigureAwait(false); - continue; - } - long remaining = size; - while (remaining > 0) - { - int want = (int)Math.Min(buffer.Length, remaining); - int read = await tar.ReadAsync(buffer.AsMemory(0, want), cancellationToken).ConfigureAwait(false); - if (read <= 0) + TarEntry? entry; + try + { + entry = await reader.GetNextEntryAsync(copyData: false, cancellationToken).ConfigureAwait(false); + } + catch (EndOfStreamException) { - // 流在中途断了。已经写出去的那部分是残缺的,必须说出来 —— - // 一个静默截断的文件比一个下载失败的提示危险得多。 - throw new EndOfStreamException( - $"tar 流在读到 {size - remaining:N0} / {size:N0} 字节时结束了,文件不完整。"); + return 0; } - await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); - remaining -= read; + if (entry is null) + { + return 0; + } + if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile + or TarEntryType.ContiguousFile)) + { + continue; + } + long size = entry.Length; + long remaining = size; + Stream? data = entry.DataStream; + while (remaining > 0) + { + int want = (int)Math.Min(buffer.Length, remaining); + int read = data is null + ? 0 + : await data.ReadAsync(buffer.AsMemory(0, want), cancellationToken).ConfigureAwait(false); + if (read <= 0) + { + // 流在中途断了。已经写出去的那部分是残缺的,必须说出来 —— + // 一个静默截断的文件比一个下载失败的提示危险得多。 + throw new EndOfStreamException( + $"tar 流在读到 {size - remaining:N0} / {size:N0} 字节时结束了,文件不完整。"); + } + await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + remaining -= read; + } + return size; } - await SkipAsync(tar, padded - size, cancellationToken).ConfigureAwait(false); - return size; } } @@ -158,64 +343,4 @@ private static void WriteOctal(byte[] buffer, int offset, int length, ulong valu string text = Convert.ToString((long)value, 8).PadLeft(length - 1, '0'); WriteString(buffer, offset, length, text); } - - private static string ReadString(byte[] buffer, int offset, int length) - { - int end = offset; - while (end < offset + length && buffer[end] != 0) - { - end++; - } - return Encoding.UTF8.GetString(buffer, offset, end - offset); - } - - private static ulong ReadOctal(byte[] buffer, int offset, int length) - { - ulong value = 0; - for (int i = offset; i < offset + length; i++) - { - byte b = buffer[i]; - if (b is 0 or (byte)' ') - { - continue; - } - if (b is < (byte)'0' or > (byte)'7') - { - break; - } - value = value * 8 + (ulong)(b - '0'); - } - return value; - } - - private static async Task SkipAsync(Stream stream, long count, CancellationToken cancellationToken) - { - byte[] scratch = new byte[Math.Min(count, 64 * 1024) is var n && n > 0 ? n : 1]; - long left = count; - while (left > 0) - { - int read = await stream.ReadAsync(scratch.AsMemory(0, (int)Math.Min(left, scratch.Length)), cancellationToken) - .ConfigureAwait(false); - if (read <= 0) - { - return; - } - left -= read; - } - } - - private static async Task ReadExactlyAsync(Stream stream, Memory buffer, CancellationToken cancellationToken) - { - int read = 0; - while (read < buffer.Length) - { - int n = await stream.ReadAsync(buffer[read..], cancellationToken).ConfigureAwait(false); - if (n <= 0) - { - return false; - } - read += n; - } - return true; - } } diff --git a/plugins/VelaShell.Plugin.DockerPanel/PluginMain.cs b/plugins/VelaShell.Plugin.DockerPanel/PluginMain.cs index b5da3d4..8cdefab 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/PluginMain.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/PluginMain.cs @@ -40,16 +40,18 @@ public async Task DeactivateAsync(CancellationToken cancellationToken) { _command?.Dispose(); _command = null; + // 先把字段摘下来再 await:关面板会同步触发 Closed,那边看到字段已空就不会再释放一遍。 + DockerPanelViewModel? viewModel = _viewModel; + _viewModel = null; if (_panel is { } panel) { - await panel.CloseAsync().ConfigureAwait(false); _panel = null; + await panel.CloseAsync().ConfigureAwait(false); } - if (_viewModel is { } viewModel) + if (viewModel is not null) { // 事件流、日志流、统计流、隧道 —— 全都挂在这个对象上,它一走远端就干净了。 await viewModel.DisposeAsync().ConfigureAwait(false); - _viewModel = null; } // 撤掉挂在宿主 Application 上的资源订阅(见 ActivateAsync)。 ThemeBrushes.Detach(); @@ -78,22 +80,49 @@ private async Task OpenPanelAsync() new() { Title = "Docker", Icon = DockerIcon.Panel, DisplayMode = PanelDisplayMode.Document }, () => new DockerPanelView(viewModel), context.Shutdown).ConfigureAwait(false); - _panel.Closed += async () => - { - _panel = null; - await viewModel.DisposeAsync(); - if (ReferenceEquals(_viewModel, viewModel)) - { - _viewModel = null; - } - }; + IPluginPanel panel = _panel; + panel.Closed += () => OnPanelClosed(panel, viewModel, context); await viewModel.InitializeAsync().ConfigureAwait(false); } catch (Exception ex) { context.Log.Error($"failed to open the docker panel: {ex.Message}"); - await viewModel.DisposeAsync().ConfigureAwait(false); + if (ReferenceEquals(_viewModel, viewModel)) + { + _viewModel = null; + await viewModel.DisposeAsync().ConfigureAwait(false); + } + } + } + + /// + /// 面板被用户关掉。 + /// + /// 事件处理器只能是 void,所以这里自己兜住一切:async void 里漏出去的异常 + /// 会直接打到宿主的同步上下文上,把整个 VelaShell 带走。 + /// 释放权只归"把 从这个实例摘下来"的那一方 —— + /// 停用路径先摘了,这里就什么都不做,不会出现两条路径并发释放同一个对象。 + /// + /// + private async void OnPanelClosed(IPluginPanel panel, DockerPanelViewModel viewModel, IPluginContext context) + { + try + { + if (ReferenceEquals(_panel, panel)) + { + _panel = null; + } + if (!ReferenceEquals(_viewModel, viewModel)) + { + return; + } + // 先摘字段、后 await:释放期间再次触发的停用不会再拿到它。 _viewModel = null; + await viewModel.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + context.Log.Error($"failed to dispose the docker panel: {ex.Message}"); } } } diff --git a/plugins/VelaShell.Plugin.DockerPanel/README.md b/plugins/VelaShell.Plugin.DockerPanel/README.md index d37b868..04e7abd 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/README.md +++ b/plugins/VelaShell.Plugin.DockerPanel/README.md @@ -47,6 +47,8 @@ SDK 1.1 的远程执行只有两种**文本**形态:整段 UTF-8 解码,或按 ` 输出干净且"失败"与"没有输出"区分得开。 3. **容器内文件浏览与在线编辑** —— `/archive` 的 tar 流读写单个文件,不经 shell, 因此不受登录 shell、引用规则与 locale 的影响。文件树上带 `docker diff` 的 A/C/D 标记。 + 打开符号链接时顺着链接读目标(最多 8 跳);保存时**沿用原文件的 mode / uid / gid** + 并写到链接指向的真文件上 —— 只有新建的文件才用 0644 root:root。 --- @@ -63,7 +65,8 @@ SDK 1.1 的远程执行只有两种**文本**形态:整段 UTF-8 解码,或按 ` 「浏览卷内文件」借一个已经挂着它的运行中容器去看 —— 不为了看一眼去拉一个 alpine。 - **网络** —— 新建(驱动 / 子网 / 网关 / internal / attachable / IPv6)、接入 / 摘除容器、 删除、清理未使用。内置的 `bridge` / `host` / `none` 删除按钮直接置灰。 -- **Compose** —— 三栏:项目列表 / `compose.yaml` 编辑器 + 服务表 / 执行记录。 +- **Compose** —— 三栏:项目列表 / `compose.yaml` 编辑器 + 服务表 / 执行记录。按路径打开或新建的项目在刷新时保留 + (`compose ls` 只列起过的项目),项目名按 compose 的规则从目录名推(Windows 路径同样认)。 - **系统** —— `system df -v` 的堆叠占用条与明细表、六张回收卡片(按安全 / 注意 / 危险 / 会丢数据分级)、引擎信息。 @@ -75,13 +78,35 @@ SDK 1.1 的远程执行只有两种**文本**形态:整段 UTF-8 解码,或按 ` 事件密集时会合并(350ms 窗口:`compose up` 一次能推来几十条,逐条刷新等于把远端敲成筛子); 流断掉时退化为 30 秒轮询,并且状态栏与徽章都会说清楚 —— 一块静止的、看起来正常的面板, -比明说"没连上"更糟。 +比明说"没连上"更糟。重连时从**最后收到的那条事件**续上(往前多让 1 秒),接上之后再主动刷一次当前页。 + +几条规矩,都是踩过的坑: + +- **只刷当前页,而且只在当前页说要的时候刷。**系统页刻意不跟事件走(`/system/df` 要 daemon 把每个卷 + du 一遍);总览不在前台时也不替它刷 —— 切回去本来就会整页重拉。容器页不在前台时, + 容器列表在后台跟上一次(采样目标与状态栏计数靠它)。 +- **不改变任何列表的容器事件直接丢掉**:`exec_create / exec_start / exec_die / exec_detach`、`top`、 + `attach / detach / resize`、`archive-path / extract-to-dir`、`export`。健康检查每几秒就是一组 `exec_*`, + 面板自己读进程表、读写容器内文件、开终端也会产生它们 —— 拿来触发刷新,轻则白刷,重则成环 + (系统页借容器跑 `df` → `exec_*` → 刷新 → 再跑 `df`)。`health_status` 照常处理。 +- 系统页的"宿主盘"那一句借一个运行中的容器跑 `df`,而 Docker Root Dir 是**宿主**路径, + 在容器里多半不存在。探过一次不行就不再探,换了端点才重来。 +- 当前这条 SSH 会话断开时,面板立刻翻到"会话已断开"那一屏,停掉事件流、采样、日志与终端, + 而不是在一条死掉的会话上无休止地重试。 ### 日志 跟随是真的 `docker logs -f`。攒批更新(每 120ms 交一次),缓冲 512 KB 并**按行**截断 —— 半行开头的日志比少几行更难读。带正则搜索(命中整行着色)、时间戳单列、只看 stderr。 +- 「仅错误」只看 **stderr**,而且只是视图上的筛选:缓冲里的行都还在,关掉就回来。 +- 搜索正则不预编译(每敲一个字就是一个新正则),单行匹配超时 100ms;一行超时就整个停用并说明原因, + 而不是让几千行各等 100ms、或者把超时异常抛到界面线程上。 +- 合并日志最多同时接 **8** 条流 —— 每条 `logs -f` 是一条长连接、占一个 SSH 通道。 + 每个来源的 TTY 取自 inspect 的 `Config.Tty`(创建时定的,按容器 id 缓存), + 不是"在不在跑":TTY 容器的日志是裸字节,当多路复用帧去解就是乱码。 +- 勾选来源停手 250ms 才换流;重开流是串行的,每一代流带着自己的号,上一代被取消时迟到的行直接丢掉。 + ### 进度 三个层级:对话框内的详细进度 → 顶栏任务中心的并行任务 → 状态栏与行内的就地反馈。 @@ -112,11 +137,23 @@ SDK 1.1 的远程执行只有两种**文本**形态:整段 UTF-8 解码,或按 ` --- +### 与宿主几何的偏离 + +宿主的令牌是 36px 文档头 / 26px 列头 / 28px 行 / 24px 状态条。面板有三处刻意不同,依据都是设计稿 +`VelaShell.Plugin.DockerPanel.pen`: + +| 位置 | 面板 | 宿主 | 为什么 | +| --- | --- | --- | --- | +| 列表数据行(容器 / 镜像 / 卷 / 网络) | **32px**(设置里关掉「紧凑行高」是 40px) | 28px | 设计稿 `C/ContainerRow` 是 32:一行里坐着状态点、项目徽标、行内 sparkline 与四颗动作按钮,28px 装不下而不显得挤。「紧凑行高」开关真的作用在这四张表上 | +| 选中条 / 批量进度条 | 32px | — | 它原地替换成批量进度条(设计稿「批量操作 · 选中条原地变进度条」),高度与数据行对齐 | +| 设置抽屉的标题栏 | 40px | 36px | 设计稿「C 设置」的 Panel/H 是 40:抽屉是浮在页面上的独立面板,不是文档头 | + ## 五、已知边界(有意为之) | 边界 | 为什么 | | --- | --- | | 只能管**已经连上**的 SSH 主机 | SDK v1:插件不能自行发起连接。这是契约 | +| 同时跟随的日志源最多 6 条(`DockerClient.MaxFollowStreams`) | 隧道配额每插件 16 条,按"短请求 4 / 长连接 10(事件 1 + 统计流 1 + 跟随日志 6 + 传输 2)/ exec 直连 2"切分。长连接与短请求分池,日志再多也不会把普通请求挤到超时 | | 需要 SDK ≥ 1.2 且 `hostMode = inProcess` | 隧道交出去的是一条活的 `Stream`,跨进程代理不了;面板也要以停靠标签的身份进主窗口 | | Compose 仍走远端的 `docker compose` CLI | **Engine API 里没有 compose 这一块** —— 它是个 CLI 插件,自己读 yml、算依赖顺序,再调一串普通 API。在面板里重写一遍注定与远端那个版本行为不一致 | | **本机端点没有 Compose 页** | 那需要在宿主机上跑进程,不在插件的职责里 | @@ -124,9 +161,10 @@ SDK 1.1 的远程执行只有两种**文本**形态:整段 UTF-8 解码,或按 ` | credential helper 保存的凭据取不到 | 那需要在远端跑一个 helper 可执行文件。界面上会说清楚,私有镜像请先在终端里 `docker pull` | | 控制台是**逐条命令**,不是终端仿真器 | `vim` / `top` 这类要伪终端的程序跑不了 —— 那是终端标签的活儿,面板不假装自己能干 | | 在线编辑只认文本,单文件上限 2 MB | 把一个 ELF 塞进文本编辑器,点一次保存就毁了,而"毁了"要等容器下次启动失败才被发现 | +| 在线编辑只认 **UTF-8**;别的编码只读打开 | 按 UTF-8 宽松解码再写回,解不开的字节全变成 `EF BF BD` —— 一个 GBK 配置文件点一次保存就毁了。BOM 照原样保留;有未保存修改时切文件 / 关编辑器要先确认 | | 界面只有中文 | v0.1 的双语文案表没有迁过来 | | 没有 `docker login` | 口令走命令行会留在进程表与 shell 历史里。私有仓库请先在终端标签里登录 | -| Windows 容器未验证 | 命令与解析按 Linux 写(`ls` 的列格式尤其) | +| Windows 容器未验证 | 命令与解析按 Linux 写(`ls` 的列格式尤其;GNU 与 BusyBox 两种 `ls` 都认) | --- diff --git a/plugins/VelaShell.Plugin.DockerPanel/Syntax/DotEnv.xshd b/plugins/VelaShell.Plugin.DockerPanel/Syntax/DotEnv.xshd index 2e2c304..c3d3bf3 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Syntax/DotEnv.xshd +++ b/plugins/VelaShell.Plugin.DockerPanel/Syntax/DotEnv.xshd @@ -14,9 +14,10 @@ - - - + + diff --git a/plugins/VelaShell.Plugin.DockerPanel/Syntax/Yaml.xshd b/plugins/VelaShell.Plugin.DockerPanel/Syntax/Yaml.xshd index d80a10d..1917cc3 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Syntax/Yaml.xshd +++ b/plugins/VelaShell.Plugin.DockerPanel/Syntax/Yaml.xshd @@ -13,7 +13,9 @@ - + + diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/ConfirmGate.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/ConfirmGate.cs index 6125bca..31e6020 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/ConfirmGate.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/ConfirmGate.cs @@ -264,6 +264,9 @@ public Task AskAsync(ConfirmRequest request) { if (_pending is not null) { + // 拒绝不能是静默的:用户按了「删除」,什么都没发生,他只会再按一次 —— + // 或者以为删掉了。外壳挂在这个事件上,在状态栏里说清楚为什么没反应。 + RejectedWhileBusy?.Invoke(request); return Task.FromResult(false); } _pending = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -296,6 +299,9 @@ public Task AskAsync(ConfirmRequest request) return _pending.Task; } + /// 闸门正开着时又来了一条请求(那一条被拒绝了)。 + public event Action? RejectedWhileBusy; + /// 面板关闭时把等待中的请求当作取消。 public void CancelPending() => Complete(false); diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Converters.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Converters.cs index 9107146..54aa8a0 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Converters.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Converters.cs @@ -95,6 +95,15 @@ public static class Converters /// 键盘选中项的底色。 public static readonly IValueConverter ActiveBackground = new ActiveBackgroundConverter(); + /// + /// 日志搜索命中行的底色。做成单例:写在行模板里的 <ui:MatchBackgroundConverter /> + /// 每画一行就 new 一个,五千行就是五千个一模一样的转换器。 + /// + public static readonly IValueConverter MatchBackground = new MatchBackgroundConverter(); + + /// 日志正文的前景色(stderr 红、stdout 终端前景色),单例的理由同上。 + public static readonly IValueConverter LogLineForeground = new LogLineForegroundConverter(); + /// 非空字符串为 true。 public static readonly IValueConverter NotEmpty = new FuncValueConverter(static v => !string.IsNullOrEmpty(v)); diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Dialogs.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Dialogs.cs index 66ffe72..c896af7 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Dialogs.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Dialogs.cs @@ -197,7 +197,12 @@ public async Task ShowRunContainerAsync(string image) $"{(form.ContainerName.Length > 0 ? form.ContainerName : Humanize.ShortId(created.Id))} · {image}"); await GoToAsync(PanelPage.Containers).ConfigureAwait(true); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (OperationCanceledException) + { + // 从任务中心取消(或面板关闭)也得把任务收尾,不然它会一直挂在"进行中"。 + task.Finish(PanelTaskState.Cancelled, "已取消"); + } + catch (Exception ex) { task.Finish(PanelTaskState.Failed, "失败", ex.Message); Feedback.ReportError("运行容器", ex); diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Events.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Events.cs index 0c19d9c..c2375b5 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Events.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.Events.cs @@ -11,11 +11,32 @@ public sealed partial class DockerPanelViewModel /// 事件流断掉时的兜底轮询间隔。 private static readonly TimeSpan FallbackInterval = TimeSpan.FromSeconds(30); + /// + /// 不改变任何列表内容的容器事件(冒号前的那一段)。 + /// + /// 健康检查每隔几秒就是一组 exec_create / exec_start / exec_die;面板自己读进程表是 + /// top,读写容器内文件是 archive-path / extract-to-dir,开终端是 exec_* + /// 加 resize。拿它们去触发刷新,轻则每几秒白刷一次,重则成环: + /// 系统页刷新时借容器跑一次 df → exec_* 事件 → 再刷新 → 再跑 df…… + /// + /// + private static readonly HashSet IgnoredContainerActions = new(StringComparer.Ordinal) + { + "exec_create", "exec_start", "exec_die", "exec_detach", + "top", "attach", "detach", "resize", "archive-path", "extract-to-dir", "export" + }; + private CancellationTokenSource? _eventCts; private Task? _eventTask; private DispatcherTimer? _coalesceTimer; private DispatcherTimer? _fallbackTimer; private DateTimeOffset _eventsSince; + // 最近一条事件的时刻(Unix 纳秒)。重连时从这里续上,而不是从"现在往前 5 秒" —— + // 退避最长 15 秒,后者会把断线期间的大半截事件漏掉。 + private long _lastEventNanos; + // 合并窗口里来过需要容器列表的事件,而当前页不是容器页:那份列表仍要在后台跟上, + // 采样的目标与状态栏的计数都靠它。 + private bool _containersStale; /// /// 事件流接上了没有。顶栏那枚「实时」徽章绑的就是它 —— @@ -52,26 +73,47 @@ private set ? "事件流已断开,已退化为 30 秒定时刷新 —— 看到的状态最多可能滞后 30 秒。" : "事件流已断开,且自动刷新是关的 —— 现在看到的状态不会自己更新。"; + /// + /// 这条事件是不是"不改变任何列表"的噪声。 + /// 动作串可能带参数(exec_start: sh -c 'curl -f localhost'),只比冒号前那一段。 + /// + internal static bool IsIgnorableEvent(DockerEvent dockerEvent) + { + if (dockerEvent.Type != "container" || dockerEvent.Action is not { Length: > 0 } action) + { + return false; + } + int colon = action.IndexOf(':'); + string verb = (colon >= 0 ? action[..colon] : action).Trim(); + return IgnoredContainerActions.Contains(verb); + } + /// 起事件流。 private void StartEventStream() { - _eventCts = CancellationTokenSource.CreateLinkedTokenSource(Lifetime); + var cts = CancellationTokenSource.CreateLinkedTokenSource(Lifetime); + _eventCts = cts; _eventsSince = DateTimeOffset.UtcNow; - CancellationToken token = _eventCts.Token; + Interlocked.Exchange(ref _lastEventNanos, 0); + CancellationToken token = cts.Token; _eventTask = Task.Run(() => EventLoopAsync(token), token); } - /// 停事件流并等它收尾。 + /// 停事件流并等它收尾。重复调用、并发调用都安全。 private async Task StopEventStreamAsync() { StopTimers(); EventsConnected = false; - if (_eventCts is null) + // 先把字段摘下来再等:等的这段时间里另一次调用进来,看到的已经是"没有流", + // 不会去 Dispose 同一个令牌源,也不会把下一条刚起的流当成旧的掐掉。 + CancellationTokenSource? cts = Interlocked.Exchange(ref _eventCts, null); + Task? task = Interlocked.Exchange(ref _eventTask, null); + if (cts is null) { return; } - await _eventCts.CancelAsync().ConfigureAwait(false); - if (_eventTask is { } task) + await cts.CancelAsync().ConfigureAwait(false); + if (task is not null) { try { @@ -82,9 +124,7 @@ private async Task StopEventStreamAsync() // 收尾时的异常一律吞掉:这条流本来就是被我们掐断的。 } } - _eventCts.Dispose(); - _eventCts = null; - _eventTask = null; + cts.Dispose(); } private async Task EventLoopAsync(CancellationToken token) @@ -92,6 +132,7 @@ private async Task EventLoopAsync(CancellationToken token) // 退避从 1 秒起、封顶 15 秒:daemon 重启时不该被我们每 100ms 敲一次, // 但用户也不该为了看到界面复活而等上一分钟。 var backoff = TimeSpan.FromSeconds(1); + bool reconnecting = false; while (!token.IsCancellationRequested) { DockerClient? client = Client; @@ -103,8 +144,18 @@ private async Task EventLoopAsync(CancellationToken token) { Ui.Post(() => { + if (token.IsCancellationRequested) + { + return; + } EventsConnected = true; StopFallbackTimer(); + // 断过一次:补回来的事件会触发刷新,但断线期间若什么都没发生就不会有事件 —— + // 而兜底轮询也可能刚好没赶上。接上时主动刷一次当前页,不赌这两件事。 + if (reconnecting) + { + _ = RefreshActiveAsync(); + } }); await client.StreamEventsAsync(_eventsSince, OnDockerEvent, token).ConfigureAwait(false); // 流正常结束(daemon 关了连接)也走重连,而不是安静地不再更新。 @@ -119,8 +170,13 @@ private async Task EventLoopAsync(CancellationToken token) Context.Log.Debug($"docker events stream ended: {ex.Message}"); backoff = backoff < TimeSpan.FromSeconds(15) ? backoff * 2 : TimeSpan.FromSeconds(15); } + DateTimeOffset droppedAt = DateTimeOffset.UtcNow; Ui.Post(() => { + if (token.IsCancellationRequested) + { + return; + } EventsConnected = false; StartFallbackTimer(); }); @@ -132,9 +188,15 @@ private async Task EventLoopAsync(CancellationToken token) { return; } - // 重连时从上次收到的那一刻续上,把断线期间发生的事补回来 —— - // 否则界面会漏掉整段"你没看见但确实发生了"的变化。 - _eventsSince = DateTimeOffset.UtcNow.AddSeconds(-5); + // 重连时从上次收到的最后一条事件续上(往前多让 1 秒,宁可重复一条也不漏一条), + // 把断线期间发生的事补回来 —— 否则界面会漏掉整段"你没看见但确实发生了"的变化。 + // 一条事件都没收到过,就从流断掉那一刻往前 1 秒算。 + long lastNanos = Interlocked.Read(ref _lastEventNanos); + DateTimeOffset resumeFrom = lastNanos > 0 + ? DateTimeOffset.FromUnixTimeMilliseconds(lastNanos / 1_000_000) + : droppedAt; + _eventsSince = resumeFrom.AddSeconds(-1); + reconnecting = true; } } @@ -143,32 +205,81 @@ private async Task EventLoopAsync(CancellationToken token) /// private void OnDockerEvent(DockerEvent dockerEvent) { + long nanos = dockerEvent.TimeNano > 0 ? dockerEvent.TimeNano : dockerEvent.Time * 1_000_000_000; + if (nanos > Interlocked.Read(ref _lastEventNanos)) + { + Interlocked.Exchange(ref _lastEventNanos, nanos); + } + if (IsIgnorableEvent(dockerEvent)) + { + return; + } Ui.Post(() => { Overview.AcceptEvent(dockerEvent); + // 只看**当前页**要不要。系统页刻意说"不要"(它的刷新要 daemon 把每个卷 du 一遍), + // 早先"总览要就刷当前页"的写法把这条约定绕过去了。 + // 总览不在前台时不必替它刷:切回总览本来就会整页重拉一次。 bool wanted = ActivePage?.WantsRefresh(dockerEvent) ?? false; - // 总览页永远关心计数,即使它不在前台 —— 用户切回去时不该看到一份旧数字。 - if (!wanted && !Overview.WantsRefresh(dockerEvent)) + if (dockerEvent.Type == "container" && !ReferenceEquals(ActivePage, Containers)) + { + _containersStale = true; + } + if (!wanted && !_containersStale) { return; } - RequestCoalescedRefresh(); + RequestCoalescedRefresh(refreshActive: wanted); }); } + private bool _coalescedActiveRefresh; + /// 把这一刻起 350ms 内的所有刷新请求并成一次。 - private void RequestCoalescedRefresh() + private void RequestCoalescedRefresh(bool refreshActive) { + _coalescedActiveRefresh |= refreshActive; _coalesceTimer ??= CreateTimer(CoalesceWindow, () => { StopCoalesceTimer(); - _ = RefreshActiveAsync(); + bool active = _coalescedActiveRefresh; + bool containers = _containersStale; + _coalescedActiveRefresh = false; + _containersStale = false; + if (active) + { + _ = RefreshActiveAsync(); + } + if (containers && !ReferenceEquals(ActivePage, Containers)) + { + _ = RefreshContainersQuietlyAsync(); + } }); // 重新计时:事件还在涌进来的时候不急着刷,等它停下来那一刻刷一次就够了。 _coalesceTimer.Stop(); _coalesceTimer.Start(); } + /// + /// 容器页不在前台时,在后台把容器列表跟上(一次 /containers/json)。 + /// 总览的 CPU / 内存卡与 Top 5 吃的是它的采样,状态栏的计数也来自它。失败不打扰用户。 + /// + private async Task RefreshContainersQuietlyAsync() + { + if (!IsReady) + { + return; + } + try + { + await Containers.RefreshAsync(Lifetime).ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Context.Log.Debug($"background containers refresh failed: {ex.Message}"); + } + } + private void StartFallbackTimer() { if (!Settings.AutoRefreshFallback || _fallbackTimer is not null) @@ -197,6 +308,8 @@ private void StopTimers() { StopCoalesceTimer(); StopFallbackTimer(); + _coalescedActiveRefresh = false; + _containersStale = false; }); } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.cs index 99930ff..99bdca3 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/DockerPanelViewModel.cs @@ -93,6 +93,9 @@ public sealed partial class DockerPanelViewModel : ObservableObject, IAsyncDispo /// 建外壳。 public DockerPanelViewModel(IPluginContext context) { + // 令牌在构造时取一次存下:令牌源 Dispose 之后再读 .Token 会抛 ObjectDisposedException, + // 而释放之后仍可能有迟到的回调来问"面板还活着吗"。 + Lifetime = _lifetime.Token; Context = context; Settings = new(context.Storage); Confirm = new(); @@ -162,17 +165,50 @@ public DockerPanelViewModel(IPluginContext context) }); ClearFinishedTasksCommand = new RelayCommand(_ => Tasks.ClearFinished()); - RelayCommand.UnhandledCommandError += ex => Feedback.ReportError("操作", ex); - Settings.Changed += () => + // 静态事件:订阅者被它强引用着。不在释放时退订的话,每开一次面板, + // 整张视图模型图(连同它的客户端与页面)就永远留在内存里。 + _commandErrorHandler = ex => Feedback.ReportError("操作", ex); + RelayCommand.UnhandledCommandError += _commandErrorHandler; + Confirm.RejectedWhileBusy += request => Feedback.Status(FeedbackKind.Warning, + $"还有一个确认在等你决定 —— 先处理完它,再来「{request.Title}」。"); + _sparklinesSetting = Settings.InlineSparklines; + Settings.Changed += OnSettingsChanged; + } + + private readonly Action _commandErrorHandler; + private bool _sparklinesSetting; + private int _disposed; + + // 每次 ConnectAsync(以及会话掉线)都把它加一。每个 await 之后对一下号: + // 号变了说明有一次更新的连接(或断开)已经接手,这一次就该收手并把自己建的东西释放掉 —— + // 否则两次重连交错时,会留下两条事件流、一个没人释放的隧道,以及一块显示着错误主机的面板。 + private int _connectGeneration; + + private void OnSettingsChanged() + { + _ = Settings.SaveAsync(Lifetime); + // 「显示已停止」改了要立刻重排列表,不能等下一次刷新。 + Containers.ReapplyView(); + // 「自动刷新兜底」要立刻作用到正在跑(或该跑)的那个定时器上,横幅的话也跟着改口。 + if (!Settings.AutoRefreshFallback) + { + StopFallbackTimer(); + } + else if (EventsDegraded) + { + StartFallbackTimer(); + } + OnPropertiesChanged(nameof(EventsText), nameof(EventsDegradedText)); + // 关掉"实时统计"要立刻停下采样,而不是等下次切页 —— 那个开关的整个卖点就是省远端开销。 + // 只在这一项真的变了时才动:别的设置(日志行数之类)不该顺手把采样重启一遍。 + if (_sparklinesSetting != Settings.InlineSparklines) { - _ = Settings.SaveAsync(_lifetime.Token); - // 关掉"实时统计"要立刻停下采样,而不是等下次切页 —— - // 那个开关的整个卖点就是省远端开销。 + _sparklinesSetting = Settings.InlineSparklines; if (IsReady) { Containers.StartSampling(); } - }; + } } /// 宿主上下文。 @@ -200,7 +236,7 @@ public DockerPanelViewModel(IPluginContext context) public RegistryAuthProvider? RegistryAuth { get; private set; } /// 面板生命周期令牌。 - public CancellationToken Lifetime => _lifetime.Token; + public CancellationToken Lifetime { get; } // ── 端点 ────────────────────────────────────────────────────── @@ -546,9 +582,10 @@ private static string DescribeContainer(ContainerRow row) => /// 面板打开时调用:读设置、列端点、自动连上唯一那个。 public async Task InitializeAsync() { - await Settings.LoadAsync(_lifetime.Token).ConfigureAwait(true); + await Settings.LoadAsync(Lifetime).ConfigureAwait(true); + _sparklinesSetting = Settings.InlineSparklines; Context.Events.SessionConnected += OnSessionChanged; - Context.Events.SessionDisconnected += OnSessionChanged; + Context.Events.SessionDisconnected += OnSessionDisconnected; await ReloadEndpointsAsync().ConfigureAwait(true); // 只有一个可用端点时直接连上 —— 让用户为一个没得选的选择再点一次没有意义。 EndpointItem[] usable = [.. Endpoints.Where(static e => e.Available)]; @@ -564,7 +601,7 @@ public async Task ReloadEndpointsAsync() IReadOnlyList sessions; try { - sessions = await Context.Sessions.ListAsync(_lifetime.Token).ConfigureAwait(true); + sessions = await Context.Sessions.ListAsync(Lifetime).ConfigureAwait(true); } catch (Exception ex) when (ex is not OperationCanceledException) { @@ -585,11 +622,7 @@ public async Task ReloadEndpointsAsync() } Ui.Post(() => { - Endpoints.Clear(); - foreach (EndpointItem item in items) - { - Endpoints.Add(item); - } + MergeEndpoints(items); if (State == PanelConnectionState.NoEndpoint) { SetNoEndpoint(sessions.Count(s => s.State == SessionState.Connected)); @@ -597,37 +630,161 @@ public async Task ReloadEndpointsAsync() }); } + /// 端点的身份:本机只有一个;远端按会话 id。 + private static string EndpointKey(DockerEndpoint endpoint) => + endpoint.Kind == DockerEndpointKind.Local ? "local" : $"ssh:{endpoint.SessionId}"; + + /// + /// 按身份把新列表合进旧列表。 + /// + /// 不能 Clear + Add: 指着的是旧实例,整表重建之后它就成了 + /// 一个不在列表里的孤儿 —— 菜单里看不到选中项,失败页的「重试」改的也是一个没人显示的对象。 + /// 当前连着的那一项保留自己的状态短语("通道已建立"比"已连接"更准)。 + /// + /// + private void MergeEndpoints(IReadOnlyList fresh) + { + Dictionary existing = []; + foreach (EndpointItem item in Endpoints) + { + existing[EndpointKey(item.Endpoint)] = item; + } + List merged = []; + foreach (EndpointItem item in fresh) + { + if (existing.Remove(EndpointKey(item.Endpoint), out EndpointItem? current)) + { + bool keepState = ReferenceEquals(current, SelectedEndpoint) && item.Available + && State is PanelConnectionState.Ready or PanelConnectionState.Failed; + if (!keepState) + { + current.Update(item.Available, item.StateText, item.StateKind); + } + merged.Add(current); + } + else + { + merged.Add(item); + } + } + // 当前选中的端点即使已经从宿主的会话表里消失,也留在列表里(置灰), + // 否则顶栏写着一台菜单里找不到的机器。 + if (SelectedEndpoint is { } selected && !merged.Contains(selected) + && existing.ContainsKey(EndpointKey(selected.Endpoint))) + { + selected.Update(false, "已断开", FeedbackKind.Error); + merged.Add(selected); + } + for (int i = Endpoints.Count - 1; i >= 0; i--) + { + if (!merged.Contains(Endpoints[i])) + { + Endpoints.RemoveAt(i); + } + } + for (int i = 0; i < merged.Count; i++) + { + int at = Endpoints.IndexOf(merged[i]); + if (at < 0) + { + Endpoints.Insert(i, merged[i]); + } + else if (at != i) + { + Endpoints.Move(at, i); + } + } + } + private void OnSessionChanged(SessionInfo session) => _ = ReloadEndpointsAsync(); /// - /// 连到一个端点:建客户端 → 探一次 /version → 起事件流 → 刷新当前页。 + /// 一条会话断了。是**当前**这条的话,面板要立刻承认: + /// 停掉事件流、采样、日志与终端,翻到"会话已断开"那一屏。 + /// + /// 早先这里只是重列一遍端点 —— 状态还停在「已连接」,事件流在一条死掉的会话上无休止地重试, + /// 兜底轮询每 30 秒报一次错,采样每 5 秒失败一次。一块看起来正常、其实全是旧数据的面板。 + /// /// - public async Task ConnectAsync(EndpointItem? item) + private void OnSessionDisconnected(SessionInfo session) { - if (item is null) + Ui.Post(() => + { + if (SelectedEndpoint is { Endpoint: { Kind: DockerEndpointKind.Remote } endpoint } item + && endpoint.SessionId == session.SessionId + && State is PanelConnectionState.Ready or PanelConnectionState.Connecting) + { + _ = HandleSessionLostAsync(item); + } + }); + _ = ReloadEndpointsAsync(); + } + + private async Task HandleSessionLostAsync(EndpointItem item) + { + // 作废任何还在进行中的连接尝试 —— 它们在下一个 await 之后会看到号变了而收手。 + int generation = ++_connectGeneration; + await TearDownConnectionAsync().ConfigureAwait(true); + if (generation != _connectGeneration || Volatile.Read(ref _disposed) != 0) { return; } + SetFailed(new DockerUnreachableException("SSH 会话已断开", DockerUnreachableReason.SessionUnavailable), item); + Feedback.Status(FeedbackKind.Warning, $"{item.DisplayName} 的 SSH 会话已断开"); + } + + /// + /// 拆掉当前连接:事件流、采样、各页(日志 / 终端 / 抽屉随页面一起收)、客户端与 compose 通道。 + /// 字段先置空、再等释放 —— 等的过程中别的路径读到的已经是"没有连接"。 + /// + private async Task TearDownConnectionAsync() + { await StopEventStreamAsync().ConfigureAwait(true); - if (Client is not null) - { - await Client.DisposeAsync().ConfigureAwait(true); - Client = null; - } + Containers.StopSampling(); + DockerClient? old = Client; + Client = null; // 通道跟着连接一起作废 —— 留着旧的,导航栏会显示 Compose 可点, // 点进去却是上一台机器的项目。 Compose = null; + RegistryAuth = null; OnPropertyChanged(nameof(ComposeAvailable)); foreach (PageViewModel page in AllPages) { page.Reset(); } + if (old is not null) + { + await old.DisposeAsync().ConfigureAwait(true); + } + } + + /// + /// 连到一个端点:建客户端 → 探一次 /version → 起事件流 → 刷新当前页。 + /// + public async Task ConnectAsync(EndpointItem? item) + { + if (item is null || Volatile.Read(ref _disposed) != 0) + { + return; + } + // 恢复页上的「重试」、主机菜单、设置里的「应用」都直接调这里,完全可能交错 —— + // 每一次领一个号,之后每个 await 回来都对一下,不是最新的就收手。 + int generation = ++_connectGeneration; SelectedEndpoint = item; State = PanelConnectionState.Connecting; RecoveryActions.Clear(); + await TearDownConnectionAsync().ConfigureAwait(true); + if (generation != _connectGeneration) + { + return; + } DockerEndpoint endpoint = item.Endpoint; - string? remembered = await Settings.GetSocketPathAsync(endpoint.DisplayName, _lifetime.Token).ConfigureAwait(true); + string? remembered = await Settings.GetSocketPathAsync(endpoint.DisplayName, Lifetime).ConfigureAwait(true); + if (generation != _connectGeneration) + { + return; + } if (!string.IsNullOrWhiteSpace(remembered) && remembered != endpoint.SocketPath) { endpoint = endpoint with { SocketPath = remembered }; @@ -640,7 +797,13 @@ public async Task ConnectAsync(EndpointItem? item) var client = new DockerClient(endpoint, transport); try { - SystemVersion version = await client.PingAsync(_lifetime.Token).ConfigureAwait(true); + SystemVersion version = await client.PingAsync(Lifetime).ConfigureAwait(true); + if (generation != _connectGeneration || Volatile.Read(ref _disposed) != 0) + { + // 探活期间已经有更新的一次连接(或断开、或面板关了)接手 —— 这条隧道没人要了。 + await client.DisposeAsync().ConfigureAwait(true); + return; + } Client = client; RegistryAuth = new(Context.RemoteFs, endpoint); // compose 只有 CLI,所以要一条"跑命令"的通道:远端是 SSH,本机是本地进程。 @@ -656,13 +819,30 @@ public async Task ConnectAsync(EndpointItem? item) StartEventStream(); // 容器列表 + 统计采样在后台先跑起来:总览页那几张卡靠它喂, // 而用户可能整段时间都不会点开容器页。 - _ = Containers.PrimeAsync(_lifetime.Token); + _ = Containers.PrimeAsync(Lifetime); await RefreshActiveAsync().ConfigureAwait(true); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (OperationCanceledException) { + // 面板关了:探活中途被掐。隧道要还回去,但这不是一次"连不上"。 + if (!ReferenceEquals(Client, client)) + { + await client.DisposeAsync().ConfigureAwait(true); + } + } + catch (Exception ex) + { + if (ReferenceEquals(Client, client)) + { + // 探活之后的步骤(刷新当前页)失败:连接本身是好的,页面自己会报错,不翻成失败页。 + Feedback.ReportError("连接", ex); + return; + } await client.DisposeAsync().ConfigureAwait(true); - SetFailed(ex, item); + if (generation == _connectGeneration) + { + SetFailed(ex, item); + } } } @@ -685,7 +865,7 @@ private async Task ApplySocketPathAsync() Feedback.Status(FeedbackKind.Warning, "socket 路径不能为空。"); return; } - await Settings.SetSocketPathAsync(item.DisplayName, path, _lifetime.Token).ConfigureAwait(true); + await Settings.SetSocketPathAsync(item.DisplayName, path, Lifetime).ConfigureAwait(true); SettingsOpen = false; OnPropertyChanged(nameof(SocketPathChanged)); await ConnectAsync(item).ConfigureAwait(true); @@ -711,7 +891,7 @@ public async Task SendToHostTerminalAsync(string command) } try { - await Context.Terminal.WriteAsync(endpoint.SessionId, command + "\n", _lifetime.Token) + await Context.Terminal.WriteAsync(endpoint.SessionId, command + "\n", Lifetime) .ConfigureAwait(true); _ = Feedback.Notify(FeedbackKind.Info, "已送到宿主终端", command); } @@ -844,7 +1024,7 @@ or DockerUnreachableReason.PermissionDenied or DockerUnreachableReason.Unknown private async Task RefineFailureAsync(EndpointItem item) { SocketProbeResult probe = await SocketProbe - .RunAsync(Context.RemoteExec, item.Endpoint, _lifetime.Token).ConfigureAwait(true); + .RunAsync(Context.RemoteExec, item.Endpoint, Lifetime).ConfigureAwait(true); // 探测期间用户可能已经换了端点、或者又连上了 —— 那就别再动这一屏。 if (State != PanelConnectionState.Failed || !ReferenceEquals(SelectedEndpoint, item)) { @@ -985,7 +1165,7 @@ public async Task GoToAsync(PanelPage page) { try { - await target.ActivateAsync(_lifetime.Token).ConfigureAwait(true); + await target.ActivateAsync(Lifetime).ConfigureAwait(true); } catch (Exception ex) when (ex is not OperationCanceledException) { @@ -1003,7 +1183,7 @@ public async Task RefreshActiveAsync() } try { - await page.RefreshAsync(_lifetime.Token).ConfigureAwait(true); + await page.RefreshAsync(Lifetime).ConfigureAwait(true); } catch (Exception ex) when (ex is not OperationCanceledException) { @@ -1055,10 +1235,21 @@ public ConfirmRequest BuildConfirm(ConfirmRequest request) => request with }; /// + /// + /// 幂等:宿主关标签时(Closed)与插件停用时(DeactivateAsync)各会调一次。 + /// 第二次进来什么都不做 —— 否则会去 Cancel 一个已经 Dispose 的令牌源。 + /// public async ValueTask DisposeAsync() { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + _connectGeneration++; + RelayCommand.UnhandledCommandError -= _commandErrorHandler; + Settings.Changed -= OnSettingsChanged; Context.Events.SessionConnected -= OnSessionChanged; - Context.Events.SessionDisconnected -= OnSessionChanged; + Context.Events.SessionDisconnected -= OnSessionDisconnected; Confirm.CancelPending(); Tasks.CancelAll(); await _lifetime.CancelAsync().ConfigureAwait(false); @@ -1070,10 +1261,10 @@ public async ValueTask DisposeAsync() await disposable.DisposeAsync().ConfigureAwait(false); } } - if (Client is not null) + if (Client is { } client) { - await Client.DisposeAsync().ConfigureAwait(false); Client = null; + await client.DisposeAsync().ConfigureAwait(false); } _lifetime.Dispose(); } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/LineBuffer.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/LineBuffer.cs index f536a14..1ed655c 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/LineBuffer.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/LineBuffer.cs @@ -25,6 +25,9 @@ public sealed class LineBuffer(ObservableCollection target, int max) private readonly Lock _gate = new(); private readonly List _pending = []; private DispatcherTimer? _timer; + // 定时器已经在走(或者启动请求已经排进 UI 队列)时为 1。早先每一行都 Post 一次 Start —— + // 三千行就是三千个调度任务,攒批省下来的开销又原样花了回去。 + private int _armed; /// 加一行。可以从任何线程调用。 public void Add(T item) @@ -33,7 +36,10 @@ public void Add(T item) { _pending.Add(item); } - Ui.Post(Start); + if (Interlocked.Exchange(ref _armed, 1) == 0) + { + Ui.Post(Start); + } } /// 清空(界面上的和还没交出去的一起)。 @@ -69,21 +75,26 @@ private void OnTick(object? sender, EventArgs e) { // 空转两轮就把定时器停了 —— 一个面板上同时开着好几处日志时, // 常驻的定时器加起来也是一笔开销。 - if (_timer is { } idle) + if (_timer is { IsEnabled: true } idle) { idle.Tick -= OnTick; idle.Stop(); } + // 在锁里放下标志:Add 先进 _pending 再看标志,锁保证两者不会错过彼此。 + Volatile.Write(ref _armed, 0); return; } - batch = [.. _pending]; + // 这一批本身就超过上限(tail=all 的开头常见)时,超出的部分直接不交 —— + // 先加进集合再从头一行一行删,是 O(n²) 的白干。 + int skip = Math.Max(0, _pending.Count - max); + batch = _pending.GetRange(skip, _pending.Count - skip); _pending.Clear(); } foreach (T? item in batch) { target.Add(item); } - // 按行截断:从最旧的开始扔,直到回到上限之内。 + // 按行截断:从最旧的开始扔,直到回到上限之内(最多扔这一批的行数)。 while (target.Count > max) { target.RemoveAt(0); diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Mvvm.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Mvvm.cs index 19fa3af..c4f4a90 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Mvvm.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Mvvm.cs @@ -198,35 +198,116 @@ public sealed class KeyedCollection(Func keySelector) : Observable /// /// 新快照(顺序即目标顺序)。 /// 把新数据合并进旧实例。 - public void Merge(IReadOnlyList snapshot, Action update) + public void Merge(IReadOnlyList snapshot, Action update) => + MergeCore(snapshot, (current, incoming) => + { + update(current, incoming); + return current; + }); + + /// + /// 与 同一套就地合并,但给不可变的项用:同 key 而内容变了的项 + /// **换成新实例**(一次 Replace 通知),内容没变的保留原实例。 + /// + /// 新快照(顺序即目标顺序)。 + public void MergeReplacing(IReadOnlyList snapshot) => + MergeCore(snapshot, static (current, incoming) => + EqualityComparer.Default.Equals(current, incoming) ? current : incoming); + + /// + /// 合并的本体。 + /// + /// 先删掉消失的项,再从前往后对齐 —— 顺序不变时(绝大多数刷新都是这样)每一项都是 + /// "原地就是它",整轮 O(n)。早先的写法边插边找(每项一次 IndexOf), + /// 而插入与移动会让后面的下标全部漂移,几百行的列表每次刷新都是 O(n²)。 + /// + /// + private void MergeCore(IReadOnlyList snapshot, Func resolve) { - Dictionary existing = []; - foreach (T? item in this) + HashSet incomingKeys = new(snapshot.Count); + foreach (T item in snapshot) { - existing[keySelector(item)] = item; + _ = incomingKeys.Add(keySelector(item)); + } + for (int i = Count - 1; i >= 0; i--) + { + if (!incomingKeys.Contains(keySelector(this[i]))) + { + RemoveAt(i); + } } for (int i = 0; i < snapshot.Count; i++) { - T? incoming = snapshot[i]; + T incoming = snapshot[i]; string key = keySelector(incoming); - if (existing.TryGetValue(key, out T? current)) + int at = -1; + // 已经对齐的前缀不必再看:要找的那一项只可能在 i 及其之后。 + for (int j = i; j < Count; j++) { - update(current, incoming); - int at = IndexOf(current); - if (at != i && at >= 0) + if (keySelector(this[j]) == key) { - Move(at, i); + at = j; + break; } - _ = existing.Remove(key); } - else + if (at < 0) { Insert(i, incoming); + continue; + } + if (at != i) + { + Move(at, i); + } + T current = this[i]; + T resolved = resolve(current, incoming); + if (!ReferenceEquals(resolved, current)) + { + this[i] = resolved; } } - foreach (T? stale in existing.Values) + // 快照里有重复 key 时,多出来的旧项会剩在尾巴上。 + while (Count > snapshot.Count) { - _ = Remove(stale); + RemoveAt(Count - 1); } } } + +/// +/// 把"从任何线程来的、很密的界面更新请求"压成每个间隔最多一次。 +/// +/// 拉取 / 推送 / 导入的进度帧一秒能来上百条,每条一次 就是上百次调度、 +/// 上百次布局 —— 而人眼只需要每 100ms 看到一次新数字。 +/// +/// +/// 在 UI 线程上执行的更新。 +/// 最短间隔。 +public sealed class UiThrottle(Action action, TimeSpan interval) +{ + private int _queued; + + /// 用默认的 100ms 间隔。 + public UiThrottle(Action action) : this(action, TimeSpan.FromMilliseconds(100)) + { + } + + /// 请求一次更新。已经排着一次时什么都不做。可以从任何线程调用。 + public void Request() + { + if (Interlocked.Exchange(ref _queued, 1) != 0) + { + return; + } + _ = Task.Delay(interval).ContinueWith(_ => Ui.Post(Run), TaskScheduler.Default); + } + + /// 立刻在 UI 线程上执行一次(收尾时用,免得最后那一帧要再等一个间隔)。 + public void Flush() => Ui.Post(Run); + + private void Run() + { + Volatile.Write(ref _queued, 0); + action(); + } +} diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/PageViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/PageViewModel.cs index 9880796..36a11ff 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/PageViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/PageViewModel.cs @@ -34,11 +34,30 @@ public enum PanelPage /// 就能同时喂饱所有页面,而不是每页各挂一个定时器把远端敲成筛子。 /// /// -public abstract class PageViewModel(DockerPanelViewModel shell) : ObservableObject +public abstract class PageViewModel : ObservableObject { + /// 建页面。 + protected PageViewModel(DockerPanelViewModel shell) + { + Shell = shell; + // 设置里的「紧凑行高」改了,列表行要跟着变 —— 行模板绑的是这一页的 RowHeight。 + shell.Settings.PropertyChanged += (_, e) => + { + if (e.PropertyName is nameof(PanelSettings.RowHeight)) + { + OnPropertyChanged(nameof(RowHeight)); + } + }; + } /// 外壳(拿客户端、闸门、任务中心、反馈)。 - protected DockerPanelViewModel Shell { get; } = shell; + protected DockerPanelViewModel Shell { get; } + + /// + /// 列表数据行的行高(设置里的「紧凑行高」:32 / 40)。 + /// 32 取自设计稿 C/ContainerRow,与宿主 28px 的偏离见 README。 + /// + public double RowHeight => Shell.Settings.RowHeight; /// 当前端点的客户端;还没连上时为 。 protected DockerClient? Client => Shell.Client; diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ComposePageViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ComposePageViewModel.cs index 01f6430..1bcca06 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ComposePageViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ComposePageViewModel.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Collections.ObjectModel; using Avalonia.Controls; using VelaShell.Plugin.DockerPanel.Docker; @@ -121,7 +122,14 @@ public sealed class ComposePageViewModel : PageViewModel private readonly LineBuffer _output; private readonly LineBuffer _logs; // 服务列表里没有的日志来源(已删掉的容器、一次性任务),各自也要一个稳定的颜色序号。 - private readonly Dictionary _extraSources = []; + // 它在读日志流的线程上被写,在 UI 线程上被清 —— 所以是并发字典。 + private readonly ConcurrentDictionary _extraSources = new(StringComparer.Ordinal); + // 服务名 / 容器名 → 颜色序号的不可变快照。每次服务列表变了在 UI 线程上整份换掉; + // 读日志流的线程只读这份快照,不去枚举 UI 线程随时在改的 Services。 + private IReadOnlyDictionary _sourceIndex = new Dictionary(); + private int _extraNext; + // 按路径打开 / 新建出来的项目。compose ls 只列"起过的"项目,刷新时不能把它们冲掉。 + private readonly Dictionary _manualProjects = new(StringComparer.Ordinal); private int _lastExitCode; /// 当前页签。 @@ -285,7 +293,7 @@ public ComposePageViewModel(DockerPanelViewModel shell) : base(shell) public override string Title => "Compose"; /// 项目。 - public ObservableCollection Projects { get; } = []; + public KeyedCollection Projects { get; } = new(static p => p.Name); /// 选中项目的服务。 public ObservableCollection Services { get; } = []; @@ -460,11 +468,25 @@ public override async Task RefreshAsync(CancellationToken cancellationToken) ? await compose.ListProjectsAsync(cancellationToken).ConfigureAwait(true) : []; string? keep = Selected?.Name; - Projects.Clear(); - foreach (ComposeProject? project in projects.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase)) + // 当前选中的项目即使从 compose ls 里消失了(刚 down 掉),也留在列表里 —— + // 否则右侧还开着它的 compose.yaml(也许还有没保存的修改),左边却找不到它。 + if (Selected is { } current && projects.All(p => p.Name != current.Name)) { - Projects.Add(project); + _manualProjects.TryAdd(current.Name, current); } + // 按 key 就地合并,而不是 Clear + Add:那会把按路径打开的项目冲掉, + // 每来一条容器事件,选中项都会变成一个不在列表里的孤儿。 + Dictionary merged = new(StringComparer.Ordinal); + foreach (ComposeProject project in projects) + { + merged[project.Name] = project; + } + foreach ((string name, ComposeProject project) in _manualProjects) + { + // compose ls 认得它了(起过了)就以 ls 的为准 —— 状态串是真的。 + merged.TryAdd(name, project); + } + Projects.MergeReplacing([.. merged.Values.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase)]); LoadedOnce = true; OnPropertyChanged(nameof(IsEmpty)); if (keep is not null && Projects.FirstOrDefault(p => p.Name == keep) is { } same) @@ -486,11 +508,16 @@ public override async Task RefreshAsync(CancellationToken cancellationToken) /// public override void Reset() { + // 先掐掉上一台主机的 compose logs -f:不掐的话它会继续往新主机的日志页里写。 + CancelLogs(); Projects.Clear(); + _manualProjects.Clear(); Services.Clear(); + PublishSourceIndex(); _output.Clear(); _logs.Clear(); _extraSources.Clear(); + Volatile.Write(ref _extraNext, 0); Selected = null; Yaml = ""; _originalYaml = ""; @@ -524,6 +551,7 @@ private async Task SelectAsync(ComposeProject project) _logs.Clear(); // 换项目就换一组服务,旧的颜色序号留着只会让新项目的颜色对不上名字。 _extraSources.Clear(); + Volatile.Write(ref _extraNext, 0); Tab = ComposeTab.Yaml; await LoadServicesAsync(project, Shell.Lifetime).ConfigureAwait(true); await LoadYamlAsync(project).ConfigureAwait(true); @@ -694,8 +722,9 @@ private async Task ToggleLogsAsync() { return; } - _logsCts = CancellationTokenSource.CreateLinkedTokenSource(Shell.Lifetime); - CancellationToken token = _logsCts.Token; + var cts = CancellationTokenSource.CreateLinkedTokenSource(Shell.Lifetime); + _logsCts = cts; + CancellationToken token = cts.Token; LogsFollowing = true; string tail = Shell.Settings.LogTail; _ = Task.Run(async () => @@ -703,7 +732,14 @@ private async Task ToggleLogsAsync() try { _ = await compose.FollowLogsAsync(project, tail == "all" ? "all" : tail, - new DirectProgress(output => _logs.Add(MergedLine(output))), token) + new DirectProgress(output => + { + // 被掐掉之后到达的行不再收:换了项目 / 换了主机,它们属于上一个。 + if (!token.IsCancellationRequested) + { + _logs.Add(MergedLine(output)); + } + }), token) .ConfigureAwait(false); } catch (OperationCanceledException) @@ -711,10 +747,23 @@ private async Task ToggleLogsAsync() } catch (Exception ex) { - _logs.Add(new(DateTimeOffset.Now.ToString("HH:mm:ss"), - $"日志流断开:{ex.Message}", true, false)); + if (!token.IsCancellationRequested) + { + _logs.Add(new(DateTimeOffset.Now.ToString("HH:mm:ss"), + $"日志流断开:{ex.Message}", true, false)); + } } - Ui.Post(() => LogsFollowing = false); + // 只有**这一条**流还是当前那条时才改状态:旧流的收尾晚到, + // 会把刚开起来的新流标成"没在跟随"。 + Ui.Post(() => + { + if (ReferenceEquals(_logsCts, cts)) + { + _logsCts = null; + cts.Dispose(); + LogsFollowing = false; + } + }); }, token); } @@ -727,61 +776,71 @@ private async Task ToggleLogsAsync() /// private OutputLine MergedLine(ExecOutput output) { - (string? source, string? body) = MergedLog.Split(output.Line, IsKnownSource); + // 在读流的线程上:只碰不可变快照与并发字典。 + IReadOnlyDictionary index = Volatile.Read(ref _sourceIndex); + (string? source, string? body) = MergedLog.Split(output.Line, + name => index.ContainsKey(name) || _extraSources.ContainsKey(name)); return new(DateTimeOffset.Now.ToString("HH:mm:ss"), body, - output.Stream == ExecStream.StandardError, false, source, SourceIndex(source)); + output.Stream == ExecStream.StandardError, false, source, SourceIndex(index, source)); } /// - /// 这个前缀是不是本项目里的一个服务。 + /// 按当前服务列表发布一份"名字 → 颜色序号"的快照。只在 UI 线程上调用(服务列表变了之后)。 /// /// compose logs 的前缀有时是服务名、有时是容器名(取决于 compose 的版本与 - /// container_name 有没有写),两个都认。 + /// container_name 有没有写),两个都登记。 /// /// - private bool IsKnownSource(string name) + private void PublishSourceIndex() { - foreach (ComposeService service in Services) + Dictionary index = new(StringComparer.Ordinal); + for (int i = 0; i < Services.Count; i++) { - if (service.Service == name || service.Name == name) - { - return true; - } + _ = index.TryAdd(Services[i].Service, i); + _ = index.TryAdd(Services[i].Name, i); } - return _extraSources.ContainsKey(name); + Volatile.Write(ref _sourceIndex, index); } - private int SourceIndex(string source) + /// + /// 这个前缀是不是本项目里的一个服务。 + /// + /// compose logs 的前缀有时是服务名、有时是容器名(取决于 compose 的版本与 + /// container_name 有没有写),两个都认。 + /// + /// + private int SourceIndex(IReadOnlyDictionary index, string source) { if (source.Length == 0) { return 0; } - for (int i = 0; i < Services.Count; i++) - { - if (Services[i].Service == source || Services[i].Name == source) - { - return i; - } - } - // 服务列表里没有的来源(还没刷新到的、一次性任务),各自也要一个稳定的序号。 - if (!_extraSources.TryGetValue(source, out int extra)) + if (index.TryGetValue(source, out int known)) { - extra = Services.Count + _extraSources.Count; - _extraSources[source] = extra; + return known; } - return extra; + // 服务列表里没有的来源(还没刷新到的、一次性任务),各自也要一个稳定的序号: + // 排在全部服务之后,按第一次出现的先后。 + return _extraSources.GetOrAdd(source, static (_, self) => + Volatile.Read(ref self._sourceIndex).Count + Interlocked.Increment(ref self._extraNext) - 1, this); } - private async Task StopLogsAsync() + private Task StopLogsAsync() + { + CancelLogs(); + return Task.CompletedTask; + } + + /// 掐掉正在跟随的 compose logs(同步完成:Reset 里等不起)。 + private void CancelLogs() { if (_logsCts is not { } cts) { return; } - await cts.CancelAsync().ConfigureAwait(true); - cts.Dispose(); _logsCts = null; + cts.Cancel(); + cts.Dispose(); LogsFollowing = false; } @@ -810,7 +869,8 @@ await compose.WriteFileAsync(path, NewComposeProjectForm.Skeleton(form.ProjectNa Log($"✔ 已创建 {path}"); _ = Shell.Feedback.Notify(FeedbackKind.Success, "项目已创建", $"{path} —— 改完 compose.yaml 之后按 up -d 起它。"); - await OpenPathAsync(path).ConfigureAwait(true); + // 带上表单里的项目名:骨架里写的就是它,按目录名重新推一遍可能对不上。 + await OpenPathAsync(path, form.ProjectName).ConfigureAwait(true); } catch (Exception ex) when (ex is not OperationCanceledException) { @@ -830,6 +890,7 @@ private async Task LoadServicesAsync(ComposeProject project, CancellationToken c { Services.Add(service); } + PublishSourceIndex(); } private async Task LoadYamlAsync(ComposeProject project) @@ -1035,20 +1096,54 @@ private async Task OpenByPathAsync() /// 把一个 compose 文件加进项目列表并选中它。 private async Task OpenPathAsync(string filePath, string? projectName = null) { - // compose 的项目名默认取项目目录名 —— 与 compose 自己的规则一致, - // 不一致的话面板起的容器会带上一个和命令行不同的前缀。 - string directory = filePath[..Math.Max(0, filePath.LastIndexOf('/'))]; - string name = projectName is { Length: > 0 } given - ? given - : directory[(directory.LastIndexOf('/') + 1)..]; - var project = new ComposeProject(name, "(未起过)", filePath); - if (Projects.All(p => p.PrimaryFile != filePath)) + string name = projectName is { Length: > 0 } given ? given.Trim() : DeriveProjectName(filePath); + if (name.Length == 0) { - Projects.Add(project); + Shell.Feedback.Status(FeedbackKind.Warning, $"从 {filePath} 推不出项目名 —— 请在表单里填一个。"); + return; + } + // 同一个文件已经在列表里(compose ls 列出来的,或者之前打开过)就直接选它。 + ComposeProject project = Projects.FirstOrDefault(p => p.PrimaryFile == filePath) + ?? Projects.FirstOrDefault(p => p.Name == name) + ?? new ComposeProject(name, "(未起过)", filePath); + if (!Projects.Contains(project)) + { + // 记下来:compose ls 只列起过的项目,下一次刷新不能把它冲掉。 + _manualProjects[project.Name] = project; + int at = 0; + while (at < Projects.Count && StringComparer.OrdinalIgnoreCase.Compare(Projects[at].Name, project.Name) < 0) + { + at++; + } + Projects.Insert(at, project); } await SelectAsync(project).ConfigureAwait(true); OnPropertyChanged(nameof(IsEmpty)); } + + /// + /// 按 compose 自己的规则从文件路径推项目名:取所在目录名,转小写,只留字母、数字、- 与 _, + /// 去掉开头不是字母数字的部分。 + /// + /// 两种分隔符都认(本机端点上是 D:\stacks\web\compose.yaml):早先只按 / 切, + /// Windows 路径推出来是空串,于是下发的是 compose -p "",当场失败。 + /// 不归一化的话,目录名里的大写与空格会让 compose 拒绝这个名字,或者起出和命令行不同前缀的容器。 + /// + /// + internal static string DeriveProjectName(string filePath) + { + string directory = ComposePath.DirectoryOf(filePath); + string segment = directory == filePath.TrimEnd('/', '\\') ? "" : ComposePath.LastSegment(directory); + var sb = new System.Text.StringBuilder(segment.Length); + foreach (char c in segment.ToLowerInvariant()) + { + if (char.IsAsciiLetterOrDigit(c) || ((c is '-' or '_') && sb.Length > 0)) + { + _ = sb.Append(c); + } + } + return sb.ToString(); + } } /// 按路径打开一个 compose 项目。 @@ -1098,7 +1193,7 @@ public string ProjectName return explicitName; } // 项目名默认取**文件所在目录**的名字 —— compose 自己也是这么推的。 - return ComposePath.LastSegment(ComposePath.DirectoryOf(FilePath)); + return ComposePageViewModel.DeriveProjectName(FilePath); } } @@ -1172,7 +1267,7 @@ public NewComposeProjectForm(bool isLocal) public string Directory => _directory.Value.Trim(); /// 项目名。 - public string ProjectName => _name.Value.Trim() is { Length: > 0 } explicitName ? explicitName : ComposePath.LastSegment(Directory); + public string ProjectName => _name.Value.Trim() is { Length: > 0 } explicitName ? explicitName : ComposePageViewModel.DeriveProjectName(ComposePath.Combine(Directory, "compose.yaml")); /// 骨架内容。注释里写清下一步该干什么,而不是丢一个空文件给用户。 public static string Skeleton(string projectName) => diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerDetailViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerDetailViewModel.cs index f63f54c..2919d84 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerDetailViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerDetailViewModel.cs @@ -45,9 +45,15 @@ public enum DetailTab public sealed class ContainerDetailViewModel : ObservableObject, IAsyncDisposable { private readonly DockerPanelViewModel _shell; + // 抽屉自己的生命周期:关抽屉(DisposeAsync)时取消。抽屉里发出去的每个请求都挂在它上面 —— + // 早先挂的是整个面板的生命周期,抽屉关了、加载却还在跑,回来之后又起了一条没人收的 stats 流。 + private readonly CancellationTokenSource _life; + private readonly CancellationToken _lifeToken; private CancellationTokenSource? _statsCts; private ContainerRow _row; private ContainerInspect? _inspect; + private Task? _loadTask; + private bool _disposed; /// 建抽屉。 public ContainerDetailViewModel(DockerPanelViewModel shell, ContainersPageViewModel page, ContainerRow row) @@ -55,12 +61,14 @@ public ContainerDetailViewModel(DockerPanelViewModel shell, ContainersPageViewMo _shell = shell; Owner = page; _row = row; - Logs = new(shell, row.Id, () => _inspect?.Config is not null && IsTty); + _life = CancellationTokenSource.CreateLinkedTokenSource(shell.Lifetime); + _lifeToken = _life.Token; + Logs = new(shell, row.Id, () => IsTty); Files = new(shell, row.Id, row.Name); Terminal = new(shell, row.Id, row.Name); SetTabCommand = new RelayCommand(p => p is DetailTab tab ? SetTabAsync(tab) : Task.CompletedTask); - RefreshProcessesCommand = new RelayCommand(_ => RefreshProcessesAsync(_shell.Lifetime)); + RefreshProcessesCommand = new RelayCommand(_ => RefreshProcessesAsync(_lifeToken)); CloseCommand = new RelayCommand(_ => page.CloseDetailCommand.Execute(null)); CommitCommand = new RelayCommand(_ => CommitAsync()); ToggleRawCommand = new RelayCommand(_ => ShowRaw = !ShowRaw); @@ -106,8 +114,12 @@ public ContainerDetailViewModel(DockerPanelViewModel shell, ContainersPageViewMo /// 暂停按钮的文字(暂停 / 恢复)。 public string PauseLabel => IsPaused ? "恢复" : "暂停"; - /// 容器有没有分配 TTY —— 决定日志与 exec 的解帧方式。 - public bool IsTty { get => _inspect?.Config is not null && _row.Summary.State == "running" && field; private set; } + /// + /// 容器有没有分配 TTY —— 决定日志的解帧方式。取自 inspect 的 Config.Tty: + /// 那是**创建时**定下的,跟容器现在跑没跑无关。早先这里还要求"在跑", + /// 于是已停止的 TTY 容器的日志被当成多路复用帧去解,读出来是一串乱码。 + /// + public bool IsTty => _inspect?.Config?.Tty == true; /// 当前页签。 public DetailTab Tab @@ -401,15 +413,29 @@ private async Task CommitAsync() public RelayCommand RestartPolicyCommand { get; } /// 加载详情。 - public async Task LoadAsync(CancellationToken cancellationToken) + public Task LoadAsync(CancellationToken cancellationToken) { - if (_shell.Client is not { } client) + Task load = LoadCoreAsync(cancellationToken); + _loadTask = load; + return load; + } + + private async Task LoadCoreAsync(CancellationToken cancellationToken) + { + if (_disposed || _shell.Client is not { } client) + { + return; + } + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _lifeToken); + // 原文只取一次,结构化的那份从原文解出来 —— 早先是两次请求拿同一份 JSON。 + string raw = await client.InspectContainerRawAsync(ContainerId, linked.Token).ConfigureAwait(true); + if (_disposed) { return; } - _inspect = await client.InspectContainerAsync(ContainerId, cancellationToken).ConfigureAwait(true); - RawInspect = await client.InspectContainerRawAsync(ContainerId, cancellationToken).ConfigureAwait(true); - IsTty = RawInspect.Contains("\"Tty\": true", StringComparison.Ordinal); + _inspect = DockerJson.TryDeserialize(raw) + ?? throw new InvalidDataException("daemon 返回的 inspect 不是可解析的 JSON。"); + RawInspect = raw; BuildOverview(); if (IsRunning) { @@ -417,6 +443,23 @@ public async Task LoadAsync(CancellationToken cancellationToken) } } + /// 等第一次加载落地(TTY 等信息要靠它);加载失败不在这里报,那是打开抽屉那一步的事。 + private async Task AwaitLoadAsync() + { + if (_loadTask is not { IsCompleted: false } load) + { + return; + } + try + { + await load.ConfigureAwait(true); + } + catch (Exception) + { + // 由 OpenDetailAsync 报。 + } + } + /// 切到某个页签(右键菜单与命令面板从外面调)。 public Task GoToTabAsync(DetailTab tab) => SetTabAsync(tab); @@ -430,6 +473,10 @@ public async Task OpenFilesAtAsync(string path) /// 列表刷新后同步这一行的新状态。 public void ApplySummary(ContainerRow row) { + if (_disposed) + { + return; + } _row = row; OnPropertiesChanged(nameof(Name), nameof(Status), nameof(Tone), nameof(IsRunning), nameof(IsPaused), nameof(PauseLabel), nameof(ComposePath), nameof(HasCompose)); @@ -533,6 +580,12 @@ private async Task SetTabAsync(DetailTab tab) switch (tab) { case DetailTab.Logs: + // 日志的解帧方式取决于 inspect 里的 TTY:抽屉刚打开就点日志时,先等 inspect 落地。 + await AwaitLoadAsync().ConfigureAwait(true); + if (_disposed) + { + return; + } await Logs.EnsureStartedAsync().ConfigureAwait(true); break; case DetailTab.Files: @@ -542,7 +595,7 @@ private async Task SetTabAsync(DetailTab tab) await Terminal.EnsureStartedAsync().ConfigureAwait(true); break; case DetailTab.Stats: - await RefreshProcessesAsync(_shell.Lifetime).ConfigureAwait(true); + await RefreshProcessesAsync(_lifeToken).ConfigureAwait(true); break; } } @@ -570,6 +623,10 @@ private async Task RefreshProcessesAsync(CancellationToken cancellationToken) { ContainerTopResult top = await client.TopAsync(ContainerId, cancellationToken: cancellationToken) .ConfigureAwait(true); + if (_disposed) + { + return; + } Processes.Clear(); foreach (ProcessRow row in ProcessTable.Normalize(top)) { @@ -578,6 +635,10 @@ private async Task RefreshProcessesAsync(CancellationToken cancellationToken) ProcessCpuTitle = ProcessTable.CpuColumnTitle(top); ProcessNote = Processes.Count == 0 ? "这一刻没有读到进程。" : ""; } + catch (OperationCanceledException) when (_disposed) + { + // 抽屉关了,没人再看这张表。 + } catch (Exception ex) when (ex is not OperationCanceledException) { Processes.Clear(); @@ -593,12 +654,12 @@ private async Task RefreshProcessesAsync(CancellationToken cancellationToken) /// private void StartStatsStream() { - if (_shell.Client is not { } client) + if (_disposed || _shell.Client is not { } client) { return; } StopStatsStream(); - _statsCts = CancellationTokenSource.CreateLinkedTokenSource(_shell.Lifetime); + _statsCts = CancellationTokenSource.CreateLinkedTokenSource(_lifeToken); CancellationToken token = _statsCts.Token; string id = ContainerId; _ = Task.Run(async () => @@ -694,8 +755,16 @@ await client.UpdateRestartPolicyAsync(ContainerId, form.Policy, form.MaxRetries, /// public async ValueTask DisposeAsync() { + if (_disposed) + { + return; + } + _disposed = true; + // 先取消:还在路上的 inspect、进程表、stats 都挂在这上面,回来之后看到的是"已经关了"。 + await _life.CancelAsync().ConfigureAwait(false); StopStatsStream(); await Logs.DisposeAsync().ConfigureAwait(false); await Terminal.DisposeAsync().ConfigureAwait(false); + _life.Dispose(); } } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesView.axaml b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesView.axaml index 683194d..25adfd6 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesView.axaml +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesView.axaml @@ -231,7 +231,7 @@ - _lineStarts = [0]; + private string? _indexedText; + /// protected override void OnLoaded(RoutedEventArgs e) { base.OnLoaded(e); + // 视图在页签之间切来切去时会反复 Loaded / Unloaded:每次都 += 的话, + // 同一个处理器挂上好几份,光标每动一下就报好几次。 + DetachEditor(); if (this.FindControl("Editor") is { } editor) { + _editor = editor; // 光标位置要在**每次选区变化**时报,不只是敲字时 —— 点一下也会移动光标。 - editor.PropertyChanged += (_, args) => - { - if (args.Property == TextBox.CaretIndexProperty - && DataContext is ContainerFilesViewModel viewModel) - { - ReportCaret(viewModel, editor); - } - }; + editor.PropertyChanged += OnEditorPropertyChanged; } } - private static void ReportCaret(ContainerFilesViewModel viewModel, TextBox editor) + /// + protected override void OnUnloaded(RoutedEventArgs e) + { + DetachEditor(); + base.OnUnloaded(e); + } + + private void DetachEditor() + { + if (_editor is { } editor) + { + editor.PropertyChanged -= OnEditorPropertyChanged; + _editor = null; + } + } + + private void OnEditorPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs args) + { + if (args.Property == TextBox.CaretIndexProperty + && sender is TextBox editor + && DataContext is ContainerFilesViewModel viewModel) + { + ReportCaret(viewModel, editor); + } + } + + private void ReportCaret(ContainerFilesViewModel viewModel, TextBox editor) { string text = editor.Text ?? ""; + if (!ReferenceEquals(text, _indexedText)) + { + _lineStarts.Clear(); + _lineStarts.Add(0); + for (int i = text.IndexOf('\n'); i >= 0; i = text.IndexOf('\n', i + 1)) + { + _lineStarts.Add(i + 1); + } + _indexedText = text; + } int caret = Math.Clamp(editor.CaretIndex, 0, text.Length); - int line = 1; - int lineStart = 0; - for (int i = 0; i < caret; i++) + (int line, int column) = LocateCaret(_lineStarts, caret); + viewModel.ReportCaret(line, column); + } + + /// 在行首偏移表里二分出光标所在的行与列(都从 1 开始)。 + internal static (int Line, int Column) LocateCaret(IReadOnlyList lineStarts, int caret) + { + int lo = 0; + int hi = lineStarts.Count - 1; + while (lo < hi) { - if (text[i] == '\n') + int mid = (lo + hi + 1) / 2; + if (lineStarts[mid] <= caret) + { + lo = mid; + } + else { - line++; - lineStart = i + 1; + hi = mid - 1; } } - viewModel.ReportCaret(line, caret - lineStart + 1); + return (lo + 1, caret - lineStarts[lo] + 1); } private void OnDragOver(object? sender, DragEventArgs e) diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesViewModel.cs index 5eec4f1..a5d6908 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerFilesViewModel.cs @@ -1,6 +1,7 @@ using System.Collections.ObjectModel; using System.Text; using Avalonia.Platform.Storage; +using Avalonia.Threading; using VelaShell.Plugin.DockerPanel.Docker; namespace VelaShell.Plugin.DockerPanel.Ui.Pages; @@ -142,11 +143,25 @@ public bool Current public sealed class ContainerFilesViewModel(DockerPanelViewModel shell, string containerId, string containerName) : ObservableObject { + /// 严格的 UTF-8:遇到非法字节抛异常,而不是悄悄换成 U+FFFD。 + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + private readonly Dictionary _changes = []; private readonly List _history = []; private bool _loaded; private string _originalText = ""; private ContainerFileEntry? _openEntry; + // 原文件以 UTF-8 BOM 开头。编辑器里不显示它(否则第一行开头多一个看不见的字符),写回时补上。 + private bool _hasBom; + // "打开文件"领号:慢的那次读取晚回来时,不能把用户后点开的那个文件盖掉。 + private int _openTicket; + // 差异只算一次、多处共用:状态条的"已修改 N 行"与差异视图都从这里取。 + // 每敲一个字重算一遍 LCS 在几千行的配置文件上是看得见的卡顿,所以停手 250ms 之后才算。 + private IReadOnlyList? _diff; + private string? _diffOriginal; + private string? _diffEdited; + private DispatcherTimer? _diffTimer; + private string _modifiedLinesText = "未修改"; /// 只看相对镜像有变更的那些条目。 public bool ChangedOnly @@ -176,7 +191,8 @@ public bool DiffMode if (SetField(ref field, value)) { OnPropertiesChanged(nameof(EditMode)); - RebuildEditorLines(); + // 切到差异态要立刻有结果,不等防抖。 + RefreshDiff(); } } } @@ -210,20 +226,84 @@ public string CaretText private set => SetField(ref field, value); } = "行 1, 列 1"; - /// 已改了几行。 - public string ModifiedLinesText + /// 已改了几行(停止输入 250ms 之后更新)。 + public string ModifiedLinesText => IsModified ? _modifiedLinesText : "未修改"; + + /// + /// 这个文件以只读方式打开(不是合法的 UTF-8)。 + /// + /// 按 UTF-8 宽松解码再写回,会把每个解不开的字节换成 EF BF BD —— 一个 GBK 编码的配置文件, + /// 点一次保存就整个毁了,而且看上去只是"几个字显示成了问号"。所以干脆不让改。 + /// + /// + public bool IsReadOnly { - get + get; + private set { - if (!IsModified) + if (SetField(ref field, value)) { - return "未修改"; + OnPropertyChanged(nameof(CanEdit)); } - int changed = LineDiff.CountChanged(LineDiff.Compute(_originalText, EditorText)); - return $"已修改 {changed} 行"; } } + /// 编辑器可写(与 相反,给绑定用)。 + public bool CanEdit => !IsReadOnly; + + /// 当前文本相对原文的差异;两边都没变就复用上一次的结果。 + private IReadOnlyList CurrentDiff() + { + string original = _originalText; + string edited = EditorText; + if (_diff is null || !ReferenceEquals(_diffOriginal, original) || !ReferenceEquals(_diffEdited, edited)) + { + _diff = LineDiff.Compute(original, edited); + _diffOriginal = original; + _diffEdited = edited; + } + return _diff; + } + + /// 编辑停下来之后算一次差异,喂给状态条与差异视图。 + private void ScheduleDiff() + { + if (!IsModified) + { + _diffTimer?.Stop(); + _modifiedLinesText = "未修改"; + OnPropertyChanged(nameof(ModifiedLinesText)); + RebuildEditorLines(); + return; + } + if (_modifiedLinesText == "未修改") + { + // 第一次改动:行数还没算出来,先别继续说"未修改"。 + _modifiedLinesText = "已修改"; + OnPropertyChanged(nameof(ModifiedLinesText)); + } + if (_diffTimer is null) + { + _diffTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; + _diffTimer.Tick += (_, _) => + { + _diffTimer.Stop(); + RefreshDiff(); + }; + } + _diffTimer.Stop(); + _diffTimer.Start(); + } + + /// 立刻算差异并更新状态条与差异视图。 + private void RefreshDiff() + { + _diffTimer?.Stop(); + _modifiedLinesText = IsModified ? $"已修改 {LineDiff.CountChanged(CurrentDiff())} 行" : "未修改"; + OnPropertyChanged(nameof(ModifiedLinesText)); + RebuildEditorLines(); + } + /// 换行符(照原文件的,保存时不改它)。 public string LineEnding => _originalText.Contains("\r\n", StringComparison.Ordinal) ? "CRLF" : "LF"; @@ -345,7 +425,7 @@ public string EditorText if (SetField(ref field, value)) { OnPropertiesChanged(nameof(IsModified), nameof(ModifiedText), nameof(ModifiedLinesText)); - RebuildEditorLines(); + ScheduleDiff(); } } } = ""; @@ -375,21 +455,70 @@ public string ModifiedText } /// 打开一个目录或文件。 - public RelayCommand OpenCommand => field ??= new(p => p is FileEntryItem item - ? item.IsDirectory ? ToggleAsync(item) : OpenFileAsync(item.FullPath) - : Task.CompletedTask); + public RelayCommand OpenCommand => field ??= new(p => + { + if (p is not FileEntryItem item) + { + return Task.CompletedTask; + } + if (item.IsDirectory) + { + return ToggleAsync(item); + } + // 打开文件不占着命令:上一个文件还在读的时候点了另一个,要的是后点的那个 + // (OpenFileAsync 自己按"最后一次点击"取舍),而不是这一下被静默吞掉。 + _ = OpenFileAsync(item.FullPath); + return Task.CompletedTask; + }); /// 重新列一次(整棵树丢掉重建,并重新取一次相对镜像的变更)。 public RelayCommand RefreshCommand => field ??= new(_ => ReloadTreeAsync()); - /// 关掉编辑器。 - public RelayCommand CloseFileCommand => field ??= new(_ => + /// 关掉编辑器(有未保存的修改时先问一句)。 + public RelayCommand CloseFileCommand => field ??= new(async _ => { + if (!await ConfirmDiscardAsync("关掉编辑器").ConfigureAwait(true)) + { + return; + } OpenFilePath = null; - EditorText = ""; _originalText = ""; + _hasBom = false; + IsReadOnly = false; + EditorText = ""; }); + /// + /// 有未保存的修改时,问一句要不要扔掉。 + /// + /// 早先点开另一个文件就直接把改了一半的内容换掉了,连一句提示都没有 —— + /// 而这一页的用法恰恰是在几个相邻文件之间来回跳。 + /// + /// + private async Task ConfirmDiscardAsync(string action) + { + if (!IsModified || OpenFilePath is null) + { + return true; + } + return await shell.Confirm.AskAsync(shell.BuildConfirm(new() + { + Title = $"放弃对 {OpenFileName} 的修改?", + Icon = "Docker.undo-2", + Tier = ConfirmTier.Destructive, + ConfirmLabel = $"放弃修改并{action}", + ConfirmIcon = "Docker.undo-2", + HostName = "", + Commands = [$"(本地)丢弃编辑器里 {OpenFilePath} 的未保存内容"], + CommandNote = "容器里的文件不受影响 —— 改动还没写回去。", + Consequences = + [ + new(2, $"编辑器里对 {OpenFileName} 的改动({ModifiedText})会丢失,无法撤销。"), + new(0, "想留着的话先取消,按「保存…」写回容器。") + ] + })).ConfigureAwait(true); + } + /// 撤销未保存的修改。 public RelayCommand RevertCommand => field ??= new(_ => EditorText = _originalText); @@ -487,7 +616,7 @@ private void RebuildEditorLines() { return; } - foreach (DiffLine line in LineDiff.Compute(_originalText, EditorText)) + foreach (DiffLine line in CurrentDiff()) { (string? marker, RowTone tone) = line.Marker switch { @@ -543,7 +672,7 @@ private void Record(string path, string summary) /// 这次改动的摘要,进写入历史(+2 −1 这种)。 private string DescribeEdit() { - IReadOnlyList diff = LineDiff.Compute(_originalText, EditorText); + IReadOnlyList diff = CurrentDiff(); int added = diff.Count(static l => l.Marker is DiffMarker.Added or DiffMarker.Changed); int removed = diff.Count(static l => l.Marker is DiffMarker.Removed or DiffMarker.Changed); return _originalText.Length == 0 ? "新建" @@ -896,7 +1025,12 @@ private async Task LoadChangesAsync() private async Task OpenFileAsync(string path) { - if (shell.Client is not { } client) + if (shell.Client is not { } client || path == OpenFilePath) + { + return; + } + int ticket = ++_openTicket; + if (!await ConfirmDiscardAsync("打开另一个文件").ConfigureAwait(true) || ticket != _openTicket) { return; } @@ -906,14 +1040,27 @@ private async Task OpenFileAsync(string path) { byte[] bytes = await client.ReadFileAsync(containerId, path, DockerClient.MaxEditableFileBytes, shell.Lifetime) .ConfigureAwait(true); + // 读的这段时间里用户又点了别的文件:这一份已经没人要了,别把后点开的那个盖掉。 + if (ticket != _openTicket) + { + return; + } if (LooksBinary(bytes)) { Error = $"{path} 看起来是二进制文件 —— 面板只在线编辑文本。"; return; } - _originalText = Encoding.UTF8.GetString(bytes); + (string text, bool bom, bool valid) = DecodeText(bytes); + _hasBom = bom; + IsReadOnly = !valid; + _originalText = text; EditorText = _originalText; OpenFilePath = path; + if (!valid) + { + Error = $"{path} 不是合法的 UTF-8(可能是 GBK / Latin-1 之类的编码)—— 以只读方式打开。" + + "按 UTF-8 写回会把解不开的字节换成 U+FFFD,文件就毁了;要改请用终端里的编辑器。"; + } // 从树里取元数据,而不是从"当前目录的列表"里 —— // 树上点开的文件所在目录,未必是 Path 指着的那一个。 _openEntry = FindNode(path)?.Entry; @@ -923,19 +1070,67 @@ private async Task OpenFileAsync(string path) } DiffMode = false; BuildFileProperties(); - OnPropertiesChanged(nameof(ModifiedLinesText), nameof(LineEnding), nameof(Language), + RefreshDiff(); + OnPropertiesChanged(nameof(LineEnding), nameof(Language), nameof(ReloadCommand), nameof(HasReloadCommand)); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (OperationCanceledException) { - Error = ex is DockerApiException api ? api.Message : ex.Message; + } + catch (Exception ex) + { + if (ticket == _openTicket) + { + Error = ex is DockerApiException api ? api.Message : ex.Message; + } } finally { - Busy = false; + if (ticket == _openTicket) + { + Busy = false; + } + } + } + + /// + /// 按严格 UTF-8 解码。返回(正文, 有没有 BOM, 是不是合法 UTF-8)。 + /// + /// BOM 从正文里剥掉(编辑器里不该有一个看不见的首字符),由 写回时补上。 + /// 不合法时仍然给一份宽松解码的正文 —— 只读地看一眼总比什么都不显示强。 + /// + /// + internal static (string Text, bool Bom, bool Valid) DecodeText(byte[] bytes) + { + // 注意不能取 StrictUtf8.Preamble:它构造时关了 BOM,那是个空串,StartsWith 恒为真。 + ReadOnlySpan preamble = Encoding.UTF8.Preamble; + bool bom = bytes.AsSpan().StartsWith(preamble); + ReadOnlySpan body = bom ? bytes.AsSpan(preamble.Length) : bytes; + try + { + return (StrictUtf8.GetString(body), bom, true); + } + catch (DecoderFallbackException) + { + return (Encoding.UTF8.GetString(body), bom, false); } } + /// 把正文编回字节;原文件有 BOM 就照样带上。 + internal static byte[] EncodeText(string text, bool bom) + { + byte[] body = StrictUtf8.GetBytes(text); + if (!bom) + { + return body; + } + byte[] preamble = Encoding.UTF8.GetPreamble(); + byte[] result = new byte[preamble.Length + body.Length]; + preamble.CopyTo(result, 0); + body.CopyTo(result, preamble.Length); + return result; + } + /// /// 二进制探测:前 8 KB 里出现 NUL 就当二进制。 /// @@ -958,10 +1153,21 @@ private static bool LooksBinary(ReadOnlySpan bytes) private async Task SaveAsync() { - if (shell.Client is not { } client || OpenFilePath is not { } path || !IsModified) + if (shell.Client is not { } client || OpenFilePath is not { } path || !IsModified || IsReadOnly) { return; } + byte[] content; + try + { + content = EncodeText(EditorText, _hasBom); + } + catch (EncoderFallbackException) + { + // 编辑器里混进了孤立的代理项(粘贴来的坏文本):不能编成合法的 UTF-8,就不写。 + Error = "编辑器里有无法编码成 UTF-8 的字符(孤立的代理项),没有写回。"; + return; + } bool confirmed = await shell.Confirm.AskAsync(shell.BuildConfirm(new() { Title = $"覆盖容器内的 {OpenFileName}?", @@ -988,13 +1194,17 @@ private async Task SaveAsync() Busy = true; try { - await client.WriteFileAsync(containerId, path, Encoding.UTF8.GetBytes(EditorText), shell.Lifetime) + // 闸门开着的时候编辑器里的字可能又变了:写回去的必须正是"被确认的那一刻"的这一份, + // 之后把原文也记成这一份 —— 两者不一致,"未修改"就是在撒谎。 + string saved = EditorText; + content = EncodeText(saved, _hasBom); + await client.WriteFileAsync(containerId, path, content, shell.Lifetime) .ConfigureAwait(true); Record(path, DescribeEdit()); - _originalText = EditorText; - OnPropertiesChanged(nameof(IsModified), nameof(ModifiedText), nameof(ModifiedLinesText)); - RebuildEditorLines(); - _ = shell.Feedback.Notify(FeedbackKind.Success, "已写回容器", $"{path} · {Humanize.Bytes(Encoding.UTF8.GetByteCount(EditorText))}"); + _originalText = saved; + OnPropertiesChanged(nameof(IsModified), nameof(ModifiedText)); + RefreshDiff(); + _ = shell.Feedback.Notify(FeedbackKind.Success, "已写回容器", $"{path} · {Humanize.Bytes(content.Length)}"); await LoadChangesAsync().ConfigureAwait(true); if (ReloadAfterSave && HasReloadCommand) { diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerTerminalViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerTerminalViewModel.cs index 269d603..673c7e4 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerTerminalViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainerTerminalViewModel.cs @@ -29,6 +29,13 @@ public sealed class ContainerTerminalViewModel(DockerPanelViewModel shell, strin private DockerExecSession? _session; private CancellationTokenSource? _sessionCts; private bool _starting; + // 这个终端页自己的生命周期,DisposeAsync 时取消。建会话的每一步都挂在它上面, + // 每个 await 回来都看一眼 —— 否则抽屉关掉之后才建成的那条劫持连接没人释放,一直占着一个通道。 + private readonly CancellationTokenSource _life = CancellationTokenSource.CreateLinkedTokenSource(shell.Lifetime); + private bool _disposed; + // 用户在「切换用户」里亲手挑过 shell。挑过就照办,不再替他探测 —— + // 早先挑了 /bin/sh,重连时又被探测改回了 bash。 + private bool _shellPinned; /// 终端控件(交给视图去承载;宿主给的是 Avalonia Control)。 public object? TerminalControl => _view?.Control; @@ -165,7 +172,8 @@ private async Task SwitchUserAsync() return; } User = form.User; - Shell = form.Shell; + _shellPinned = !string.IsNullOrWhiteSpace(form.Shell); + Shell = _shellPinned ? form.Shell.Trim() : "/bin/bash"; await RestartAsync().ConfigureAwait(true); } @@ -195,7 +203,7 @@ private async Task SwitchWorkingDirAsync() /// 第一次进这一页时才建终端并连上。 public async Task EnsureStartedAsync() { - if (_view is not null || _starting) + if (_view is not null || _starting || _disposed) { return; } @@ -226,21 +234,32 @@ public async Task EnsureStartedAsync() private async Task StartSessionAsync() { - if (_view is not { } view || shell.Client is not { } client) + if (_disposed || _view is not { } view || shell.Client is not { } client) { return; } Status = "正在建立 exec 会话…"; + CancellationToken life = _life.Token; try { - string resolved = await ResolveShellAsync(client).ConfigureAwait(true); + string resolved = await ResolveShellAsync(client, life).ConfigureAwait(true); + if (_disposed) + { + return; + } Shell = resolved; DockerExecSession session = await client.StartExecAsync(containerId, [resolved], tty: true, string.IsNullOrWhiteSpace(User) ? null : User, string.IsNullOrWhiteSpace(WorkingDir) ? null : WorkingDir, - shell.Lifetime).ConfigureAwait(true); + life).ConfigureAwait(true); + if (_disposed) + { + // 建成的那一刻抽屉已经关了:这条劫持连接没人要,当场还回去。 + await session.DisposeAsync().ConfigureAwait(true); + return; + } _session = session; - _sessionCts = CancellationTokenSource.CreateLinkedTokenSource(shell.Lifetime); + _sessionCts = CancellationTokenSource.CreateLinkedTokenSource(life); Connected = true; Status = "已连接"; OnPropertiesChanged(nameof(ExecIdText), nameof(HeaderText)); @@ -248,6 +267,10 @@ private async Task StartSessionAsync() await ResizeRemoteAsync(view.Columns, view.Rows).ConfigureAwait(true); _ = PumpAsync(view, session, _sessionCts.Token); } + catch (OperationCanceledException) when (life.IsCancellationRequested) + { + // 抽屉关了(或面板关了):不是失败,不必在一块没人看的终端上写字。 + } catch (Exception ex) when (ex is not OperationCanceledException) { Connected = false; @@ -271,10 +294,10 @@ private async Task StartSessionAsync() /// 所以先探一次,探不动就退回 /bin/sh。 /// /// - private async Task ResolveShellAsync(DockerClient client) + private async Task ResolveShellAsync(DockerClient client, CancellationToken cancellationToken) { - // 用户手动指定过就不猜了。 - if (Shell.Length > 0 && !ShellCandidates.Contains(Shell)) + // 用户手动指定过就不猜了 —— 包括他明确挑了候选里的某一个(比如 /bin/sh)。 + if (Shell.Length > 0 && (_shellPinned || !ShellCandidates.Contains(Shell))) { return Shell; } @@ -284,7 +307,7 @@ private async Task ResolveShellAsync(DockerClient client) { ExecCapture probe = await client .ExecCaptureAsync(containerId, ["/bin/sh", "-c", $"command -v {candidate} >/dev/null"], - cancellationToken: shell.Lifetime) + cancellationToken: cancellationToken) .ConfigureAwait(true); if (probe.ExitCode == 0) { @@ -310,13 +333,21 @@ private async Task PumpAsync(IPluginTerminalView view, DockerExecSession session } catch (Exception ex) when (ex is not OperationCanceledException) { - Ui.Post(() => Status = $"会话中断:{ex.Message}"); + Ui.Post(() => + { + if (ReferenceEquals(_session, session)) + { + Status = $"会话中断:{ex.Message}"; + } + }); } finally { Ui.Post(() => { - if (Connected) + // 只收拾**自己那一个**会话。重连时旧泵的收尾可能晚于新会话建好才轮到 —— + // 不认身份的话,它会把刚连上的新会话标成"已结束"。 + if (ReferenceEquals(_session, session) && Connected) { Connected = false; Status = "会话已结束"; @@ -337,13 +368,13 @@ private void OnResized(int columns, int rows) /// private async Task ResizeRemoteAsync(int columns, int rows) { - if (_session is not { } session || !Connected || columns <= 0 || rows <= 0) + if (_disposed || _session is not { } session || !Connected || columns <= 0 || rows <= 0) { return; } try { - await session.ResizeAsync(rows, columns, shell.Lifetime).ConfigureAwait(true); + await session.ResizeAsync(rows, columns, _life.Token).ConfigureAwait(true); } catch (Exception) { @@ -360,16 +391,19 @@ private async Task RestartAsync() private async Task StopSessionAsync(string? status) { - if (_sessionCts is { } cts) + // 字段先摘下来再等:等的时候进来的另一次调用(或旧泵的收尾)看到的已经是"没有会话"。 + CancellationTokenSource? cts = _sessionCts; + _sessionCts = null; + DockerExecSession? session = _session; + _session = null; + if (cts is not null) { await cts.CancelAsync().ConfigureAwait(true); cts.Dispose(); - _sessionCts = null; } - if (_session is { } session) + if (session is not null) { await session.DisposeAsync().ConfigureAwait(true); - _session = null; } Connected = false; if (status is not null) @@ -408,6 +442,13 @@ await shell.Context.Terminal.WriteAsync(endpoint.SessionId, command + "\n", shel /// public async ValueTask DisposeAsync() { + if (_disposed) + { + return; + } + _disposed = true; + // 先取消:还在建立中的 exec 会在它的 await 回来之后看到这一位,把建成的会话当场还回去。 + await _life.CancelAsync().ConfigureAwait(false); await StopSessionAsync(null).ConfigureAwait(false); if (_view is { } view) { @@ -415,5 +456,6 @@ public async ValueTask DisposeAsync() view.Dispose(); _view = null; } + _life.Dispose(); } } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageView.axaml b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageView.axaml index ecdd8be..576e203 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageView.axaml +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageView.axaml @@ -538,7 +538,7 @@ Background="{DynamicResource VelaBgActive}" /> - + diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageViewModel.cs index b96d2e7..0edc8b8 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ContainersPageViewModel.cs @@ -36,6 +36,13 @@ public sealed class ContainersPageViewModel : PageViewModel, IAsyncDisposable { private readonly List _all = []; private readonly StatsSampler _sampler; + // 每次刷新在 UI 线程上发布一份"在跑的行"的不可变快照。采样器在线程池上读它 —— + // 早先它直接去枚举 _all,刷新正好在改 _all 时就是一次未捕获的异常,采样循环从此再也不转。 + private IReadOnlyList _runningSnapshot = []; + // 容器 id → 有没有分配 TTY(合并日志要知道每个来源该不该解多路复用帧)。TTY 是创建时定的,按 id 缓存不会过期。 + private readonly Dictionary _ttyCache = []; + private int _detailTicket; + private int _sourceTicket; /// 建容器页。 public ContainersPageViewModel(DockerPanelViewModel shell) : base(shell) @@ -48,7 +55,15 @@ public ContainersPageViewModel(DockerPanelViewModel shell) : base(shell) Filter = filter; } }); - OpenDetailCommand = new RelayCommand(p => p is ContainerRow row ? OpenDetailAsync(row) : Task.CompletedTask); + // 不等加载完就让命令结束:RelayCommand 跑着的时候不接受下一次点击, + // 抽屉还在读 inspect 时点别的行会被静默吞掉。打开是"最后一次点击说了算"(见 OpenDetailAsync)。 + OpenDetailCommand = new RelayCommand(p => + { + if (p is ContainerRow row) + { + _ = OpenDetailAsync(row); + } + }); CloseDetailCommand = new RelayCommand(_ => CloseDetail()); ClearSelectionCommand = new RelayCommand(_ => ClearSelection()); StartCommand = new RelayCommand(p => BatchAsync("启动", Targets(p), @@ -374,10 +389,19 @@ public void StartSampling() Shell.Overview.SetStatsDisabled(); return; } - _sampler.Start(() => [.. _all.Where(r => r.IsRunning)], + _sampler.Start(() => Volatile.Read(ref _runningSnapshot), rows => Shell.Overview.AcceptStatsSnapshot(rows), Shell.Lifetime); } + /// 按当前筛选与设置(「显示已停止」)重排一遍列表,不重新拉数据。 + public void ReapplyView() + { + if (LoadedOnce) + { + ApplyView(); + } + } + /// 停止采样(断开时)。 public void StopSampling() => _sampler.Stop(); @@ -437,9 +461,12 @@ .. summaries _all.Add(row); } } + Volatile.Write(ref _runningSnapshot, [.. _all.Where(static r => r.IsRunning)]); LoadedOnce = true; BuildProjectFilters(); ApplyView(); + // 被删掉的容器不能还算在"已选 N 个"里 —— 下一步批量操作会拿着一个不存在的 id 去敲 daemon。 + RecountSelection(); OnPropertiesChanged(nameof(TotalCount), nameof(RunningCount), nameof(StoppedCount), nameof(ProblemCount)); Shell.SetContainerCount(_all.Count); if (Detail is { } detail && _all.FirstOrDefault(r => r.Id == detail.ContainerId) is { } updated) @@ -460,6 +487,8 @@ public override void Reset() _ = ExitLogsModeAsync(); _sampler.Stop(); _all.Clear(); + Volatile.Write(ref _runningSnapshot, []); + _ttyCache.Clear(); View.Clear(); LoadedOnce = false; SelectedCount = 0; @@ -789,18 +818,47 @@ private void RemoveLogSource(LogSource source) /// 来源全选 / 全不选。 public RelayCommand ToggleAllSourcesCommand => field ??= new(_ => { - bool select = LogSources.Any(s => !s.Selected); - foreach (LogSourceItem item in LogSources) + // 已经勾满上限时这颗按钮就是"全不选" —— 否则它会卡在一个永远勾不上的状态。 + bool select = SelectedSourceCount < LogsViewModel.MaxMergedSources + && LogSources.Any(static s => s is { Selected: false, Visible: true }); + if (!select) { - item.Selected = select; + foreach (LogSourceItem item in LogSources) + { + item.Selected = false; + } + return Task.CompletedTask; + } + // "全选"选到上限为止,先选过滤后看得见的那些:一次接上几十条长连接, + // 会把事件流、终端、统计要用的通道全吃光。 + int room = LogsViewModel.MaxMergedSources - SelectedSourceCount; + foreach (LogSourceItem item in LogSources.Where(static s => s is { Selected: false, Visible: true })) + { + if (room <= 0) + { + Shell.Feedback.Status(FeedbackKind.Warning, + $"合并日志最多同时接 {LogsViewModel.MaxMergedSources} 条流,只勾选了前 {LogsViewModel.MaxMergedSources} 个。"); + break; + } + item.Selected = true; + room--; } return Task.CompletedTask; }); private async Task EnterLogsModeAsync(IReadOnlyList seed) { + if (seed.Count > LogsViewModel.MaxMergedSources) + { + Shell.Feedback.Status(FeedbackKind.Warning, + $"合并日志最多同时接 {LogsViewModel.MaxMergedSources} 条流,先接前 {LogsViewModel.MaxMergedSources} 个。"); + seed = [.. seed.Take(LogsViewModel.MaxMergedSources)]; + } BuildLogSources(seed); - var logs = new LogsViewModel(Shell, SelectedSources()) + // 起流之前先把每个来源的 TTY 问清楚:TTY 容器的日志是裸字节,拿它当多路复用帧解, + // 每行开头都会被吃掉 8 个字节(或者整条流被当成一个巨大的坏帧)。 + List sources = await WithTtyAsync(SelectedSources()).ConfigureAwait(true); + var logs = new LogsViewModel(Shell, sources) { // chip 上的 × 走勾选那条路,左边面板跟着一起变。 SourceRemover = source => @@ -840,8 +898,10 @@ private void BuildLogSources(IReadOnlyList seed) int index = 0; foreach (ContainerRow row in _all) { + // TTY 先填缓存里的(没问过就先当 false),真正起流之前由 WithTtyAsync 补齐。 + // 早先这里填的是"在不在跑" —— 跟 TTY 毫无关系。 var item = new LogSourceItem( - new(row.Id, row.Name, row.Summary.State == "running"), + new(row.Id, row.Name, _ttyCache.GetValueOrDefault(row.Id)), row.IsRunning ? "运行中" : row.IsPaused ? "已暂停" : row.Uptime, row.Tone, index++) @@ -854,12 +914,87 @@ private void BuildLogSources(IReadOnlyList seed) ApplyLogSourceView(); } - private void OnLogSourceToggled() + private void OnLogSourceToggled(LogSourceItem item) { + if (item.Selected && SelectedSourceCount > LogsViewModel.MaxMergedSources) + { + // 超过上限的那一下不算数(取消勾选会再进来一次,走下面的普通路径)。 + item.Selected = false; + Shell.Feedback.Status(FeedbackKind.Warning, + $"合并日志最多同时接 {LogsViewModel.MaxMergedSources} 条流 —— 先取消一个再勾这个。"); + return; + } OnPropertiesChanged(nameof(SelectedSourceCount), nameof(MergedText)); - // 勾选变化直接换流。清屏是有意的 —— 合并流按到达顺序排, + // 勾选变化换流。清屏是有意的 —— 合并流按到达顺序排, // 留着旧行再补新来源的 tail,拼出来的时间线是假的。 - _ = MergedLogs?.SetSourcesAsync(SelectedSources()); + _ = ApplySourcesDebouncedAsync(); + } + + /// + /// 勾选停下来 250ms 之后才换流。「全选」是逐项改勾选, + /// 不压一下的话勾 8 个就是连着重开 8 次流。 + /// + private async Task ApplySourcesDebouncedAsync() + { + int ticket = ++_sourceTicket; + try + { + await Task.Delay(250, Shell.Lifetime).ConfigureAwait(true); + if (ticket != _sourceTicket || MergedLogs is not { } logs) + { + return; + } + List sources = await WithTtyAsync(SelectedSources()).ConfigureAwait(true); + if (ticket != _sourceTicket || !ReferenceEquals(MergedLogs, logs)) + { + return; + } + await logs.SetSourcesAsync(sources).ConfigureAwait(true); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + Shell.Feedback.ReportError("切换日志来源", ex); + } + } + + /// + /// 给每个来源补上真实的 TTY(Config.Tty)。没问过的容器各 inspect 一次并缓存; + /// 问不到(容器刚好被删)就按非 TTY 算 —— 绝大多数容器都不分配 TTY。 + /// + private async Task> WithTtyAsync(List sources) + { + if (Client is { } client) + { + string[] unknown = [.. sources.Select(static s => s.ContainerId).Distinct() + .Where(id => !_ttyCache.ContainsKey(id))]; + if (unknown.Length > 0) + { + (string Id, bool? Tty)[] answers = await Task.WhenAll(unknown.Select(async id => + { + try + { + ContainerInspect inspect = await client.InspectContainerAsync(id, Shell.Lifetime) + .ConfigureAwait(false); + return (id, (bool?)(inspect.Config?.Tty == true)); + } + catch (Exception) + { + return (id, (bool?)null); + } + })).ConfigureAwait(true); + foreach ((string id, bool? tty) in answers) + { + if (tty is { } known) + { + _ttyCache[id] = known; + } + } + } + } + return [.. sources.Select(s => s with { Tty = _ttyCache.GetValueOrDefault(s.ContainerId) })]; } private List SelectedSources() @@ -921,7 +1056,7 @@ private void ApplyLogSourceView() private async Task OpenDetailAtTabAsync(ContainerRow row, DetailTab tab) { await OpenDetailAsync(row).ConfigureAwait(true); - if (Detail is { } detail) + if (DetailFor(row) is { } detail) { await detail.GoToTabAsync(tab).ConfigureAwait(true); } @@ -931,7 +1066,7 @@ private async Task OpenDetailAtTabAsync(ContainerRow row, DetailTab tab) private async Task RowDetailActionAsync(ContainerRow row, Func pick) { await OpenDetailAsync(row).ConfigureAwait(true); - if (Detail is { } detail) + if (DetailFor(row) is { } detail) { pick(detail).Execute(null); } @@ -988,26 +1123,52 @@ await Shell.Context.Clipboard public async Task OpenDetailAtFilesAsync(ContainerRow row, string path) { await OpenDetailAsync(row).ConfigureAwait(true); - if (Detail is { } detail) + if (DetailFor(row) is { } detail) { await detail.OpenFilesAtAsync(path).ConfigureAwait(true); } } + /// + /// 打开某一行的详情。最后一次点击说了算:上一个抽屉还在读 inspect 时点了别的行, + /// 那个抽屉直接让位(释放时它自己的加载会被取消),而不是把这次点击吞掉。 + /// private async Task OpenDetailAsync(ContainerRow row) { + int ticket = ++_detailTicket; if (Detail is { } existing && existing.ContainerId == row.Id) { return; } // 换容器时钉住也要让位 —— 用户明确点了另一行。 await CloseDetail(force: true); + if (ticket != _detailTicket) + { + return; + } var detail = new ContainerDetailViewModel(Shell, this, row); Detail = detail; MarkCurrent(row.Id); - await detail.LoadAsync(Shell.Lifetime).ConfigureAwait(true); + try + { + await detail.LoadAsync(Shell.Lifetime).ConfigureAwait(true); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + if (ReferenceEquals(Detail, detail)) + { + Shell.Feedback.ReportError($"读取 {row.Name} 的详情", ex); + } + } } + /// 抽屉开着、而且开的正是这一行。 + private ContainerDetailViewModel? DetailFor(ContainerRow row) => + Detail is { } detail && detail.ContainerId == row.Id ? detail : null; + /// 关抽屉。钉住的抽屉只有 才关得掉。 private async Task CloseDetail(bool force = false) { diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageView.axaml b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageView.axaml index e19d150..dbfa939 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageView.axaml +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageView.axaml @@ -192,7 +192,7 @@ Classes.selected="{Binding Selected}"> - + diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageViewModel.cs index 8cfca85..58f4417 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/ImagesPageViewModel.cs @@ -444,6 +444,15 @@ private async Task PushAsync(ImageRow row) string reference = $"{row.Repository}:{row.Tag}"; PanelTask task = Shell.Tasks.Start("Icon.upload", $"推送 {reference}", indeterminate: false); var aggregator = new PullAggregator(); + // 帧在读流的线程上进聚合器(它自己带锁),界面每 100ms 最多读一次 —— 见 UiThrottle。 + var progress = new UiThrottle(() => + { + if (task.IsRunning) + { + task.Progress = aggregator.Progress; + task.Detail = aggregator.Summary; + } + }); try { string? header = await auth.GetAuthHeaderAsync(row.Repository, task.Token).ConfigureAwait(true); @@ -451,16 +460,16 @@ await client.PushImageAsync(row.Repository, row.Tag, header, new DirectProgress(frame => { aggregator.Accept(frame); - Ui.Post(() => - { - task.Progress = aggregator.Progress; - task.Detail = aggregator.Summary; - }); + progress.Request(); }), task.Token).ConfigureAwait(true); task.Finish(PanelTaskState.Succeeded, "完成"); _ = Shell.Feedback.Notify(FeedbackKind.Success, "推送完成", reference); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (OperationCanceledException) + { + task.Finish(PanelTaskState.Cancelled, "已取消"); + } + catch (Exception ex) { task.Finish(PanelTaskState.Failed, "失败", ex.Message); // 401/403 的出路只有一条:去登录。面板不代劳(那要一个它不该拿的口令), @@ -506,12 +515,19 @@ private async Task SaveAsync(IReadOnlyList targets) byte[] buffer = new byte[128 * 1024]; long total = 0; int read; + // 每 128 KB 一次的更新压到每 100ms 一次:一个 1 GB 的镜像是八千次调度。 + var progress = new UiThrottle(() => + { + if (task.IsRunning) + { + task.Detail = $"已写出 {Humanize.Bytes(Interlocked.Read(ref total))}"; + } + }); while ((read = await archive.ReadAsync(buffer, task.Token).ConfigureAwait(true)) > 0) { await output.WriteAsync(buffer.AsMemory(0, read), task.Token).ConfigureAwait(true); - total += read; - long written = total; - Ui.Post(() => task.Detail = $"已写出 {Humanize.Bytes(written)}"); + _ = Interlocked.Add(ref total, read); + progress.Request(); } task.Finish(PanelTaskState.Succeeded, "完成", Humanize.Bytes(total)); _ = Shell.Feedback.Notify(FeedbackKind.Success, "镜像已导出", $"{target.Name} · {Humanize.Bytes(total)}"); @@ -541,6 +557,14 @@ private async Task LoadAsync() } PanelTask task = Shell.Tasks.Start("Docker.arrow-down-to-line", $"导入 {source.Name}", indeterminate: false); var aggregator = new PullAggregator(); + var progress = new UiThrottle(() => + { + if (task.IsRunning) + { + task.Progress = aggregator.Progress; + task.Detail = aggregator.Summary; + } + }); try { // 请求体直接挂在文件流上,不缓冲。 @@ -548,11 +572,7 @@ private async Task LoadAsync() await client.LoadImagesAsync(input, new DirectProgress(frame => { aggregator.Accept(frame); - Ui.Post(() => - { - task.Progress = aggregator.Progress; - task.Detail = aggregator.Summary; - }); + progress.Request(); }), task.Token).ConfigureAwait(true); task.Finish(PanelTaskState.Succeeded, "完成"); _ = Shell.Feedback.Notify(FeedbackKind.Success, "镜像已导入", source.Name); diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsView.axaml b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsView.axaml index 061b2b3..a2d6a21 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsView.axaml +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsView.axaml @@ -99,7 +99,7 @@ + ToolTip.Tip="只看标准错误(stderr)输出的行 —— 其余行仍在缓冲里,关掉就回来" IsChecked="{Binding ErrorsOnly}"> - - - - - - - - + - - - - - - - - + Foreground="{Binding IsError, Converter={x:Static ui:Converters.LogLineForeground}}" + TextWrapping="{Binding $parent[ItemsControl].((pages:LogsViewModel)DataContext).Wrap, Converter={x:Static ui:Converters.WrapMode}}" /> diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsViewModel.cs index 9ff92c5..7d2ffe0 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/LogsViewModel.cs @@ -15,6 +15,7 @@ namespace VelaShell.Plugin.DockerPanel.Ui.Pages; /// 日志里的一行。 public sealed class LogLineItem(string timestamp, string source, int sourceIndex, bool isError, string text) + : ObservableObject { /// 时间戳文本;没开时间戳时为空。 public string Timestamp { get; } = timestamp; @@ -52,8 +53,15 @@ public sealed class LogLineItem(string timestamp, string source, int sourceIndex /// public RowTone Tone => IsError ? RowTone.Danger : LogLevels.Tone(Level); - /// 是不是当前搜索的命中行。 - public bool Matched { get; set; } + /// + /// 是不是当前搜索的命中行。改了要通知:搜索词变了之后已经画出来的行也得换底色, + /// 不通知的话高亮停在上一次搜索的结果上。 + /// + public bool Matched + { + get; + set => SetField(ref field, value); + } } /// 来源选择器里的一项。 @@ -90,13 +98,13 @@ public bool Selected { if (SetField(ref field, value)) { - SelectionChanged?.Invoke(); + SelectionChanged?.Invoke(this); } } } - /// 勾选变了。 - public event Action? SelectionChanged; + /// 勾选变了(参数是变了的那一项)。 + public event Action? SelectionChanged; } /// @@ -112,28 +120,45 @@ public sealed partial class LogsViewModel : ObservableObject, IAsyncDisposable /// 缓冲上限。 private const int MaxBufferedChars = 512 * 1024; - /// 界面上最多留多少行。 + /// 缓冲里最多留多少行。 private const int MaxLines = 5000; + /// + /// 合并流最多同时接几条。每条 logs -f 是一条长连接、占一个 SSH 通道; + /// 不设上限的话「全选」一下就能把事件流、终端、统计要用的通道全吃光。 + /// + public const int MaxMergedSources = DockerClient.MaxFollowStreams; // 与 DockerClient 的长连接流配额一致 + private readonly DockerPanelViewModel _shell; private readonly Func _ttyAccessor; private readonly List _pending = []; private readonly Lock _pendingGate = new(); private readonly List _sources = []; + // 收到的全部行(按行截断之后)。界面上的 Lines 只是它按「仅错误」筛过的一份视图 —— + // 早先筛选发生在入队时,被筛掉的行就此丢了:关掉「仅错误」也找不回来。 + private readonly List _buffer = []; + // 重开流的串行化:设置项、来源勾选、跟随开关都会触发重开,而且常常是一口气好几次。 + private readonly SemaphoreSlim _restartGate = new(1, 1); + private readonly Dictionary<(string Pattern, bool Regex), Regex?> _filterCache = []; + // 每次重开(以及停止)加一。流的回调带着自己的号,号对不上的行直接丢掉 —— + // 上一代流在被取消的那一瞬间还可能再吐几行,它们不该混进新的时间线。 + private int _generation; + private int _droppedSources; private DateTimeOffset _startedAt; private CancellationTokenSource? _cts; private DispatcherTimer? _flushTimer; private Regex? _filter; private long _bufferedChars; private bool _started; + private bool _disposed; /// 单容器(详情抽屉的日志页签)。 public LogsViewModel(DockerPanelViewModel shell, string containerId, Func ttyAccessor) - : this(shell, ttyAccessor) => _sources.Add(new(containerId, "", ttyAccessor())); + : this(shell, ttyAccessor) => _sources.Add(new(containerId, "", false)); /// 多容器合并流(容器页的日志模式)。 public LogsViewModel(DockerPanelViewModel shell, IEnumerable sources) - : this(shell, static () => false) => _sources.AddRange(sources); + : this(shell, static () => false) => SetSourceList(sources); private LogsViewModel(DockerPanelViewModel shell, Func ttyAccessor) { @@ -192,8 +217,7 @@ public string StreamSummary /// public async Task SetSourcesAsync(IEnumerable sources) { - _sources.Clear(); - _sources.AddRange(sources); + SetSourceList(sources); OnPropertiesChanged(nameof(SourceCount), nameof(IsMerged), nameof(Sources), nameof(StreamSummary)); if (_started) { @@ -201,6 +225,15 @@ public async Task SetSourcesAsync(IEnumerable sources) } } + /// 换来源清单,超出 的部分不接(并记下来告诉用户)。 + private void SetSourceList(IEnumerable sources) + { + List all = [.. sources]; + _droppedSources = Math.Max(0, all.Count - MaxMergedSources); + _sources.Clear(); + _sources.AddRange(all.Take(MaxMergedSources)); + } + /// 是否跟随(-f)。 public bool Follow { @@ -218,7 +251,10 @@ public bool Follow /// 跟随按钮上的字。开着时说"跟随中" —— 这颗按钮本身就是状态灯。 public string FollowLabel => Follow ? "跟随中" : "跟随"; - /// 只看标准错误。 + /// + /// 只看标准错误(stderr)。只是**视图**上的筛选:缓冲里所有行都还在, + /// 关掉之后原样回来;打开时已经显示的 stdout 行也会一起藏起来。 + /// public bool ErrorsOnly { get; @@ -226,7 +262,7 @@ public bool ErrorsOnly { if (SetField(ref field, value)) { - ApplyFilter(); + RebuildView(); } } } @@ -272,8 +308,21 @@ private set } } - /// 命中数文本。 - public string MatchText => Search.Length == 0 ? "" : $"{MatchCount} 处"; + /// 命中数文本;正则写坏了 / 太慢被停用时换成一句说明。 + public string MatchText => FilterHint.Length > 0 ? FilterHint : Search.Length == 0 ? "" : $"{MatchCount} 处"; + + /// 搜索词用不了时的那句说明(没写完的正则、匹配超时);能用时为空。 + public string FilterHint + { + get; + private set + { + if (SetField(ref field, value)) + { + OnPropertyChanged(nameof(MatchText)); + } + } + } = ""; /// 底部状态条那句话。 public string StatusText @@ -329,8 +378,10 @@ public bool Wrap /// 清屏。 public RelayCommand ClearCommand => field ??= new(_ => { + _buffer.Clear(); Lines.Clear(); _bufferedChars = 0; + MatchCount = 0; OnPropertiesChanged(nameof(BufferText), nameof(LineCountText)); }); @@ -409,7 +460,7 @@ private async Task DownloadAsync() /// 第一次进这一页时才起流。 public async Task EnsureStartedAsync() { - if (_started) + if (_started || _disposed) { return; } @@ -417,30 +468,96 @@ public async Task EnsureStartedAsync() await RestartAsync().ConfigureAwait(true); } - /// 按当前选项重开一条日志流。 + /// + /// 按当前选项重开一条日志流。 + /// + /// 串行化。跟随 / 行数 / 时间戳的开关、来源的勾选都会触发重开,而且常常一口气来好几次 + /// (「全选」是逐项改勾选)。早先几次重开交错执行:后一次在等前一次的取消时,前一次已经把 + /// 新建的令牌源换了上去,于是被取消、被释放的是**新**流,旧流漏掉了 —— 结果是重复行与泄漏的通道。 + /// 现在每次重开领一个号、排队进闸;轮到自己时号已经不是最新的,就让给后来的那一次。 + /// + /// public async Task RestartAsync() { - if (!_started || _shell.Client is not { } client) + if (!_started || _disposed) { return; } - await StopAsync().ConfigureAwait(true); - Lines.Clear(); - _bufferedChars = 0; - if (_sources.Count == 0) + int generation = Interlocked.Increment(ref _generation); + await _restartGate.WaitAsync().ConfigureAwait(true); + try + { + if (generation != Volatile.Read(ref _generation) || _disposed) + { + return; + } + await CancelStreamsAsync().ConfigureAwait(true); + // 等取消的时候可能又来了一次重开(或者面板关了)—— 那就别再起这一代的流。 + if (generation != Volatile.Read(ref _generation) || _disposed) + { + return; + } + ResetBuffer(); + if (_shell.Client is not { } client) + { + return; + } + if (_sources.Count == 0) + { + StatusText = "没有选中任何来源"; + OnPropertiesChanged(nameof(BufferText), nameof(LineCountText), nameof(StreamSummary)); + return; + } + var cts = CancellationTokenSource.CreateLinkedTokenSource(_shell.Lifetime); + _cts = cts; + StartStreams(client, generation, cts.Token); + } + finally + { + _ = _restartGate.Release(); + } + } + + /// 取消当前这一代的流。先把字段摘下来再等,等的时候别人看到的已经是"没有流"。 + private async Task CancelStreamsAsync() + { + CancellationTokenSource? cts = _cts; + _cts = null; + if (cts is null) { - StatusText = "没有选中任何来源"; - OnPropertiesChanged(nameof(BufferText), nameof(LineCountText), nameof(StreamSummary)); return; } - _cts = CancellationTokenSource.CreateLinkedTokenSource(_shell.Lifetime); - CancellationToken token = _cts.Token; + await cts.CancelAsync().ConfigureAwait(true); + cts.Dispose(); + } + + /// 清掉缓冲、界面与还没交出去的那一批(换代时用)。 + private void ResetBuffer() + { + lock (_pendingGate) + { + _pending.Clear(); + } + _buffer.Clear(); + Lines.Clear(); + _bufferedChars = 0; + MatchCount = 0; + OnPropertiesChanged(nameof(BufferText), nameof(LineCountText)); + } + + private void StartStreams(DockerClient client, int generation, CancellationToken token) + { _startedAt = DateTimeOffset.UtcNow; StartFlushTimer(); - StatusText = Follow ? "跟随中 · 新行即时到达" : "已加载历史"; + StatusText = _droppedSources > 0 + ? $"最多同时合并 {MaxMergedSources} 条流 —— 另外 {_droppedSources} 个来源没有接" + : Follow ? "跟随中 · 新行即时到达" : "已加载历史"; OnPropertyChanged(nameof(StreamSummary)); bool timestamps = Timestamps; + bool follow = Follow; string tail = Tail; + // 在 UI 线程上取定:回调在读流的线程上跑,不能再去读 _sources(它随勾选随时在变)。 + bool merged = _sources.Count > 1; int live = _sources.Count; // 每个来源一条独立的流,全部写进同一个待刷队列 —— @@ -450,13 +567,14 @@ public async Task RestartAsync() { LogSource source = _sources[i]; int index = i; - bool tty = _sources.Count == 1 ? _ttyAccessor() : source.Tty; + // 单容器的 TTY 由抽屉现问(它知道 inspect 读回来没有);合并流的每个来源各自带着。 + bool tty = merged ? source.Tty : _ttyAccessor(); _ = Task.Run(async () => { try { - await client.StreamLogsAsync(source.ContainerId, tty, Follow, tail, timestamps, null, - line => Enqueue(line, timestamps, source, index), token).ConfigureAwait(false); + await client.StreamLogsAsync(source.ContainerId, tty, follow, tail, timestamps, null, + line => Enqueue(line, timestamps, merged, source, index, generation), token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -465,33 +583,44 @@ await client.StreamLogsAsync(source.ContainerId, tty, Follow, tail, timestamps, catch (Exception ex) { // 一条流断了不该把整块面板说成失败 —— 另外几条还在跑。 - Ui.Post(() => StatusText = _sources.Count > 1 - ? $"{source.Name} 的日志流断开:{ex.Message}" - : $"日志流断开:{ex.Message}"); + Ui.Post(() => + { + if (generation == Volatile.Read(ref _generation)) + { + StatusText = merged + ? $"{source.Name} 的日志流断开:{ex.Message}" + : $"日志流断开:{ex.Message}"; + } + }); return; } Ui.Post(() => { - if (--live <= 0) + if (generation == Volatile.Read(ref _generation) && --live <= 0) { - StatusText = Follow ? "全部流已结束(容器可能停了)" : "已加载历史"; + StatusText = follow ? "全部流已结束(容器可能停了)" : "已加载历史"; } }); }, token); } } - private void Enqueue(DockerLogLine line, bool timestamps, LogSource source, int index) + private void Enqueue(DockerLogLine line, bool timestamps, bool merged, LogSource source, int index, int generation) { var item = new LogLineItem( timestamps && line.Timestamp is { } stamp ? stamp.ToLocalTime().ToString("HH:mm:ss.fff") : "", // 只有合并流才显示来源列:单容器时那一列每行都一样,纯属占地方。 - _sources.Count > 1 ? source.Name : "", + merged ? source.Name : "", index, line.Kind == DockerStreamKind.StdErr, line.Text); lock (_pendingGate) { + // 在锁里对号:换代时先加号、再在锁里清队列,两者不会错过彼此。 + if (generation != Volatile.Read(ref _generation)) + { + return; + } _pending.Add(item); } } @@ -519,71 +648,186 @@ private void OnFlush(object? sender, EventArgs e) batch = [.. _pending]; _pending.Clear(); } - foreach (LogLineItem item in batch) + AppendBatch(batch); + } + + /// + /// 把一批行收进缓冲,并把通过筛选的那些摆上界面。只在 UI 线程上调用。 + /// + /// 先裁这一批、再裁旧行:tail=all 的开头一批就可能是几万行, + /// 全加进去再从头一行一行删是 O(n²) 的白干。 + /// + /// + internal void AppendBatch(IReadOnlyList batch) + { + int skip = Math.Max(0, batch.Count - MaxLines); + for (int i = skip; i < batch.Count; i++) { - if (ErrorsOnly && !item.IsError) + LogLineItem item = batch[i]; + item.Matched = Matches(item.Text); + _buffer.Add(item); + _bufferedChars += item.Text.Length + 1; + if (Visible(item)) { - continue; + Lines.Add(item); } - item.Matched = _filter?.IsMatch(item.Text) ?? false; - Lines.Add(item); - _bufferedChars += item.Text.Length + 1; } // 按行截断:从最旧的开始扔,直到缓冲回到上限之内。 - while ((_bufferedChars > MaxBufferedChars || Lines.Count > MaxLines) && Lines.Count > 0) + int drop = 0; + long chars = _bufferedChars; + while (drop < _buffer.Count && (chars > MaxBufferedChars || _buffer.Count - drop > MaxLines)) + { + chars -= _buffer[drop].Text.Length + 1; + drop++; + } + if (drop > 0) { - _bufferedChars -= Lines[0].Text.Length + 1; - Lines.RemoveAt(0); + // 界面上的行是缓冲按同一顺序筛出来的子序列,所以被扔掉的可见行恰好是 Lines 打头那几行。 + int visibleDrop = 0; + for (int i = 0; i < drop; i++) + { + if (Visible(_buffer[i])) + { + visibleDrop++; + } + } + for (int i = 0; i < visibleDrop && Lines.Count > 0; i++) + { + Lines.RemoveAt(0); + } + _buffer.RemoveRange(0, drop); + _bufferedChars = chars; } MatchCount = _filter is null ? 0 : Lines.Count(static l => l.Matched); OnPropertiesChanged(nameof(BufferText), nameof(LineCountText), nameof(StreamSummary)); } + /// 缓冲里的行数(含被「仅错误」藏起来的那些)。 + internal int BufferedLineCount => _buffer.Count; + + /// 这一行在当前筛选下该不该显示。 + private bool Visible(LogLineItem item) => !ErrorsOnly || item.IsError; + + /// 按当前筛选把界面上的行从缓冲重摆一遍(切「仅错误」时)。 + private void RebuildView() + { + Lines.Clear(); + foreach (LogLineItem item in _buffer) + { + if (Visible(item)) + { + Lines.Add(item); + } + } + MatchCount = _filter is null ? 0 : Lines.Count(static l => l.Matched); + OnPropertyChanged(nameof(LineCountText)); + } + + /// + /// 编译搜索词。 + /// + /// 不用 :那会为每个搜索词生成一份 IL, + /// 而这里**每敲一个字**就是一个新搜索词 —— 编译的成本远大于它在几千行上省下的时间。 + /// 编译过的搜索词留一份小缓存,退格回去不必重来。 + /// + /// private void CompileFilter() { + FilterHint = ""; if (Search.Length == 0) { _filter = null; return; } + (string, bool) key = (Search, UseRegex); + if (!_filterCache.TryGetValue(key, out Regex? regex)) + { + try + { + regex = new(UseRegex ? Search : Regex.Escape(Search), + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100)); + } + catch (ArgumentException) + { + // 正则还没写完就开始匹配是常态,写坏了不该把日志视图弄崩。 + regex = null; + } + if (_filterCache.Count >= 32) + { + _filterCache.Clear(); + } + _filterCache[key] = regex; + } + _filter = regex; + if (regex is null) + { + FilterHint = "正则还没写完整"; + } + } + + /// + /// 一行命中没有。 + /// + /// 匹配超时(灾难性回溯的正则)不能漏到界面线程上 —— 那是一个直接的崩溃。 + /// 而且一行超时就该整个停用:几千行每行再等 100ms,界面就是好几分钟不动。 + /// + /// + private bool Matches(string text) + { + if (_filter is not { } filter) + { + return false; + } try { - _filter = new(UseRegex ? Search : Regex.Escape(Search), - RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromMilliseconds(100)); + return filter.IsMatch(text); } - catch (ArgumentException) + catch (RegexMatchTimeoutException) { - // 正则还没写完就开始匹配是常态,写坏了不该把日志视图弄崩。 _filter = null; + _filterCache[(Search, UseRegex)] = null; + FilterHint = "这个正则太慢(单行匹配超时),已停用 —— 换个更具体的写法"; + return false; } } private void ApplyFilter() { - foreach (LogLineItem line in Lines) + foreach (LogLineItem line in _buffer) { - line.Matched = _filter?.IsMatch(line.Text) ?? false; + line.Matched = Matches(line.Text); + } + if (_filter is null) + { + // 匹配途中被停用时,前面已经标上的那些也要撤掉。 + foreach (LogLineItem line in _buffer) + { + line.Matched = false; + } } MatchCount = _filter is null ? 0 : Lines.Count(static l => l.Matched); } - /// 停掉流。 + /// 停掉流。之后迟到的行一律丢弃。 public async Task StopAsync() { + _ = Interlocked.Increment(ref _generation); if (_flushTimer is { IsEnabled: true } timer) { timer.Stop(); timer.Tick -= OnFlush; } - if (_cts is null) + await CancelStreamsAsync().ConfigureAwait(true); + } + + /// + public async ValueTask DisposeAsync() + { + if (_disposed) { return; } - await _cts.CancelAsync().ConfigureAwait(true); - _cts.Dispose(); - _cts = null; + _disposed = true; + await StopAsync().ConfigureAwait(false); } - - /// - public async ValueTask DisposeAsync() => await StopAsync().ConfigureAwait(false); } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/NetworksPageView.axaml b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/NetworksPageView.axaml index bf6d504..a588dca 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/NetworksPageView.axaml +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/NetworksPageView.axaml @@ -116,7 +116,7 @@ CommandParameter="{Binding}"> - + diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/OverviewPageViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/OverviewPageViewModel.cs index da37c5d..e6c1d1f 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/OverviewPageViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/OverviewPageViewModel.cs @@ -424,6 +424,10 @@ public override void Reset() ReclaimDetail = ""; _hostMemory = 0; _hostCpus = 0; + // 峰值与"持续高占用从何时起"都是上一台机器的 —— 换主机后留着, + // 新主机的 CPU 卡会顶着别人的峰值,Top 5 的"已持续 N 分钟"也是错的。 + _cpuPeak = 0; + _hotSince.Clear(); _reclaimRequested = false; OnPropertyChanged(nameof(HasAttention)); } diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/PullImageViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/PullImageViewModel.cs index c3f2906..2bbeda5 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/PullImageViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/PullImageViewModel.cs @@ -380,8 +380,10 @@ private async Task StartAsync() _startedAt = DateTimeOffset.UtcNow; _lastSample = _startedAt; _lastBytes = 0; - _cts = CancellationTokenSource.CreateLinkedTokenSource(_shell.Lifetime); _task = _shell.Tasks.Start("Docker.arrow-down-to-line", $"拉取 {FullReference}", indeterminate: false); + // 两头都能取消:对话框里的「取消」,以及转入后台之后任务中心里那颗 ×。 + // 只链面板生命周期的话,后者按下去什么都不会发生。 + _cts = CancellationTokenSource.CreateLinkedTokenSource(_shell.Lifetime, _task.Token); string reference = Reference.Trim(); string tag = Tag.Trim(); string platform = Platform.Trim(); @@ -393,6 +395,8 @@ private async Task StartAsync() : null; await client.PullImageAsync(reference, tag, platform, allTags, header, new DirectProgress(OnFrame), _cts.Token).ConfigureAwait(true); + // 最后一帧不必再等一个节拍。 + ApplyProgress(); _task.Finish(PanelTaskState.Succeeded, "完成", _aggregator.Summary); DoneElapsed = Humanize.Duration(DateTimeOffset.UtcNow - _startedAt); DoneSize = _aggregator.TotalBytes > 0 @@ -418,22 +422,35 @@ await client.PullImageAsync(reference, tag, platform, allTags, header, } } + /// + /// 一帧进度到了。在**读流的线程**上被调用:聚合器自己带锁,可以直接吃; + /// 界面那一侧(层列表、速率、任务中心)压到每 100ms 最多刷新一次 —— + /// daemon 一秒能推上百帧,逐帧 Post 就是逐帧排版。 + /// private void OnFrame(PullProgressFrame frame) { _aggregator.Accept(frame); - Ui.Post(() => + (_progressThrottle ??= new UiThrottle(ApplyProgress)).Request(); + } + + private UiThrottle? _progressThrottle; + + private void ApplyProgress() + { + if (Stage != PullStage.Running) { - Progress = _aggregator.Progress; - SummaryText = _aggregator.Summary; - if (_task is { } task) - { - task.Progress = _aggregator.Progress; - task.Detail = _aggregator.Summary; - } - UpdateSpeed(); - SyncLayers(); - OnPropertiesChanged(nameof(BytesText), nameof(ReusedText), nameof(HasReused)); - }); + return; + } + Progress = _aggregator.Progress; + SummaryText = _aggregator.Summary; + if (_task is { IsRunning: true } task) + { + task.Progress = _aggregator.Progress; + task.Detail = _aggregator.Summary; + } + UpdateSpeed(); + SyncLayers(); + OnPropertiesChanged(nameof(BytesText), nameof(ReusedText), nameof(HasReused)); } private void UpdateSpeed() diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/SystemPageViewModel.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/SystemPageViewModel.cs index 5e6b977..43afb17 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/SystemPageViewModel.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/SystemPageViewModel.cs @@ -174,6 +174,9 @@ public override void Reset() _usage = null; _info = null; _version = null; + _hostDiskUnavailable = false; + HostDiskText = ""; + OnPropertyChanged(nameof(HostDiskText)); Stats.Clear(); DiskRows.Clear(); Segments.Clear(); @@ -226,26 +229,42 @@ private void BuildStats() /// private async Task LoadHostDiskAsync(DockerClient client, CancellationToken cancellationToken) { + // 探过一次不行就不再探(换了端点才重来):Docker Root Dir 是**宿主**上的路径, + // 在借来的容器里多半根本不存在(ENOENT)。每次刷新都再跑一遍,只是每次白开一个 exec —— + // 早先它还会引来一串 exec_* 事件,再触发刷新,成了环。 + if (_hostDiskUnavailable || FirstRunningContainerId is not { } containerId) + { + return; + } string root = _info?.DockerRootDir is { Length: > 0 } dir ? dir : "/var/lib/docker"; try { ExecCapture result = await client - .ExecCaptureAsync(FirstRunningContainerId ?? "", ["/bin/sh", "-c", $"df -PB1 {Sh.Quote(root)}"], + .ExecCaptureAsync(containerId, ["/bin/sh", "-c", $"df -PB1 {Sh.Quote(root)} 2>/dev/null"], cancellationToken: cancellationToken) .ConfigureAwait(true); if (result.ExitCode != 0 || ParseDf(result.StandardOutput) is not var (total, used)) { + _hostDiskUnavailable = true; return; } HostDiskText = $"宿主盘 {Humanize.Bytes(total)} 中已用 {Humanize.Bytes(used)}"; OnPropertyChanged(nameof(HostDiskText)); } - catch (Exception) + catch (OperationCanceledException) + { + // 页面刷新被取消,不代表这条路走不通 —— 下次再试。 + } + catch (Exception ex) { - // 没有可借的容器、镜像里没有 df、路径不存在 —— 三种都很常见,都不值得报。 + // 镜像里没有 sh / df、路径不存在 —— 都很常见,都不值得报,也不值得每次刷新再撞一次。 + _hostDiskUnavailable = true; + Shell.Context.Log.Debug($"host disk probe failed: {ex.Message}"); } } + private bool _hostDiskUnavailable; + /// 借一个正在跑的容器来执行 df —— 面板没有"在宿主上执行命令"的通道。 private string? FirstRunningContainerId => Shell.Containers.View.FirstOrDefault(static r => r.IsRunning)?.Id; @@ -390,7 +409,7 @@ private async Task PruneContainersAsync() { return; } - await RunPruneAsync("清理已停止容器", () => client.PruneContainersAsync(Shell.Lifetime)).ConfigureAwait(true); + await RunPruneAsync("清理已停止容器", ct => client.PruneContainersAsync(ct)).ConfigureAwait(true); } private async Task PruneBuildCacheAsync() @@ -418,7 +437,7 @@ private async Task PruneBuildCacheAsync() { return; } - await RunPruneAsync("清理构建缓存", () => client.PruneBuildCacheAsync(false, Shell.Lifetime)).ConfigureAwait(true); + await RunPruneAsync("清理构建缓存", ct => client.PruneBuildCacheAsync(false, ct)).ConfigureAwait(true); } private async Task PruneAllAsync(bool withVolumes) @@ -467,14 +486,14 @@ private async Task PruneAllAsync(bool withVolumes) { return; } - await RunPruneAsync(withVolumes ? "全部清理(含卷)" : "全部清理", async () => + await RunPruneAsync(withVolumes ? "全部清理(含卷)" : "全部清理", async ct => { - PruneReport containers = await client.PruneContainersAsync(Shell.Lifetime).ConfigureAwait(false); - PruneReport images = await client.PruneImagesAsync(false, Shell.Lifetime).ConfigureAwait(false); - PruneReport networks = await client.PruneNetworksAsync(Shell.Lifetime).ConfigureAwait(false); - PruneReport cache = await client.PruneBuildCacheAsync(true, Shell.Lifetime).ConfigureAwait(false); + PruneReport containers = await client.PruneContainersAsync(ct).ConfigureAwait(false); + PruneReport images = await client.PruneImagesAsync(false, ct).ConfigureAwait(false); + PruneReport networks = await client.PruneNetworksAsync(ct).ConfigureAwait(false); + PruneReport cache = await client.PruneBuildCacheAsync(true, ct).ConfigureAwait(false); PruneReport volumes = withVolumes - ? await client.PruneVolumesAsync(Shell.Lifetime).ConfigureAwait(false) + ? await client.PruneVolumesAsync(ct).ConfigureAwait(false) : new PruneReport(); return new PruneReport { @@ -489,19 +508,25 @@ await RunPruneAsync(withVolumes ? "全部清理(含卷)" : "全部清理", async }).ConfigureAwait(true); } - private async Task RunPruneAsync(string title, Func> action) + private async Task RunPruneAsync(string title, Func> action) { PanelTask task = Shell.Tasks.Start("Docker.broom", title, indeterminate: true); + // 任务中心里的取消要真的能停下后面那几步(全部清理是五个请求串着跑的)。 + using var cts = CancellationTokenSource.CreateLinkedTokenSource(Shell.Lifetime, task.Token); try { - PruneReport report = await action().ConfigureAwait(true); + PruneReport report = await action(cts.Token).ConfigureAwait(true); task.Finish(PanelTaskState.Succeeded, "完成", $"删除 {report.DeletedCount} 项 · 回收 {Humanize.Bytes(report.SpaceReclaimed)}"); _ = Shell.Feedback.Notify(FeedbackKind.Success, $"{title} 完成", $"删除 {report.DeletedCount} 项 · 回收 {Humanize.Bytes(report.SpaceReclaimed)}"); await RefreshAsync(Shell.Lifetime).ConfigureAwait(true); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (OperationCanceledException) + { + task.Finish(PanelTaskState.Cancelled, "已取消"); + } + catch (Exception ex) { task.Finish(PanelTaskState.Failed, "失败", ex.Message); Shell.Feedback.ReportError(title, ex); diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/VolumesPageView.axaml b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/VolumesPageView.axaml index a07f4e1..da380a2 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/VolumesPageView.axaml +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/Pages/VolumesPageView.axaml @@ -117,7 +117,7 @@ CommandParameter="{Binding}"> - + diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/StatsSampler.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/StatsSampler.cs index 85224ec..4b01e47 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/StatsSampler.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/StatsSampler.cs @@ -26,7 +26,10 @@ public sealed class StatsSampler(Func clientAccessor) : IAsyncDis private Action>? _onRound; /// 开始采样。 - /// 每一轮要采哪些行(通常是"当前可见且在跑的")。 + /// + /// 每一轮要采哪些行。它在**线程池**上被调用,所以只能返回一份已经发布好的不可变快照, + /// 不能现场去枚举 UI 线程正在改的集合。 + /// /// /// 每采完一轮回调一次。总览页的 CPU 趋势与 Top 5 靠它喂 —— /// 让总览自己再发一轮请求等于把同一批数据要两遍。 @@ -56,16 +59,29 @@ private async Task LoopAsync(CancellationToken token) { while (!token.IsCancellationRequested) { - DockerClient? client = clientAccessor(); - IReadOnlyList rows = _targets?.Invoke() ?? []; - if (client is not null && rows.Count > 0) + // 整轮包在 try 里:这一圈要是因为任何意外(目标回调、客户端刚被换掉)抛出来, + // 没接住的话循环就此死掉 —— 而界面上看到的只是 sparkline 从此不再动,没人知道为什么。 + try { - await Task.WhenAll(rows.Select(row => SampleAsync(client, row, token))).ConfigureAwait(false); - if (!token.IsCancellationRequested && _onRound is { } onRound) + DockerClient? client = clientAccessor(); + IReadOnlyList rows = _targets?.Invoke() ?? []; + if (client is not null && rows.Count > 0) { - Ui.Post(() => onRound(rows)); + await Task.WhenAll(rows.Select(row => SampleAsync(client, row, token))).ConfigureAwait(false); + if (!token.IsCancellationRequested && _onRound is { } onRound) + { + Ui.Post(() => onRound(rows)); + } } } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + return; + } + catch (Exception) + { + // 这一轮作废,下一轮照常 —— 采样是锦上添花,不值得为一次意外停掉。 + } try { await Task.Delay(Interval, token).ConfigureAwait(false); diff --git a/plugins/VelaShell.Plugin.DockerPanel/Ui/TaskCenter.cs b/plugins/VelaShell.Plugin.DockerPanel/Ui/TaskCenter.cs index 9a3881a..5f71017 100644 --- a/plugins/VelaShell.Plugin.DockerPanel/Ui/TaskCenter.cs +++ b/plugins/VelaShell.Plugin.DockerPanel/Ui/TaskCenter.cs @@ -233,7 +233,16 @@ private void Trim() } } - private void RaiseSummary() => Ui.Post(() => + /// + /// 汇总通知压到每 100ms 最多一次。 + /// + /// 每个任务的**每一次**属性变化都会走到这里 —— 拉镜像时进度一秒变几十次, + /// 而每次要通知六个计算属性,其中两个还要把全部任务扫一遍。顶栏那枚小环一秒刷新十次足够了。 + /// + /// + private void RaiseSummary() => SummaryThrottle.Request(); + + private UiThrottle SummaryThrottle => field ??= new(() => OnPropertiesChanged(nameof(RunningCount), nameof(FinishedCount), nameof(HasRunning), nameof(OverallProgress), nameof(IndicatorText), nameof(IndicatorPercent))); } @@ -247,12 +256,16 @@ private void RaiseSummary() => Ui.Post(() => /// public sealed class PullAggregator { + // 帧在读流的线程上进来,界面在 UI 线程上读 —— 两边同时碰一个 Dictionary, + // 枚举到一半被改就是 InvalidOperationException(或者更糟:静默读到撕裂的状态)。 + // 每帧的工作量很小,一把锁足够。 + private readonly Lock _gate = new(); private readonly Dictionary _layers = []; /// 层的状态。 private sealed record LayerState(string Status, long Current, long Total); - /// 吃进一帧。 + /// 吃进一帧。可以从任何线程调用。 public void Accept(PullProgressFrame frame) { if (string.IsNullOrEmpty(frame.Id)) @@ -263,42 +276,63 @@ public void Accept(PullProgressFrame frame) long current = frame.ProgressDetail?.Current ?? 0; long total = frame.ProgressDetail?.Total ?? 0; string status = frame.Status ?? ""; - // "Pull complete" / "Already exists" 之后不再有字节明细, - // 但它们已经算 100% —— 沿用上一次拿到的 total,免得进度条在最后一刻回退。 - if (_layers.TryGetValue(frame.Id, out LayerState? previous)) + lock (_gate) { - if (total == 0) - { - total = previous.Total; - } - if (IsComplete(status)) + // "Pull complete" / "Already exists" 之后不再有字节明细, + // 但它们已经算 100% —— 沿用上一次拿到的 total,免得进度条在最后一刻回退。 + if (_layers.TryGetValue(frame.Id, out LayerState? previous)) { - current = total; + if (total == 0) + { + total = previous.Total; + } + if (IsComplete(status)) + { + current = total; + } } + _layers[frame.Id] = new(status, current, total); + } + } + + /// 当前各层的一份拷贝(在锁里取,出了锁随便枚举)。 + private LayerState[] Layers() + { + lock (_gate) + { + return [.. _layers.Values]; } - _layers[frame.Id] = new(status, current, total); } /// 层总数。 - public int LayerCount => _layers.Count; + public int LayerCount + { + get + { + lock (_gate) + { + return _layers.Count; + } + } + } /// 已经完成的层数(含复用)。 - public int CompletedLayers => _layers.Values.Count(static l => IsComplete(l.Status)); + public int CompletedLayers => Layers().Count(static l => IsComplete(l.Status)); /// 复用(本地已有)的层数。 - public int ReusedLayers => _layers.Values.Count(static l => + public int ReusedLayers => Layers().Count(static l => l.Status.Contains("Already exists", StringComparison.OrdinalIgnoreCase)); /// 正在下载或解压的层数。 - public int ActiveLayers => _layers.Values.Count(static l => + public int ActiveLayers => Layers().Count(static l => l.Status.StartsWith("Downloading", StringComparison.OrdinalIgnoreCase) || l.Status.StartsWith("Extracting", StringComparison.OrdinalIgnoreCase)); /// 已下载字节。 - public long CurrentBytes => _layers.Values.Sum(static l => l.Current); + public long CurrentBytes => Layers().Sum(static l => l.Current); /// 总字节(只统计报了 total 的层)。 - public long TotalBytes => _layers.Values.Sum(static l => l.Total); + public long TotalBytes => Layers().Sum(static l => l.Total); /// /// 总进度 0–1。 @@ -328,8 +362,19 @@ public void Accept(PullProgressFrame frame) : $"完成 {CompletedLayers} / {LayerCount} 层 · 复用 {ReusedLayers} 层"; /// 逐层快照,给对话框里的层列表用。 - public IReadOnlyList<(string Id, string Status, double Progress, string SizeText)> Snapshot() => - [.. _layers.Select(static kv => ( + public IReadOnlyList<(string Id, string Status, double Progress, string SizeText)> Snapshot() + { + KeyValuePair[] layers; + lock (_gate) + { + layers = [.. _layers]; + } + return Project(layers); + } + + private static IReadOnlyList<(string Id, string Status, double Progress, string SizeText)> Project( + KeyValuePair[] layers) => + [.. layers.Select(static kv => ( Id: kv.Key, kv.Value.Status, Progress: kv.Value.Total > 0 ? Math.Clamp((double)kv.Value.Current / kv.Value.Total, 0, 1) : IsComplete(kv.Value.Status) ? 1d : 0d, diff --git a/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs b/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs index 018a21a..89f53d4 100644 --- a/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs +++ b/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs @@ -171,7 +171,8 @@ internal sealed record ExplainAdvice(string ReasonKey, string ReasonArgument, Bs /// /// 认三种形态:find 的 queryPlanner + executionStats;aggregate 的 stages[0].$cursor 包裹 /// (其后是 $group / $sort 这些管道阶段);分片集群的 shards[](取第一个分片,尽力而为)。 -/// SBE 引擎的 queryPlan 也按经典形状读。认不出的字段一概忽略 —— 解读失败不该让原始 JSON 也看不到。 +/// SBE 引擎(explainVersion: "2")的阶段树按 winningPlan.queryPlan 建 —— 它的 executionStages 是槽位执行树, +/// 不是查询计划的形状;各节点的统计按 planNodeId 尽力从槽位树里取,总数取 executionStats 顶层。认不出的字段一概忽略 —— 解读失败不该让原始 JSON 也看不到。 /// /// internal sealed class ExplainPlan @@ -298,8 +299,13 @@ public static ExplainPlan Parse(BsonDocument explain) } BsonDocument? winning = Unwrap(queryPlanner.GetValue("winningPlan", null) as BsonDocument); - BsonDocument? executionRoot = Unwrap(executionStats?.GetValue("executionStages", null) as BsonDocument); + // explainVersion "2"(SBE,7.0+ 把 $group / $lookup 下推之后):executionStages 是槽位执行树 + // (project / group / ixseek …),不是查询计划的形状。树按 winningPlan.queryPlan 建, + // 每个节点的统计按 planNodeId 从槽位树里尽力取(取不到就留空),总数仍取 executionStats 顶层。 + bool sbe = IsSbe(explain) || IsSbe(queryPlanner); + BsonDocument? executionRoot = sbe ? null : Unwrap(executionStats?.GetValue("executionStages", null) as BsonDocument); BsonDocument? root = executionRoot ?? winning; + Dictionary? sbeStats = sbe && executionStats?.GetValue("executionStages", null) is BsonDocument slots ? CollectSbeStats(slots) : null; // 树:管道阶段在上(最后一个是根),查询层的阶段树挂在最下面那个管道阶段之下。 var tree = new List(); @@ -316,7 +322,7 @@ public static ExplainPlan Parse(BsonDocument explain) }; tree.Add(pipelineStages[p]); } - ExplainStage? rootStage = root is null ? null : Build(root, pipelineStages.Count, tree); + ExplainStage? rootStage = root is null ? null : Build(root, pipelineStages.Count, tree, sbeStats); var linear = new List(); for (ExplainStage? s = rootStage; s is not null; s = s.Children.Count > 0 ? s.Children[0] : null) { @@ -438,7 +444,63 @@ public static ExplainPlan Parse(BsonDocument explain) return stage; } - private static ExplainStage Build(BsonDocument raw, int depth, List tree) + /// SBE 槽位树里同一个 planNodeId 的统计:输出取最外层那个槽位阶段,扫描键数累加。 + private sealed record SbeStats(long? NReturned, long? CumulativeMs, long? KeysExamined, bool? IsEof); + + private static bool IsSbe(BsonDocument document) => + document.GetValue("explainVersion", null) is BsonString { Value: "2" }; + + /// + /// 按 planNodeId 汇总 SBE 槽位树的统计。一个查询计划节点会展开成几个槽位阶段(GROUP → project / group / project), + /// 先序遍历遇到的第一个(最外层)就是这个节点的输出。分片时只看第一个分片(与经典形态一致)。 + /// + private static Dictionary CollectSbeStats(BsonDocument root) + { + var result = new Dictionary(); + void Walk(BsonDocument stage) + { + if (stage.GetValue("planNodeId", null) is { IsNumeric: true } id) + { + int key = id.ToInt32(); + long? keys = Long(stage, "keysExamined"); + if (result.TryGetValue(key, out SbeStats? seen)) + { + if (keys is not null) + { + result[key] = seen with { KeysExamined = (seen.KeysExamined ?? 0) + keys }; + } + } + else + { + result[key] = new SbeStats(Long(stage, "nReturned"), Long(stage, "executionTimeMillisEstimate"), keys, + stage.TryGetValue("isEOF", out BsonValue eof) ? eof.ToBoolean() : null); + } + } + foreach (string child in (string[])["inputStage", "outerStage", "innerStage", "thenStage", "elseStage"]) + { + if (stage.GetValue(child, null) is BsonDocument next) + { + Walk(next); + } + } + if (stage.GetValue("inputStages", null) is BsonArray many) + { + foreach (BsonDocument next in many.OfType()) + { + Walk(next); + } + } + if (stage.GetValue("shards", null) is BsonArray shards && shards.Count > 0 && shards[0] is BsonDocument shard + && shard.GetValue("executionStages", null) is BsonDocument shardStages) + { + Walk(shardStages); + } + } + Walk(root); + return result; + } + + private static ExplainStage Build(BsonDocument raw, int depth, List tree, Dictionary? sbe = null) { var children = new List(); if (raw.GetValue("inputStage", null) is BsonDocument input) @@ -459,23 +521,26 @@ private static ExplainStage Build(BsonDocument raw, int depth, List Build(c, depth + 1, tree)).ToList(); + var built = children.Select(c => Build(c, depth + 1, tree, sbe)).ToList(); + // SBE:queryPlan 节点本身不带统计,按 planNodeId 去槽位树里取;docsExamined / works 槽位树里没有对应量,留空。 + SbeStats? slot = sbe is not null && raw.GetValue("planNodeId", null) is { IsNumeric: true } nodeId + && sbe.TryGetValue(nodeId.ToInt32(), out SbeStats? found) ? found : null; var stage = new ExplainStage { Name = raw.GetValue("stage", "?").ToString() ?? "?", Raw = raw, Depth = depth, - NReturned = Long(raw, "nReturned"), - KeysExamined = Long(raw, "keysExamined"), + NReturned = Long(raw, "nReturned") ?? slot?.NReturned, + KeysExamined = Long(raw, "keysExamined") ?? slot?.KeysExamined, DocsExamined = Long(raw, "docsExamined"), Works = Long(raw, "works"), - CumulativeMs = Long(raw, "executionTimeMillisEstimate"), + CumulativeMs = Long(raw, "executionTimeMillisEstimate") ?? slot?.CumulativeMs, IndexName = raw.GetValue("indexName", null)?.ToString(), KeyPattern = raw.GetValue("keyPattern", null) as BsonDocument, Direction = raw.GetValue("direction", null)?.ToString(), Bounds = raw.GetValue("indexBounds", null) is BsonDocument bounds ? FormatBounds(bounds) : null, Filter = raw.GetValue("filter", null) as BsonDocument, - IsEof = raw.TryGetValue("isEOF", out BsonValue eof) ? eof.ToBoolean() : null, + IsEof = raw.TryGetValue("isEOF", out BsonValue eof) ? eof.ToBoolean() : slot?.IsEof, Children = built }; tree[index] = stage; @@ -531,7 +596,7 @@ private static List BuildCandidates(BsonDocument queryPlanner, } string winnerChain = Chain(winning); BsonDocument? winnerStats = all?.OfType() - .FirstOrDefault(p => p.GetValue("executionStages", null) is BsonDocument s && Chain(Unwrap(s)!) == winnerChain); + .FirstOrDefault(p => p.GetValue("executionStages", null) is BsonDocument s && SameChain(Chain(Unwrap(s)!), winnerChain)); candidates.Add(Candidate(true, winnerChain, winnerStats)); var used = new HashSet(ReferenceEqualityComparer.Instance); if (winnerStats is not null) @@ -542,7 +607,7 @@ private static List BuildCandidates(BsonDocument queryPlanner, { string chain = Chain(Unwrap(plan)!); BsonDocument? stats = all?.OfType() - .FirstOrDefault(p => !used.Contains(p) && p.GetValue("executionStages", null) is BsonDocument s && Chain(Unwrap(s)!) == chain); + .FirstOrDefault(p => !used.Contains(p) && p.GetValue("executionStages", null) is BsonDocument s && SameChain(Chain(Unwrap(s)!), chain)); if (stats is not null) { _ = used.Add(stats); @@ -552,6 +617,13 @@ private static List BuildCandidates(BsonDocument queryPlanner, return candidates; } + /// + /// 试运行的阶段链与计划链对得上:相同,或试运行链是计划链的开头 —— SBE 下多计划试运行发生在下推 $group 之前 + /// (试运行是 IXSCAN → PROJECTION_COVERED,获胜计划是 IXSCAN → PROJECTION_COVERED → GROUP)。 + /// + private static bool SameChain(string trial, string plan) => + trial == plan || plan.StartsWith(trial + " → ", StringComparison.Ordinal); + private static ExplainCandidate Candidate(bool winner, string chain, BsonDocument? stats) => new( winner, chain, diff --git a/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs b/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs index 2185ce0..78cab07 100644 --- a/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs +++ b/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs @@ -182,6 +182,20 @@ internal sealed record AdvisorIndex(string Name, BsonDocument Key, BsonDocument /// 部分 / 稀疏索引(只覆盖一部分文档,不能拿来替代全量索引)。 public bool Partial => Spec.Contains("partialFilterExpression") || Spec.GetValue("sparse", false).ToBoolean(); + + /// + /// TTL 索引(expireAfterSeconds)。它的活是后台按时删过期文档 —— TTL 线程的扫描不计入 $indexStats 的 ops, + /// "没人用"是假象;它也不能当成别的索引的冗余前缀删掉,删了过期文档就再也不会被清理。 + /// + public bool Ttl => Spec.Contains("expireAfterSeconds"); + + /// 排序规则;用简单二进制比较时为 。 + public BsonDocument? Collation => Spec.GetValue("collation", null) as BsonDocument; + + /// 与 的排序规则相同(都没有也算)。排序规则不同的索引服务的是不同的查询,不能互相替代。 + public bool SameCollation(AdvisorIndex other) => + Equals(Collation, other.Collation) || (Collation?.GetValue("locale", null)?.ToString() == "simple" && other.Collation is null) + || (other.Collation?.GetValue("locale", null)?.ToString() == "simple" && Collation is null); } /// 建议的种类(设计稿 07「索引建议」的三种卡片)。 @@ -345,10 +359,18 @@ internal static bool TryExtract(BsonDocument entry, out BsonDocument filter, out /// 慢查询组()。 /// 现有索引。 /// 当前时间(UTC;单测注入)。 - public static IReadOnlyList Advise(IReadOnlyList groups, IReadOnlyList indexes, DateTime now) + /// + /// 分片集合的分片键(config.collections 的 key);未分片为 。 + /// 以分片键为前缀的索引是分片键的支撑索引,删了分片就坏了 —— 不出"冗余 / 未使用"。 + /// + public static IReadOnlyList Advise(IReadOnlyList groups, IReadOnlyList indexes, DateTime now, + BsonDocument? shardKey = null) { ArgumentNullException.ThrowIfNull(groups); ArgumentNullException.ThrowIfNull(indexes); + // 不能建议删的:_id、TTL、分片键的支撑索引。 + bool Protected(AdvisorIndex index) => + index.Name == "_id_" || index.Ttl || shardKey is { ElementCount: > 0 } && IsPrefix(shardKey, index.Key); var advice = new List(); var suggested = new HashSet(StringComparer.Ordinal); foreach (AdvisorQueryGroup group in groups) @@ -373,13 +395,13 @@ public static IReadOnlyList Advise(IReadOnlyList - other.Name != index.Name && !other.Hidden && !other.Partial + other.Name != index.Name && !other.Hidden && !other.Partial && index.SameCollation(other) && other.Key.ElementCount > index.Key.ElementCount && IsPrefix(index.Key, other.Key)); if (cover is not null) { @@ -388,7 +410,8 @@ public static IReadOnlyList Advise(IReadOnlyListISO 8601 UTC(毫秒精度),与 mongosh 的 ISODate 输出一致。 + /// 毫秒值落在 .NET 能表示的范围里(0001-01-01 至 9999-12-31)。 + public static bool IsRepresentableDate(long ms) => ms is >= -62135596800000L and <= 253402300799999L; + + /// + /// ISO 8601 UTC(毫秒精度),与 mongosh 的 ISODate 输出一致。 + /// 超出 .NET 可表示范围的毫秒值(BSON 允许)原样给毫秒数,不抛。 + /// public static string IsoDate(BsonValue value) { long ms = value.AsBsonDateTime.MillisecondsSinceEpoch; + if (!IsRepresentableDate(ms)) + { + return ms.ToString(CultureInfo.InvariantCulture); + } var at = DateTimeOffset.FromUnixTimeMilliseconds(ms); return at.UtcDateTime.ToString(at.Millisecond == 0 ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture); diff --git a/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs b/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs index 7b6b041..a511e75 100644 --- a/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs +++ b/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs @@ -1,4 +1,5 @@ using System.Text; +using System.Text.RegularExpressions; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; @@ -33,7 +34,7 @@ public sealed class ShellJsonException(string message, int offset) : FormatExcep /// 认成**错误**而不是悄悄加引号 —— mongosh 自己就会在那里报错,设计稿 03 也把它画成了一条诊断。 /// /// -public static class ShellJson +public static partial class ShellJson { /// 解析一份文档;空白文本视为空文档 {}。 /// 语法错误。 @@ -175,6 +176,14 @@ internal static string Normalize(string text, out IReadOnlyList i++; continue; } + // mongosh 的 Timestamp({ t, i }) / MinKey() / MaxKey() 驱动读不了:换成它认的写法 + // (BsonText 的 Shell 输出就是 mongosh 的样子,这样文档编辑器里没动过的字段才能原样存回去)。 + if (IsIdentifierStart(c) && (i == 0 || !IsIdentifierPart(text[i - 1]) && text[i - 1] != '.') + && RewriteShellConstructor(text, i, output) is var consumed and > 0) + { + i += consumed; + continue; + } if (IsIdentifierStart(c) && stack.Count > 0 && stack.Peek() == '{') { int start = i; @@ -211,6 +220,33 @@ internal static string Normalize(string text, out IReadOnlyList return output.ToString(); } + /// + /// Timestamp({ t: 1, i: 2 }) → Timestamp(1, 2);MinKey() / MaxKey() → { "$minKey" : 1 } / { "$maxKey" : 1 }。 + /// 不是这几种写法返回 0(什么都不写)。 + /// + private static int RewriteShellConstructor(string text, int start, StringBuilder output) + { + Match timestamp = ShellTimestamp().Match(text, start); + if (timestamp.Success && timestamp.Index == start) + { + _ = output.Append("Timestamp(").Append(timestamp.Groups["t"].Value).Append(", ").Append(timestamp.Groups["i"].Value).Append(')'); + return timestamp.Length; + } + Match key = ShellMinMaxKey().Match(text, start); + if (key.Success && key.Index == start) + { + _ = output.Append(key.Groups["kind"].Value == "Min" ? "{ \"$minKey\" : 1 }" : "{ \"$maxKey\" : 1 }"); + return key.Length; + } + return 0; + } + + [GeneratedRegex("""\GTimestamp\s*\(\s*\{\s*["']?t["']?\s*:\s*(?\d+)\s*,\s*["']?i["']?\s*:\s*(?\d+)\s*,?\s*\}\s*\)""")] + private static partial Regex ShellTimestamp(); + + [GeneratedRegex(@"\G(?Min|Max)Key\s*\(\s*\)")] + private static partial Regex ShellMinMaxKey(); + private static bool LastSignificantIsKeyPosition(StringBuilder output) => PreviousSignificant(output) is '{' or ','; private static char PreviousSignificant(StringBuilder output) diff --git a/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs b/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs index 3b25100..1972334 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs @@ -107,9 +107,21 @@ private static Target TargetOf(WorkspaceConnectRequest request, MongoSettings se { options.Add(("authMechanism", uriMechanism)); } - if (url.ReadPreference is { } preference && preference.ReadPreferenceMode != ReadPreferenceMode.Primary) + // 表单里显式改过的读偏好覆盖 URI 的(与 MongoConnection.BuildSettings 同一口径)。 + ReadPreferenceMode? mode = settings.ReadPreferenceSet + ? MongoConnection.ParseReadPreference(settings.ReadPreference).ReadPreferenceMode + : url.ReadPreference?.ReadPreferenceMode; + if (mode is { } readMode && readMode != ReadPreferenceMode.Primary) { - options.Add(("readPreference", ReadPreferenceName(preference.ReadPreferenceMode))); + options.Add(("readPreference", ReadPreferenceName(readMode))); + } + if (settings.AppNameSet && settings.AppName is { Length: > 0 } formApp) + { + options.Add(("appName", formApp)); + } + else if (url.ApplicationName is { Length: > 0 } uriApp) + { + options.Add(("appName", uriApp)); } if (url.UseTls && !srv) { diff --git a/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs b/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs index 41ad001..d85e294 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs @@ -401,12 +401,18 @@ internal sealed class GridFsService(MongoConnection connection, GridFsBucketInfo /// <bucket>.chunks。 public IMongoCollection Chunks => connection.Collection(Bucket.Database, Bucket.ChunksCollection); + /// + /// 驱动的桶对象按块大小缓存(库与桶名在这个服务上是定的)。每次操作 new 一个的话,驱动每次都要重新确认 + /// files / chunks 上的索引(第一次写入前会查一遍 listIndexes)—— 批量上传一个文件夹时这是每个文件一次往返。 + /// + private readonly System.Collections.Concurrent.ConcurrentDictionary _drivers = new(); + private GridFSBucket Driver(int chunkSize = DefaultChunkSize) => - new(connection.Database(Bucket.Database), new GridFSBucketOptions + _drivers.GetOrAdd(chunkSize, size => new GridFSBucket(connection.Database(Bucket.Database), new GridFSBucketOptions { BucketName = Bucket.Name, - ChunkSizeBytes = chunkSize - }); + ChunkSizeBytes = size + })); // ── 读 ───────────────────────────────────────────────────────────────── diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs index 6b3bc50..3b67e7f 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs @@ -35,12 +35,24 @@ public async Task> ListDatabasesAsync(CancellationTo return [.. list.OrderBy(static d => d.IsSystem ? 0 : 1).ThenBy(static d => d.Name, StringComparer.Ordinal)]; } - /// 列出一个库里的集合与视图(含 options)。 + /// + /// 列出一个库里的集合与视图(含 options)。 + /// 只授了集合级权限的用户({ db: "shop", collection: "orders" } 上的 find)没有库级的 listCollections, + /// 完整列表会报 Unauthorized;那时退回 nameOnly + authorizedCollections —— 服务器只回他有权限的集合(没有 options)。 + /// public async Task> ListCollectionsAsync(string database, CancellationToken cancellationToken = default) { - using IAsyncCursor cursor = await Database(database) - .ListCollectionsAsync(cancellationToken: cancellationToken).ConfigureAwait(false); - List raw = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); + List raw; + try + { + using IAsyncCursor cursor = await Database(database) + .ListCollectionsAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + raw = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); + } + catch (MongoCommandException ex) when (IsUnauthorized(ex)) + { + raw = await ListAuthorizedCollectionsAsync(database, cancellationToken).ConfigureAwait(false); + } return [ .. raw.Select(doc => ToCollectionInfo(database, doc)) @@ -48,6 +60,55 @@ .. raw.Select(doc => ToCollectionInfo(database, doc)) ]; } + /// Unauthorized(13)。 + internal static bool IsUnauthorized(MongoCommandException ex) => ex.Code == 13 || ex.CodeName == "Unauthorized"; + + /// { listCollections: 1, nameOnly: true, authorizedCollections: true },把游标取完。 + private async Task> ListAuthorizedCollectionsAsync(string database, CancellationToken cancellationToken) + { + BsonDocument reply = await RunCommandAsync(database, new BsonDocument + { + { "listCollections", 1 }, + { "nameOnly", true }, + { "authorizedCollections", true }, + { "cursor", new BsonDocument() } + }, cancellationToken).ConfigureAwait(false); + var list = new List(); + BsonDocument cursor = reply.GetValue("cursor", new BsonDocument()).AsBsonDocument; + list.AddRange(cursor.GetValue("firstBatch", new BsonArray()).AsBsonArray.OfType()); + long id = cursor.GetValue("id", 0L).ToInt64(); + string collectionName = cursor.GetValue("ns", $"{database}.$cmd.listCollections").ToString()!; + collectionName = collectionName[(collectionName.IndexOf('.', StringComparison.Ordinal) + 1)..]; + while (id != 0) + { + BsonDocument more = await RunCommandAsync(database, new BsonDocument { { "getMore", id }, { "collection", collectionName } }, cancellationToken) + .ConfigureAwait(false); + BsonDocument next = more.GetValue("cursor", new BsonDocument()).AsBsonDocument; + list.AddRange(next.GetValue("nextBatch", new BsonArray()).AsBsonArray.OfType()); + id = next.GetValue("id", 0L).ToInt64(); + } + return list; + } + + /// + /// 分片集合的分片键(config.collections 里的 key);未分片、不是 mongos 或读不了 config 库时为 。 + /// 索引顾问拿它排除分片键的支撑索引()。 + /// + public async Task GetShardKeyAsync(string database, string collection, CancellationToken cancellationToken = default) + { + try + { + BsonDocument? entry = await Collection("config", "collections") + .Find(new BsonDocument("_id", $"{database}.{collection}")) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + return entry?.GetValue("key", null) as BsonDocument; + } + catch (MongoException) + { + return null; + } + } + internal static CollectionInfo ToCollectionInfo(string database, BsonDocument doc) { string name = doc["name"].AsString; @@ -95,8 +156,9 @@ public async Task GetStatsAsync(string database, string collect ]; using IAsyncCursor cursor = await Collection(database, collection) .AggregateAsync(pipeline, cancellationToken: cancellationToken).ConfigureAwait(false); - BsonDocument? first = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); - storage = first?.GetValue("storageStats", new BsonDocument()).AsBsonDocument ?? []; + // mongos 上 $collStats 每个分片回一份:只取第一份会把分片集合的文档数、大小少算成一个分片的量。 + List perShard = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); + storage = MergeShardStorage(perShard); } catch (MongoCommandException) { @@ -134,6 +196,52 @@ public async Task GetStatsAsync(string database, string collect }; } + /// 可以跨分片相加的量。 + private static readonly string[] AdditiveStats = ["count", "size", "storageSize", "totalIndexSize", "totalSize", "freeStorageSize"]; + + /// + /// 把 $collStats 的各分片结果并成一份:数量与大小相加,各索引大小按名相加,索引个数取最大, + /// 平均文档大小按合计重算。只有一份(未分片)时原样返回;多份时原文里另挂 shards: { 分片名: storageStats }。 + /// + internal static BsonDocument MergeShardStorage(IReadOnlyList perShard) + { + List storages = [.. perShard.Select(static d => d.GetValue("storageStats", new BsonDocument()) as BsonDocument ?? [])]; + if (storages.Count <= 1) + { + return storages.Count == 1 ? storages[0] : []; + } + var merged = new BsonDocument(storages[0].Where(static e => e.Name != "indexSizes")); + foreach (string name in AdditiveStats) + { + if (storages.Any(s => s.Contains(name))) + { + merged[name] = storages.Sum(s => Number(s, name)); + } + } + merged["nindexes"] = storages.Max(static s => Number(s, "nindexes")); + long count = Number(merged, "count"); + merged["avgObjSize"] = count > 0 ? Number(merged, "size") / count : 0; + var indexSizes = new BsonDocument(); + foreach (BsonDocument storage in storages) + { + if (storage.GetValue("indexSizes", null) is BsonDocument sizes) + { + foreach (BsonElement element in sizes) + { + indexSizes[element.Name] = (indexSizes.TryGetValue(element.Name, out BsonValue seen) ? seen.ToInt64() : 0) + element.Value.ToInt64(); + } + } + } + merged["indexSizes"] = indexSizes; + var shards = new BsonDocument(); + for (int i = 0; i < perShard.Count; i++) + { + shards[perShard[i].GetValue("shard", $"shard{i}").ToString()!] = storages[i]; + } + merged["shards"] = shards; + return merged; + } + /// 数据库统计(dbStats)。 public Task GetDatabaseStatsAsync(string database, CancellationToken cancellationToken = default) => RunCommandAsync(database, new BsonDocument("dbStats", 1), cancellationToken); diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs index f952c5f..6ff10b0 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using MongoDB.Bson; @@ -89,7 +90,10 @@ public static async Task ConnectAsync( CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); - TlsTrust? trust = settings.UseTls || settings.Topology != MongoTopology.Hosts ? new(settings.TrustedThumbprint) : null; + // 经隧道时驱动连的是 127.0.0.1,证书上的名字永远对不上:把真实目标交给 TlsTrust 自己核对。 + TlsTrust? trust = settings.UseTls || settings.Topology != MongoTopology.Hosts + ? new(settings.TrustedThumbprint, request.Tunnel?.TargetHost) + : null; MongoClientSettings clientSettings = BuildSettings(request, settings, trust); var client = new MongoClient(clientSettings); string endpoint = DescribeEndpoint(request, settings); @@ -148,18 +152,25 @@ public static async Task ConnectAsync(string connectionString, internal static MongoClientSettings BuildSettings(WorkspaceConnectRequest request, MongoSettings settings, TlsTrust? trust) { MongoClientSettings client; + HashSet uriOptions = []; switch (settings.Topology) { case MongoTopology.Uri: { // URI 写在"主机"那一栏里。凭据可以在 URI 里,也可以填在用户名/密码两栏 —— // 后者优先:那两栏的密码是宿主加密落盘的,URI 里的密码是明文。 - var url = new MongoUrlBuilder(request.Host.Trim()); + string uri = request.Host.Trim(); + var url = new MongoUrlBuilder(uri); + uriOptions = UriOptionNames(uri); if (request.Tunnel is not null) { - // 走隧道时宿主把主机改写成了本地端点 —— 但 URI 模式下"主机"一栏是整条串, - // 宿主改写的是它解析出来的第一台。这里按宿主给的端点直连那一台。 - url.Server = new(request.Host, request.Port); + // 走隧道时"主机"一栏仍是整条连接串(SshTunnel.RewriteTo 不动它),本地转发端口在 Port 上: + // 解析原串,把服务器换成回环上的转发端口并直连 —— 其余成员的真实地址经隧道够不着。 + if (url.Scheme == ConnectionStringScheme.MongoDBPlusSrv) + { + throw new NotSupportedException("mongodb+srv:// cannot be forwarded through an SSH jump host."); + } + url.Server = new(IPAddress.Loopback.ToString(), request.Port); url.DirectConnection = true; } if (!string.IsNullOrEmpty(request.Username)) @@ -188,8 +199,8 @@ internal static MongoClientSettings BuildSettings(WorkspaceConnectRequest reques default: { client = new MongoClientSettings(); - var servers = new List { new(request.Host.Trim(), request.Port) }; bool tunneled = request.Tunnel is not null; + var servers = new List { new(tunneled ? IPAddress.Loopback.ToString() : request.Host.Trim(), request.Port) }; if (!tunneled) { foreach (string extra in settings.AdditionalHosts) @@ -211,12 +222,30 @@ internal static MongoClientSettings BuildSettings(WorkspaceConnectRequest reques } } - client.ApplicationName = settings.AppName; - client.ConnectTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs); - client.ServerSelectionTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs); - client.ReadPreference = ParseReadPreference(settings.ReadPreference); + // URI 形态:连接串里写了的选项以连接串为准,只有用户在表单里显式改过(键在)才覆盖 —— + // 否则预览(ConnectionProbe.Preview,照 URI 画)与实际行为对不上。 + bool fromUri = settings.Topology == MongoTopology.Uri; + if (!fromUri || settings.AppNameSet || client.ApplicationName is null) + { + client.ApplicationName = settings.AppName; + } + if (!fromUri || settings.ConnectTimeoutSet || !uriOptions.Contains("connecttimeoutms")) + { + client.ConnectTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs); + } + if (!fromUri || settings.ConnectTimeoutSet || !uriOptions.Contains("serverselectiontimeoutms")) + { + client.ServerSelectionTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs); + } + if (!fromUri || settings.ReadPreferenceSet) + { + client.ReadPreference = ParseReadPreference(settings.ReadPreference); + } // 压缩:服务器不支持的会在握手时被协商掉,写上没有坏处 —— 远端大结果集上能省一大半带宽。 - client.Compressors = [new(CompressorType.ZStandard), new(CompressorType.Snappy), new(CompressorType.Zlib)]; + if (!fromUri || client.Compressors is not { Count: > 0 }) + { + client.Compressors = [new(CompressorType.ZStandard), new(CompressorType.Snappy), new(CompressorType.Zlib)]; + } bool tls = settings.UseTls || client.UseTls; if (tls) @@ -264,6 +293,23 @@ private static void ApplyCredential(MongoClientSettings client, WorkspaceConnect }; } + /// 连接串里写了哪些选项(小写名;?a=1&b=2 与 ; 分隔都认)。 + internal static HashSet UriOptionNames(string uri) + { + var names = new HashSet(StringComparer.Ordinal); + int query = uri.IndexOf('?', StringComparison.Ordinal); + if (query < 0) + { + return names; + } + foreach (string pair in uri[(query + 1)..].Split(['&', ';'], StringSplitOptions.RemoveEmptyEntries)) + { + int eq = pair.IndexOf('=', StringComparison.Ordinal); + _ = names.Add(Uri.UnescapeDataString(eq < 0 ? pair : pair[..eq]).Trim().ToLowerInvariant()); + } + return names; + } + internal static MongoServerAddress ParseAddress(string text) { int colon = text.LastIndexOf(':'); diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs index 66f7fe5..a07c90f 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs @@ -130,7 +130,16 @@ public Task ProbeAsync(MongoProfile profile, string password, IProg return ConnectionProbe.ProbeAsync(request, Loc, (ex, s) => Translate(ex, profile.ToRequest(""), s).Message, openTunnel, progress, cancellationToken); } - /// SRV 没有跳板可走:它靠 DNS 解析出一组成员,一条本地转发只通得到其中一台。 + /// 连接串是 mongodb+srv://(URI 形态下"主机"一栏的写法)。 + /// "主机"一栏。 + /// 是不是 SRV 连接串。 + internal static bool IsSrvUri(string host) => + host.TrimStart().StartsWith("mongodb+srv://", StringComparison.OrdinalIgnoreCase); + + /// + /// SRV 没有跳板可走:它靠 DNS 解析出一组成员,一条本地转发只通得到其中一台。 + /// URI 形态写的 mongodb+srv:// 仍返回 true —— 开转发那一步会以 Conn_SshNoSrv 拒绝,而不是悄悄绕过跳板直连。 + /// /// 设置。 /// 要不要建转发。 public static bool UsesTunnel(MongoSettings settings) => @@ -138,6 +147,12 @@ public static bool UsesTunnel(MongoSettings settings) => private async Task OpenTunnelAsync(MongoProfile profile, WorkspaceConnectRequest request, MongoSettings settings, CancellationToken cancellationToken) { + // URI 形态里写的 mongodb+srv:// 与 SRV 形态同理走不了跳板;但用户明确配了跳板, + // 悄悄改成直连会绕过跳板 —— 报清楚原因(连接失败卡片 / 测试的 SSH 一步)。 + if (settings.Topology == MongoTopology.Uri && IsSrvUri(request.Host)) + { + throw new NotSupportedException(Loc["Conn_SshNoSrv"]); + } (string host, int port) = SshTunnel.TargetOf(request, settings); string name = profile.Name.Length > 0 ? profile.Name : $"{host}:{port}"; return await SshTunnel.OpenAsync(context, settings.JumpSessionId, host, port, diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs index 49788ef..1ff3582 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs @@ -33,14 +33,31 @@ internal sealed class MongoProfile /// 用户名;空 = 匿名。 public string Username { get; set; } = ""; - /// 其余设置(键见 )。 - public Dictionary Settings { get; set; } = [with(StringComparer.Ordinal)]; + /// + /// 其余设置(键见 )。**改值走 **: 有缓存, + /// 只在 与整体替换时失效。 + /// + public Dictionary Settings + { + get => _settings; + set + { + _settings = value; + _parsed = null; + } + } + + private Dictionary _settings = [with(StringComparer.Ordinal)]; + private MongoSettings? _parsed; /// 最近一次连上的时间(对象树按它排,常用的在上面)。 public DateTimeOffset? LastConnectedAt { get; set; } - /// 解析好的设置。 - public MongoSettings Parsed => MongoSettings.From(ToRequest("")); + /// + /// 解析好的设置(惰性缓存:对象树每画一行都要读 ,每次都拷一份字典重新解析太浪费)。 + /// 只依赖 ,所以只在 与替换 时失效。 + /// + public MongoSettings Parsed => _parsed ??= MongoSettings.From(ToRequest("")); /// 环境标记(对象树上的色点、生产连接默认只读)。 public MongoEnvironment Environment => Parsed.Environment; @@ -85,6 +102,7 @@ public string Get(string key, string fallback = "") => /// 值。 public void Set(string key, string? value) { + _parsed = null; if (string.IsNullOrEmpty(value)) { _ = Settings.Remove(key); @@ -105,6 +123,15 @@ internal sealed class MongoProfileStore(IPluginContext context) { private const string ProfilesKey = "connections"; + /// + /// 每个存储一把锁(按存储实例取,同一插件里 new 了几个 store 也是同一把)。 + /// 保存 / 删除都是"读整表 → 改一条 → 写整表":连上时回写 与对话框里点保存撞在一起, + /// 后写的那个会拿着旧表把先写的改动盖掉。 + /// + private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Locks = []; + + private SemaphoreSlim Gate => Locks.GetValue(context.Storage, static _ => new SemaphoreSlim(1, 1)); + private static string SecretName(string id) => $"password:{id}"; /// 全部已保存的连接。 @@ -124,17 +151,26 @@ public async Task> LoadAsync(CancellationToken cance public async Task SaveAsync(MongoProfile profile, string? password, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(profile); - List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)]; - int index = list.FindIndex(p => p.Id == profile.Id); - if (index >= 0) + MongoProfile copy = profile.Clone(); + await Gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try { - list[index] = profile.Clone(); + List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)]; + int index = list.FindIndex(p => p.Id == copy.Id); + if (index >= 0) + { + list[index] = copy; + } + else + { + list.Add(copy); + } + await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false); } - else + finally { - list.Add(profile.Clone()); + _ = Gate.Release(); } - await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false); if (password is null) { return; @@ -149,16 +185,54 @@ public async Task SaveAsync(MongoProfile profile, string? password, Cancellation } } + /// + /// 只回写"最近连上的时间"(在锁里按 id 改存储里那一条的这一个字段)。连上时用它,而不是拿手里那份 + /// 可能已经过时的 整条 —— 那会把对话框刚存的修改盖回去。 + /// 存储里已经没有这条(连的时候被删了)时什么都不做。 + /// + /// 连接 id。 + /// 时间。 + /// 取消令牌。 + /// 存储里有没有这条。 + public async Task TouchLastConnectedAsync(string id, DateTimeOffset at, CancellationToken cancellationToken = default) + { + await Gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)]; + MongoProfile? stored = list.Find(p => p.Id == id); + if (stored is null) + { + return false; + } + stored.LastConnectedAt = at; + await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false); + return true; + } + finally + { + _ = Gate.Release(); + } + } + /// 删掉一条(连同口令)。 /// 连接 id。 /// 取消令牌。 /// 任务。 public async Task DeleteAsync(string id, CancellationToken cancellationToken = default) { - List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)]; - if (list.RemoveAll(p => p.Id == id) > 0) + await Gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try { - await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false); + List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)]; + if (list.RemoveAll(p => p.Id == id) > 0) + { + await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false); + } + } + finally + { + _ = Gate.Release(); } _ = await context.Secrets.DeleteAsync(SecretName(id), cancellationToken).ConfigureAwait(false); } diff --git a/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs b/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs index 69ed00c..b766975 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs @@ -3,7 +3,9 @@ using System.Net; using System.Net.Sockets; using MongoDB.Driver; +using MongoDB.Driver.Core.Configuration; using VelaShell.PluginSdk; +using VelaShell.PluginSdk.Logging; using VelaShell.PluginSdk.RemoteTunnel; using VelaShell.PluginSdk.Sessions; using VelaShell.PluginSdk.Workspaces; @@ -30,7 +32,11 @@ internal interface IMongoTunnel : IAsyncDisposable /// 毫秒。 Task CheckTargetAsync(CancellationToken cancellationToken); - /// 把请求改写成连本地端点( 记下真实目标)。 + /// + /// 把请求改写成连本地端点( 记下真实目标)。 + /// 本地端点 = 回环 + ;主机列表形态的"主机"一栏改成回环, + /// URI 形态的"主机"一栏是整条连接串,原样保留(见 )。 + /// /// 原请求。 /// 改写后的请求。 WorkspaceConnectRequest Rewrite(WorkspaceConnectRequest request); @@ -43,7 +49,7 @@ internal interface IMongoTunnel : IAsyncDisposable internal sealed class SshTunnel : IMongoTunnel { private readonly IPluginContext _context; - private readonly JumpLease _lease; + private readonly SshJumpLease _lease; private readonly TcpListener _listener; private readonly CancellationTokenSource _lifetime = new(); private readonly ConcurrentDictionary _pumps = new(); @@ -52,7 +58,7 @@ internal sealed class SshTunnel : IMongoTunnel private int _nextPump; private int _disposed; - private SshTunnel(IPluginContext context, JumpLease lease, string host, int port) + private SshTunnel(IPluginContext context, SshJumpLease lease, string host, int port) { _context = context; _lease = lease; @@ -91,7 +97,8 @@ public static async Task OpenAsync( string reason, CancellationToken cancellationToken) { - JumpLease lease = await JumpLease.AcquireAsync(context, savedSessionId, reason, cancellationToken).ConfigureAwait(false); + SshJumpLease lease = await SshJumpLease.AcquireAsync(context.Sessions, context.RemoteTunnel, context.Log, savedSessionId, reason, cancellationToken) + .ConfigureAwait(false); try { return new SshTunnel(context, lease, host, port); @@ -111,28 +118,56 @@ public static (string Host, int Port) TargetOf(WorkspaceConnectRequest request, { if (settings.Topology == MongoTopology.Uri) { - MongoServerAddress first = new MongoUrlBuilder(request.Host.Trim()).Servers.First(); + var url = new MongoUrlBuilder(request.Host.Trim()); + if (url.Scheme == ConnectionStringScheme.MongoDBPlusSrv) + { + // SRV 连接串经 DNS 解析出一组成员,一条转发只通得到其中一台;SRV 记录里的名字本身也不是 mongod。 + throw new NotSupportedException("mongodb+srv:// cannot be forwarded through an SSH jump host."); + } + MongoServerAddress first = url.Servers.First(); return (first.Host, first.Port); } return (request.Host.Trim(), request.Port); } + /// "主机"一栏写的是整条连接串(URI 形态)。 + /// "主机"一栏。 + /// 是不是连接串。 + internal static bool IsUriHost(string host) + { + string trimmed = host.TrimStart(); + return trimmed.StartsWith("mongodb://", StringComparison.OrdinalIgnoreCase) + || trimmed.StartsWith("mongodb+srv://", StringComparison.OrdinalIgnoreCase); + } + + /// + /// 改写成连本地端点。URI 形态下"主机"一栏是整条连接串(库名、选项、凭据都在里面),**不能**换成 127.0.0.1 —— + /// 那样 拿到的就不是连接串了;本地端点只记在 Port 上, + /// 拼设置时解析原串再把服务器换成回环 + Port。 + /// + /// 原请求。 + /// 本机回环上的转发端口。 + /// 真实目标与跳板名。 + /// 改写后的请求。 + internal static WorkspaceConnectRequest RewriteTo(WorkspaceConnectRequest request, int localPort, WorkspaceTunnelInfo tunnel) => request with + { + Host = IsUriHost(request.Host) ? request.Host : IPAddress.Loopback.ToString(), + Port = localPort, + Tunnel = tunnel + }; + /// public async Task CheckTargetAsync(CancellationToken cancellationToken) { var watch = Stopwatch.StartNew(); - Stream stream = await _context.RemoteTunnel.OpenTcpAsync(_lease.SessionId, _host, _port, null, cancellationToken).ConfigureAwait(false); + Stream stream = await _lease.OpenTcpAsync(_host, _port, cancellationToken).ConfigureAwait(false); await stream.DisposeAsync().ConfigureAwait(false); return (int)watch.ElapsedMilliseconds; } /// - public WorkspaceConnectRequest Rewrite(WorkspaceConnectRequest request) => request with - { - Host = IPAddress.Loopback.ToString(), - Port = LocalPort, - Tunnel = new WorkspaceTunnelInfo(_host, _port, JumpName) - }; + public WorkspaceConnectRequest Rewrite(WorkspaceConnectRequest request) => + RewriteTo(request, LocalPort, new WorkspaceTunnelInfo(_host, _port, JumpName)); private async Task AcceptLoopAsync() { @@ -160,7 +195,7 @@ private async Task PumpAsync(int id, TcpClient client) Stream? remote = null; try { - remote = await _context.RemoteTunnel.OpenTcpAsync(_lease.SessionId, _host, _port, null, _lifetime.Token).ConfigureAwait(false); + remote = await _lease.OpenTcpAsync(_host, _port, _lifetime.Token).ConfigureAwait(false); _pumps[id] = (client, remote); NetworkStream local = client.GetStream(); Task up = local.CopyToAsync(remote, _lifetime.Token); @@ -169,7 +204,7 @@ private async Task PumpAsync(int id, TcpClient client) } catch (Exception ex) when (ex is not OutOfMemoryException) { - // 跳板上开不出流(目标拒连、会话断了):关掉本地这一头,驱动会当成一次普通的连接失败处理。 + // 跳板上开不出流(目标拒连、会话断了且重开失败):关掉本地这一头,驱动会当成一次普通的连接失败处理。 if (!_lifetime.IsCancellationRequested) { _context.Log.Warn($"SSH forward to {Target} via {JumpName} failed: {ex.Message}"); @@ -207,94 +242,244 @@ public async ValueTask DisposeAsync() _lifetime.Dispose(); await _lease.DisposeAsync().ConfigureAwait(false); } +} - /// - /// 一条跳板会话的引用计数。几个 MongoDB 连接走同一台跳板时共用一条 SSH 会话,最后一个走了才关; - /// 而且只关**本插件开的**那条 —— 用户自己开着的终端会话宿主不让关(),那就留着。 - /// - private sealed class JumpLease : IAsyncDisposable +/// +/// 一条跳板会话的引用计数。几个 MongoDB 连接走同一台跳板时共用一条 SSH 会话,最后一个走了才关; +/// 而且只关**本插件开的**那条 —— 用户自己开着的终端会话宿主不让关(),那就留着。 +/// +/// 跳板会话会自己断(网络抖、用户在宿主里关了它):共用表里记着的那个 SessionId 就成了死的。 +/// 开流失败且查实会话已不在时,就地重开一条、换掉共用表里的会话,再试一次 —— +/// 否则这条跳板上之后的每一次连接都会永远失败。 +/// +/// +internal sealed class SshJumpLease : IAsyncDisposable +{ + private static readonly Lock Gate = new(); + private static readonly Dictionary Open = [with(StringComparer.Ordinal)]; + + private readonly ISessionsApi _sessions; + private readonly IRemoteTunnelApi _tunnel; + private readonly IPluginLogger _log; + private readonly string _savedSessionId; + private readonly Shared _shared; + private int _disposed; + + private SshJumpLease(ISessionsApi sessions, IRemoteTunnelApi tunnel, IPluginLogger log, string savedSessionId, Shared shared) { - private static readonly Lock Gate = new(); - private static readonly Dictionary Open = [with(StringComparer.Ordinal)]; + _sessions = sessions; + _tunnel = tunnel; + _log = log; + _savedSessionId = savedSessionId; + _shared = shared; + } - private readonly IPluginContext _context; - private readonly string _savedSessionId; - private readonly Shared _shared; - private int _disposed; + /// 当前用的会话 id(断线重开后会换)。 + public string SessionId => _shared.Session.SessionId; - private JumpLease(IPluginContext context, string savedSessionId, Shared shared) + /// 跳板的显示名。 + public string Name => _shared.Name; + + /// 共用表里这条已保存连接的引用数;不在表里为 0(单测用)。 + /// 已保存的 SSH 连接 id。 + /// 引用数。 + internal static int SharedCount(string savedSessionId) + { + lock (Gate) { - _context = context; - _savedSessionId = savedSessionId; - _shared = shared; + return Open.TryGetValue(savedSessionId, out Shared? shared) ? shared.Count : 0; } + } - public string SessionId => _shared.Session.SessionId; - - public string Name => _shared.Name; - - public static async Task AcquireAsync(IPluginContext context, string savedSessionId, string reason, CancellationToken cancellationToken) + /// 取一份租约:表里已有就加计数,没有就请宿主开一条。 + /// 会话能力。 + /// 隧道能力。 + /// 日志。 + /// 已保存的 SSH 连接 id。 + /// 给用户看的理由。 + /// 取消令牌。 + /// 租约。 + public static async Task AcquireAsync( + ISessionsApi sessions, + IRemoteTunnelApi tunnel, + IPluginLogger log, + string savedSessionId, + string reason, + CancellationToken cancellationToken) + { + lock (Gate) { - lock (Gate) + if (Open.TryGetValue(savedSessionId, out Shared? shared)) { - if (Open.TryGetValue(savedSessionId, out Shared? shared)) - { - shared.Count++; - return new JumpLease(context, savedSessionId, shared); - } + shared.Count++; + return new SshJumpLease(sessions, tunnel, log, savedSessionId, shared); } - IReadOnlyList saved = await context.Sessions.ListSavedAsync(cancellationToken).ConfigureAwait(false); - string name = saved.FirstOrDefault(s => s.SavedSessionId == savedSessionId)?.Name ?? savedSessionId; - SessionInfo session = await context.Sessions.OpenAsync(savedSessionId, new SessionOpenOptions(reason), cancellationToken).ConfigureAwait(false); - lock (Gate) + } + IReadOnlyList saved = await sessions.ListSavedAsync(cancellationToken).ConfigureAwait(false); + string name = saved.FirstOrDefault(s => s.SavedSessionId == savedSessionId)?.Name ?? savedSessionId; + SessionInfo session = await sessions.OpenAsync(savedSessionId, new SessionOpenOptions(reason), cancellationToken).ConfigureAwait(false); + Shared? winner = null; + lock (Gate) + { + if (Open.TryGetValue(savedSessionId, out Shared? raced)) { - // 等宿主连的这段时间里可能已经有别的连接开好了同一条:用先到的那条,自己这条交还计数。 - if (Open.TryGetValue(savedSessionId, out Shared? raced)) - { - raced.Count++; - return new JumpLease(context, savedSessionId, raced); - } - var fresh = new Shared(session, name) { Count = 1 }; + raced.Count++; + winner = raced; + } + else + { + var fresh = new Shared(session, name, reason) { Count = 1 }; Open[savedSessionId] = fresh; - return new JumpLease(context, savedSessionId, fresh); + return new SshJumpLease(sessions, tunnel, log, savedSessionId, fresh); } } + // 等宿主连的这段时间里已经有别的连接开好了同一条:用先到的那条,自己刚开的这条关掉 —— + // 不关就是宿主里一条没人管的 SSH 会话。宿主复用了同一条会话(id 相同)时不能关,那是先到者在用的。 + if (!string.Equals(session.SessionId, winner.Session.SessionId, StringComparison.Ordinal)) + { + await CloseQuietlyAsync(sessions, log, session.SessionId, name).ConfigureAwait(false); + } + return new SshJumpLease(sessions, tunnel, log, savedSessionId, winner); + } - public async ValueTask DisposeAsync() + /// + /// 在跳板机上开一条到目标的流。失败且查实跳板会话已经不在(宿主说找不到、或状态是断开 / 出错)时, + /// 重开一条会话换进共用表,再试一次;只重试这一次,第二次失败原样抛。 + /// + /// 目标主机(跳板机看到的)。 + /// 目标端口。 + /// 取消令牌。 + /// 双工流。 + public async Task OpenTcpAsync(string host, int port, CancellationToken cancellationToken) + { + SessionInfo session = _shared.Session; + try + { + return await _tunnel.OpenTcpAsync(session.SessionId, host, port, null, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException)) { - if (Interlocked.Exchange(ref _disposed, 1) != 0) + if (!await IsGoneAsync(session.SessionId, ex, cancellationToken).ConfigureAwait(false)) { - return; + throw; } + _log.Info($"SSH jump session '{Name}' is gone ({ex.Message}); reopening it."); + } + SessionInfo fresh = await ReopenAsync(session, cancellationToken).ConfigureAwait(false); + return await _tunnel.OpenTcpAsync(fresh.SessionId, host, port, null, cancellationToken).ConfigureAwait(false); + } + + private async Task IsGoneAsync(string sessionId, Exception failure, CancellationToken cancellationToken) + { + if (failure is PluginSessionNotFoundException) + { + return true; + } + try + { + SessionInfo? now = await _sessions.GetAsync(sessionId, cancellationToken).ConfigureAwait(false); + return now is null || now.State is SessionState.Disconnected or SessionState.Error; + } + catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException)) + { + // 连查都查不了:不猜,按原来的失败报。 + return false; + } + } + + /// 重开跳板会话(同一时刻只开一条:几条泵同时发现会话断了,只有第一条去开,其余用它开好的)。 + private async Task ReopenAsync(SessionInfo stale, CancellationToken cancellationToken) + { + await _shared.ReopenGate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + ObjectDisposedException.ThrowIf(_shared.Closed, this); + if (!string.Equals(_shared.Session.SessionId, stale.SessionId, StringComparison.Ordinal)) + { + return _shared.Session; + } + SessionInfo fresh = await _sessions.OpenAsync(_savedSessionId, new SessionOpenOptions(_shared.Reason), cancellationToken).ConfigureAwait(false); + bool closed; lock (Gate) { - if (--_shared.Count > 0) + closed = _shared.Closed; + if (!closed) { - return; + _shared.Session = fresh; } - _ = Open.Remove(_savedSessionId); } - try + if (closed) { - await _context.Sessions.CloseAsync(_shared.Session.SessionId).ConfigureAwait(false); + // 重开的这段时间里最后一个租约走了:新开的这条没人用,关掉。 + await CloseQuietlyAsync(_sessions, _log, fresh.SessionId, Name).ConfigureAwait(false); + throw new ObjectDisposedException(nameof(SshJumpLease)); } - catch (PluginPermissionDeniedException) + return fresh; + } + finally + { + _ = _shared.ReopenGate.Release(); + } + } + + /// + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + string sessionId; + lock (Gate) + { + if (--_shared.Count > 0) { - // 宿主复用了用户自己开着的那条会话:不归插件关。 + return; } - catch (Exception ex) when (ex is not OutOfMemoryException) + _shared.Closed = true; + sessionId = _shared.Session.SessionId; + if (Open.TryGetValue(_savedSessionId, out Shared? current) && ReferenceEquals(current, _shared)) { - _context.Log.Warn($"Closing the SSH jump session '{_shared.Name}' failed: {ex.Message}"); + _ = Open.Remove(_savedSessionId); } } + await CloseQuietlyAsync(_sessions, _log, sessionId, _shared.Name).ConfigureAwait(false); + } - private sealed class Shared(SessionInfo session, string name) + private static async Task CloseQuietlyAsync(ISessionsApi sessions, IPluginLogger log, string sessionId, string name) + { + try { - public SessionInfo Session { get; } = session; + await sessions.CloseAsync(sessionId).ConfigureAwait(false); + } + catch (PluginPermissionDeniedException) + { + // 宿主复用了用户自己开着的那条会话:不归插件关。 + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + log.Warn($"Closing the SSH jump session '{name}' failed: {ex.Message}"); + } + } - public string Name { get; } = name; + private sealed class Shared(SessionInfo session, string name, string reason) + { + private volatile SessionInfo _session = session; - public int Count { get; set; } + public SessionInfo Session + { + get => _session; + set => _session = value; } + + public string Name { get; } = name; + + public string Reason { get; } = reason; + + public int Count { get; set; } + + public bool Closed { get; set; } + + public SemaphoreSlim ReopenGate { get; } = new(1, 1); } } diff --git a/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs b/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs index c57f835..6d7c2d3 100644 --- a/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs +++ b/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs @@ -13,7 +13,11 @@ namespace VelaShell.Plugin.Mongo.Core; /// /// /// 用户此前确认信任的指纹;为空表示还没信任过。 -internal sealed class TlsTrust(string? trustedThumbprint) +/// +/// 经 SSH 跳板时的真实目标主机。驱动连的是本机回环,系统校验必报 ; +/// 这时改由这里拿证书的 SAN / CN 对真实主机核对,对上了才把这一条错误抹掉。不走跳板为 。 +/// +internal sealed class TlsTrust(string? trustedThumbprint, string? tunnelTargetHost = null) { /// 最近一次校验失败时看到的证书;没失败过为 。 public X509Certificate2? SeenCertificate { get; private set; } @@ -40,6 +44,15 @@ public bool Validate(X509Certificate? certificate, X509Chain? chain, SslPolicyEr } X509Certificate2 typed = certificate as X509Certificate2 ?? X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); + if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0 && MatchesTunnelTarget(typed)) + { + // 名字不匹配只是因为驱动连的是 127.0.0.1;证书确实是发给真实目标的,这一条不算错。 + errors &= ~SslPolicyErrors.RemoteCertificateNameMismatch; + if (errors == SslPolicyErrors.None) + { + return true; + } + } if (!string.IsNullOrEmpty(trustedThumbprint) && string.Equals(typed.Thumbprint, trustedThumbprint, StringComparison.OrdinalIgnoreCase)) { @@ -61,4 +74,21 @@ public bool Validate(X509Certificate? certificate, X509Chain? chain, SslPolicyEr PolicyErrors = errors; return false; } + + /// 证书的 SAN(没有 SAN 时退回 CN)覆盖跳板后面的真实主机。 + private bool MatchesTunnelTarget(X509Certificate2 certificate) + { + if (string.IsNullOrWhiteSpace(tunnelTargetHost)) + { + return false; + } + try + { + return certificate.MatchesHostname(tunnelTargetHost.Trim().Trim('[', ']')); + } + catch (ArgumentException) + { + return false; + } + } } diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs index d406189..18b3963 100644 --- a/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs +++ b/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs @@ -259,8 +259,17 @@ private static readonly (string Key, string En, string Zh)[] DesignTexts = ("Design_ApplyTitle", "Apply validation rule", "应用验证规则"), ("Design_ApplyBody", "Run collMod on {0} with validationLevel {1} · validationAction {2}?", "对 {0} 执行 collMod:validationLevel {1} · validationAction {2}?"), - ("Design_ApplyRejects", "{0} existing documents fail it; updates to them will be rejected.", "有 {0} 份现有文档不符合,对它们的更新会被拒绝。"), - ("Design_ApplyWarns", "{0} existing documents fail it; writes to them will log warnings.", "有 {0} 份现有文档不符合,对它们的写入会记录警告。"), + ("Design_ApplyFailCount", "{0} existing documents fail it.", "有 {0} 份现有文档不符合。"), + ("Design_ApplyFailSampled", "{0} of {1} sampled documents fail it.", "抽样的 {1} 份里有 {0} 份不符合。"), + ("Design_ApplyConseqReject", "Updates to such documents will be rejected.", "对这类文档的更新会被拒绝。"), + ("Design_ApplyConseqWarn", "Writes to such documents will be allowed and logged as warnings.", "对这类文档的写入照常进行,并记录警告。"), + ("Design_ApplyConseqModerate", "With moderate, updates to documents that already fail are not validated; inserts and updates to valid documents are.", + "moderate 下,对本就不符合的文档的更新不做校验;插入与对合规文档的更新照常校验。"), + ("Design_ApplyConseqOff", "Validation is off, so nothing is enforced.", "validationLevel 为 off,规则不生效。"), + ("Design_ApplyUnknown", "The pre-check hasn't finished, so it's unknown how many existing documents fail.", "预检尚未完成,现有文档有多少不符合还不知道。"), + ("Design_ViewAllInGrid", "View all failing in grid", "在网格中查看全部不通过"), + ("Design_ViewAllInGridTip", "This group is too large to list by _id: the grid shows every document that fails the rule, not only this group.", + "这一组太多,无法按 _id 列出:网格里显示的是全部不符合规则的文档,而不只是这一组。"), ("Design_PrecheckFailures", "Failing (pre-check)", "预检不通过"), ("Design_Applied", "Validation rule applied", "已应用验证规则"), ("Design_CompletionKeyword", "keyword", "关键字"), diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs b/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs index e577e71..09d81b7 100644 --- a/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs +++ b/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs @@ -77,6 +77,10 @@ private static readonly (string Key, string En, string Zh)[] GridFsTexts = ("Fs_Idle", "No transfers", "无传输任务"), ("Fs_CancelTransfers", "Cancel transfers", "取消传输"), ("Fs_TransfersCancelled", "Transfers cancelled", "已取消传输"), + ("Fs_CloseTransfersTitle", "Cancel transfers and close?", "取消传输并关闭?"), + ("Fs_CloseTransfersBody", "{0} transfers are still running or queued. Closing the tab cancels them; partly downloaded files are deleted and a cancelled upload leaves nothing behind.", + "还有 {0} 个传输在进行或排队。关闭标签会全部取消:下载到一半的文件会删掉,取消的上传不留残余。"), + ("Fs_CloseTransfersConfirm", "Cancel and close", "取消并关闭"), ("Fs_UploadDone", "Uploaded {0} files · {1}", "已上传 {0} 个文件 · {1}"), ("Fs_DownloadDone", "Downloaded {0} files · {1}", "已下载 {0} 个文件 · {1}"), ("Fs_TransferFailed", "{0} failed: {1}", "{0} 失败:{1}"), diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs index 08a30ca..fc19253 100644 --- a/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs +++ b/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs @@ -92,6 +92,7 @@ private static readonly (string Key, string En, string Zh)[] ObjectsTexts = ("Obj_CopiedDdl", "Copied the structure of {0}", "已复制 {0} 的结构"), ("Obj_CopiedDdlDetail", "{0} lines of mongosh", "{0} 行 mongosh 脚本"), ("Obj_DropBucketTitle", "Drop GridFS bucket", "删除 GridFS 存储桶"), + ("Obj_DropBucketPartial", "Bucket {0} was only partly dropped: {1} is still there ({2})", "存储桶 {0} 只删掉了一半:{1} 还在({2})"), ("Obj_DropBucketBody", "This permanently deletes the bucket {0} — both .files and .chunks — and every file in it. This cannot be undone.", "将永久删除存储桶 {0}(.files 与 .chunks 两个集合)及其中全部文件。此操作无法撤销。") ]; diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs index f76876a..24bbe47 100644 --- a/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs +++ b/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs @@ -242,6 +242,10 @@ private static readonly (string Key, string En, string Zh)[] QueryTexts = ("Query_SnipMatchEqHint", "Keep documents whose field equals a value.", "保留字段等于某个值的文档。"), ("Query_SnipGroupCount", "$group count…", "$group 计数…"), ("Query_SnipGroupCountHint", "Count documents per value of a field.", "按字段取值分组计数。"), + ("Query_SnipField", "", "<字段>"), + ("Query_SnipValue", "", "<值>"), + ("Query_CodeTunnelNote", "VelaShell reaches this server through an SSH jump host; the address below is the real target, so this code must reach it directly (or through its own tunnel).", + "VelaShell 经 SSH 跳板连接这台服务器;下面是跳板后面的真实地址,运行这段代码的机器要能直接到达它(或自己建隧道)。"), // ── 右侧面板 ── ("Query_HelperFields", "Fields", "字段"), diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs index 831f89a..861ac97 100644 --- a/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs +++ b/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs @@ -234,6 +234,12 @@ private static readonly (string Key, string En, string Zh)[] TransferTexts = ("Imp_OpenReport", "Show error report", "打开错误报告"), ("Imp_NotWritten", "Not written: the ordered batch stopped at row {0}", "未写入:ordered 批次在第 {0} 行出错后停止"), ("Imp_Stop", "Stop import", "停止导入"), + ("Imp_StopTitle", "Stop the import?", "停止导入?"), + ("Imp_StopBody", "Rows already written stay in the collection; the batch being written may or may not be committed. A stopped import can't be resumed — the error report and backup written so far are kept.", + "已写入的行留在集合里;正在写的那一批可能写进去、也可能没有。停止后不能接着导 —— 已写出的错误报告与备份会保留。"), + ("Imp_FailedPartial", "Import failed: {0} — {1} inserted and {2} updated before the failure", "导入失败:{0} —— 失败前已新增 {1}、更新 {2}"), + ("Imp_BackupFile", "Backup of overwritten documents", "覆盖前备份"), + ("Imp_OpenBackup", "Show backup", "打开备份"), ("Imp_SaveProfile", "Save as import profile", "保存为导入配置"), // ── 数据传输(设计稿 21) ── diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs index 353b628..f21fee1 100644 --- a/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs +++ b/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs @@ -70,6 +70,7 @@ private static readonly (string Key, string En, string Zh)[] UsersTexts = ("Users_BadAddress", "Not an IP address or CIDR: {0}", "不是 IP 地址或 CIDR:{0}"), ("Users_NeedName", "Enter a user name", "请填写用户名"), ("Users_NeedPassword", "Enter or generate a password", "请填写或生成密码"), + ("Users_NeedConfirmPassword", "Type the password again to confirm it", "请再输一遍密码以确认"), ("Users_NameTaken", "{0} already exists", "{0} 已存在"), // ── 角色编辑器 ── @@ -124,6 +125,13 @@ private static readonly (string Key, string En, string Zh)[] UsersTexts = "A strong random password replaces the current one of {0}. It is copied to the clipboard and shown once. Applications still using the old password fail at their next login.", "将为 {0} 生成一个强随机密码并立即替换当前密码;新密码复制到剪贴板并只显示一次。仍在用旧密码的应用下次登录时会失败。"), ("Users_PasswordChanged", "Password of {0} changed", "已更新 {0} 的密码"), + ("Users_SelfPasswordTitle", "Change the password of the current connection's user?", "修改当前连接所用账号的密码?"), + ("Users_SelfPasswordBody", + "{0} is the identity this connection logged in with. Sockets already open stay authenticated, but new pooled sockets and reconnects use the password the connection was opened with and will be rejected until you reconnect. If this connection has a saved password, it is updated to the new one.", + "{0} 是这条连接登录所用的身份。已打开的连接不受影响,但连接池新开的连接与重连仍用打开时的密码,会被拒绝,直到重新连接。这条连接若保存了密码,会一并更新成新密码。"), + ("Users_SelfPasswordContinue", "Continue", "继续"), + ("Users_SavedPasswordUpdated", "Saved password of this connection updated — reconnect to use it", "已更新这条连接保存的密码 —— 重新连接后生效"), + ("Users_SavedPasswordFailed", "The saved password of this connection could not be updated: {0}", "未能更新这条连接保存的密码:{0}"), ("Users_ResetTitle", "Reset password", "重置密码"), ("Users_NewPassword", "New password", "新密码"), ("Users_ConfirmPassword", "Type it again", "再输一遍"), diff --git a/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs b/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs index ea39625..b128f07 100644 --- a/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs +++ b/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs @@ -203,10 +203,25 @@ public static MongoSettings From(WorkspaceConnectRequest request) }, ShowSystemDatabases = request.GetBoolean(KeyShowSystemDatabases), JumpSessionId = request.GetString(KeyJumpSession), - TrustedThumbprint = request.GetString(KeyTrustedThumbprint) + TrustedThumbprint = request.GetString(KeyTrustedThumbprint), + ReadPreferenceSet = request.Settings.ContainsKey(KeyReadPreference), + AppNameSet = request.Settings.ContainsKey(KeyAppName), + ConnectTimeoutSet = request.Settings.ContainsKey(KeyConnectTimeout) }; } + // 下面三个标记只给 URI 形态用:对话框把默认值存成"没有这个键",所以"键在"就是用户在表单里改过。 + // URI 里写了 readPreference / appName / connectTimeoutMS 时,表单没改过就听 URI 的。 + + /// 读偏好是用户在表单里显式设的(不是默认值)。 + public bool ReadPreferenceSet { get; init; } + + /// appName 是用户在表单里显式设的。 + public bool AppNameSet { get; init; } + + /// 连接超时是用户在表单里显式设的。 + public bool ConnectTimeoutSet { get; init; } + private static bool? ExplicitBool(WorkspaceConnectRequest request, string key) => request.Settings.TryGetValue(key, out string? raw) && bool.TryParse(raw, out bool parsed) ? parsed : null; diff --git a/plugins/VelaShell.Plugin.Mongo/MongoStore.cs b/plugins/VelaShell.Plugin.Mongo/MongoStore.cs index 704f015..db97773 100644 --- a/plugins/VelaShell.Plugin.Mongo/MongoStore.cs +++ b/plugins/VelaShell.Plugin.Mongo/MongoStore.cs @@ -30,7 +30,7 @@ internal sealed record SavedItem(string Name, string Content, DateTimeOffset Sav /// /// /// 插件上下文。 -internal sealed class MongoStore(IPluginContext context) +internal sealed partial class MongoStore(IPluginContext context) { private const string HistoryMeasurement = "query_history"; private const int HistoryLimit = 300; @@ -103,7 +103,11 @@ public async Task SaveItemAsync(string kind, string connectionKey, SavedItem ite await SetAsync(Key("saved-" + kind, connectionKey, ""), next).ConfigureAwait(false); } - /// 追加一条查询历史。 + /// + /// 追加一条查询历史。落盘前先脱敏(:口令字面量换成星号)再截断到 + /// —— 口令只该在宿主的密钥库里,不该躺在明文的历史表里; + /// 一段几兆的脚本也不该整段塞进每一条历史。 + /// public async Task AppendQueryHistoryAsync(string connectionKey, QueryHistoryEntry entry) { if (await OpenHistoryAsync().ConfigureAwait(false) is not { } series) @@ -117,7 +121,7 @@ await series.WriteAsync(new( new Dictionary { ["conn"] = connectionKey, ["db"] = entry.Database }, new Dictionary { - ["text"] = TimeSeriesValue.FromText(entry.Text), + ["text"] = TimeSeriesValue.FromText(PrepareHistoryText(entry.Text)), ["ms"] = TimeSeriesValue.FromInteger(entry.ElapsedMs), ["ok"] = TimeSeriesValue.FromFlag(entry.Ok) })).ConfigureAwait(false); @@ -193,4 +197,49 @@ public async Task> LoadQueryHistoryAsync(string private static string Key(string kind, string connectionKey, string ns) => string.Create(CultureInfo.InvariantCulture, $"{kind}:{connectionKey}:{ns}"); + + /// 一条历史最多存多少个字符(超出截断并加省略号)。 + internal const int HistoryTextLimit = 8 * 1024; + + /// 脱敏 + 截断(先脱敏再截,免得截断把口令字面量切成半截、正则认不出来)。 + internal static string PrepareHistoryText(string text) + { + string redacted = RedactHistoryText(text); + return redacted.Length > HistoryTextLimit ? redacted[..HistoryTextLimit] + "…" : redacted; + } + + /// + /// 把语句里的口令换成 "***": + /// pwd / password / passwordDigest 键后的字符串字面量(createUser、updateUser、db.auth({…})); + /// changeUserPassword(user, "…") 与 db.auth(user, "…") 的第二个实参;连接串里 user:口令@ 的口令。 + /// pwd: passwordPrompt() 之类不是字面量的值原样保留 —— 那里本来就没有口令。 + /// + internal static string RedactHistoryText(string text) + { + if (string.IsNullOrEmpty(text)) + { + return text; + } + string result = PasswordField().Replace(text, static m => m.Groups["key"].Value + Mask(m.Groups["quote"].Value)); + result = PasswordArgument().Replace(result, static m => m.Groups["head"].Value + Mask(m.Groups["quote"].Value)); + return UriPassword().Replace(result, static m => m.Groups["head"].Value + "****@"); + } + + private static string Mask(string quote) => quote + "***" + quote; + + // 字符串字面量:"…" 或 '…' 或 `…`,含转义。 + private const string Literal = """(?["'`])(?:\\.|(?!\k).)*\k"""; + + [System.Text.RegularExpressions.GeneratedRegex( + """(?(?:["']?)\b(?:pwd|password|passwordDigest)\b(?:["']?)\s*:\s*)""" + Literal, + System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline)] + private static partial System.Text.RegularExpressions.Regex PasswordField(); + + [System.Text.RegularExpressions.GeneratedRegex( + """(?\b(?:changeUserPassword|auth)\s*\(\s*(?:["'`](?:\\.|[^"'`\\])*["'`]|[\w.$]+)\s*,\s*)""" + Literal, + System.Text.RegularExpressions.RegexOptions.Singleline)] + private static partial System.Text.RegularExpressions.Regex PasswordArgument(); + + [System.Text.RegularExpressions.GeneratedRegex("""(?mongodb(?:\+srv)?://[^:/@\s"'`]+:)[^@\s"'`]*@""", System.Text.RegularExpressions.RegexOptions.IgnoreCase)] + private static partial System.Text.RegularExpressions.Regex UriPassword(); } diff --git a/plugins/VelaShell.Plugin.Mongo/README.md b/plugins/VelaShell.Plugin.Mongo/README.md index ea0f0d1..4274be2 100644 --- a/plugins/VelaShell.Plugin.Mongo/README.md +++ b/plugins/VelaShell.Plugin.Mongo/README.md @@ -37,7 +37,17 @@ Navicat 式的对象树与大图标工具栏,补齐 Compass 的聚合管道、Sc - **连接由插件自己管**:已保存的连接进插件存储(`MongoProfileStore`,键 `connections`),**口令进宿主的加密密钥库** (`ISecretsApi`,按连接 id),不写进连接串、不写进插件存储。SSH 跳板经宿主里已保存的 SSH 连接转发 (`ISessionsApi.OpenAsync` + `IRemoteTunnelApi.OpenTcpAsync`,本机回环上起转发端口)—— 插件一行 SSH 代码都不写, - 也碰不到跳板机的凭据;几条连接走同一台跳板时共用一条会话,只关本插件开的那条。 + 也碰不到跳板机的凭据;几条连接走同一台跳板时共用一条会话,只关本插件开的那条(并发连同一台跳板时后到者自己开的那条当场关掉; + 跳板会话断了,下一次开流时查实后重开一条再试一次)。连接串形态经跳板时"主机"一栏仍是整条连接串,驱动按串里的选项连、 + 服务器换成本机转发端口并直连;`mongodb+srv://` 不能走跳板(报 `Conn_SshNoSrv`,不悄悄绕过跳板直连)。经跳板的 TLS 由插件拿证书的 + SAN / CN 对真实目标主机核对(驱动连的是 127.0.0.1,系统校验的主机名必然对不上)。 +- **连接串形态的选项以连接串为准**:`readPreference` / `appName` / `connectTimeoutMS` / `serverSelectionTimeoutMS` / `compressors` + 写在连接串里时,只有用户在表单里显式改过(设置键存在)才覆盖 —— 与连接串预览一致。 +- **CSV / XLSX 导出默认无损**:Decimal128 原样全精度、日期写 ISO 8601 UTC(带毫秒);"保留 2 位"、"本地时间"要在字段表里显式选。 + XLSX 里超过 2^53 的 Int64、有效位数超过 double 的 Decimal128 写成文本(写成数字 Excel 会悄悄改值)。导入时逗号只在合法千分位里才去掉, + `1,5` 这种报错而不是变成 15。 +- **查询历史落盘前脱敏**:`pwd` / `password` / `passwordDigest` 后的字符串字面量、`changeUserPassword` / `db.auth` 的口令实参、 + 连接串里的口令换成星号(`passwordPrompt()` 原样),每条最多存 8 KB。 - **数据传输的"目标连接"**:本插件此刻开着的连接(`MongoSessionRegistry`)或手填一条连接串。 ## 与设计稿 / DESIGN.md 的偏离(刻意的) @@ -120,6 +130,10 @@ Navicat 式的对象树与大图标工具栏,补齐 Compass 的聚合管道、Sc | 设计稿底部那行状态栏 | 面板自己画一条 24px 状态条:当前连接 · 范围 · 当前标签的状态(待提交数等并在标签的那一段里);没有「UTF-8」那一格 | 面板没有宿主状态栏可用(那是会话标签的);编码对 MongoDB 无意义 | | 时序集合不能「创建后立即编辑验证规则」 | 服务器不允许给时序集合设 validator,对话框里这一项置灰 | | 弹出层(补全、右键菜单、类型菜单)不进 headless 截图 | 它们是独立的顶层窗口;接线由单测覆盖 | +| 查询编辑器的 `.readPref()` / `.readConcern()` 报"不支持" | 读偏好跟连接走;`.min()` / `.max()` / `.returnKey()` / `.showRecordId()` / `.noCursorTimeout()` / `.count(true)` 照常落到驱动 | +| 只读模式下 `runCommand` 只放行白名单里的只读命令 | `ShellParser.IsWriteCommand`:黑名单永远列不全;`aggregate` 看有没有 `$out` / `$merge`,`mapReduce` 只有 `out: { inline: 1 }` 算读,`explain` 看内层 | +| 只有集合级权限的用户,集合列表里没有选项(capped、验证规则等) | 库级 `listCollections` 被拒时退回 `nameOnly + authorizedCollections`,服务器只回名字与类型 | +| 执行计划在 SBE(`explainVersion: "2"`)下各阶段只有返回数 / 扫描键数 | 阶段树按 `queryPlan` 建,统计按 `planNodeId` 从槽位树里取;读出文档数、works 槽位树里没有对应量 | ## 开发 diff --git a/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs b/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs index 3564308..ebc9a6a 100644 --- a/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs +++ b/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs @@ -243,8 +243,18 @@ private abstract class Writer(Op op, string connectionString) protected readonly SortedSet Imports = [with(StringComparer.Ordinal)]; + /// + /// 字面量里出现过 UUID(子类型 4)。PyMongo 与 Java 驱动默认的 uuidRepresentation 是 unspecified, + /// 直接编码 uuid.UUID / java.util.UUID 会抛错 —— 生成的客户端要设成 standard。 + /// + protected bool UsesUuid { get; set; } + + /// 没有对应字面量、只能写成空值的 BSON 类型(在代码前面写一行注释说明)。 + protected readonly SortedSet Unmapped = [with(StringComparer.Ordinal)]; + public abstract string Write(); + /// 四种语言共用的双引号字符串字面量。\uXXXX 四种语言都认;U+0085 / U+2028 / U+2029 在 C# 源码里算换行,也转义。 protected static string Escape(string text) { var b = new StringBuilder(text.Length + 2); @@ -258,7 +268,8 @@ protected static string Escape(string text) '\n' => "\\n", '\r' => "\\r", '\t' => "\\t", - _ => c < ' ' ? $"\\u{(int)c:x4}" : c.ToString() + (char)0x85 or (char)0x2028 or (char)0x2029 => $"\\u{(int)c:x4}", + _ => c < ' ' || c == (char)0x7f ? $"\\u{(int)c:x4}" : c.ToString() }); } _ = b.Append('"'); @@ -267,11 +278,36 @@ protected static string Escape(string text) protected static string IsoString(BsonValue value) => BsonText.IsoDate(value); + /// 日期能用 .NET / ISO 8601 表示(公元 1–9999 年);否则各语言退回毫秒构造。 + protected static bool Representable(BsonValue value) => BsonText.IsRepresentableDate(value.AsBsonDateTime.MillisecondsSinceEpoch); + + protected static long Millis(BsonValue value) => value.AsBsonDateTime.MillisecondsSinceEpoch; + protected static DateTime Utc(BsonValue value) => DateTimeOffset.FromUnixTimeMilliseconds(value.AsBsonDateTime.MillisecondsSinceEpoch).UtcDateTime; + /// double 字面量(整数值补 .0,免得变成整型)。NaN / ±∞ 由各语言自己写。 protected static string Number(double d) => d.ToString("R", CultureInfo.InvariantCulture) is var s && (s.Contains('.') || s.Contains('E')) ? s : s + ".0"; + /// double → 目标语言字面量;、、 是该语言的写法。 + protected static string DoubleLiteral(double d, string nan, string positive, string negative) => + double.IsNaN(d) ? nan : double.IsPositiveInfinity(d) ? positive : double.IsNegativeInfinity(d) ? negative : Number(d); + + /// 二进制的 base64 文本。 + protected static string Base64(BsonValue value) => Convert.ToBase64String(value.AsBsonBinaryData.Bytes); + + /// 记一个没有字面量的类型,返回该语言的空值。 + protected string Unsupported(BsonValue value, string nullLiteral) + { + _ = Unmapped.Add(value.BsonType.ToString()); + return nullLiteral; + } + + /// 代码前面的说明注释(有没有字面量可写的类型时)。 + protected string UnmappedNote(string commentPrefix) => Unmapped.Count == 0 + ? "" + : $"{commentPrefix} Note: BSON type(s) {string.Join(", ", Unmapped)} have no literal in this language; they are written as null below.\n"; + protected static string Pad(int level) => new(' ', level * 4); } @@ -525,7 +561,7 @@ private static string Lit(BsonValue value, int level) case BsonType.Int64: return value.AsInt64.ToString(CultureInfo.InvariantCulture) + "L"; case BsonType.Double: - return Number(value.AsDouble); + return DoubleLiteral(value.AsDouble, "double.NaN", "double.PositiveInfinity", "double.NegativeInfinity"); case BsonType.Decimal128: return $"Decimal128.Parse({Escape(value.AsDecimal128.ToString())})"; case BsonType.Boolean: @@ -534,6 +570,9 @@ private static string Lit(BsonValue value, int level) return "BsonNull.Value"; case BsonType.ObjectId: return $"new ObjectId({Escape(value.AsObjectId.ToString())})"; + case BsonType.DateTime when !Representable(value): + // DateTime 表示不了(公元 1 年前 / 9999 年后):按毫秒构造 BsonDateTime。 + return $"new BsonDateTime({Millis(value).ToString(CultureInfo.InvariantCulture)}L)"; case BsonType.DateTime: { DateTime at = Utc(value); @@ -566,13 +605,15 @@ public override string Write() { _ = head.Append(import).Append('\n'); } - _ = head.Append("\nclient = MongoClient(").Append(Escape(ConnectionString)).Append(")\n"); + // uuid.UUID 要求客户端 uuidRepresentation=standard(PyMongo 4 默认 unspecified,编码时直接抛错)。 + _ = head.Append("\nclient = MongoClient(").Append(Escape(ConnectionString)) + .Append(UsesUuid ? ", uuidRepresentation=\"standard\")\n" : ")\n"); _ = head.Append("db = client[").Append(Escape(Op.Database)).Append("]\n"); if (Op.Collection is { } c) { _ = head.Append("collection = db[").Append(Escape(c)).Append("]\n"); } - return head.Append('\n').Append(Body).ToString().TrimEnd() + "\n"; + return head.Append('\n').Append(UnmappedNote("#")).Append(Body).ToString().TrimEnd() + "\n"; } private void Var(string name, BsonValue value) => Body.Append(name).Append(" = ").Append(Lit(value, 0)).Append('\n'); @@ -745,10 +786,14 @@ private string Lit(BsonValue value, int level) } case BsonType.String: return Escape(value.AsString); - case BsonType.Int32 or BsonType.Int64: - return value.ToInt64().ToString(CultureInfo.InvariantCulture); + case BsonType.Int32: + return value.AsInt32.ToString(CultureInfo.InvariantCulture); + case BsonType.Int64: + // 裸 int 在 PyMongo 里按大小编码:装得进 32 位就成了 Int32,类型悄悄变了。 + _ = Imports.Add("from bson.int64 import Int64"); + return $"Int64({value.AsInt64.ToString(CultureInfo.InvariantCulture)})"; case BsonType.Double: - return Number(value.AsDouble); + return DoubleLiteral(value.AsDouble, "float(\"nan\")", "float(\"inf\")", "float(\"-inf\")"); case BsonType.Decimal128: _ = Imports.Add("from bson.decimal128 import Decimal128"); return $"Decimal128({Escape(value.AsDecimal128.ToString())})"; @@ -759,6 +804,10 @@ private string Lit(BsonValue value, int level) case BsonType.ObjectId: _ = Imports.Add("from bson import ObjectId"); return $"ObjectId({Escape(value.AsObjectId.ToString())})"; + case BsonType.DateTime when !Representable(value): + // Python 的 datetime 只到 1–9999 年;越界的毫秒值用 DatetimeMS(PyMongo 4.3+)。 + _ = Imports.Add("from bson.datetime_ms import DatetimeMS"); + return $"DatetimeMS({Millis(value).ToString(CultureInfo.InvariantCulture)})"; case BsonType.DateTime: { _ = Imports.Add("from datetime import datetime, timezone"); @@ -771,9 +820,32 @@ private string Lit(BsonValue value, int level) return $"Regex({Escape(value.AsBsonRegularExpression.Pattern)}, {Escape(value.AsBsonRegularExpression.Options)})"; case BsonType.Binary when value.AsBsonBinaryData.SubType is BsonBinarySubType.UuidStandard: _ = Imports.Add("import uuid"); + UsesUuid = true; return $"uuid.UUID({Escape(value.AsBsonBinaryData.ToGuid().ToString())})"; + case BsonType.Binary: + _ = Imports.Add("import base64"); + _ = Imports.Add("from bson.binary import Binary"); + return $"Binary(base64.b64decode({Escape(Base64(value))}), {(int)value.AsBsonBinaryData.SubType})"; + case BsonType.Timestamp: + _ = Imports.Add("from bson.timestamp import Timestamp"); + return $"Timestamp({value.AsBsonTimestamp.Timestamp}, {value.AsBsonTimestamp.Increment})"; + case BsonType.MinKey: + _ = Imports.Add("from bson.min_key import MinKey"); + return "MinKey()"; + case BsonType.MaxKey: + _ = Imports.Add("from bson.max_key import MaxKey"); + return "MaxKey()"; + case BsonType.JavaScript: + _ = Imports.Add("from bson.code import Code"); + return $"Code({Escape(value.AsBsonJavaScript.Code)})"; + case BsonType.JavaScriptWithScope: + _ = Imports.Add("from bson.code import Code"); + return $"Code({Escape(value.AsBsonJavaScriptWithScope.Code)}, {Lit(value.AsBsonJavaScriptWithScope.Scope, level)})"; + case BsonType.Symbol: + return Escape(value.AsBsonSymbol.Name); default: - return Escape(value.ToString() ?? ""); + // Python 没有块注释,行内注释会把同一行后面的代码一起注释掉 —— 写 None,说明放在代码前面。 + return Unsupported(value, "None"); } } } @@ -969,8 +1041,12 @@ private string Lit(BsonValue value, int level) case BsonType.Int64: _ = Imports.Add("Long"); return $"Long.fromString({Escape(value.AsInt64.ToString(CultureInfo.InvariantCulture))})"; + case BsonType.Double when double.IsFinite(value.AsDouble) && Math.Floor(value.AsDouble) == value.AsDouble: + // JS 里 5 与 5.0 是同一个数,驱动按整数存成 Int32:整数值的 double 包一层 Double 保住类型。 + _ = Imports.Add("Double"); + return $"new Double({value.AsDouble.ToString("R", CultureInfo.InvariantCulture)})"; case BsonType.Double: - return value.AsDouble.ToString("R", CultureInfo.InvariantCulture); + return DoubleLiteral(value.AsDouble, "NaN", "Infinity", "-Infinity"); case BsonType.Decimal128: _ = Imports.Add("Decimal128"); return $"Decimal128.fromString({Escape(value.AsDecimal128.ToString())})"; @@ -981,15 +1057,39 @@ private string Lit(BsonValue value, int level) case BsonType.ObjectId: _ = Imports.Add("ObjectId"); return $"new ObjectId({Escape(value.AsObjectId.ToString())})"; + case BsonType.DateTime when !Representable(value): + return $"new Date({Millis(value).ToString(CultureInfo.InvariantCulture)})"; case BsonType.DateTime: return $"new Date({Escape(IsoString(value))})"; case BsonType.RegularExpression: - return $"/{value.AsBsonRegularExpression.Pattern.Replace("/", "\\/", StringComparison.Ordinal)}/{value.AsBsonRegularExpression.Options}"; + _ = Imports.Add("BSONRegExp"); + // 用 BSONRegExp 而不是 /…/ 字面量:BSON 正则的选项(x、s、u…)与 JS 正则的不完全一样,模式里的换行也写得进字符串。 + return $"new BSONRegExp({Escape(value.AsBsonRegularExpression.Pattern)}, {Escape(value.AsBsonRegularExpression.Options)})"; case BsonType.Binary when value.AsBsonBinaryData.SubType is BsonBinarySubType.UuidStandard: _ = Imports.Add("UUID"); return $"new UUID({Escape(value.AsBsonBinaryData.ToGuid().ToString())})"; + case BsonType.Binary: + _ = Imports.Add("Binary"); + return $"new Binary(Buffer.from({Escape(Base64(value))}, \"base64\"), {(int)value.AsBsonBinaryData.SubType})"; + case BsonType.Timestamp: + _ = Imports.Add("Timestamp"); + return $"new Timestamp({{ t: {value.AsBsonTimestamp.Timestamp}, i: {value.AsBsonTimestamp.Increment} }})"; + case BsonType.MinKey: + _ = Imports.Add("MinKey"); + return "new MinKey()"; + case BsonType.MaxKey: + _ = Imports.Add("MaxKey"); + return "new MaxKey()"; + case BsonType.JavaScript: + _ = Imports.Add("Code"); + return $"new Code({Escape(value.AsBsonJavaScript.Code)})"; + case BsonType.JavaScriptWithScope: + _ = Imports.Add("Code"); + return $"new Code({Escape(value.AsBsonJavaScriptWithScope.Code)}, {Lit(value.AsBsonJavaScriptWithScope.Scope, level)})"; + case BsonType.Symbol: + return Escape(value.AsBsonSymbol.Name); default: - return Escape(value.ToString() ?? ""); + return $"null /* {value.BsonType}: no literal */"; } } @@ -1012,12 +1112,29 @@ public override string Write() _ = Imports.Add("com.mongodb.client.MongoCollection"); } Statement(); + if (UsesUuid) + { + _ = Imports.Add("com.mongodb.ConnectionString"); + _ = Imports.Add("com.mongodb.MongoClientSettings"); + _ = Imports.Add("org.bson.UuidRepresentation"); + } var head = new StringBuilder(); foreach (string import in Imports) { _ = head.Append("import ").Append(import).Append(";\n"); } - _ = head.Append("\nMongoClient client = MongoClients.create(").Append(Escape(ConnectionString)).Append(");\n"); + if (UsesUuid) + { + // UUID.fromString 编码要求 uuidRepresentation=STANDARD(Java 驱动默认 UNSPECIFIED,编码 java.util.UUID 时抛错)。 + _ = head.Append("\nMongoClient client = MongoClients.create(MongoClientSettings.builder()\n") + .Append(Pad(1)).Append(".applyConnectionString(new ConnectionString(").Append(Escape(ConnectionString)).Append("))\n") + .Append(Pad(1)).Append(".uuidRepresentation(UuidRepresentation.STANDARD)\n") + .Append(Pad(1)).Append(".build());\n"); + } + else + { + _ = head.Append("\nMongoClient client = MongoClients.create(").Append(Escape(ConnectionString)).Append(");\n"); + } _ = head.Append("MongoDatabase database = client.getDatabase(").Append(Escape(Op.Database)).Append(");\n"); if (Op.Collection is { } c) { @@ -1235,7 +1352,7 @@ private string Lit(BsonValue value, int level) case BsonType.Int64: return value.AsInt64.ToString(CultureInfo.InvariantCulture) + "L"; case BsonType.Double: - return Number(value.AsDouble); + return DoubleLiteral(value.AsDouble, "Double.NaN", "Double.POSITIVE_INFINITY", "Double.NEGATIVE_INFINITY"); case BsonType.Decimal128: _ = Imports.Add("java.math.BigDecimal"); _ = Imports.Add("org.bson.types.Decimal128"); @@ -1247,6 +1364,9 @@ private string Lit(BsonValue value, int level) case BsonType.ObjectId: _ = Imports.Add("org.bson.types.ObjectId"); return $"new ObjectId({Escape(value.AsObjectId.ToString())})"; + case BsonType.DateTime when !Representable(value): + _ = Imports.Add("java.util.Date"); + return $"new Date({Millis(value).ToString(CultureInfo.InvariantCulture)}L)"; case BsonType.DateTime: _ = Imports.Add("java.time.Instant"); _ = Imports.Add("java.util.Date"); @@ -1256,9 +1376,31 @@ private string Lit(BsonValue value, int level) return $"new BsonRegularExpression({Escape(value.AsBsonRegularExpression.Pattern)}, {Escape(value.AsBsonRegularExpression.Options)})"; case BsonType.Binary when value.AsBsonBinaryData.SubType is BsonBinarySubType.UuidStandard: _ = Imports.Add("java.util.UUID"); + UsesUuid = true; return $"UUID.fromString({Escape(value.AsBsonBinaryData.ToGuid().ToString())})"; + case BsonType.Binary: + _ = Imports.Add("java.util.Base64"); + _ = Imports.Add("org.bson.types.Binary"); + return $"new Binary((byte) {(int)value.AsBsonBinaryData.SubType}, Base64.getDecoder().decode({Escape(Base64(value))}))"; + case BsonType.Timestamp: + _ = Imports.Add("org.bson.BsonTimestamp"); + return $"new BsonTimestamp({value.AsBsonTimestamp.Timestamp}, {value.AsBsonTimestamp.Increment})"; + case BsonType.MinKey: + _ = Imports.Add("org.bson.types.MinKey"); + return "new MinKey()"; + case BsonType.MaxKey: + _ = Imports.Add("org.bson.types.MaxKey"); + return "new MaxKey()"; + case BsonType.JavaScript: + _ = Imports.Add("org.bson.types.Code"); + return $"new Code({Escape(value.AsBsonJavaScript.Code)})"; + case BsonType.JavaScriptWithScope: + _ = Imports.Add("org.bson.types.CodeWithScope"); + return $"new CodeWithScope({Escape(value.AsBsonJavaScriptWithScope.Code)}, {Lit(value.AsBsonJavaScriptWithScope.Scope, level)})"; + case BsonType.Symbol: + return Escape(value.AsBsonSymbol.Name); default: - return Escape(value.ToString() ?? ""); + return $"null /* {value.BsonType}: no literal */"; } } } diff --git a/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs b/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs index d7770eb..bcdb310 100644 --- a/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs +++ b/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs @@ -234,17 +234,35 @@ private async Task DatabaseAsync(ShellCommand command, string datab BsonString s => new BsonDocument(s.Value, 1), _ => throw new ShellExecutionException(loc.Format("Query_ErrNeedsDocument", method.Name)) }; - if (body.ElementCount > 0 && ShellParser.WriteCommands.Contains(body.GetElement(0).Name)) + if (ShellParser.IsWriteCommand(body)) { + // 与 db.dropDatabase() / db.c.drop() / db.c.dropIndex() 同一套护栏:runCommand 不是绕过它们的后门。 + BsonElement head = body.GetElement(0); + bool dropDatabase = head.Name.Equals("dropDatabase", StringComparison.OrdinalIgnoreCase); + if (dropDatabase && guard.DisableDropDatabase) + { + throw new ShellExecutionException(loc["Query_ErrDropDatabaseDisabled"]); + } if (!guard.EnsureWritable(target)) { return Blocked(command, database); } - if (body.GetElement(0).Name.Equals("dropDatabase", StringComparison.OrdinalIgnoreCase) - && !await ConfirmDropDatabaseAsync(target).ConfigureAwait(false)) + if (dropDatabase && !await ConfirmDropDatabaseAsync(target).ConfigureAwait(false)) { return Declined(command, target); } + if (head.Name.Equals("drop", StringComparison.OrdinalIgnoreCase) && head.Value is BsonString dropped && guard.ConfirmWrites + && !await guard.ConfirmAsync(new ShellConfirmation(ShellConfirmKind.Drop, target, dropped.Value, null, + await connection.EstimatedCountAsync(target, dropped.Value, cancellationToken).ConfigureAwait(true))).ConfigureAwait(true)) + { + return Declined(command, target, dropped.Value); + } + if (head.Name.Equals("dropIndexes", StringComparison.OrdinalIgnoreCase) && head.Value is BsonString indexed && guard.ConfirmWrites + && !await guard.ConfirmAsync(new ShellConfirmation(ShellConfirmKind.DropIndex, target, indexed.Value, null, null, + body.GetValue("index", "*").ToString())).ConfigureAwait(true)) + { + return Declined(command, target, indexed.Value); + } } BsonDocument reply = await connection.RunCommandAsync(target, body, cancellationToken).ConfigureAwait(false); bool catalog = body.ElementCount > 0 && body.GetElement(0).Name is "create" or "drop" or "renameCollection" or "dropDatabase"; @@ -317,12 +335,18 @@ private async Task DatabaseAsync(ShellCommand command, string datab case "aggregate": { BsonArray pipeline = method.Arg(0) as BsonArray ?? throw new ShellExecutionException(loc.Format("Query_ErrNeedsPipeline", "aggregate")); + // 库级管道($currentOp / $documents …)末尾同样可以接 $out / $merge 写出。 + bool writes = ShellParser.WritesPipeline(pipeline); + if (writes && !guard.EnsureWritable(database)) + { + return Blocked(command, database); + } var aggregateOptions = new AggregateOptions { MaxTime = MaxTime(options.MaxTimeMs), Comment = Comment(options) }; using IAsyncCursor cursor = await db.AggregateAsync( PipelineDefinition.Create(pipeline.Select(static s => s.AsBsonDocument)), aggregateOptions, cancellationToken).ConfigureAwait(false); (List docs, bool truncated) = await DrainAsync(cursor, options.MaxDocuments, cancellationToken).ConfigureAwait(false); - return Documents(command, database, null, docs, truncated) with { Pipeline = pipeline }; + return Documents(command, database, null, docs, truncated) with { Pipeline = pipeline, ChangesCatalog = writes }; } default: throw new ShellExecutionException(loc.Format("Query_ErrUnsupportedMethod", "db." + method.Name)); @@ -352,7 +376,7 @@ private async Task CollectionAsync(ShellCommand command, string dat case "aggregate": { BsonArray pipeline = Pipeline(method); - bool writes = pipeline.Any(static s => s is BsonDocument d && (d.Contains("$out") || d.Contains("$merge"))); + bool writes = ShellParser.WritesPipeline(pipeline); if (writes && !guard.EnsureWritable(database)) { return Blocked(command, database); @@ -583,9 +607,22 @@ private async Task FindAsync(ShellCommand command, IMongoCollection BsonValue? comment, ShellRunOptions options, CancellationToken cancellationToken) { ShellCall method = command.Method!; + // 解析器认得、但这里不落到驱动上的游标修饰:明说不支持,不能悄悄忽略 —— 用户以为读的是从节点 / majority,其实不是。 + foreach (string unsupported in (string[])["readPref", "readConcern"]) + { + if (command.Modifier(unsupported) is not null) + { + throw new ShellExecutionException(loc.Format("Query_ErrUnsupportedMethod", "." + unsupported)); + } + } FindRequest request = BuildFindRequest(command, database, options.MaxTimeMs); var findOptions = new FindOptions { + Min = command.Modifier("min")?.Document(0), + Max = command.Modifier("max")?.Document(0), + ReturnKey = command.Modifier("returnKey") is { } returnKey ? returnKey.Arg(0)?.ToBoolean() ?? true : null, + ShowRecordId = command.Modifier("showRecordId") is { } showRecordId ? showRecordId.Arg(0)?.ToBoolean() ?? true : null, + NoCursorTimeout = command.Modifier("noCursorTimeout") is not null ? true : null, MaxTime = maxTime, Comment = comment, Hint = request.Hint, @@ -600,10 +637,12 @@ private async Task FindAsync(ShellCommand command, IMongoCollection // count() / size() / itcount() 接在 find 后面:变成按同一组条件计数。 if ((command.Modifier("count") ?? command.Modifier("size") ?? command.Modifier("itcount")) is { } counter) { + // count() 默认不计 skip / limit;count(true)(applySkipLimit)与 size() / itcount() 一样计。 + bool applySkipLimit = counter.Name != "count" || counter.Arg(0) is { } apply && apply.ToBoolean(); var countOptions = new CountOptions { - Skip = counter.Name != "count" && request.Skip > 0 ? request.Skip : null, - Limit = counter.Name != "count" && request.Limit > 0 ? request.Limit : null, + Skip = applySkipLimit && request.Skip > 0 ? request.Skip : null, + Limit = applySkipLimit && request.Limit > 0 ? request.Limit : null, Hint = request.Hint, MaxTime = maxTime, Comment = comment diff --git a/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs b/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs index 087c7f8..243173a 100644 --- a/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs +++ b/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs @@ -80,10 +80,15 @@ public sealed class ShellCommand public bool IsWrite => Kind switch { ShellCommandKind.Collection => Method?.Name is { } name && (ShellParser.CollectionWrites.Contains(name) - || name == "aggregate" && Method.Arg(0) is BsonArray pipeline && pipeline.Any(static s => s is BsonDocument d && (d.Contains("$out") || d.Contains("$merge")))), + || name == "aggregate" && Method.Arg(0) is BsonArray pipeline && ShellParser.WritesPipeline(pipeline)), ShellCommandKind.Database => Method?.Name is "createCollection" or "dropDatabase" or "createView" - || Method?.Name is "runCommand" or "adminCommand" && Method.Arg(0) is BsonDocument command && command.ElementCount > 0 - && ShellParser.WriteCommands.Contains(command.GetElement(0).Name), + || Method?.Name == "aggregate" && Method.Arg(0) is BsonArray dbPipeline && ShellParser.WritesPipeline(dbPipeline) + || Method?.Name is "runCommand" or "adminCommand" && Method.Arg(0) switch + { + BsonDocument command => ShellParser.IsWriteCommand(command), + BsonString name => ShellParser.IsWriteCommand(new BsonDocument(name.Value, 1)), + _ => false + }, _ => false }; } @@ -128,7 +133,11 @@ public static class ShellParser "dropIndexes", "drop", "renameCollection" }; - /// 经 runCommand 发出时算写操作的命令名。 + /// + /// 经 runCommand 发出时算写操作的典型命令名(只作文档与旧调用方参考)。 + /// **判断一律走 **:那里是白名单 —— 不在只读名单里的命令都算写, + /// 黑名单永远列不全(grantPrivilegesToRole、dropAllUsersFromDatabase、shardCollection、replSetStepDown …)。 + /// public static IReadOnlySet WriteCommands { get; } = new HashSet(StringComparer.OrdinalIgnoreCase) { "insert", "update", "delete", "findAndModify", "drop", "dropDatabase", "create", "createIndexes", "dropIndexes", @@ -137,6 +146,60 @@ public static class ShellParser "applyOps", "shutdown", "killOp", "setParameter", "fsync" }; + /// + /// 确定只读的命令(白名单)。aggregate / mapReduce / explain / profile / validate + /// 要看参数,在 里单独判断。 + /// + public static IReadOnlySet ReadOnlyCommands { get; } = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "find", "getMore", "killCursors", "count", "distinct", "listCollections", "listIndexes", "listDatabases", "listSearchIndexes", + "collStats", "dbStats", "dataSize", "serverStatus", "hello", "isMaster", "buildInfo", "ping", "connectionStatus", + "usersInfo", "rolesInfo", "getParameter", "getClusterParameter", "hostInfo", "currentOp", "top", "replSetGetStatus", + "replSetGetConfig", "getLog", "getCmdLineOpts", "listCommands", "whatsmyuri", "lockInfo", "connPoolStats", + "shardConnPoolStats", "listShards", "isdbgrid", "getShardMap", "getShardVersion", "balancerStatus", + "getDefaultRWConcern", "dbHash", "planCacheListFilters", "features", "getFreeMonitoringStatus" + }; + + /// + /// runCommand / adminCommand 的命令文档会不会写库。白名单:只有确定只读的才放过,其余一律算写 —— + /// 只读模式的护栏宁可多拦一条,也不能被一个没列进黑名单的命令绕过去。 + /// + /// 命令文档(第一个键是命令名)。 + /// 会不会写。 + public static bool IsWriteCommand(BsonDocument command) + { + ArgumentNullException.ThrowIfNull(command); + if (command.ElementCount == 0) + { + return false; + } + BsonElement first = command.GetElement(0); + switch (first.Name.ToLowerInvariant()) + { + case "aggregate": + return command.GetValue("pipeline", null) is BsonArray pipeline && WritesPipeline(pipeline); + case "mapreduce": + // 只有 out: { inline: 1 } 是只读;out 写到集合(replace / merge / reduce)就是写。 + return !(command.GetValue("out", null) is BsonDocument output && output.Contains("inline")); + case "explain": + // explain 本身不执行写,但内层命令按它自己的形状判断(与 mongosh 的只读模式口径一致,宁严勿宽)。 + return first.Value is not BsonDocument inner || IsWriteCommand(inner); + case "profile": + // { profile: -1 } 只是读当前级别;0 / 1 / 2 会改实例的设置。 + return !(first.Value.IsNumeric && first.Value.ToInt32() == -1); + case "validate": + return command.GetValue("repair", false).ToBoolean() || command.GetValue("fixMultikey", false).ToBoolean(); + default: + return !ReadOnlyCommands.Contains(first.Name); + } + } + + /// 管道里有没有写出的阶段($out / $merge)。 + /// 管道。 + /// 会不会写。 + public static bool WritesPipeline(BsonArray pipeline) => + pipeline.Any(static s => s is BsonDocument d && (d.Contains("$out") || d.Contains("$merge"))); + /// 库级方法(db.xxx() 里不是集合名的那些)。 public static IReadOnlySet DatabaseMethods { get; } = new HashSet(StringComparer.Ordinal) { diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs index 04aa035..e11c901 100644 --- a/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs +++ b/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs @@ -70,18 +70,34 @@ public static string LocalDate(BsonValue value) return DateTimeOffset.FromUnixTimeMilliseconds(ms).ToLocalTime().ToString(LocalFormat, CultureInfo.InvariantCulture); } + /// double 能精确表示的最大整数(2^53);再大 Excel 里就变了样(9007199254740993 → …992)。 + private const long MaxExactInteger = 1L << 53; + /// /// 数值单元格(Excel 里写成数字而不是文本,才能求和排序)。不是数值或换算成文本时返回 。 + /// Excel 的数字就是 double:超过 2^53 的 Int64、有效位数超过 double 的 Decimal128 写成数字会被悄悄改值, + /// 这些返回 ,由调用方写成文本(原样的全精度)。 /// public static double? Number(BsonValue? value, CellConversion conversion) => BsonKinds.Of(value) switch { BsonKind.Int32 => value!.AsInt32, - BsonKind.Int64 => value!.AsInt64, + BsonKind.Int64 when value!.AsInt64 is >= -MaxExactInteger and <= MaxExactInteger => value.AsInt64, BsonKind.Double when double.IsFinite(value!.AsDouble) => conversion == CellConversion.Fixed2 ? Math.Round(value.AsDouble, 2, MidpointRounding.AwayFromZero) : value.AsDouble, BsonKind.Decimal128 when decimal.TryParse(value!.AsDecimal128.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out decimal d) => - (double)(conversion == CellConversion.Fixed2 ? Math.Round(d, 2, MidpointRounding.AwayFromZero) : d), + ExactDouble(conversion == CellConversion.Fixed2 ? Math.Round(d, 2, MidpointRounding.AwayFromZero) : d), _ => null }; + + /// decimal → double,往返不变才给(0.0035 可以;1234567890.123456789 不行)。 + private static double? ExactDouble(decimal value) + { + // 比较最短往返文本(Excel 显示的也是它):(decimal)double 会带出二进制尾数,0.0035 都对不上。 + double converted = (double)value; + return decimal.TryParse(converted.ToString("R", CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture, out decimal back) + && back == value + ? converted + : null; + } } diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs index 78ce03e..d318347 100644 --- a/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs +++ b/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs @@ -142,6 +142,10 @@ internal static class CollectionCopier /// 日志。 /// 文案表(日志用)。 /// 取消令牌。 + /// + /// 整批开始时目标库已有的名字( 列一次,整批共用;这里建了新集合会补进去)。 + /// 不给就逐个按名字问服务器。 + /// public static async Task CopyAsync( MongoConnection source, string sourceDb, @@ -153,7 +157,8 @@ public static async Task CopyAsync( Action onDocuments, Action log, Loc loc, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + ISet? existingNames = null) { if (item.Action == XferAction.Skip) { @@ -162,23 +167,39 @@ public static async Task CopyAsync( switch (item.Kind) { case XferObjectKind.View: - await CopyViewAsync(target, targetDb, item, cancellationToken).ConfigureAwait(false); + await CopyViewAsync(target, targetDb, item, existingNames, cancellationToken).ConfigureAwait(false); return new(0, 0, 0); case XferObjectKind.Bucket: { // 先 chunks 后 files:读者从 files 找文件,files 晚到就不会看见"有文件没数据"的半截桶。 XferOutcome chunks = await CopyCollectionAsync(source, sourceDb, target, targetDb, $"{item.Name}.chunks", - [], item.Action, options, gate, onDocuments, log, loc, cancellationToken).ConfigureAwait(false); + [], item.Action, options, gate, onDocuments, log, loc, existingNames, cancellationToken).ConfigureAwait(false); XferOutcome files = await CopyCollectionAsync(source, sourceDb, target, targetDb, $"{item.Name}.files", - [], item.Action, options, gate, onDocuments, log, loc, cancellationToken).ConfigureAwait(false); + [], item.Action, options, gate, onDocuments, log, loc, existingNames, cancellationToken).ConfigureAwait(false); return new(chunks.Copied + files.Copied, chunks.Failed + files.Failed, chunks.Indexes + files.Indexes); } default: return await CopyCollectionAsync(source, sourceDb, target, targetDb, item.Name, item.Info?.Options ?? [], - item.Action, options, gate, onDocuments, log, loc, cancellationToken).ConfigureAwait(false); + item.Action, options, gate, onDocuments, log, loc, existingNames, cancellationToken).ConfigureAwait(false); } } + /// + /// 目标里有没有这个名字。调用方给了整批开始时列好的名字()就查它 —— 一批几百个集合时, + /// 每个集合都把目标库的集合列表整个拉一遍是 O(n²) 的往返;没给就只按名字过滤着问服务器这一个。 + /// + private static async Task ExistsAsync(MongoConnection target, string database, string name, ISet? known, CancellationToken cancellationToken) + { + if (known is not null) + { + return known.Contains(name); + } + using IAsyncCursor cursor = await target.Database(database) + .ListCollectionNamesAsync(new ListCollectionNamesOptions { Filter = new BsonDocument("name", name) }, cancellationToken) + .ConfigureAwait(false); + return await cursor.AnyAsync(cancellationToken).ConfigureAwait(false); + } + /// 目标库里已有的集合 / 视图名。 public static async Task> ExistingNamesAsync(MongoConnection target, string database, CancellationToken cancellationToken) { @@ -201,10 +222,11 @@ private static async Task CopyCollectionAsync( Action onDocuments, Action log, Loc loc, + ISet? existingNames, CancellationToken cancellationToken) { IMongoDatabase targetDatabase = target.Database(targetDb); - bool exists = (await ExistingNamesAsync(target, targetDb, cancellationToken).ConfigureAwait(false)).Contains(name); + bool exists = await ExistsAsync(target, targetDb, name, existingNames, cancellationToken).ConfigureAwait(false); bool created = false; switch (action) { @@ -224,6 +246,10 @@ private static async Task CopyCollectionAsync( created = true; break; } + if (created) + { + _ = existingNames?.Add(name); + } IMongoCollection from = source.Collection(sourceDb, name) .WithReadPreference(MongoConnection.ParseReadPreference(options.ReadPreference)); @@ -385,9 +411,9 @@ private static Task CreateAsync(MongoConnection target, string dat CancellationToken cancellationToken) => target.RunCommandAsync(database, CreateCommand(name, sourceOptions, options), cancellationToken); - private static async Task CopyViewAsync(MongoConnection target, string database, XferItem item, CancellationToken cancellationToken) + private static async Task CopyViewAsync(MongoConnection target, string database, XferItem item, ISet? existingNames, CancellationToken cancellationToken) { - bool exists = (await ExistingNamesAsync(target, database, cancellationToken).ConfigureAwait(false)).Contains(item.Name); + bool exists = await ExistsAsync(target, database, item.Name, existingNames, cancellationToken).ConfigureAwait(false); if (exists) { if (item.Action != XferAction.Overwrite) @@ -408,6 +434,7 @@ private static async Task CopyViewAsync(MongoConnection target, string database, command["collation"] = collation; } _ = await target.RunCommandAsync(database, command, cancellationToken).ConfigureAwait(false); + _ = existingNames?.Add(item.Name); } private static async Task CopyIndexesAsync( diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs index 095faed..e468e24 100644 --- a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs +++ b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs @@ -52,7 +52,10 @@ internal sealed record ImportJob /// 导入进度。 internal sealed record ImportProgress(long Rows, long Total, long Inserted, long Updated, long Skipped, TimeSpan Elapsed); -/// 导入结果。 +/// +/// 导入结果。取消()与中途的致命失败()也返回一份部分结果, +/// 而不是抛出 —— 错误报告与备份文件已经写了一部分,它们的路径与已确认写入的条数都要交给界面。 +/// internal sealed record ImportResult( long Rows, long Inserted, @@ -61,7 +64,9 @@ internal sealed record ImportResult( TimeSpan Elapsed, string? ErrorReport, string? BackupFile, - bool Stopped); + bool Stopped, + bool Cancelled = false, + Exception? Failure = null); /// /// 执行导入:读一条换算一条,攒满一批 bulkWrite 一次(默认 ordered: false —— @@ -87,13 +92,15 @@ public static async Task RunAsync( var report = new ReportFiles(job); var batch = new List<(ConvertedRow Row, ImportRecord Record, WriteModel Model)>(job.BatchSize); long rows = 0, inserted = 0, updated = 0, skipped = 0; - bool stopped = false; + bool stopped = false, cancelled = false; + Exception? failure = null; TimeSpan lastReport = TimeSpan.Zero; - using IImportReader reader = job.Source.Open(); try { + using IImportReader reader = job.Source.Open(); while (!stopped && reader.TryRead(out ImportRecord record)) { + cancellationToken.ThrowIfCancellationRequested(); rows++; ConvertedRow row = converter.Convert(record); if (row.Status == ImportRowStatus.Error) @@ -102,6 +109,7 @@ public static async Task RunAsync( report.Error(row.Line, [.. row.Issues.Where(static i => i.IsError).Select(i => ImportIssueText.Describe(i, loc))], record, reader.Header); if (job.StopOnError) { + // 出错行之前已经攒在批里的那些行是好的 —— 下面照常落盘,只是不再往后读。 stopped = true; break; } @@ -120,24 +128,33 @@ public static async Task RunAsync( { lastReport = watch.Elapsed; progress?.Report(new(rows, job.EstimatedTotal, inserted, updated, skipped, watch.Elapsed)); - cancellationToken.ThrowIfCancellationRequested(); } } - if (!stopped && batch.Count > 0) + // FlushAsync 叫停时批已清空;换算出错叫停时批里是出错行之前的好行,要写进去。 + if (batch.Count > 0) { (long i, long u, long s, bool stop) = await FlushAsync(collection, job, batch, report, reader.Header, loc, cancellationToken).ConfigureAwait(false); inserted += i; updated += u; skipped += s; - stopped = stop; + stopped |= stop; } } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 正在写的那一批写没写进去不得而知:计数只算服务器已确认的批次。 + cancelled = true; + } + catch (Exception ex) + { + failure = ex; + } finally { report.Dispose(); } progress?.Report(new(rows, job.EstimatedTotal, inserted, updated, skipped, watch.Elapsed)); - return new(rows, inserted, updated, skipped, watch.Elapsed, report.ErrorPath, report.BackupPath, stopped); + return new(rows, inserted, updated, skipped, watch.Elapsed, report.ErrorPath, report.BackupPath, stopped, cancelled, failure); } /// 一份文档 → 写模型。 @@ -240,9 +257,10 @@ internal static WriteModel Model(BsonDocument document, ImportRule { // ordered 批次在第一个错误处停下:它之后的那些也没写进去 —— 同样记进错误报告,修好了能补导。 int firstError = ex.WriteErrors.Count > 0 ? ex.WriteErrors.Min(static e => e.Index) : batch.Count; + HashSet failed = [.. ex.WriteErrors.Select(static e => e.Index)]; for (int i = firstError + 1; i < batch.Count; i++) { - if (ex.WriteErrors.Any(e => e.Index == i)) + if (failed.Contains(i)) { continue; } @@ -310,7 +328,8 @@ public void Backup(BsonDocument document) { if (_backup is null) { - BackupPath = Path.Combine(job.ReportDirectory, $"{job.Database}.{job.Collection}.backup-{_stamp}.jsonl"); + // 集合名可以带 ':' '/'(Windows 上 ':' 会落成 NTFS 备用数据流,'/' 是一级不存在的目录):与导出同一个清洗。 + BackupPath = Path.Combine(job.ReportDirectory, TransferText.SafeFileName($"{job.Database}.{job.Collection}") + $".backup-{_stamp}.jsonl"); _ = Directory.CreateDirectory(job.ReportDirectory); _backup = new StreamWriter(BackupPath, append: false, new UTF8Encoding(false)); } diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs index 71da425..20223fc 100644 --- a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs +++ b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs @@ -232,27 +232,57 @@ private static bool TryNumber(string text, BsonKind kind, out BsonValue? value, } } - /// 去掉引号、千分位、货币符号与空白("1,580.00" → 1580.00)。 + /// + /// 去掉引号、千分位、货币符号与空白("1,580.00" → 1580.00)。 + /// 分组符只在**合法的千分位**里才去掉(同一种分组符、首段 1–3 位、其后每段恰好 3 位、小数点在最后一段之后): + /// "1,5" 很可能是小数逗号写法的 1.5,悄悄变成 15 是错数,宁可报错 —— 返回空串,调用方按解析失败处理。 + /// internal static string CleanNumber(string text, out bool grouping) { grouping = false; - string t = text.Trim().Trim('"', '\'', '“', '”').Trim(); - var builder = new System.Text.StringBuilder(t.Length); + // 先去货币符号再修边:"¥ 1,580" 里符号后的空格不是分组符。 + string t = new string([.. text.Where(static c => c is not ('¥' or '¥' or '$' or '€' or '£'))]) + .Trim().Trim('"', '\'', '“', '”').Trim(); + char? separator = null; foreach (char c in t) { - switch (c) + // 逗号、下划线、空格、不换行空格、细空格、窄不换行空格。 + if (c is ',' or '_' or ' ' or (char)0xA0 or (char)0x2009 or (char)0x202F) { - case ',' or '_' or ' ' or ' ' or ' ': - grouping = true; - break; - case '¥' or '¥' or '$' or '€' or '£': - break; - default: - _ = builder.Append(c); - break; + if (separator is { } seen && seen != c) + { + return ""; + } + separator = c; + grouping = true; } } - return builder.ToString(); + string kept = t; + if (separator is not { } sep) + { + return kept; + } + if (!ValidGrouping(kept, sep)) + { + return ""; + } + return kept.Replace(sep.ToString(), "", StringComparison.Ordinal); + } + + /// ^[+-]?\d{1,3}(,\d{3})+(\.\d+)?$(逗号换成实际用的那一个分组符)。 + private static bool ValidGrouping(string text, char separator) + { + int start = text.Length > 0 && text[0] is '+' or '-' ? 1 : 0; + int dot = text.IndexOf('.', start); + string integer = dot < 0 ? text[start..] : text[start..dot]; + if (dot >= 0 && (dot == text.Length - 1 || !text[(dot + 1)..].All(char.IsAsciiDigit))) + { + return false; + } + string[] groups = integer.Split(separator); + return groups.Length >= 2 + && groups[0].Length is >= 1 and <= 3 && groups[0].All(char.IsAsciiDigit) + && groups.Skip(1).All(static g => g.Length == 3 && g.All(char.IsAsciiDigit)); } /// diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs index 99f6f7e..71a8fc3 100644 --- a/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs +++ b/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs @@ -96,8 +96,11 @@ public static async Task> SampleAsync( cancellationToken).ConfigureAwait(false); return await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); } - catch (MongoCommandException) + catch (MongoServerException) { + // MongoServerException 而不只是 MongoCommandException:$sample 超时报的是 MongoExecutionTimeoutException, + // 它不是命令异常 —— 只接命令异常的话,文档里说的"退回 find().limit()"在最常见的超时情形下根本不会发生。 + // 取消不在此列(OperationCanceledException 不是服务器异常),照常往外抛。 return await collection.Find(filter ?? []).Limit(size).ToListAsync(cancellationToken).ConfigureAwait(false); } } diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs index d404c82..dbdc4a5 100644 --- a/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs +++ b/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs @@ -141,12 +141,15 @@ internal sealed record XferField(string Path, IReadOnlyList Kinds, int /// 这个字段默认的换算。 public CellConversion DefaultConversion => DefaultConversionFor(Dominant); - /// 某种类型默认的换算。 + /// + /// 某种类型默认的换算。默认一律**无损**:Decimal128 原样全精度(保留两位会把 0.0035 写成 0.00), + /// 日期写 ISO 8601 UTC(带毫秒与时区;本地时间不带时区、丢毫秒,下游读回来对不上)。有损的写法留给用户在字段表里显式选。 + /// public static CellConversion DefaultConversionFor(BsonKind kind) => kind switch { BsonKind.ObjectId => CellConversion.Hex, - BsonKind.Decimal128 => CellConversion.Fixed2, - BsonKind.Date => CellConversion.LocalTime, + BsonKind.Decimal128 => CellConversion.None, + BsonKind.Date => CellConversion.IsoTime, BsonKind.Array or BsonKind.Object => CellConversion.Json, _ => CellConversion.None }; diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs index 7bb4781..26b380e 100644 --- a/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs +++ b/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs @@ -150,7 +150,11 @@ public void WriteRow(IReadOnlyList cells, bool header = false) { XlsxCell cell = cells[i]; _sheet.WriteStartElement("c", MainNs); - _sheet.WriteAttributeString("r", ColumnName(i) + rowRef); + // 单元格引用分两段写(列名缓存 + 行号):每格拼一个新字符串在几十万行的导出里是实打实的分配压力。 + _sheet.WriteStartAttribute("r"); + _sheet.WriteString(CachedColumnName(i)); + _sheet.WriteString(rowRef); + _sheet.WriteEndAttribute(); if (cell.Number is { } number) { if (cell.Fixed2) @@ -278,15 +282,28 @@ public void Dispose() /// 列号 → 列名(0 → A,26 → AA)。 public static string ColumnName(int index) { - var name = new StringBuilder(); + Span buffer = stackalloc char[8]; + int start = buffer.Length; int n = index + 1; while (n > 0) { int rem = (n - 1) % 26; - _ = name.Insert(0, (char)('A' + rem)); + buffer[--start] = (char)('A' + rem); n = (n - 1) / 26; } - return name.ToString(); + return new string(buffer[start..]); + } + + /// 列名缓存(各表共用:列名与表无关)。 + private readonly List _columnNames = []; + + private string CachedColumnName(int index) + { + while (_columnNames.Count <= index) + { + _columnNames.Add(ColumnName(_columnNames.Count)); + } + return _columnNames[index]; } /// 工作表名:去掉 []:*?/\,最长 31 个字符,不能为空。 diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Charts/BarChart.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Charts/BarChart.cs index 81f7c83..4bb29c2 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Charts/BarChart.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Charts/BarChart.cs @@ -9,7 +9,8 @@ namespace VelaShell.Plugin.Mongo.Ui; /// 图表里的一组数据。 /// 名字(图例、悬停提示里的那一行)。 /// 颜色令牌(MongoChart1、VelaShellGreen…)。 -/// 每根柱子的值。 +/// 每根柱子的值。 表示"这一格没有数据"(画成空位,提示里写「—」), +/// 与 0(采到了,确实是零)区分开。 public sealed record ChartSeries(string Name, string BrushToken, IReadOnlyList Values); /// @@ -169,7 +170,7 @@ public override void Render(DrawingContext context) double[] totals = new double[count]; for (int i = 0; i < count; i++) { - totals[i] = series.Sum(s => i < s.Values.Count ? Math.Max(0, s.Values[i]) : 0); + totals[i] = series.Sum(s => Drawable(s.Values, i)); } (double max, double step) = MaxValue > 0 ? (MaxValue, NiceStep(MaxValue)) : NiceScale(totals.Max()); Rect plot = Plot; @@ -210,7 +211,7 @@ public override void Render(DrawingContext context) for (int k = 0; k < series.Count; k++) { ChartSeries s = series[k]; - double v = i < s.Values.Count ? Math.Max(0, s.Values[i]) : 0; + double v = Drawable(s.Values, i); double h = max <= 0 ? 0 : plot.Height * Math.Min(v, max) / max; if (h <= 0) { @@ -268,6 +269,10 @@ public override void Render(DrawingContext context) } } + /// 画柱用的值:越界、负数与 NaN(没数据)都按 0 高 —— Math.Max(0, NaN) 是 NaN,不能直接用。 + private static double Drawable(IReadOnlyList values, int i) => + i < values.Count && values[i] is var v && !double.IsNaN(v) ? Math.Max(0, v) : 0; + private void DrawTooltip(DrawingContext context, Typeface typeface, IReadOnlyList series, Rect plot, double slot, double origin) { IBrush primary = ThemeBrushes.Get("VelaTextPrimary", Brushes.White); @@ -276,7 +281,8 @@ private void DrawTooltip(DrawingContext context, Typeface typeface, IReadOnlyLis foreach (ChartSeries s in series) { double v = _hover < s.Values.Count ? s.Values[_hover] : 0; - lines.Add((s.Name, v.ToString("#,0.##", CultureInfo.InvariantCulture), ThemeBrushes.Get(s.BrushToken, Brushes.SteelBlue))); + string text = double.IsNaN(v) ? "—" : v.ToString("#,0.##", CultureInfo.InvariantCulture); + lines.Add((s.Name, text, ThemeBrushes.Get(s.BrushToken, Brushes.SteelBlue))); } string title = Labels is { } labels && _hover < labels.Count ? labels[_hover] : ""; const double row = 15; diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Edit.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Edit.cs index 67fd02c..7a8cf5e 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Edit.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Edit.cs @@ -14,7 +14,8 @@ internal sealed partial class CollectionTabViewModel { private HashSet _trackedIds = []; private bool _committing; - private DispatcherTimer? _relockTimer; + private readonly Queue _conflicts = new(); + private bool _conflictOpen; /// 添加文档(打开文档编辑器)。 public RelayCommand AddDocumentCommand { get; private set; } = null!; @@ -316,7 +317,11 @@ internal void Clone(CollectionRow row) Workspace.ShowDialog(new DocumentEditorDialogViewModel(Workspace, Info, copy, OnEditorSavedAsync)); } - /// 在文档编辑器中编辑(编辑器直接写服务器;这份文档在这里的暂存随之作废)。 + /// + /// 在文档编辑器中编辑(编辑器直接写服务器;这份文档在这里的暂存随之作废)。 + /// 已有文档的原像给服务器版本、表单内容给「原像 + 暂存」:编辑器的差异因此带着暂存的修改一起提交, + /// 而不是只提交在对话框里动过的字段、再把暂存丢掉;乐观并发的 updatedAt 也取服务器上的那个。 + /// internal void OpenInEditor(CollectionRow row) { if (!Info.IsEditable) @@ -324,12 +329,13 @@ internal void OpenInEditor(CollectionRow row) Workspace.Toast(new() { Title = Loc["Cw_ViewReadOnly"], Kind = ToastKind.Warning }); return; } - var document = (BsonDocument)row.Document.DeepClone(); - Workspace.ShowDialog(new DocumentEditorDialogViewModel(Workspace, Info, document, async saved => + BsonDocument document = row.Original ?? row.Document; + BsonDocument? initial = row.Original is not null && !ReferenceEquals(row.Document, row.Original) ? row.Document : null; + Workspace.ShowDialog(new DocumentEditorDialogViewModel(Workspace, Info, (BsonDocument)document.DeepClone(), async saved => { DiscardDocument(row); await OnEditorSavedAsync(saved).ConfigureAwait(true); - })); + }, initial)); } private async Task OnEditorSavedAsync(BsonDocument? saved) @@ -457,6 +463,13 @@ private IReadOnlyList EnumChoices(string path) /// internal bool CommitEditor(InlineValueEditor editor, CollectionRow row, string path) { + BsonValue? before = BsonPath.Get(row.Document, path); + // 文本一字没动就不暂存:日期按本地时间格式化、再按本地时间解析回来,在夏令时回拨的那一小时里 + // 两个 UTC 时刻写出来是同一串字,原样回车会被解析成另一个时刻,凭空暂存一处 +1h 的修改。 + if (before is not null && string.Equals(editor.Text, editor.InitialText, StringComparison.Ordinal) && BsonKinds.Of(before) == editor.Kind) + { + return true; + } BsonValue value; if (editor.Text.Length == 0 && editor.Kind != BsonKind.String) { @@ -467,8 +480,7 @@ internal bool CommitEditor(InlineValueEditor editor, CollectionRow row, string p editor.Error = Loc[error ?? "Edit_BadLiteral"]; return false; } - BsonValue? current = BsonPath.Get(row.Document, path); - if (current is not null && StagedEdit.SameValue(current, value)) + if (before is not null && StagedEdit.SameValue(before, value)) { return true; } @@ -696,25 +708,53 @@ private async Task UndoAsync(UndoPlan plan) } } - /// 逐份弹冲突对话框(处理完一份再弹下一份)。 + /// + /// 逐份弹冲突对话框(处理完一份再弹下一份)。队列在标签页上:处理冲突 1 时的重新提交又撞上冲突(1′), + /// 1′ 排到队尾,而不是当场弹出来、再被外层接着弹的冲突 2 顶掉(外壳只有一个对话框槽位)。 + /// private void ShowConflicts(IReadOnlyList conflicts) { - var queue = new Queue(conflicts); - Next(); + foreach (EditConflict conflict in conflicts) + { + _conflicts.Enqueue(conflict); + } + ShowNextConflict(); + } - void Next() + private void ShowNextConflict() + { + if (_conflictOpen || _disposed || !_conflicts.TryDequeue(out EditConflict? conflict)) + { + return; + } + _conflictOpen = true; + var dialog = new ConflictDialogViewModel(Workspace, conflict, async resolution => { - if (queue.TryDequeue(out EditConflict? conflict)) + try { - Workspace.ShowDialog(new ConflictDialogViewModel(Workspace, conflict, async resolution => - { - await ResolveConflictAsync(conflict, resolution).ConfigureAwait(true); - Next(); - })); + await ResolveConflictAsync(conflict, resolution).ConfigureAwait(true); } - } + finally + { + _conflictOpen = false; + ShowNextConflict(); + } + }); + dialog.Closed += () => + { + if (!dialog.IsChosen) + { + // × / Esc「先不处理」:剩下的也先不弹,修改都留在暂存区,下次提交会再碰到。 + _conflictOpen = false; + _conflicts.Clear(); + } + }; + Workspace.ShowDialog(dialog); } + /// 当前排着的冲突(测试看)。 + internal int PendingConflictCount => _conflicts.Count + (_conflictOpen ? 1 : 0); + /// /// 冲突的三种出路:放弃我的(撤掉暂存、看服务器版本);覆盖(以服务器版本为新原像、我的修改全保留,再提交); /// 合并(以服务器版本为新原像、只保留勾了「我的」的那几个字段,再提交)。 @@ -788,23 +828,11 @@ private async Task UnlockAsync() { return; } - Workspace.Guard.IsReadOnly = false; - _relockTimer?.Stop(); - var timer = new DispatcherTimer { Interval = TimeSpan.FromMinutes(15) }; - timer.Tick += (_, _) => Relock(); - _relockTimer = timer; - timer.Start(); + // 计时挂在连接的护栏上:这个标签页关了,到点照样锁回去(到期的提示由会话给)。 + Workspace.Guard.UnlockFor(UnlockDuration); Workspace.Toast(new() { Title = Loc["State_Unlocked"], Kind = ToastKind.Warning }); } - private void Relock() - { - _relockTimer?.Stop(); - _relockTimer = null; - if (!Workspace.Guard.IsReadOnly) - { - Workspace.Guard.IsReadOnly = true; - Workspace.Toast(new() { Title = Loc["State_Relocked"], Kind = ToastKind.Info }); - } - } + /// 「解锁写入 15 分钟」的时长。 + internal static readonly TimeSpan UnlockDuration = TimeSpan.FromMinutes(15); } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Query.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Query.cs index 8650d2e..460b4da 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Query.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Query.cs @@ -40,6 +40,9 @@ internal sealed partial class CollectionTabViewModel private DispatcherTimer? _longQueryTimer; private long? _opid; private int _countVersion; + private int _planVersion; + private CancellationTokenSource? _countCts; + private CancellationTokenSource? _stoppingCts; /// 查找(Ctrl+Enter)。 public AsyncCommand FindCommand { get; private set; } @@ -86,7 +89,9 @@ internal sealed partial class CollectionTabViewModel [MemberNotNull(nameof(FindCommand), nameof(ResetCommand), nameof(ClearFilterCommand), nameof(ExplainCommand), nameof(ToggleFavoriteCommand), nameof(ApplyHistoryCommand), nameof(RefreshCommand), nameof(StopCommand), nameof(FirstPageCommand), nameof(PreviousPageCommand), nameof(NextPageCommand), nameof(LastPageCommand), nameof(GoToPageCommand), nameof(SortByColumnCommand))] private void InitializeQueryCommands() { - FindCommand = new(() => RunQueryAsync(resetPage: true)); + // 查找 / 刷新不等查询跑完就交还命令:正在跑的那条慢查询可以被新的一次顶掉(旧的在服务器上 killOp), + // 而不是按钮灰着、只能先点「停止」。 + FindCommand = new(() => Supersede(resetPage: true)); ResetCommand = new(ResetAsync); ClearFilterCommand = new(() => { @@ -100,7 +105,7 @@ private void InitializeQueryCommands() FilterText = item.Text; return RunQueryAsync(resetPage: true); }); - RefreshCommand = new(() => RunQueryAsync(resetPage: false)); + RefreshCommand = new(() => Supersede(resetPage: false)); StopCommand = new(StopAsync, () => IsLoading); FirstPageCommand = new(() => GoToPageAsync(0), () => _pageIndex > 0); PreviousPageCommand = new(() => GoToPageAsync(_pageIndex - 1), () => _pageIndex > 0); @@ -220,7 +225,7 @@ public string LimitText { if (SetProperty(ref _limitText, value ?? "")) { - LimitInvalid = ParseCount(_limitText, 1) is null; + LimitInvalid = ParseCount(_limitText, 1, MaxPageSize) is null; } } } @@ -269,7 +274,7 @@ public string SelectedHint public long? TotalCount { get; private set; } /// 每页行数。 - public int PageSize => ParseCount(_limitText, 1) ?? Workspace.Connection.Settings.PageSize; + public int PageSize => ParseCount(_limitText, 1, MaxPageSize) ?? Math.Clamp(Workspace.Connection.Settings.PageSize, 1, MaxPageSize); /// 基础跳过数。 public int BaseSkip => ParseCount(SkipText, 0) ?? 0; @@ -332,7 +337,13 @@ public async Task RunQueryAsync(bool resetPage) { SetPage(0); } - _queryCts?.Cancel(); + if (_queryCts is { } previous) + { + // 被新查询顶掉:本地不等了,服务器上那条也停下 —— 否则旧的 COLLSCAN 照跑到 maxTimeMS。 + previous.Cancel(); + KillOnServer(_queryComment); + } + _countCts?.Cancel(); var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); _queryCts = cts; _queryComment = request.Comment; @@ -358,6 +369,8 @@ public async Task RunQueryAsync(bool resetPage) using IAsyncCursor cursor = await Collection.FindAsync(request.Filter, options, cts.Token).ConfigureAwait(true); List documents = await cursor.ToListAsync(cts.Token).ConfigureAwait(true); watch.Stop(); + // 列统计(字段并集、主导类型、估宽)在线程池上算:一页上万份文档逐个过字段不压 UI 线程。 + ColumnScan scan = await Task.Run(() => ColumnScan.Of(documents), cts.Token).ConfigureAwait(true); if (!ReferenceEquals(_queryCts, cts)) { return; @@ -366,7 +379,7 @@ public async Task RunQueryAsync(bool resetPage) _loadedOnce = true; CurrentRequest = request; LastRunFilter = _filterText.Trim(); - ApplyResults(documents, request.Skip + 1); + ApplyResults(documents, request.Skip + 1, scan); RaisePropertiesChanged(nameof(Elapsed), nameof(LastRunFilter), nameof(HasActiveFilter), nameof(CurrentRequest), nameof(EchoText), nameof(RangeText), nameof(PageCountText)); UpdateStatus(); @@ -383,6 +396,13 @@ public async Task RunQueryAsync(bool resetPage) } catch (Exception ex) when (ex is MongoException or TimeoutException) { + if (!ReferenceEquals(_queryCts, cts) || ReferenceEquals(_stoppingCts, cts) && IsInterrupted(ex)) + { + // 被顶掉的查询、或用户点了停止之后 killOp 打断的那一条(Interrupted / MaxTimeMSExpired): + // 停止那条路自己报「已停止」,这里再弹一条「失败:Interrupted」只会让人以为出了错。 + Workspace.Log.Info($"Query on {Info.Namespace} ended after stop: {ex.Message}"); + return; + } if (ex is MongoCommandException { Code: 2 or 9 } command) { // BadValue / FailedToParse:多半是筛选写得服务器不认($foo 之类),标到筛选框上。 @@ -398,10 +418,32 @@ public async Task RunQueryAsync(bool resetPage) StopLongQueryTimer(); _queryCts = null; } + if (ReferenceEquals(_stoppingCts, cts)) + { + _stoppingCts = null; + } cts.Dispose(); } } + /// 查找 / 刷新的命令体:发起查询就返回(查询自己处理失败),好让下一次点击能顶掉它。 + private Task Supersede(bool resetPage) + { + _ = RunQueryAsync(resetPage).ContinueWith( + t => Workspace.Log.Info($"Query on {Info.Namespace} failed: {t.Exception?.GetBaseException().Message}"), + CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); + return Task.CompletedTask; + } + + /// killOp 打断的查询在客户端看到的错误:Interrupted(11601)或 MaxTimeMSExpired(50)。 + internal static bool IsInterrupted(Exception ex) => ex switch + { + MongoCommandException command => command.Code is 11601 or 50, + MongoExecutionTimeoutException => true, + MongoServerException server when server.Message.Contains("Interrupted", StringComparison.OrdinalIgnoreCase) => true, + _ => false + }; + /// 按查询栏拼一次查询;有语法错误就标红并返回 。 private bool TryBuildRequest(int pageIndex, out FindRequest request) { @@ -458,9 +500,15 @@ private void ValidateFilter() FilterDiagnostics = diagnostics; } - private static int? ParseCount(string text, int min) => + /// + /// 每页行数的上限。网格、树、JSON 卡片都按"一页"建模型;一页一百万份文档会把它们与列统计全压在 UI 线程上, + /// 要看更多就翻页或导出。 + /// + internal const int MaxPageSize = 10_000; + + private static int? ParseCount(string text, int min, int max = 1_000_000) => int.TryParse(text.Trim().Replace(",", "", StringComparison.Ordinal), NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) - && value >= min && value <= 1_000_000 + && value >= min && value <= max ? value : string.IsNullOrWhiteSpace(text) && min == 0 ? 0 : null; @@ -508,6 +556,10 @@ private void RaisePagingCanExecute() private async Task CountAsync(FindRequest request) { int version = ++_countVersion; + // 自己的令牌:新的查询一发出就取消上一次计数(countDocuments 在大集合上要扫 5 秒),而不是等标签页关了才停。 + _countCts?.Cancel(); + var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); + _countCts = cts; TotalCount = null; RaisePropertiesChanged(nameof(TotalCount), nameof(PageCountText), nameof(RangeText)); try @@ -515,10 +567,10 @@ private async Task CountAsync(FindRequest request) long? count = null; if (request.Filter.ElementCount == 0) { - count = await Workspace.Connection.EstimatedCountAsync(Database, CollectionName, _lifetime.Token).ConfigureAwait(true); + count = await Workspace.Connection.EstimatedCountAsync(Database, CollectionName, cts.Token).ConfigureAwait(true); } count ??= await Collection.CountDocumentsAsync(request.Filter, - new CountOptions { MaxTime = TimeSpan.FromSeconds(5), Hint = request.Hint }, _lifetime.Token).ConfigureAwait(true); + new CountOptions { MaxTime = TimeSpan.FromSeconds(5), Hint = request.Hint }, cts.Token).ConfigureAwait(true); if (version != _countVersion) { return; @@ -528,6 +580,18 @@ private async Task CountAsync(FindRequest request) catch (Exception ex) when (ex is MongoException or TimeoutException or OperationCanceledException) { Workspace.Log.Info($"Counting {Info.Namespace} failed: {ex.Message}"); + if (version != _countVersion) + { + return; + } + } + finally + { + if (ReferenceEquals(_countCts, cts)) + { + _countCts = null; + } + cts.Dispose(); } RaisePropertiesChanged(nameof(TotalCount), nameof(PageCountText), nameof(RangeText), nameof(PageCount)); RaisePagingCanExecute(); @@ -536,6 +600,8 @@ private async Task CountAsync(FindRequest request) /// 取一次 explain("queryPlanner") 的获胜阶段给状态栏(不跑查询本身,开销很小)。 private async Task ExplainPlanAsync(FindRequest request) { + // 连着翻几页时几次 explain 先后回来:只认最后一次,否则状态栏上是上一次筛选的计划。 + int version = ++_planVersion; try { var find = new BsonDocument { { "find", CollectionName }, { "filter", request.Filter } }; @@ -555,11 +621,17 @@ private async Task ExplainPlanAsync(FindRequest request) find["limit"] = request.Limit; BsonDocument reply = await Workspace.Connection.RunCommandAsync(Database, new BsonDocument { { "explain", find }, { "verbosity", "queryPlanner" } }, _lifetime.Token).ConfigureAwait(true); - PlanSummary = SummarizePlan(reply); + if (version == _planVersion) + { + PlanSummary = SummarizePlan(reply); + } } catch (Exception ex) when (ex is MongoException or TimeoutException or OperationCanceledException) { - PlanSummary = ""; + if (version == _planVersion && !_disposed) + { + PlanSummary = ""; + } } } @@ -615,7 +687,9 @@ private async Task FindOpidAsync(string? comment) { "currentOp", true }, { "command.comment", comment } }).ConfigureAwait(true); - if (reply.GetValue("inprog", new BsonArray()).AsBsonArray.FirstOrDefault() is BsonDocument op + // 回来时已经换了一次查询:那是上一条的 opid,不能挂到这一条的卡片上。 + if (comment == _queryComment && _queryCts is not null + && reply.GetValue("inprog", new BsonArray()).AsBsonArray.FirstOrDefault() is BsonDocument op && op.TryGetValue("opid", out BsonValue opid) && opid.IsNumeric) { _opid = opid.ToInt64(); @@ -635,6 +709,8 @@ private async Task StopAsync() { string? comment = _queryComment; CancellationTokenSource? cts = _queryCts; + // killOp 先于本地取消:查询那边会先收到 Interrupted,认出这是"停止"而不是失败。 + _stoppingCts = cts; try { if (comment is not null) @@ -653,7 +729,11 @@ private async Task StopAsync() } finally { - cts?.Cancel(); + // killOp 打断之后查询多半已经收尾、令牌也释放了:只取消还在跑的那一条。 + if (cts is not null && ReferenceEquals(_queryCts, cts)) + { + cts.Cancel(); + } } } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Views.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Views.cs index 3f8dbfd..8cab826 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Views.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.Views.cs @@ -123,7 +123,11 @@ public bool FormatOnSave set => SetProperty(ref field, value); } = true; - /// 重建卡片(只在 JSON 视图可见时)。正在编辑的卡片保留,免得刷新把用户敲了一半的文本冲掉。 + /// + /// 重建卡片(只在 JSON 视图可见时)。正在编辑的卡片保留,免得刷新把用户敲了一半的文本冲掉: + /// 行没换就原样留着;重查之后行对象是新的,按 _id(暂存的新文档按暂存身份)认出同一份文档, + /// 新卡片接过旧卡片的编辑文本与基线。 + /// internal void RebuildCards() { if (ViewMode != CollectionViewMode.Json) @@ -135,8 +139,19 @@ internal void RebuildCards() foreach (CollectionRow row in Rows) { JsonCardViewModel? kept = editing.GetValueOrDefault(row) - ?? editing.Values.FirstOrDefault(c => c.Row.Id is { } id && id.Equals(row.Id)); - cards.Add(kept is not null && ReferenceEquals(kept.Row, row) ? kept : new JsonCardViewModel(this, row)); + ?? editing.Values.FirstOrDefault(c => c.Row.Insert is null && c.Row.Id is { } id && id.Equals(row.Id) + || c.Row.Insert is { } insert && ReferenceEquals(insert, row.Insert)); + if (kept is not null && ReferenceEquals(kept.Row, row)) + { + cards.Add(kept); + continue; + } + var card = new JsonCardViewModel(this, row); + if (kept is not null) + { + card.AdoptEditFrom(kept); + } + cards.Add(card); } Cards = [with(cards)]; SyncCardSelection(); diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.cs index e31acf8..0e6f802 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/CollectionTabViewModel.cs @@ -250,6 +250,12 @@ public ObservableCollection Rows } } = []; + /// + /// 网格里建控件的列区间(),由网格视图按水平视口算好写进来; + /// 没有视图时是全部列。 + /// + internal CellWindow CellWindow { get; set; } = CellWindow.All; + /// 本页从服务器读到的文档。 public IReadOnlyList Documents => _documents; @@ -465,13 +471,22 @@ internal async Task LoadStatsAsync() } } - /// 把一页结果铺进网格(并按需重建树 / 卡片)。 - private void ApplyResults(List documents, int firstNumber) + /// + /// 把一页结果铺进网格(并按需重建树 / 卡片)。 是本页文档的列统计 —— + /// 查询那边在线程池上先算好(一页上万份文档逐个过字段不该压在 UI 线程上);没给就当场算。 + /// + private void ApplyResults(List documents, int firstNumber, ColumnScan? scan = null) { BsonValue? keepId = _selectedRow?.Id; int? keepInsert = _selectedRow?.Insert?.Key; _documents = documents; - Columns = BuildColumns(documents, Staging.Inserts.Select(static i => i.Document)); + scan ??= ColumnScan.Of(documents); + // 暂存的新文档在 UI 线程上改,只能在这里并进来(通常没几份)。 + foreach (StagedInsert insert in Staging.Inserts) + { + scan.Add(insert.Document); + } + Columns = BuildColumns(scan); var rows = new List(documents.Count + Staging.InsertCount); for (int i = 0; i < documents.Count; i++) { @@ -506,32 +521,9 @@ private void ApplyResults(List documents, int firstNumber) /// 列:本页文档顶层字段的并集,按首次出现顺序(_id 在前);宽度按类型与内容估, /// 用户拖过的宽度在翻页 / 重查之间保留(同名列沿用旧宽度)。 /// - private List BuildColumns(IReadOnlyList documents, IEnumerable extra) + private List BuildColumns(ColumnScan scan) { - var order = new List(); - var kinds = new Dictionary>(StringComparer.Ordinal); - var lengths = new Dictionary(StringComparer.Ordinal); - int seen = 0; - foreach (BsonDocument doc in documents.Concat(extra)) - { - // 宽度只看前 200 份就够估了;5 万行的页里逐格算显示文本是白花几百毫秒。 - bool measure = seen++ < 200; - foreach (BsonElement element in doc) - { - if (!kinds.TryGetValue(element.Name, out Dictionary? counts)) - { - counts = []; - kinds[element.Name] = counts; - order.Add(element.Name); - } - BsonKind kind = BsonKinds.Of(element.Value); - counts[kind] = counts.GetValueOrDefault(kind) + 1; - if (measure && lengths.GetValueOrDefault(element.Name) < 40) - { - lengths[element.Name] = Math.Max(lengths.GetValueOrDefault(element.Name), BsonText.Cell(element.Value).Length); - } - } - } + List order = [.. scan.Order]; if (order.Remove("_id")) { order.Insert(0, "_id"); @@ -541,8 +533,8 @@ private List BuildColumns(IReadOnlyList document var columns = new List(order.Count); foreach (string name in order) { - BsonKind kind = Dominant(kinds[name]); - double width = previous.TryGetValue(name, out CollectionColumn? old) ? old.Width : EstimateWidth(name, kind, lengths.GetValueOrDefault(name)); + BsonKind kind = Dominant(scan.Kinds[name]); + double width = previous.TryGetValue(name, out CollectionColumn? old) ? old.Width : EstimateWidth(name, kind, scan.Lengths.GetValueOrDefault(name)); var column = new CollectionColumn(name, kind, width); if (sort.TryGetValue(name, out BsonValue direction) && direction.IsNumeric) { @@ -553,6 +545,57 @@ private List BuildColumns(IReadOnlyList document return columns; } + /// + /// 一页文档的列统计:顶层字段按首次出现的顺序、每列各类型出现次数、显示文本长度(估列宽用)。 + /// 只碰传进来的文档,不碰视图模型 —— 查询在线程池上就能把它算完。 + /// + internal sealed class ColumnScan + { + private int _seen; + + /// 字段名,按首次出现的顺序。 + public List Order { get; } = []; + + /// 字段 → 各类型出现次数。 + public Dictionary> Kinds { get; } = new(StringComparer.Ordinal); + + /// 字段 → 显示文本的最大长度(封顶 40 就不再量)。 + public Dictionary Lengths { get; } = new(StringComparer.Ordinal); + + /// 统计一组文档。 + public static ColumnScan Of(IReadOnlyList documents) + { + var scan = new ColumnScan(); + foreach (BsonDocument doc in documents) + { + scan.Add(doc); + } + return scan; + } + + /// 并进一份文档。 + public void Add(BsonDocument doc) + { + // 宽度只看前 200 份就够估了;大页里逐格算显示文本是白花几百毫秒。 + bool measure = _seen++ < 200; + foreach (BsonElement element in doc) + { + if (!Kinds.TryGetValue(element.Name, out Dictionary? counts)) + { + counts = []; + Kinds[element.Name] = counts; + Order.Add(element.Name); + } + BsonKind kind = BsonKinds.Of(element.Value); + counts[kind] = counts.GetValueOrDefault(kind) + 1; + if (measure && Lengths.GetValueOrDefault(element.Name) < 40) + { + Lengths[element.Name] = Math.Max(Lengths.GetValueOrDefault(element.Name), BsonText.Cell(element.Value).Length); + } + } + } + } + /// 一列的主导类型:出现最多的那种,null 与缺失不计;全是 null 时就是 null。 internal static BsonKind Dominant(Dictionary counts) => counts.Where(static k => k.Key is not (BsonKind.Null or BsonKind.Missing)) @@ -663,15 +706,7 @@ internal static string SummarizePlan(BsonDocument explain) private readonly CancellationTokenSource _lifetime = new(); private void OnGuardChanged() => Dispatcher.UIThread.Post(() => - { - RaisePropertiesChanged(nameof(CanEdit), nameof(ShowReadOnlyBanner), nameof(ShowViewBanner), nameof(ReadOnlyTitle)); - if (!Workspace.Guard.IsReadOnly) - { - return; - } - _relockTimer?.Stop(); - _relockTimer = null; - }); + RaisePropertiesChanged(nameof(CanEdit), nameof(ShowReadOnlyBanner), nameof(ShowViewBanner), nameof(ReadOnlyTitle))); /// public override void Dispose() @@ -683,9 +718,14 @@ public override void Dispose() _disposed = true; Workspace.Guard.Changed -= OnGuardChanged; Staging.Changed -= OnStagingChanged; - _queryCts?.Cancel(); + if (_queryCts is { } running) + { + // 关标签页时还在跑的查询:服务器那边也停下(不等它)。 + running.Cancel(); + KillOnServer(_queryComment); + } _longQueryTimer?.Stop(); - _relockTimer?.Stop(); + _conflicts.Clear(); _lifetime.Cancel(); _lifetime.Dispose(); base.Dispose(); diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/ConflictDialogViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/ConflictDialogViewModel.cs index cb6cb91..f8b76c4 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/ConflictDialogViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/ConflictDialogViewModel.cs @@ -153,6 +153,9 @@ .. conflict.Edit.Changes.Select(change => /// 合并(按每行的选择)。 public AsyncCommand MergeCommand { get; } + /// 选了一条出路才关的(否则是 × / Esc「先不处理」,或被别的对话框顶掉)。 + internal bool IsChosen { get; private set; } + private async Task FinishAsync(ConflictChoice choice) { if (_resolved) @@ -160,6 +163,7 @@ private async Task FinishAsync(ConflictChoice choice) return; } _resolved = true; + IsChosen = true; HashSet keep = choice == ConflictChoice.Merge ? Rows.Where(static r => r.UseMine).Select(static r => r.Path).ToHashSet(StringComparer.Ordinal) : [with(StringComparer.Ordinal)]; diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/DocumentEditorDialogViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/DocumentEditorDialogViewModel.cs index 815db5b..2eee3b2 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/DocumentEditorDialogViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/DocumentEditorDialogViewModel.cs @@ -51,6 +51,7 @@ internal sealed class DocumentEditorDialogViewModel : DialogViewModel private bool _applyingJson; private bool _regeneratingJson; private DispatcherTimer? _jsonTimer; + private DispatcherTimer? _recomputeTimer; private string? _jsonError; private int _modified; private int _added; @@ -69,7 +70,13 @@ internal sealed class DocumentEditorDialogViewModel : DialogViewModel /// 所属集合。 /// 要编辑的文档; = 新建。 /// 保存成功后回调(参数是写进去的那份文档;删除为 null)—— 集合工作台据此刷新。 - public DocumentEditorDialogViewModel(IMongoWorkspace workspace, CollectionInfo collection, BsonDocument? document, Func? saved) + /// + /// 打开时表单里的内容; = 与 相同。网格里带着暂存修改的文档 + /// 从这里传「原像 + 暂存」, 仍是服务器原像 —— 要发的 $set 因此含着暂存的修改, + /// 乐观并发的筛选也用服务器上的 updatedAt,而不是暂存里改过的那个。 + /// + public DocumentEditorDialogViewModel(IMongoWorkspace workspace, CollectionInfo collection, BsonDocument? document, Func? saved, + BsonDocument? initial = null) : base(workspace) { Collection = collection; @@ -90,12 +97,14 @@ public DocumentEditorDialogViewModel(IMongoWorkspace workspace, CollectionInfo c CopyCommand = new AsyncCommand(CopyAsync); ToggleSearchCommand = new RelayCommand(() => IsSearching = !IsSearching); - BsonDocument initial = Original?.DeepClone().AsBsonDocument ?? new BsonDocument("_id", ObjectId.GenerateNewId()); + BsonDocument start = Original is not null && initial is not null + ? initial.DeepClone().AsBsonDocument + : Original?.DeepClone().AsBsonDocument ?? new BsonDocument("_id", ObjectId.GenerateNewId()); if (template) { - _ = initial.AddRange(document!.DeepClone().AsBsonDocument); + _ = start.AddRange(document!.DeepClone().AsBsonDocument); } - LoadRows(initial, keepExpansion: false); + LoadRows(start, keepExpansion: false); _dirty = false; Workspace.Guard.Changed += OnGuardChanged; RecomputeNow(); @@ -835,17 +844,25 @@ internal void Toast(string title, ToastKind kind, string? detail = null) => // ── 重算 ──────────────────────────────────────────────────────────────── - /// 空闲时重算一次(一阵连续输入合并成一次)。 + /// 重算的防抖间隔:连着敲字时只在停手之后算一次(预览、命令、校验每次都要把整份文档过一遍)。 + internal static readonly TimeSpan RecomputeDelay = TimeSpan.FromMilliseconds(120); + + /// 停手之后重算一次(一阵连续输入合并成一次)。 private void ScheduleRecompute() { - if (_recomputePending) + _recomputePending = true; + if (_recomputeTimer is null) { - return; + _recomputeTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = RecomputeDelay }; + _recomputeTimer.Tick += (_, _) => RecomputeNow(); } - _recomputePending = true; - Dispatcher.UIThread.Post(RecomputeNow, DispatcherPriority.Background); + _recomputeTimer.Stop(); + _recomputeTimer.Start(); } + /// 有一次重算在等防抖(测试用;要立刻看结果就直接调 )。 + internal bool IsRecomputePending => _recomputePending; + /// /// 重算:拼出当前文档 → 校验 → 逐行定状态 → 计数 → 预览、命令、对比、JSON。 /// 测试直接调它,不必等调度器。 @@ -853,6 +870,7 @@ private void ScheduleRecompute() internal void RecomputeNow() { _recomputePending = false; + _recomputeTimer?.Stop(); if (_closed) { return; @@ -866,7 +884,9 @@ internal void RecomputeNow() EvaluateGroup(_roots, Original, parentIsArray: false, ancestorNew: false, context); if (Original is not null) { - context.Removed += Original.Names.Count(n => _roots.All(r => r.Name != n)); + // 顶层被删掉的字段:原文档有、表单里没有。集合查一次,不是每个原字段都把全部行扫一遍。 + HashSet present = [with(StringComparer.Ordinal), .. _roots.Select(static r => r.Name)]; + context.Removed += Original.Names.Count(n => !present.Contains(n)); } // 文档级的问题:JSON 语法、_id 被删、落不到任何一行上的违规。 @@ -1804,6 +1824,7 @@ internal override void OnClosed() { _closed = true; _jsonTimer?.Stop(); + _recomputeTimer?.Stop(); Workspace.Guard.Changed -= OnGuardChanged; base.OnClosed(); } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridModels.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridModels.cs index b635ce4..4f18549 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridModels.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridModels.cs @@ -102,6 +102,15 @@ public int SortDirection public string SortIcon => SortDirection > 0 ? "Mongo.arrow-up" : "Mongo.arrow-down"; } +/// 网格里建控件的列区间(含两端,下标对应 GridColumns); = 不做水平虚拟化。 +/// 第一列。 +/// 最后一列。 +internal readonly record struct CellWindow(int First, int Last) +{ + /// 全部列(没有视图量视口时,例如单测)。 + public static CellWindow All { get; } = new(0, int.MaxValue); +} + /// /// 网格的一行。单元格按需生成(虚拟化只给可见的几十行建容器,大页里绝大多数行的单元格从来不会被算出来)。 /// @@ -217,6 +226,77 @@ public string PathOf(CollectionColumn column) => /// 单元格。 public IReadOnlyList Cells => _cells ??= BuildCells(); + /// + /// 网格里真正建控件的那几格:水平视口(加一点余量)里的列()。 + /// 一行几十列时,每个可见行都给全部列建一套单元格控件,横向滚动、纵向滚动(容器回收换数据)都要整行重建; + /// 视口外的列用 / 两段空白占位,行宽与列头保持一致。 + /// + public IReadOnlyList VisibleCells + { + get + { + IReadOnlyList cells = Cells; + (int first, int last) = WindowRange(cells.Count); + if (first == 0 && last == cells.Count - 1) + { + return cells; + } + if (last < first) + { + return []; + } + var visible = new List(last - first + 1); + for (int i = first; i <= last; i++) + { + visible.Add(cells[i]); + } + return visible; + } + } + + /// 视口左边那些没建控件的列的总宽。 + public double LeadWidth + { + get + { + IReadOnlyList columns = Drill?.Columns ?? Owner.Columns; + (int first, _) = WindowRange(columns.Count); + double width = 0; + for (int i = 0; i < first && i < columns.Count; i++) + { + width += columns[i].Width; + } + return width; + } + } + + /// 视口右边那些没建控件的列的总宽。 + public double TrailWidth + { + get + { + IReadOnlyList columns = Drill?.Columns ?? Owner.Columns; + (int first, int last) = WindowRange(columns.Count); + double width = 0; + for (int i = Math.Max(last + 1, first); i < columns.Count; i++) + { + width += columns[i].Width; + } + return width; + } + } + + /// 水平视口变了(或列宽变了):重新取可见的单元格与两段占位。 + internal void RefreshWindow() => RaisePropertiesChanged(nameof(VisibleCells), nameof(LeadWidth), nameof(TrailWidth)); + + private (int First, int Last) WindowRange(int count) + { + CellWindow window = Owner.CellWindow; + int first = Math.Clamp(window.First, 0, count); + int last = Math.Min(window.Last, count - 1); + return (first, last); + } + /// 暂存区变了之后重算这一行(只对已经生成过单元格的行做实事)。 public void Recompute() { @@ -239,7 +319,7 @@ public void Recompute() if (_cells is not null) { _cells = null; - RaisePropertyChanged(nameof(Cells)); + RaisePropertiesChanged(nameof(Cells), nameof(VisibleCells)); } RaisePropertiesChanged(nameof(Document), nameof(State), nameof(IsModified), nameof(IsAdded), nameof(IsDeleted), nameof(HasStateIcon), nameof(StateIcon), nameof(StateIconToken)); @@ -444,10 +524,14 @@ internal sealed class InlineValueEditor : ObservableObject public InlineValueEditor(string text, BsonKind kind, IReadOnlyList choices) { _text = text; + InitialText = text; Kind = kind; Choices = choices; } + /// 打开编辑器时的文本(原样提交时据此认出"没改",不再解析一遍)。 + public string InitialText { get; } + /// 编辑中的文本。 public string Text { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml index b4de839..f50883f 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml @@ -133,7 +133,9 @@ - + + + @@ -158,6 +160,7 @@ + diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml.cs index 8617e44..c638b5d 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/GridPaneView.axaml.cs @@ -23,7 +23,11 @@ public GridPaneView() GridList.TemplateApplied += (_, e) => { _rowsScroll = e.NameScope.Find("PART_ScrollViewer"); - _rowsScroll?.ScrollChanged += (_, _) => HeaderScroll.Offset = new Vector(_rowsScroll.Offset.X, 0); + _rowsScroll?.ScrollChanged += (_, _) => + { + HeaderScroll.Offset = new Vector(_rowsScroll.Offset.X, 0); + UpdateCellWindow(force: false); + }; }; GridList.AddHandler(PointerPressedEvent, OnPointerPressed, RoutingStrategies.Tunnel, handledEventsToo: true); GridList.AddHandler(KeyDownEvent, OnKeyDown, RoutingStrategies.Tunnel); @@ -55,6 +59,137 @@ internal void Attach(CollectionTabViewModel viewModel) { _viewModel = viewModel; viewModel.RowAdded += GridList.ScrollIntoView; + viewModel.PropertyChanged += OnViewModelChanged; + WatchColumns(viewModel.GridColumns); + UpdateCellWindow(force: true); + } + + // ── 水平虚拟化 ────────────────────────────────────────────────────────── + + /// 行号格的宽度(Border.rownum)。 + private const double RowNumberWidth = 40; + + /// 视口两侧多建的宽度:横向滚动一小段时不必每一下都重建单元格。 + private const double WindowBuffer = 320; + + private IReadOnlyList _watchedColumns = []; + + private void OnViewModelChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + switch (e.PropertyName) + { + case nameof(CollectionTabViewModel.GridColumns): + // 列换了(重查、钻入 / 回退):在行绑上新列之前先把区间算好。 + WatchColumns(_viewModel!.GridColumns); + UpdateCellWindow(force: true); + break; + case nameof(CollectionTabViewModel.CurrentColumn): + BringColumnIntoView(_viewModel!.CurrentColumn); + break; + } + } + + private void WatchColumns(IReadOnlyList columns) + { + foreach (CollectionColumn column in _watchedColumns) + { + column.PropertyChanged -= OnColumnChanged; + } + _watchedColumns = columns; + foreach (CollectionColumn column in columns) + { + column.PropertyChanged += OnColumnChanged; + } + } + + /// 列宽变了(拖、双击自适应):两段占位的宽度跟着变,区间也可能变。 + private void OnColumnChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(CollectionColumn.Width)) + { + UpdateCellWindow(force: true); + } + } + + /// + /// 按水平视口算出要建控件的列区间,变了(或 )就让已实现的行重取可见单元格。 + /// 还没量出视口时(刚挂上、单测里没有窗口)不做虚拟化,全部列照建。 + /// + private void UpdateCellWindow(bool force) + { + if (_viewModel is not { } vm) + { + return; + } + IReadOnlyList columns = vm.GridColumns; + CellWindow window = CellWindow.All; + if (_rowsScroll is { Viewport.Width: > 0 } scroll) + { + double left = scroll.Offset.X - WindowBuffer; + double right = scroll.Offset.X + scroll.Viewport.Width + WindowBuffer; + double x = RowNumberWidth; + int first = columns.Count; + int last = columns.Count - 1; + for (int i = 0; i < columns.Count; i++) + { + double width = columns[i].Width; + if (x > right) + { + last = i - 1; + break; + } + if (first == columns.Count && x + width >= left) + { + first = i; + } + x += width; + } + window = new CellWindow(first, last); + } + if (!force && window == vm.CellWindow) + { + return; + } + vm.CellWindow = window; + foreach (Control container in GridList.GetRealizedContainers()) + { + if (container.DataContext is CollectionRow row) + { + row.RefreshWindow(); + } + } + } + + /// 当前列换了(← →、Tab 编辑下一格):横向滚到它,好让它的单元格建出来、编辑框拿得到焦点。 + private void BringColumnIntoView(CollectionColumn? column) + { + if (column is null || _viewModel is not { } vm || _rowsScroll is not { Viewport.Width: > 0 } scroll) + { + return; + } + double x = RowNumberWidth; + foreach (CollectionColumn c in vm.GridColumns) + { + if (ReferenceEquals(c, column)) + { + double offset = scroll.Offset.X; + if (x < offset) + { + // 行号格跟着内容一起滚:滚到第一列时把它也露出来。 + offset = Math.Max(0, x - RowNumberWidth); + } + else if (x + c.Width > offset + scroll.Viewport.Width) + { + offset = x + c.Width - scroll.Viewport.Width; + } + if (Math.Abs(offset - scroll.Offset.X) > 0.5) + { + scroll.Offset = new Vector(offset, scroll.Offset.Y); + } + return; + } + x += c.Width; + } } private void OnHeaderClick(object? sender, RoutedEventArgs e) diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardViewModel.cs index a92884a..e688cd6 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardViewModel.cs @@ -133,17 +133,35 @@ public JsonCardViewModel(CollectionTabViewModel owner, CollectionRow row) /// 编辑中。 public bool IsEditing { - get; + get => _isEditing; private set { - if (SetProperty(ref field, value)) + if (SetProperty(ref _isEditing, value)) { - RaisePropertiesChanged(nameof(IsReadOnlyView), nameof(EditBadge)); + RaisePropertiesChanged(nameof(IsReadOnlyView), nameof(EditBadge), nameof(EditSurface)); _owner.OnCardEditingChanged(this); } } } + private bool _isEditing; + + /// 编辑器的内容(视图里的编辑器按它按需生成):编辑中是这张卡片自己,否则为 。 + public JsonCardViewModel? EditSurface => _isEditing ? this : null; + + /// + /// 重查之后接过旧卡片的编辑状态(同一份文档,行对象是新的):敲了一半的文本、「还原」的基线照旧, + /// 差异按新读到的原像重算。卡片此刻还没挂到界面上,不发编辑状态变化的通知(不去取消别的卡片)。 + /// + /// 重查前正在编辑的那张卡片。 + internal void AdoptEditFrom(JsonCardViewModel previous) + { + _editStart = previous._editStart; + _editText = previous._editText; + _isEditing = true; + Analyze(); + } + /// 只读显示中。 public bool IsReadOnlyView => !IsEditing; diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardsView.axaml b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardsView.axaml index 85dfdac..7c33db4 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardsView.axaml +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Collection/JsonCardsView.axaml @@ -128,10 +128,18 @@ - + + + + + + + + diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignModels.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignModels.cs index cd6cd16..7aa5cd2 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignModels.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignModels.cs @@ -88,10 +88,18 @@ internal sealed class IndexRow : ObservableObject public IReadOnlyList Keys { get; init; } = []; /// 形态。 - public IndexForm Form { get; init; } + public IndexForm Form + { + get; + set => SetProperty(ref field, value); + } - /// 类型列文字。 - public string TypeText { get; init; } = ""; + /// 类型列文字(多键探测是表格出来之后才补的,所以可变)。 + public string TypeText + { + get; + set => SetProperty(ref field, value); + } = ""; /// 属性标签。 public IReadOnlyList Attributes { get; init; } = []; @@ -121,7 +129,11 @@ internal sealed class IndexRow : ObservableObject public DateTime? Since { get; init; } /// 多键。 - public bool MultiKey { get; init; } + public bool MultiKey + { + get; + set => SetProperty(ref field, value); + } /// 被标成"未使用"(名称与 ops 变橙)。 public bool IsUnused { get; init; } @@ -477,6 +489,12 @@ internal sealed class FailureReasonRow /// 在网格中查看时用的筛选。 public required string Filter { get; init; } + + /// 「在网格中查看」链接的字(这一组太大、筛选退成全部不符合的文档时是「查看全部不通过」)。 + public string ViewText { get; init; } = ""; + + /// 链接的悬停说明;按 _id 精确列出这一组时为 。 + public string? ViewTip { get; init; } } /// 选项页里的一条 TTL 索引。 diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Indexes.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Indexes.cs index 78a9296..17760b8 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Indexes.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Indexes.cs @@ -152,14 +152,6 @@ private async Task LoadIndexesCoreAsync() _indexStats = stats; Dictionary usage = await LoadIndexUsageAsync().ConfigureAwait(true); Dictionary progress = await LoadBuildProgressAsync().ConfigureAwait(true); - var multiKey = new HashSet(StringComparer.Ordinal); - foreach ((BsonDocument spec, bool building) in specs) - { - if (!building && await IsMultiKeyAsync(spec).ConfigureAwait(true)) - { - _ = multiKey.Add(spec.GetValue("name", "").ToString()!); - } - } DateTime now = Now(); long maxOps = usage.Count == 0 ? 0 : usage.Values.Max(static u => u.Ops); @@ -170,7 +162,8 @@ private async Task LoadIndexesCoreAsync() bool hasUsage = usage.TryGetValue(name, out (long Ops, DateTime Since) u); bool unused = hasUsage && u.Ops == 0 && name != "_id_" && !building && (now - u.Since).TotalDays >= IndexAdvisor.UnusedWindowDays; - IndexForm form = IndexAdvisor.ShapeOf(spec, multiKey.Contains(name)); + // 多键要靠逐个 explain 才知道:先按"不是多键"出表,下面再并发补上。 + IndexForm form = IndexAdvisor.ShapeOf(spec, false); long size = stats.IndexSizes.GetValueOrDefault(name); var row = new IndexRow { @@ -185,7 +178,6 @@ private async Task LoadIndexesCoreAsync() Ops = hasUsage ? u.Ops : null, UsageRatio = hasUsage && maxOps > 0 ? (double)u.Ops / maxOps : 0, Since = hasUsage ? u.Since : null, - MultiKey = multiKey.Contains(name), IsUnused = unused, IsBuilding = building || progress.ContainsKey(name) }; @@ -215,7 +207,7 @@ private async Task LoadIndexesCoreAsync() { StartBuildPoll(); } - await LoadAdviceAsync(rows).ConfigureAwait(true); + await Task.WhenAll(FillMultiKeyAsync(rows), LoadAdviceAsync(rows)).ConfigureAwait(true); } catch (Exception ex) when (IsExpected(ex)) { @@ -345,6 +337,33 @@ private async Task> LoadBuildProgressAsync() /// 多键:键模式看不出来,要看执行计划。用 hint 指定这个索引做一次 queryPlanner 级的 explain /// (不执行查询),读 IXSCAN 阶段的 isMultiKey。文本 / 隐藏 / 通配符索引不能这样 hint,跳过。 /// + /// + /// 表格出来之后再补"多键":每个索引一次 explain,限 4 路并发(几十个索引串着探,整张表要等好几秒才出来)。 + /// 探出来是多键的那一行就地改类型列。 + /// + private async Task FillMultiKeyAsync(IReadOnlyList rows) + { + using var gate = new SemaphoreSlim(4); + await Task.WhenAll(rows.Where(static r => !r.IsBuilding).Select(async row => + { + await gate.WaitAsync(Lifetime).ConfigureAwait(true); + try + { + if (_disposed || !await IsMultiKeyAsync(row.Spec).ConfigureAwait(true)) + { + return; + } + row.MultiKey = true; + row.Form = IndexAdvisor.ShapeOf(row.Spec, true); + row.TypeText = FormText(row.Form); + } + finally + { + _ = gate.Release(); + } + })).ConfigureAwait(true); + } + private async Task IsMultiKeyAsync(BsonDocument spec) { IndexForm form = IndexAdvisor.ShapeOf(spec); @@ -438,7 +457,9 @@ private async Task LoadAdviceAsync(IReadOnlyList rows) .Select(static r => new AdvisorIndex(r.Name, r.Key, r.Spec, r.Ops, r.Since, r.Size)) .ToList(); IReadOnlyList groups = IndexAdvisor.GroupSlowQueries(profile); - IReadOnlyList suggestions = IndexAdvisor.Advise(groups, usages, Now()); + // 分片键的支撑索引永远不该被建议删掉;拿不到(非分片、无权限)时它返回 null,按非分片处理。 + BsonDocument? shardKey = await Workspace.Connection.GetShardKeyAsync(Database, CollectionName, Lifetime).ConfigureAwait(true); + IReadOnlyList suggestions = IndexAdvisor.Advise(groups, usages, Now(), shardKey); Advice.Clear(); foreach (AdvisorSuggestion suggestion in suggestions) diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Validation.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Validation.cs index 2552d5a..2bbfca5 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Validation.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignTabViewModel.Validation.cs @@ -54,6 +54,9 @@ internal sealed partial class DesignTabViewModel private List _precheckIds = []; private long _passCount; private long _failCount = -1; + + /// 是按哪一版规则判出来的(与 _ruleValidator 不是同一个对象就是过期的)。 + private BsonDocument? _precheckedValidator; private DispatcherTimer? _tryTimer; private DispatcherTimer? _ruleTimer; private int _tryVersion; @@ -151,7 +154,13 @@ public string RuleSyntaxText public bool IsPrechecking { get; - private set => SetProperty(ref field, value); + private set + { + if (SetProperty(ref field, value)) + { + ApplyRuleCommand.RaiseCanExecuteChanged(); + } + } } /// 预检抽了多少份(抽样 1,000)。 @@ -322,9 +331,8 @@ private void InitializeValidation() RuleLevel = _appliedLevel; RuleAction = _appliedAction; }); - ApplyRuleCommand = new(() => _ruleValidator is null - ? Task.CompletedTask - : ApplyValidatorAsync(_ruleValidator, RuleLevel, RuleAction, _failCount), () => RuleSyntaxOk); + // 预检进行中不让点:那时的份数还属于上一版规则。 + ApplyRuleCommand = new(ApplyRuleAsync, () => RuleSyntaxOk && !IsPrechecking); RefreshPrecheckCommand = new(() => RunPrecheckAsync(resample: true)); OpenFailureCommand = new(row => Workspace.OpenCollection(Database, CollectionName, row.Filter)); FailureReasons.CollectionChanged += (_, _) => RaisePropertyChanged(nameof(HasFailureReasons)); @@ -482,6 +490,7 @@ internal async Task RunPrecheckAsync(bool resample) if (_precheckIds.Count == 0) { SetPrecheck(0, 0, []); + _precheckedValidator = validator; return; } List failing = []; @@ -501,6 +510,7 @@ internal async Task RunPrecheckAsync(bool resample) return; } SetPrecheck(_precheckIds.Count - failing.Count, failing.Count, GroupFailures(validator, failing)); + _precheckedValidator = validator; } catch (Exception ex) when (IsExpected(ex)) { @@ -574,7 +584,10 @@ .. order List ids = groups[k]; BsonValue first = ids[0]; string example = first.IsObjectId ? BsonText.Shorten(first.AsObjectId.ToString()) : BsonText.Inline(first); - BsonDocument filter = ids.Count <= 200 + // 200 份以内按 _id 精确列出这一组;再多筛选框里放不下,退成"全部不符合规则的文档" —— + // 那就不再是这一组了,链接文字与悬停说明要照实写。 + bool exact = ids.Count <= 200; + BsonDocument filter = exact ? new BsonDocument("_id", new BsonDocument("$in", new BsonArray(ids))) : new BsonDocument("$nor", new BsonArray { validator }); return new FailureReasonRow @@ -585,7 +598,9 @@ .. order Count = ids.Count, CountText = Loc.Format("Design_Copies", BsonText.Grouped(ids.Count)), Example = Loc.Format("Design_Example", example), - Filter = BsonText.Literal(filter) + Filter = BsonText.Literal(filter), + ViewText = Loc[exact ? "Design_ViewInGrid" : "Design_ViewAllInGrid"], + ViewTip = exact ? null : Loc["Design_ViewAllInGridTip"] }; }) ]; @@ -825,7 +840,12 @@ private async Task LoadHistoryAsync() /// 应用一条验证规则(collMod)。写护栏 → 确认(写清 level / action 与已知的不符合份数)→ /// 先把旧规则存进历史 → collMod → 重探集合信息、重置编辑器、重新预检。 /// - internal async Task ApplyValidatorAsync(BsonDocument validator, string level, string action, long knownFailures) + /// 规则。 + /// validationLevel。 + /// validationAction。 + /// 已知不符合的份数;负数 = 不知道(预检没跑完 / 失败)。 + /// 份数是从多少份抽样里数出来的; = 全集合计数。 + internal async Task ApplyValidatorAsync(BsonDocument validator, string level, string action, long knownFailures, int? sampledOf = null) { if (!CanValidate) { @@ -843,16 +863,18 @@ internal async Task ApplyValidatorAsync(BsonDocument validator, string level, st }; if (knownFailures > 0) { - facts.Add(new(Loc["Design_PrecheckFailures"], BsonText.Grouped(knownFailures))); + facts.Add(new(Loc["Design_PrecheckFailures"], sampledOf is { } n + ? $"{BsonText.Grouped(knownFailures)} / {BsonText.Grouped(n)}" + : BsonText.Grouped(knownFailures))); } bool confirmed = await Workspace.ConfirmAsync(new() { Title = Loc["Design_ApplyTitle"], - Message = Loc.Format("Design_ApplyBody", Namespace, level, action) - + (knownFailures > 0 ? " " + Loc.Format(action == "error" ? "Design_ApplyRejects" : "Design_ApplyWarns", BsonText.Grouped(knownFailures)) : ""), + Message = Loc.Format("Design_ApplyBody", Namespace, level, action) + ApplyConsequence(level, action, knownFailures, sampledOf), ConfirmLabel = Loc["Design_ApplyRule"], IconKey = "Mongo.shield-check", - Danger = action == "error" && level != "off" && knownFailures > 0, + // 只有 strict + 拒绝 才真会把对现有不合规文档的更新挡回去;moderate 不校验它们,warn 只记日志。 + Danger = IsRejecting(action) && level == "strict" && knownFailures > 0, Facts = facts, TypeToConfirm = Workspace.Guard.ConfirmWrites ? CollectionName : null }).ConfigureAwait(true); @@ -882,6 +904,60 @@ internal async Task ApplyValidatorAsync(BsonDocument validator, string level, st } } + /// validationAction 是不是会拒绝写入(error,以及 8.1 起的 errorAndLog 一类)。 + internal static bool IsRejecting(string action) => action.StartsWith("error", StringComparison.Ordinal); + + /// + /// 确认框里"现有文档"那一句:份数(抽样的写明是抽样的几分之几)+ 按 level / action 的真实后果 —— + /// moderate 不校验对本就不合规文档的更新,warn 只记日志,off 什么都不管。 + /// + internal string ApplyConsequence(string level, string action, long knownFailures, int? sampledOf) + { + if (knownFailures < 0) + { + return " " + Loc["Design_ApplyUnknown"]; + } + if (knownFailures == 0) + { + return ""; + } + string count = sampledOf is { } n + ? Loc.Format("Design_ApplyFailSampled", BsonText.Grouped(knownFailures), BsonText.Grouped(n)) + : Loc.Format("Design_ApplyFailCount", BsonText.Grouped(knownFailures)); + string consequence = level switch + { + "off" => Loc["Design_ApplyConseqOff"], + "moderate" => Loc["Design_ApplyConseqModerate"], + _ => Loc[IsRejecting(action) ? "Design_ApplyConseqReject" : "Design_ApplyConseqWarn"] + }; + return $" {count} {consequence}"; + } + + /// + /// 「应用」:预检的份数必须对应编辑器里这一版规则。规则刚改过、预检还没跟上时先补一次预检再弹确认框 —— + /// 否则框里可能写着 0 份不符合、也不标红,而实际上新规则会挡掉一批文档。 + /// + private async Task ApplyRuleAsync() + { + if (_ruleValidator is not { } validator) + { + return; + } + if (!ReferenceEquals(_precheckedValidator, validator)) + { + _ruleTimer?.Stop(); + await RunPrecheckAsync(resample: false).ConfigureAwait(true); + } + if (!ReferenceEquals(validator, _ruleValidator)) + { + // 等预检的时候规则又改了:不按旧的那一版应用。 + return; + } + bool known = ReferenceEquals(_precheckedValidator, validator); + await ApplyValidatorAsync(validator, RuleLevel, RuleAction, known ? _failCount : -1, + known ? _precheckIds.Count : null).ConfigureAwait(true); + } + /// 把当前生效的规则存进历史(最多 20 版)。 private async Task SaveHistoryAsync() { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignValidationView.axaml b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignValidationView.axaml index 3dac003..1acff85 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignValidationView.axaml +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Design/DesignValidationView.axaml @@ -146,8 +146,8 @@ diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Dialogs/ConnectionDialogViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Dialogs/ConnectionDialogViewModel.cs index b341787..c62fdc7 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Dialogs/ConnectionDialogViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Dialogs/ConnectionDialogViewModel.cs @@ -248,6 +248,7 @@ internal sealed class ConnectionDialogViewModel : DialogViewModel, IDisposable private string _topology; private string _srvHost = ""; private string _uri = ""; + private string? _uriPassword; private string _replicaSet; private string _database; private string _readPreference; @@ -308,13 +309,16 @@ public ConnectionDialogViewModel(MongoWorkspaceViewModel shell, MongoProfile pro ]; _environment = profile.Get(MongoSettings.KeyEnvironment, "development"); _topology = profile.Get(MongoSettings.KeyTopology, "hosts"); + string? uriUser = null; switch (s.Topology) { case MongoTopology.Srv: _srvHost = profile.Host; break; case MongoTopology.Uri: - _uri = profile.Host; + // 框里只放不带凭据的 URI:早先存进来的 user:pass@ 拆到用户名栏与内存里(保存时口令进密钥库), + // 不在界面上露出明文口令。 + (_uri, uriUser, _uriPassword) = StripCredentials(profile.Host); break; } Hosts.Add(new HostRowViewModel(s.Topology == MongoTopology.Hosts ? profile.Host : "", @@ -329,7 +333,12 @@ public ConnectionDialogViewModel(MongoWorkspaceViewModel shell, MongoProfile pro _readPreference = s.ReadPreference; _mechanism = s.AuthMechanism; _authSource = s.AuthSource; - _username = profile.Username; + _username = profile.Username.Length > 0 ? profile.Username : uriUser ?? ""; + if (!string.Equals(_username, uriUser, StringComparison.Ordinal)) + { + // 用户名栏另填了账号:连接时以那一栏为准(MongoConnection.BuildSettings),URI 里那个口令本来就不用。 + _uriPassword = null; + } _sshEnabled = s.JumpSessionId.Length > 0; _tlsEnabled = s.UseTls; _tlsCaFile = s.TlsCaFile; @@ -1083,7 +1092,35 @@ private async Task EffectivePasswordAsync() { return Password; } - return await _shell.Profiles.GetPasswordAsync(_passwordFrom ?? _original.Id).ConfigureAwait(true); + string stored = await _shell.Profiles.GetPasswordAsync(_passwordFrom ?? _original.Id).ConfigureAwait(true); + return stored.Length == 0 && _uriPassword is { Length: > 0 } fromUri ? fromUri : stored; + } + + /// + /// 把 URI 里的 user:pass@ 拆出来:返回不带凭据的 URI、用户名与口令。没有凭据(或解析不了)时原样返回, + /// 不让驱动把串重新排一遍。口令只该进宿主的密钥库,不进插件存储里的连接串。 + /// + /// 连接串。 + /// (不带凭据的 URI, 用户名, 口令)。 + internal static (string Uri, string? Username, string? Password) StripCredentials(string uri) + { + try + { + var builder = new MongoDB.Driver.MongoUrlBuilder(uri.Trim()); + if (builder.Username is null && builder.Password is null) + { + return (uri, null, null); + } + string? username = builder.Username; + string? password = builder.Password; + builder.Username = null; + builder.Password = null; + return (builder.ToString(), username, password); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + return (uri, null, null); + } } private async Task TestAsync() @@ -1178,12 +1215,28 @@ private void ApplyBadges(IReadOnlyList endpoints) private async Task SaveAsync(bool connect) { MongoProfile profile = ToProfile(); + string? uriPassword = _uriPassword; + if (_topology == "uri") + { + // URI 里写了 user:pass@:用户名挪到用户名栏(那一栏空着时),口令走下面存密钥库那条路, + // 存进插件存储的只是不带凭据的 URI —— 不然口令明文落盘,再打开编辑时还原样显示在框里。 + (string clean, string? uriUser, string? fromUri) = StripCredentials(profile.Host); + profile.Host = clean; + if (uriUser is { Length: > 0 } && profile.Username.Length == 0) + { + profile.Username = uriUser; + } + if (fromUri is not null && string.Equals(profile.Username, uriUser, StringComparison.Ordinal)) + { + uriPassword = fromUri; + } + } if (Validate(profile) is { } problem) { Error = problem; return; } - // 口令:填了就存;匿名就把存着的删掉;复制来的连接带上原来那条的;其余(编辑时留空)不动。 + // 口令:填了就存;匿名就把存着的删掉;URI 里带的存进密钥库;复制来的连接带上原来那条的;其余(编辑时留空)不动。 string? password; if (Password.Length > 0) { @@ -1193,9 +1246,22 @@ private async Task SaveAsync(bool connect) { password = ""; } + else if (uriPassword is { Length: > 0 }) + { + password = uriPassword; + } else if (_passwordFrom is not null) { - password = await _shell.Profiles.GetPasswordAsync(_passwordFrom).ConfigureAwait(true); + try + { + password = await _shell.Profiles.GetPasswordAsync(_passwordFrom).ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // 密钥库读不出来:说清楚,别让「保存」一声不响地什么都没做(命令外壳会吞掉异常)。 + Error = Loc.Format("Conn_SaveFailed", MongoConnector.Describe(ex)); + return; + } } else { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Editor/CodeEditor.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Editor/CodeEditor.cs index a9dc37d..34fceef 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Editor/CodeEditor.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Editor/CodeEditor.cs @@ -572,9 +572,14 @@ private async Task RequestCompletionAsync(bool explicitRequest) var cts = new CancellationTokenSource(); _completionRequest = cts; CompletionSet? set; + // 记下发请求那一刻的文档版本与光标:补全是异步算的,回来时文本或光标已经变了, + // 这份候选的替换起点就对不上了(严重时算出负长度,GetText 抛出没人接的异常)。 + AvaloniaEdit.Document.TextDocument document = Editor.Document; + AvaloniaEdit.Document.ITextSourceVersion? version = document.Version; + int caret = Editor.CaretOffset; try { - set = await provider(new CompletionRequest(Editor.Text, Editor.CaretOffset, explicitRequest)).ConfigureAwait(true); + set = await provider(new CompletionRequest(Editor.Text, caret, explicitRequest)).ConfigureAwait(true); } catch (Exception) { @@ -584,9 +589,15 @@ private async Task RequestCompletionAsync(bool explicitRequest) { return; } - int prefixLength = Math.Max(0, Editor.CaretOffset - set.ReplaceOffset); - string prefix = Editor.Document.GetText(Math.Clamp(set.ReplaceOffset, 0, Editor.Document.TextLength), - Math.Min(prefixLength, Editor.Document.TextLength - set.ReplaceOffset)); + if (!ReferenceEquals(Editor.Document, document) || Editor.CaretOffset != caret + || version is not null && (document.Version is not { } now || !version.BelongsToSameDocumentAs(now) || version.CompareAge(now) != 0)) + { + return; + } + int textLength = document.TextLength; + int replaceOffset = Math.Clamp(set.ReplaceOffset, 0, textLength); + int prefixLength = Math.Clamp(caret - replaceOffset, 0, textLength - replaceOffset); + string prefix = document.GetText(replaceOffset, prefixLength); var session = new CompletionSession(set) { InitialPrefix = prefix }; if (prefix.Length > 0 && !session.Filter(prefix)) { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsEntry.cs b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsEntry.cs index 480d1c8..c43b101 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsEntry.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsEntry.cs @@ -256,8 +256,17 @@ internal sealed class GridFsTransfer /// 种类。 public required GridFsTransferKind Kind { get; init; } - /// 本地路径(上传的源 / 下载的目标)。 - public required string LocalPath { get; init; } + /// 本地路径(上传的源 / 下载的目标;下载落盘时若要避让同名文件会改成实际写到的那个)。 + public required string LocalPath { get; set; } + + /// + /// 下载:目标已有同名文件时另起 name (2).ext,不覆盖。多项下载到文件夹时为 ; + /// 单个文件走另存为对话框(用户已确认过覆盖)、外部打开写临时目录,都是 。 + /// + public bool KeepExisting { get; init; } + + /// 下载中写的临时文件(写完再挪成 ;失败、取消只删它)。 + public string? PartPath { get; set; } /// GridFS 文件名(上传的目标 / 下载的源)。 public required string Filename { get; init; } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.Actions.cs b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.Actions.cs index fa19fd5..8e0a78f 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.Actions.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.Actions.cs @@ -23,6 +23,14 @@ internal sealed partial class GridFsTabViewModel /// 缩略图只读这么大以内的图片(整块进内存,一屏几十张)。 private const long ThumbnailLimit = 4L * 1024 * 1024; + /// 一次最多给多少张图出缩略图。 + private const int ThumbnailsPerView = 120; + + /// 跨刷新的缩略图缓存;容量必须大于 。 + private readonly GridFsThumbnailCache _thumbnails = new(ThumbnailsPerView * 2); + + private bool _disposed; + private readonly Queue _queue = new(); private readonly List _pendingRows = []; private readonly DispatcherTimer _transferTicker; @@ -293,13 +301,15 @@ internal async Task DownloadFileAsync(GridFsFile file) internal async Task DownloadToFolderAsync(IReadOnlyList targets, string folder) { var jobs = new List(); + // 同一批里撞名(不同虚拟目录下的同名文件平铺到一处、清洗后同名)与本地已有的文件都不覆盖:另起 name (2).ext。 + var taken = new HashSet(StringComparer.OrdinalIgnoreCase); try { foreach (GridFsEntry target in targets) { if (target is { IsFile: true, File: { } file }) { - jobs.Add(DownloadJob(file, SafeLocalPath(folder, file.BaseName))); + jobs.Add(DownloadJob(file, UniqueLocalPath(SafeLocalPath(folder, file.BaseName), taken), keepExisting: true)); } else if (target.IsFolder) { @@ -307,7 +317,8 @@ internal async Task DownloadToFolderAsync(IReadOnlyList targets, st root = GridFsPaths.BaseName(root); foreach (GridFsFile inner in await Service.FilesUnderAsync(target.Path, latestOnly: true).ConfigureAwait(true)) { - jobs.Add(DownloadJob(inner, SafeLocalPath(folder, root + "/" + inner.Filename[target.Path.Length..]))); + string path = SafeLocalPath(folder, root + "/" + inner.Filename[target.Path.Length..]); + jobs.Add(DownloadJob(inner, UniqueLocalPath(path, taken), keepExisting: true)); } } } @@ -328,10 +339,11 @@ internal Task OpenExternalAsync(GridFsFile file) return Task.CompletedTask; } - private static GridFsTransfer DownloadJob(GridFsFile file, string localPath, Func? then = null) => new() + private static GridFsTransfer DownloadJob(GridFsFile file, string localPath, Func? then = null, bool keepExisting = false) => new() { Kind = GridFsTransferKind.Download, LocalPath = localPath, + KeepExisting = keepExisting, Filename = file.Filename, Source = file, Size = file.Length, @@ -368,6 +380,24 @@ internal static string SafeLocalPath(string root, string relative) return full.StartsWith(rootWithSep, StringComparison.OrdinalIgnoreCase) ? full : Path.Combine(rootFull, parts[^1]); } + /// + /// 避让同名: 已存在(文件或目录)或已被这一批占用时依次试 name (2).ext、name (3).ext…; + /// 选中的那个记进 。 + /// + internal static string UniqueLocalPath(string path, ISet taken) + { + string directory = Path.GetDirectoryName(path) ?? ""; + string stem = Path.GetFileNameWithoutExtension(path); + string extension = Path.GetExtension(path); + string candidate = path; + for (int n = 2; taken.Contains(candidate) || File.Exists(candidate) || Directory.Exists(candidate); n++) + { + candidate = Path.Combine(directory, $"{stem} ({n.ToString(CultureInfo.InvariantCulture)}){extension}"); + } + _ = taken.Add(candidate); + return candidate; + } + /// 一段文件名里换掉本机不允许的字符;Windows 的保留名(CON、NUL…)前面加下划线。 internal static string SafeSegment(string segment) { @@ -452,11 +482,21 @@ private async Task PumpAsync() else { _ = Directory.CreateDirectory(Path.GetDirectoryName(job.LocalPath)!); - await using (var target = new FileStream(job.LocalPath, FileMode.Create, FileAccess.Write, FileShare.None, + // 先写到旁边的 .part,写完再挪过去:中途失败 / 取消只删半截的临时文件, + // 绝不会动到目标位置上原本就有的那个文件。 + job.PartPath = $"{job.LocalPath}.{Guid.NewGuid().ToString("N")[..8]}.part"; + await using (var target = new FileStream(job.PartPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous)) { await Service.DownloadAsync(job.Source!.Id, target, job.Reporter, cts.Token).ConfigureAwait(true); } + if (job.KeepExisting && (File.Exists(job.LocalPath) || Directory.Exists(job.LocalPath))) + { + // 排队期间那个名字被别人占了:照样不覆盖。 + job.LocalPath = UniqueLocalPath(job.LocalPath, new HashSet(StringComparer.OrdinalIgnoreCase)); + } + File.Move(job.PartPath, job.LocalPath, overwrite: !job.KeepExisting); + job.PartPath = null; if (job.Then is { } then) { await then(job.LocalPath).ConfigureAwait(true); @@ -561,18 +601,39 @@ private void RemovePendingRow(GridFsTransfer job) private static void DeletePartial(GridFsTransfer job) { - if (job.Kind != GridFsTransferKind.Download) + // 只删自己写的临时文件;目标路径上的文件(可能是用户原有的)一概不碰。 + if (job.Kind != GridFsTransferKind.Download || job.PartPath is not { } part) { return; } try { - File.Delete(job.LocalPath); + File.Delete(part); + job.PartPath = null; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - // 删不掉半截文件不影响主流程;它会在下一次同名下载时被覆盖。 + // 删不掉半截文件不影响主流程。 + } + } + + /// 传输队列还在跑时关标签 = 全部取消:先问一句。 + public override async Task ConfirmCloseAsync() + { + if (_current is null && _queue.Count == 0) + { + return await base.ConfirmCloseAsync().ConfigureAwait(true); } + int count = _queue.Count + (_current is null ? 0 : 1); + bool confirmed = await Workspace.ConfirmAsync(new() + { + Title = Loc["Fs_CloseTransfersTitle"], + Message = Loc.Format("Fs_CloseTransfersBody", count), + ConfirmLabel = Loc["Fs_CloseTransfersConfirm"], + IconKey = "Mongo.triangle-alert", + Danger = true + }).ConfigureAwait(true); + return confirmed && await base.ConfirmCloseAsync().ConfigureAwait(true); } private void CancelTransfers() @@ -992,16 +1053,40 @@ internal void SwitchBucket(string name) /// /// 缩略图视图里给图片懒加载缩略图:只取 4 MB 以内的、最多 120 张,一张一张来 —— - /// 缩略图是锦上添花,不能为它把连接塞满。 + /// 缩略图是锦上添花,不能为它把连接塞满。解出来的(按 192 宽缩小解码)进跨刷新的缓存, + /// 重列时命中的直接挂上,只下没见过的。 /// private async Task LoadThumbnailsAsync() { _thumbCts?.Cancel(); var cts = new CancellationTokenSource(); _thumbCts = cts; - List candidates = [.. Entries - .Where(static e => e is { IsFile: true, Category: GridFsCategory.Image, Thumbnail: null, File.Length: > 0 and <= ThumbnailLimit }) - .Take(120)]; + // 一次最多给 120 张(命中的也算):缓存容量比它大,正在显示的这些就不会被新解的挤出去释放掉。 + List visible = [.. Entries + .Where(static e => e is { IsFile: true, Category: GridFsCategory.Image, File.Length: > 0 and <= ThumbnailLimit }) + .Take(ThumbnailsPerView)]; + // 这一轮之外的行一律摘掉缩略图:它们的位图随时可能被挤出缓存释放,不能还挂在界面上。 + var shown = new HashSet(visible); + foreach (GridFsEntry entry in _listed) + { + if (entry.Thumbnail is not null && !shown.Contains(entry)) + { + entry.Thumbnail = null; + } + } + var candidates = new List(); + foreach (GridFsEntry entry in visible) + { + if (_thumbnails.TryGet(GridFsThumbnailCache.Key(entry.File!), out Bitmap? cached)) + { + entry.Thumbnail = cached; + } + else + { + entry.Thumbnail = null; + candidates.Add(entry); + } + } foreach (GridFsEntry entry in candidates) { if (cts.IsCancellationRequested) @@ -1010,8 +1095,15 @@ private async Task LoadThumbnailsAsync() } try { + string key = GridFsThumbnailCache.Key(entry.File!); byte[] bytes = await Service.ReadAllAsync(entry.File!.Id, cts.Token).ConfigureAwait(true); - entry.Thumbnail = await Task.Run(() => Decode(bytes, 192), cts.Token).ConfigureAwait(true); + Bitmap? decoded = await Task.Run(() => Decode(bytes, 192), cts.Token).ConfigureAwait(true); + if (_disposed) + { + decoded?.Dispose(); + return; + } + entry.Thumbnail = _thumbnails.Add(key, decoded); } catch (OperationCanceledException) { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.cs index b12d44b..7995196 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsTabViewModel.cs @@ -678,6 +678,12 @@ public override void Dispose() _transferTicker.Stop(); _transferCts?.Cancel(); _thumbCts?.Cancel(); + _disposed = true; + foreach (GridFsEntry entry in _listed) + { + entry.Thumbnail = null; + } + _thumbnails.Dispose(); Details.Dispose(); base.Dispose(); } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsThumbnailCache.cs b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsThumbnailCache.cs new file mode 100644 index 0000000..50d456b --- /dev/null +++ b/plugins/VelaShell.Plugin.Mongo/Ui/GridFs/GridFsThumbnailCache.cs @@ -0,0 +1,78 @@ +using Avalonia.Media.Imaging; +using VelaShell.Plugin.Mongo.Core; + +namespace VelaShell.Plugin.Mongo.Ui.GridFs; + +/// +/// 缩略图的跨刷新缓存(LRU)。F5、搜索、改名、删除、批量上传时每秒一次的重列都会换一批 +/// ,没有它每次都要把最多 120 张图整块重新下一遍。 +/// +/// 键是 _id + uploadDate + length:GridFS 文件不可改写,同一个 _id 内容变了只可能是删了重传, +/// 上传时间跟着变。解不了的图也记一笔(),免得每次重列都再下一遍去失败。 +/// 被挤出去的位图就地 ;容量要大于一屏最多给的张数,正在显示的那些才不会被挤掉。 +/// 只在 UI 线程上用。 +/// +/// +internal sealed class GridFsThumbnailCache(int capacity) : IDisposable +{ + private readonly Dictionary> _map = new(StringComparer.Ordinal); + private readonly LinkedList<(string Key, Bitmap? Bitmap)> _order = new(); + + /// 当前条数。 + public int Count => _map.Count; + + /// 一个文件的缓存键。 + public static string Key(GridFsFile file) => + $"{file.Id.BsonType}:{file.Id}|{file.UploadDate?.Ticks ?? 0}|{file.Length}"; + + /// 取一张(命中即挪到最近用过); 为 表示"解不了"。 + public bool TryGet(string key, out Bitmap? bitmap) + { + if (_map.TryGetValue(key, out LinkedListNode<(string Key, Bitmap? Bitmap)>? node)) + { + _order.Remove(node); + _order.AddFirst(node); + bitmap = node.Value.Bitmap; + return true; + } + bitmap = null; + return false; + } + + /// + /// 放一张,返回该用的那一张;超出容量时挤掉最久没用的并释放它。 + /// 已经有了(被取消的上一轮与这一轮同时解了同一张)就留旧的、释放新的 —— 旧的可能已经挂在界面上了。 + /// + public Bitmap? Add(string key, Bitmap? bitmap) + { + if (_map.TryGetValue(key, out LinkedListNode<(string Key, Bitmap? Bitmap)>? existing)) + { + if (!ReferenceEquals(existing.Value.Bitmap, bitmap)) + { + bitmap?.Dispose(); + } + _order.Remove(existing); + _order.AddFirst(existing); + return existing.Value.Bitmap; + } + _map[key] = _order.AddFirst((key, bitmap)); + while (_map.Count > capacity && _order.Last is { } last) + { + _order.RemoveLast(); + _map.Remove(last.Value.Key); + last.Value.Bitmap?.Dispose(); + } + return bitmap; + } + + /// + public void Dispose() + { + foreach ((_, Bitmap? bitmap) in _order) + { + bitmap?.Dispose(); + } + _order.Clear(); + _map.Clear(); + } +} diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Monitor/MonitorTabViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Monitor/MonitorTabViewModel.cs index 55d25a5..a722752 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Monitor/MonitorTabViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Monitor/MonitorTabViewModel.cs @@ -37,6 +37,18 @@ internal sealed class MonitorTabViewModel : WorkspaceTab private readonly Dictionary _indexBuilds = [with(StringComparer.Ordinal)]; private readonly SemaphoreSlim _tickGate = new(1, 1); private ServerSample? _last; + + /// + /// 算率值用的上一次采样。采样一停(切走、暂停)就作废:不然恢复后的第一个率值是整段停顿期的平均, + /// 却被画在"现在"那一根柱子上。 留着给界面显示当前连接数。 + /// + private ServerSample? _rateBase; + + /// 每停一次采样加一:停之前已经发出去的那一轮回来时,不再把它的采样当作率值基准。 + private int _samplingEpoch; + + /// 低频项(Oplog、存储 Top、profiler 级别、慢查询计数)在采样之外跑的那个任务;同一时刻至多一个。 + private Task? _background; private BsonDocument? _lastStatus; private BsonDocument? _lastReplStatus; private BsonDocument? _replConfig; @@ -446,6 +458,8 @@ private void UpdatePolling(bool delayFirst = false) else { _poller.Stop(); + _rateBase = null; + _samplingEpoch++; } } @@ -479,6 +493,7 @@ private async Task SampleAsync(CancellationToken token) { MongoConnection connection = Workspace.Connection; DateTime now = DateTime.UtcNow; + int epoch = _samplingEpoch; BsonDocument status; try { @@ -497,9 +512,10 @@ private async Task SampleAsync(CancellationToken token) _failureShown = false; _lastStatus = status; var sample = ServerSample.Parse(status, now); - ServerSample? previous = _last; + // 采样停过(epoch 变了):这一轮只当新的基准,不出率值。 + ServerSample? previous = epoch == _samplingEpoch ? _rateBase : null; RateSample? rate = previous is null ? null : RateSample.Between(previous, sample); - if (previous is not null && sample.Uptime < previous.Uptime) + if (_last is { } before && sample.Uptime < before.Uptime) { // 服务器重启过:旧计数器作废,历史从头攒。 _history.Clear(); @@ -509,28 +525,14 @@ private async Task SampleAsync(CancellationToken token) _history.Add(rate); } _last = sample; + if (epoch == _samplingEpoch) + { + _rateBase = sample; + } await SampleReplicaAsync(now, token).ConfigureAwait(true); await TrackIndexBuildsAsync(previous, sample, now, token).ConfigureAwait(true); - if (now - _oplogAt > TimeSpan.FromSeconds(60)) - { - _oplogAt = now; - await LoadOplogAsync(token).ConfigureAwait(true); - } - if (now - _storageAt > TimeSpan.FromSeconds(120)) - { - _storageAt = now; - await LoadStorageAsync(token).ConfigureAwait(true); - } - if (now - _profileLevelsAt > TimeSpan.FromMinutes(5)) - { - _profileLevelsAt = now; - await LoadProfileLevelsAsync(token).ConfigureAwait(true); - } - if (now - _slowCheckedAt > TimeSpan.FromSeconds(60)) - { - await CheckSlowQueriesAsync(now, token).ConfigureAwait(true); - } + StartBackgroundWork(now, token); if (token.IsCancellationRequested || _disposed) { return; @@ -547,6 +549,61 @@ private async Task SampleAsync(CancellationToken token) UpdateStatus(); } + /// + /// 低频项放到采样之外:存储 Top 一次最多上百次 $collStats、profiler 级别每库一次 —— 串在采样里, + /// 那一轮就晚了好几秒,下一个率值的时间差被拉长、柱子跟着失真。这里另起一个任务跑, + /// 上一个没跑完就不再起(不重叠),各项的时间戳在做完时才记,被取消的下一轮再补。 + /// + private void StartBackgroundWork(DateTime now, CancellationToken token) + { + if (_background is { IsCompleted: false } || token.IsCancellationRequested || _disposed) + { + return; + } + bool oplog = now - _oplogAt > TimeSpan.FromSeconds(60); + bool storage = now - _storageAt > TimeSpan.FromSeconds(120); + bool levels = now - _profileLevelsAt > TimeSpan.FromMinutes(5); + bool slow = now - _slowCheckedAt > TimeSpan.FromSeconds(60); + if (oplog || storage || levels || slow) + { + _background = RunBackgroundAsync(oplog, storage, levels, slow, token); + } + } + + private async Task RunBackgroundAsync(bool oplog, bool storage, bool levels, bool slow, CancellationToken token) + { + try + { + if (oplog) + { + await LoadOplogAsync(token).ConfigureAwait(true); + _oplogAt = DateTime.UtcNow; + } + if (storage && !_disposed) + { + await LoadStorageAsync(token).ConfigureAwait(true); + _storageAt = DateTime.UtcNow; + } + if (levels && !_disposed) + { + await LoadProfileLevelsAsync(token).ConfigureAwait(true); + _profileLevelsAt = DateTime.UtcNow; + } + // 慢查询要用刚读到的 profiler 级别:放在它之后。 + if (slow && !_disposed && !token.IsCancellationRequested) + { + await CheckSlowQueriesAsync(DateTime.UtcNow, token).ConfigureAwait(true); + } + } + catch (OperationCanceledException) + { + // 切走 / 暂停:没做完的项时间戳没记,下次采样再补。 + } + } + + /// 测试用:等后台低频项这一轮跑完。 + internal Task BackgroundWork => _background ?? Task.CompletedTask; + private void Fail(Exception ex) { string reason = MongoConnector.Describe(ex); @@ -783,12 +840,14 @@ private async Task LoadStorageAsync(CancellationToken token) $"{i.Database}.{i.Collection}\n" + Loc.Format("Mon_StorageTip", BsonText.Bytes(i.Data), BsonText.Bytes(i.Index)))) ]; StorageSubtitle = Loc.Format("Mon_StorageSubtitle", oneDb && top.Count > 0 ? top[0].Database : Loc["Mon_StorageAllDbs"]); + // 只有真的读成功了才能说"没有集合";读失败时副标题里是原因,不能再同时说"空"。 + StorageEmpty = true; } catch (Exception ex) when (ex is MongoException or TimeoutException) { StorageSubtitle = MongoConnector.Describe(ex); + StorageEmpty = false; } - StorageEmpty = true; RaisePropertyChanged(nameof(StorageEmpty)); } @@ -915,8 +974,9 @@ private async Task TrackIndexBuildsAsync(ServerSample? previous, ServerSample sa _ = _indexBuilds.Remove(opid); } } - catch (MongoCommandException) + catch (MongoCommandException ex) when (ex.Code == 13) { + // 只有"没权限"(Unauthorized)才永久放弃 $currentOp;其余命令错误(超时、主从切换)下一轮再试。 _currentOpDenied = true; } catch (Exception ex) when (ex is MongoException or TimeoutException) @@ -1108,12 +1168,14 @@ private void UpdateCharts() labels[^1] += " " + Loc["Mon_Now"]; } OpsLabels = labels; + // 没采到样的桶(标签页隐藏期间、刚启动那段)给 NaN:图上画成空位,而不是一根读作"没流量"的 0。 + static double Gap(RateBucket b, double value) => b.Samples > 0 ? value : double.NaN; OpsSeries = [ - new("query", "MongoChart1", [.. buckets.Select(static b => b.Query)]), - new("insert", "MongoChart2", [.. buckets.Select(static b => b.Insert)]), - new("update", "MongoChart3", [.. buckets.Select(static b => b.Update)]), - new("delete", "MongoChart4", [.. buckets.Select(static b => b.Delete)]) + new("query", "MongoChart1", [.. buckets.Select(static b => Gap(b, b.Query))]), + new("insert", "MongoChart2", [.. buckets.Select(static b => Gap(b, b.Insert))]), + new("update", "MongoChart3", [.. buckets.Select(static b => Gap(b, b.Update))]), + new("delete", "MongoChart4", [.. buckets.Select(static b => Gap(b, b.Delete))]) ]; string bar = BarText(set.BarSeconds); OpsSubtitle = set.Covered >= window @@ -1128,7 +1190,7 @@ private void UpdateCharts() new("delete", "MongoChart4", MonitorFormat.Rate(latest?.Delete ?? 0)) ]; ConnLabels = labels; - ConnSeries = [new(Loc["Mon_ConnSeries"], "MongoChart1", [.. buckets.Select(static b => b.Connections)])]; + ConnSeries = [new(Loc["Mon_ConnSeries"], "MongoChart1", [.. buckets.Select(static b => Gap(b, b.Connections))])]; OpsMax = MonitorFormat.NiceThirds(buckets.Select(static b => b.Query + b.Insert + b.Update + b.Delete).DefaultIfEmpty(0).Max()); ConnMax = MonitorFormat.NiceThirds(buckets.Select(static b => b.Connections).DefaultIfEmpty(0).Max()); long current = _last?.Connections ?? 0; diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Objects/ObjectsTabViewModel.Details.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Objects/ObjectsTabViewModel.Details.cs index f4d4bae..b2c18c2 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Objects/ObjectsTabViewModel.Details.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Objects/ObjectsTabViewModel.Details.cs @@ -734,8 +734,39 @@ private async Task DropSelectedAsync() IMongoDatabase database = Workspace.Connection.Database(Database); if (item.Bucket is { } bucket) { - await database.DropCollectionAsync(bucket.FilesCollection).ConfigureAwait(true); - await database.DropCollectionAsync(bucket.ChunksCollection).ConfigureAwait(true); + // 一个桶是两个集合、两次独立的 drop:两次都试,哪一半没删掉要说清楚 —— + // 只剩 .files 或只剩 .chunks 的半个桶,不说的话用户以为已经删干净了。 + var failures = new List<(string Collection, Exception Error)>(); + foreach (string collection in new[] { bucket.FilesCollection, bucket.ChunksCollection }) + { + try + { + await database.DropCollectionAsync(collection).ConfigureAwait(true); + } + catch (Exception ex) when (ex is MongoException or TimeoutException) + { + failures.Add((collection, ex)); + } + } + if (failures.Count > 0) + { + string reason = MongoConnector.Describe(failures[0].Error); + Workspace.Toast(new() + { + Title = failures.Count == 2 + ? Loc.Format("Common_Failed", reason) + : Loc.Format("Obj_DropBucketPartial", item.Namespace, $"{Database}.{failures[0].Collection}", reason), + Kind = ToastKind.Error, + Duration = TimeSpan.FromSeconds(10) + }); + if (failures.Count < 2) + { + CloseTabsOf(item); + await Workspace.RefreshTreeAsync(Database).ConfigureAwait(true); + await ReloadAsync().ConfigureAwait(true); + } + return; + } } else { @@ -777,7 +808,8 @@ private async Task EmptySelectedAsync() Message = Loc.Format("Tree_EmptyBody", item.Namespace, BsonText.Grouped(count ?? 0)), ConfirmLabel = Loc["Tree_EmptyConfirm"], IconKey = "Mongo.eraser", - TypeToConfirm = Workspace.Guard.ConfirmWrites ? item.Name : null + // 与删除同口径:写前确认开着,或集合里有数据,都要手打名称 —— 清空和删除一样回不去。 + TypeToConfirm = Workspace.Guard.ConfirmWrites || (count ?? 0) > 0 ? item.Name : null }).ConfigureAwait(true)) { return; diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Pipeline/PipelineTabViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Pipeline/PipelineTabViewModel.cs index 114d4f8..68914dc 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Pipeline/PipelineTabViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Pipeline/PipelineTabViewModel.cs @@ -680,12 +680,26 @@ private void SwitchMode(PipelineMode mode) private void ScheduleTextSync() { - _textDebounce?.Cancel(); + Retire(_textDebounce); var cts = new CancellationTokenSource(); _textDebounce = cts; _ = SyncTextLaterAsync(cts.Token); } + /// + /// 换下一个防抖令牌:先取消(等着的 Task.Delay 随之结束)再释放 —— 每敲一个字换一个, + /// 不释放的话每个都挂着一份等待句柄,等终结器来收。 + /// + private static void Retire(CancellationTokenSource? cts) + { + if (cts is null) + { + return; + } + cts.Cancel(); + cts.Dispose(); + } + private async Task SyncTextLaterAsync(CancellationToken cancellationToken) { try @@ -761,7 +775,7 @@ private void SyncStages(IReadOnlyList specs) private void SchedulePreview(bool immediate = false) { - _previewDebounce?.Cancel(); + Retire(_previewDebounce); var cts = new CancellationTokenSource(); _previewDebounce = cts; _ = PreviewLaterAsync(immediate ? TimeSpan.Zero : TimeSpan.FromMilliseconds(400), cts.Token); @@ -829,7 +843,10 @@ internal async Task RefreshPreviewAsync() if (ReferenceEquals(_previewRun, cts)) { IsPreviewing = false; + _previewRun = null; } + // 驱动用完了这个令牌才释放(被下一次顶掉的那份也在这里释放)。 + cts.Dispose(); } } @@ -967,6 +984,7 @@ private async Task ExecuteAsync(List pipeline, (string Database, s { _runCts = null; } + cts.Dispose(); IsRunning = false; RaisePropertyChanged(nameof(ResultSummary)); } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerDetail.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerDetail.cs index 39f8944..c60c8b1 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerDetail.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerDetail.cs @@ -75,8 +75,21 @@ public ProfilerDetail(ProfilerShapeRow group, ProfileEntry sample, Loc loc) StatementHeight = (lines * 14) + 12; } - /// 所属形状。 - public ProfilerShapeRow Group { get; } + /// 所属形状(定时重读后换成新一轮统计的那一个,见 )。 + public ProfilerShapeRow Group { get; private set; } + + /// + /// 同一形状、同一条样本的新一轮统计:只改标题与次数 / 占比,不重建详情 + /// (重建会闪、丢滚动与选择,还要再查一次已有索引)。 + /// + public void UpdateGroup(ProfilerShapeRow group) + { + Group = group; + Title = $"{group.Title} · {ProfilerFormat.PlanText(group.Plan, Sample.PlanSummary)}"; + Subtitle = Loc.Format("Prof_DetailCount", BsonText.Grouped(group.Count), + (group.Share * 100).ToString("0", CultureInfo.InvariantCulture) + "%"); + RaisePropertiesChanged(nameof(Group), nameof(Title), nameof(Subtitle)); + } /// 文案(详情模板里的标签 {Binding Loc[...]})。 public Loc Loc { get; } @@ -88,10 +101,10 @@ public ProfilerDetail(ProfilerShapeRow group, ProfileEntry sample, Loc loc) public string Collection => Group.Shape.Collection; /// 标题(orders.find · COLLSCAN)。 - public string Title { get; } + public string Title { get; private set; } /// 副标题(1,204 次 · 占慢查询总耗时 71%)。 - public string Subtitle { get; } + public string Subtitle { get; private set; } /// 「最近一次样本 · 21:08:44」。 public string SampleHeader { get; } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerModels.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerModels.cs index e496010..22fcc48 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerModels.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerModels.cs @@ -434,25 +434,57 @@ public string Summary public bool MillisWarn => Entry.Plan is SlowPlanKind.CollectionScan or SlowPlanKind.InMemorySort; } -/// 当前操作表的一行。 -/// opid 原值(killOp 要原样传回去:单机是整数,mongos 是 shard:opid 字符串)。 -/// opid 文字。 -/// 类型(query / getmore / update / command)。 -/// 命名空间。 -/// 命令摘要。 -/// 客户端。 -/// 已运行秒数。 -/// 进度条比例(相对当前最长的那条)。 -internal sealed record ProfilerOpRow( - BsonValue OpId, - string OpIdText, - string Type, - string Namespace, - string Summary, - string Client, - double Seconds, - double Ratio) +/// +/// 当前操作表的一行。按 opid 原地更新(每 2 秒一次):整表 Clear + Add 会把滚动位置、悬停态打掉, +/// 用户正要点「终止」时鼠标下面那一行还可能换成了别的操作。 +/// +internal sealed class ProfilerOpRow : ObservableObject { + /// 构造。 + /// opid 原值(killOp 要原样传回去:单机是整数,mongos 是 shard:opid 字符串)。 + /// opid 文字。 + /// 类型(query / getmore / update / command)。 + /// 命名空间。 + /// 命令摘要。 + /// 客户端。 + /// 已运行秒数。 + /// 进度条比例(相对当前最长的那条)。 + public ProfilerOpRow(BsonValue opId, string opIdText, string type, string ns, string summary, string client, double seconds, double ratio) + { + OpId = opId; + OpIdText = opIdText; + Type = type; + Namespace = ns; + Summary = summary; + Client = client; + Seconds = seconds; + Ratio = ratio; + } + + /// opid 原值。 + public BsonValue OpId { get; } + + /// opid 文字(行的身份)。 + public string OpIdText { get; } + + /// 类型。 + public string Type { get; private set; } + + /// 命名空间。 + public string Namespace { get; private set; } + + /// 命令摘要。 + public string Summary { get; private set; } + + /// 客户端。 + public string Client { get; private set; } + + /// 已运行秒数。 + public double Seconds { get; private set; } + + /// 进度条比例。 + public double Ratio { get; private set; } + /// 运行超过 10 秒(整行淡红 + 红色进度条与按钮)。 public bool IsLong => Seconds > 10; @@ -461,4 +493,20 @@ internal sealed record ProfilerOpRow( /// 进度条颜色令牌。 public string BarToken => IsLong ? "VelaError" : "MongoChart1"; + + /// 同一个 opid 的新一轮数据:就地改,只通知变了的。 + public void Update(ProfilerOpRow fresh) + { + if (Type != fresh.Type || Namespace != fresh.Namespace || Summary != fresh.Summary || Client != fresh.Client) + { + Type = fresh.Type; + Namespace = fresh.Namespace; + Summary = fresh.Summary; + Client = fresh.Client; + RaisePropertiesChanged(nameof(Type), nameof(Namespace), nameof(Summary), nameof(Client)); + } + Seconds = fresh.Seconds; + Ratio = fresh.Ratio; + RaisePropertiesChanged(nameof(Seconds), nameof(Ratio), nameof(IsLong), nameof(ElapsedText), nameof(BarToken)); + } } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabView.axaml b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabView.axaml index 437fd1e..23632cd 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabView.axaml +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabView.axaml @@ -109,7 +109,7 @@ M10 2 h4 M12 14 l3 -3 M4 14 a8 8 0 1 0 16 0 a8 8 0 1 0 -16 0 z - + @@ -161,8 +161,16 @@ + + + + + + + + - + @@ -223,7 +231,7 @@ - + diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabViewModel.cs index 2e2e0b8..11a1d08 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Profiler/ProfilerTabViewModel.cs @@ -30,6 +30,9 @@ internal sealed class ProfilerTabViewModel : WorkspaceTab private bool _loaded; private bool _disposed; private bool _failureShown; + private string _opsError = ""; + private string _slowError = ""; + private string _statusError = ""; private int _slowMs = 100; private double _sampleRate = 1; private bool _ownOpsOnly; @@ -182,7 +185,8 @@ public bool OnlyLong { if (SetProperty(ref field, value)) { - _ = RefreshOpsAsync(CancellationToken.None); + // 与定时器走同一道闸:不然两次 $currentOp 并发,晚到的旧筛选结果会盖掉新的。 + _ = RefreshOpsGatedAsync(); } } } @@ -285,6 +289,22 @@ private set /// 有没有详情。 public bool HasDetail => Detail is not null; + /// 最近一次刷新失败的原因(顶部红条,与监控页一样);成功一次就清掉。 + public string ErrorText + { + get; + private set + { + if (SetProperty(ref field, value)) + { + RaisePropertyChanged(nameof(HasError)); + } + } + } = ""; + + /// 有错误条。 + public bool HasError => ErrorText.Length > 0; + /// 慢查询列表为空时的说明(profiler 没开 / 近 24 小时没有 / 没权限)。 public string SlowEmptyText { @@ -331,9 +351,18 @@ public override async Task LoadAsync() /// public override async Task RefreshAsync() { - await LoadProfileStatusAsync(CancellationToken.None).ConfigureAwait(true); - await RefreshOpsAsync(CancellationToken.None).ConfigureAwait(true); - await LoadSlowAsync(CancellationToken.None).ConfigureAwait(true); + // 与定时器同一道闸:F5 / 清空之后的刷新不和定时那一轮并发。 + await _tickGate.WaitAsync(CancellationToken.None).ConfigureAwait(true); + try + { + await LoadProfileStatusAsync(CancellationToken.None).ConfigureAwait(true); + await RefreshOpsAsync(CancellationToken.None).ConfigureAwait(true); + await LoadSlowAsync(CancellationToken.None).ConfigureAwait(true); + } + finally + { + _ = _tickGate.Release(); + } } /// @@ -385,14 +414,53 @@ private async Task TickAsync(CancellationToken token) } } - private void Fail(Exception ex) + /// + /// 一处刷新失败:原因进顶部红条(一直挂着,直到那一处成功一次);提示只在"从好到坏"时弹一次, + /// 免得每 2 秒弹一条 —— 但恢复之后再坏要重新提醒。 + /// + private void Fail(ref string slot, Exception ex) { + slot = Loc.Format("Common_Failed", MongoConnector.Describe(ex)); + UpdateError(); if (_failureShown) { return; } _failureShown = true; - Workspace.Toast(new() { Title = Loc.Format("Common_Failed", MongoConnector.Describe(ex)), Kind = ToastKind.Error }); + Workspace.Toast(new() { Title = slot, Kind = ToastKind.Error }); + } + + /// 一处刷新成功:清掉它那条原因;全好了才允许下一次失败再弹提示。 + private void Succeed(ref string slot) + { + slot = ""; + UpdateError(); + } + + private void UpdateError() + { + ErrorText = _opsError.Length > 0 ? _opsError : _slowError.Length > 0 ? _slowError : _statusError; + if (ErrorText.Length == 0) + { + _failureShown = false; + } + } + + /// 不在定时器里的刷新(勾选「仅 > 1 s」、终止之后):等定时器那一轮做完再来,不并发。 + private async Task RefreshOpsGatedAsync() + { + await _tickGate.WaitAsync(CancellationToken.None).ConfigureAwait(true); + try + { + if (!_disposed) + { + await RefreshOpsAsync(CancellationToken.None).ConfigureAwait(true); + } + } + finally + { + _ = _tickGate.Release(); + } } /// @@ -414,10 +482,11 @@ private async Task LoadProfileStatusAsync(CancellationToken token) BsonDocument r = await Workspace.Connection.RunCommandAsync(Database, Tagged(new BsonDocument("profile", -1)), token) .ConfigureAwait(true); ApplyStatus(r); + Succeed(ref _statusError); } catch (Exception ex) when (ex is MongoException or TimeoutException) { - Fail(ex); + Fail(ref _statusError, ex); } UpdateStatus(); } @@ -583,27 +652,68 @@ private async Task RefreshOpsAsync(CancellationToken token) } catch (Exception ex) when (ex is MongoException or TimeoutException) { - Fail(ex); + if (!_disposed) + { + // 列表已经不代表服务器的现状:清掉,免得有人对着过期的 opid 点「终止」。 + Ops.Clear(); + ActiveCount = 0; + Fail(ref _opsError, ex); + } return; } if (token.IsCancellationRequested || _disposed) { return; } + Succeed(ref _opsError); double longest = ops.Select(Seconds).DefaultIfEmpty(0).Max(); - var rows = ops + List rows = [.. ops .OrderByDescending(Seconds) - .Select(op => ToRow(op, Math.Max(longest, 1))) - .ToList(); - Ops.Clear(); - foreach (ProfilerOpRow row in rows) - { - Ops.Add(row); - } + .Select(op => ToRow(op, Math.Max(longest, 1)))]; + SyncOps(Ops, rows); ActiveCount = rows.Count; RaisePropertyChanged(nameof(OpsHeader)); } + /// + /// 按 opid 原地同步:还在的行就地更新(同一个对象,滚动位置与悬停不动),没了的删掉,新来的插到该在的位置。 + /// 顺序照新一轮(按已运行时长倒序)排,只在顺序真的变了时挪动。 + /// + internal static void SyncOps(ObservableCollection target, IReadOnlyList fresh) + { + var wanted = new HashSet(fresh.Select(static r => r.OpIdText), StringComparer.Ordinal); + for (int i = target.Count - 1; i >= 0; i--) + { + if (!wanted.Contains(target[i].OpIdText)) + { + target.RemoveAt(i); + } + } + for (int i = 0; i < fresh.Count; i++) + { + ProfilerOpRow row = fresh[i]; + int at = -1; + for (int j = i; j < target.Count; j++) + { + if (target[j].OpIdText == row.OpIdText) + { + at = j; + break; + } + } + if (at < 0) + { + target.Insert(i, row); + continue; + } + target[at].Update(row); + if (at != i) + { + target.Move(at, i); + } + } + } + private static double Seconds(BsonDocument op) => op.TryGetValue("microsecs_running", out BsonValue us) && us.IsNumeric ? us.ToDouble() / 1_000_000 @@ -728,7 +838,7 @@ private async Task KillAsync(ProfilerOpRow row) { Workspace.Toast(new() { Title = Loc.Format("Common_Failed", MongoConnector.Describe(ex)), Kind = ToastKind.Error }); } - await RefreshOpsAsync(CancellationToken.None).ConfigureAwait(true); + await RefreshOpsGatedAsync().ConfigureAwait(true); } // ── 慢查询 ──────────────────────────────────────────────────────────── @@ -770,13 +880,17 @@ internal async Task LoadSlowAsync(CancellationToken token) } catch (Exception ex) when (ex is MongoException or TimeoutException) { - Fail(ex); + if (!_disposed) + { + Fail(ref _slowError, ex); + } return; } if (token.IsCancellationRequested || _disposed) { return; } + Succeed(ref _slowError); ProfileCount = count; RaisePropertyChanged(nameof(ProfileCount)); List entries = [.. docs.Select(ProfileEntry.Parse).Where(static e => !e.IsDiagnostic)]; @@ -799,7 +913,14 @@ internal async Task LoadSlowAsync(CancellationToken token) RaisePropertyChanged(nameof(SelectedEntry)); if (again is not null && EntryMode) { - ShowDetail(again.Group, again.Entry); + if (Detail is { } current && SameSample(current.Sample, again.Entry)) + { + current.UpdateGroup(again.Group); + } + else + { + ShowDetail(again.Group, again.Entry); + } } } @@ -830,14 +951,26 @@ private void ApplyShapes(List groups) Shapes.Add(g); } ProfilerShapeRow? select = (keep is null ? null : Shapes.FirstOrDefault(s => s.Shape.Key == keep)) ?? Shapes.FirstOrDefault(); - _selectedShape = null; - SelectedShape = select; - if (select is null) + _selectedShape = select; + RaisePropertyChanged(nameof(SelectedShape)); + if (select is null || !ShapeMode) + { + // 逐条模式下详情跟着逐条那边的选中项走(LoadSlowAsync 里处理),这里不碰。 + return; + } + // 每 30 秒重读一次:选中的还是同一个形状、最近一次样本也没变,就只刷新统计 —— + // 整个详情重建会闪一下、丢掉滚动位置与文字选择,还要再查一次 listIndexes。 + if (Detail is { } current && current.Group.Shape.Key == select.Shape.Key && SameSample(current.Sample, select.Latest)) { - RaisePropertyChanged(nameof(SelectedShape)); + current.UpdateGroup(select); + return; } + ShowDetail(select, select.Latest); } + private static bool SameSample(ProfileEntry a, ProfileEntry b) => + a.Time == b.Time && string.Equals(a.Shape.Key, b.Shape.Key, StringComparison.Ordinal); + private void ShowDetail(ProfilerShapeRow group, ProfileEntry sample) { var detail = new ProfilerDetail(group, sample, Loc); @@ -855,7 +988,17 @@ private async Task CheckExistingIndexAsync(ProfilerDetail detail) { return; } - IReadOnlyList indexes = await Workspace.Connection.ListIndexesAsync(Database, detail.Collection).ConfigureAwait(true); + IReadOnlyList indexes; + try + { + indexes = await Workspace.Connection.ListIndexesAsync(Database, detail.Collection).ConfigureAwait(true); + } + catch (Exception ex) when (ex is MongoException or TimeoutException) + { + // 只是"已有索引"的提示查不到:建议照常给,不打扰(发后不管的任务,异常不能漏成未观察的)。 + Workspace.Log.Info($"listIndexes for {Database}.{detail.Collection} failed: {ex.Message}"); + return; + } BsonDocument? hit = indexes.FirstOrDefault(i => i.GetValue("key", BsonNull.Value) is BsonDocument key && advice.CoveredBy(key)); if (hit is not null && ReferenceEquals(detail, Detail)) { @@ -872,7 +1015,16 @@ private async Task CreateIndexAsync() return; } string ns = $"{Database}.{detail.Collection}"; - long? docs = await Workspace.Connection.EstimatedCountAsync(Database, detail.Collection).ConfigureAwait(true); + long? docs = null; + try + { + docs = await Workspace.Connection.EstimatedCountAsync(Database, detail.Collection).ConfigureAwait(true); + } + catch (Exception ex) when (ex is MongoException or TimeoutException) + { + // 文档数只是确认框里的参考信息:取不到就写「—」,照常让人确认。 + Workspace.Log.Info($"Estimated count for {ns} failed: {ex.Message}"); + } if (!await Workspace.ConfirmAsync(new() { Title = Loc["Prof_CreateIndexTitle"], diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Query/CodeExportDialogViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Query/CodeExportDialogViewModel.cs index 265dcae..fa50dcf 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Query/CodeExportDialogViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Query/CodeExportDialogViewModel.cs @@ -12,15 +12,24 @@ internal sealed class CodeExportDialogViewModel : DialogViewModel, IViewFactory private readonly ShellCommand _command; private readonly string _database; private readonly string _connectionString; + private readonly string? _note; private string _target; /// 构造。 - public CodeExportDialogViewModel(IMongoWorkspace workspace, ShellCommand command, string database, string connectionString, CodeTarget target) + /// 外壳服务。 + /// 语句。 + /// 生效的库。 + /// 示例代码里的连接串(不带凭据)。 + /// 初始语言。 + /// 写在代码最前面的一行注释(走 SSH 跳板时的提醒);没有为 。 + public CodeExportDialogViewModel(IMongoWorkspace workspace, ShellCommand command, string database, string connectionString, CodeTarget target, + string? note = null) : base(workspace) { _command = command; _database = database; _connectionString = connectionString; + _note = note; _target = target.ToString(); Title = workspace.Loc["Query_ExportCodeTitle"]; Subtitle = command.Collection is { } c ? $"{command.Database ?? database}.{c} · {command.Operation}" : command.Operation; @@ -62,7 +71,11 @@ public string Code private CodeTarget Parsed => Enum.TryParse(_target, out CodeTarget t) ? t : CodeTarget.CSharp; - private void Generate() => Code = CodeExport.Generate(_command, _database, Parsed, _connectionString); + private void Generate() => Code = WithNote(CodeExport.Generate(_command, _database, Parsed, _connectionString), _note, Parsed); + + /// 在生成的代码前面加一行注释(Python 用 #,其余 //)。 + internal static string WithNote(string code, string? note, CodeTarget target) => + note is null ? code : (target == CodeTarget.Python ? "# " : "// ") + note + "\n" + code; private async Task CopyAsync() { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Editor.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Editor.cs index f65f795..61c9132 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Editor.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Editor.cs @@ -432,13 +432,19 @@ private List ValueSnippets(bool operators) return items; } - private IEnumerable StageSnippets(string? chipsTitle, IReadOnlyList chips) => - [ - WithChips(Snippet(Loc["Query_SnipSortDesc"], "$sort: { |: -1 }", Loc["Query_SnipSortDescHint"], "{ $sort: { <字段>: -1 } }"), chipsTitle, chips), - WithChips(Snippet(Loc["Query_SnipMatchEq"], "$match: { |: \"\" }", Loc["Query_SnipMatchEqHint"], "{ $match: { <字段>: <值> } }"), chipsTitle, chips), - WithChips(Snippet(Loc["Query_SnipGroupCount"], "$group: { _id: \"$|\", count: { $sum: 1 } }", Loc["Query_SnipGroupCountHint"], - "{ $group: { _id: \"$<字段>\", count: { $sum: 1 } } }"), chipsTitle, chips) - ]; + private IEnumerable StageSnippets(string? chipsTitle, IReadOnlyList chips) + { + // 详情栏里的占位符跟界面语言走(<字段> / ),与阶段词汇表的写法一致。 + string field = Loc["Query_SnipField"]; + string value = Loc["Query_SnipValue"]; + return + [ + WithChips(Snippet(Loc["Query_SnipSortDesc"], "$sort: { |: -1 }", Loc["Query_SnipSortDescHint"], $"{{ $sort: {{ {field}: -1 }} }}"), chipsTitle, chips), + WithChips(Snippet(Loc["Query_SnipMatchEq"], "$match: { |: \"\" }", Loc["Query_SnipMatchEqHint"], $"{{ $match: {{ {field}: {value} }} }}"), chipsTitle, chips), + WithChips(Snippet(Loc["Query_SnipGroupCount"], "$group: { _id: \"$|\", count: { $sum: 1 } }", Loc["Query_SnipGroupCountHint"], + $"{{ $group: {{ _id: \"${field}\", count: {{ $sum: 1 }} }} }}"), chipsTitle, chips) + ]; + } private IEnumerable OptionItems(CompletionContext context) { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Panels.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Panels.cs index 73925fa..ad9b644 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Panels.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Panels.cs @@ -291,7 +291,41 @@ internal async Task SaveAsAsync(string name) // ── 导出为代码 / code lens ────────────────────────────────────────────── /// 示例代码里的连接串(只有端点,不带凭据)。 - private string SampleConnectionString => "mongodb://" + Workspace.Connection.Endpoint; + private string SampleConnectionString => SampleConnection().Uri; + + /// + /// 示例代码里的连接串:按保存的连接重新拼一条**真实可用**、不带凭据的串 —— + /// 是给人看的(URI 形态自带 mongodb://、 + /// 跳板形态后面跟着 ↝ 跳板名、SRV 要写成 mongodb+srv://),拼在 mongodb:// 后面就是一条坏串。 + /// 走 SSH 跳板时串里是跳板后面的真实目标,另给一句注释提醒代码那台机器得自己够得着它。 + /// + /// (连接串, 注释文字;没有为 )。 + internal (string Uri, string? Note) SampleConnection() => + SampleConnection((Workspace as MongoSession)?.Entry.Profile, Workspace.Connection.Endpoint, Loc); + + /// 按保存的连接拼示例连接串(不带用户名与口令);没有保存的连接时退回端点。 + /// 保存的连接;没有为 。 + /// 连接的显示端点(退路)。 + /// 文案表。 + /// (连接串, 注释文字)。 + internal static (string Uri, string? Note) SampleConnection(MongoProfile? saved, string endpoint, Loc loc) + { + string fallback = endpoint.StartsWith("mongodb", StringComparison.Ordinal) ? endpoint : "mongodb://" + endpoint; + if (saved is null) + { + return (fallback, null); + } + MongoProfile profile = saved.Clone(); + profile.Username = ""; + if (profile.Parsed.Topology == MongoTopology.Uri) + { + profile.Host = ConnectionDialogViewModel.StripCredentials(profile.Host).Uri; + } + // 草稿里不放跳板:预览按保存的目标地址拼(跳板只在连接时改写成本机转发端口)。 + string uri = ConnectionProbe.Preview(profile.ToRequest(""), loc)?.Text ?? fallback; + string? note = profile.Parsed.JumpSessionId.Length > 0 ? loc["Query_CodeTunnelNote"] : null; + return (uri, note); + } private (ShellCommand? Command, string Database) CommandAt(ShellStatement? statement) { @@ -320,7 +354,8 @@ internal void ExportCode(ShellStatement? statement, CodeTarget target) } return; } - Workspace.ShowDialog(new CodeExportDialogViewModel(Workspace, command, database, SampleConnectionString, target)); + (string uri, string? note) = SampleConnection(); + Workspace.ShowDialog(new CodeExportDialogViewModel(Workspace, command, database, uri, target, note)); } /// code lens「复制为 C#」。 @@ -331,7 +366,9 @@ private async Task CopyAsCSharpAsync(ShellStatement statement) { return; } - await Workspace.CopyAsync(CodeExport.Generate(command, database, CodeTarget.CSharp, SampleConnectionString)).ConfigureAwait(true); + (string uri, string? note) = SampleConnection(); + string code = CodeExportDialogViewModel.WithNote(CodeExport.Generate(command, database, CodeTarget.CSharp, uri), note, CodeTarget.CSharp); + await Workspace.CopyAsync(code).ConfigureAwait(true); Workspace.Toast(new ToastRequest { Title = Loc.Format("Query_CodeCopied", "C#"), Kind = ToastKind.Success }); } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Run.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Run.cs index 03e399f..6a461ac 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Run.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.Run.cs @@ -22,6 +22,8 @@ internal sealed partial class QueryTabViewModel private string _runningText = ""; private string? _lastRunSummary; private string _execState = "idle"; + private int _probeVersion; + private int _explainVersion; /// 正在运行。 public bool IsRunning @@ -156,6 +158,9 @@ internal async Task RunStatementsAsync(IReadOnlyList targets) int position = 0; string state = "ok"; IsRunning = true; + // 新的一跑:上一跑后台补的计划摘要、还没回来的 explain 都作废(回来了也不许盖掉这一跑的)。 + _probeVersion++; + _explainVersion++; try { for (int i = 0; i < targets.Count; i++) @@ -332,11 +337,13 @@ public async Task StopAsync() /// private async Task ProbePlanAsync(ShellCommand command, string database) { + int version = ++_probeVersion; try { var options = new ShellRunOptions { MaxTimeMs = 5000 }; ShellResult result = await Task.Run(() => _executor.ExplainAsync(command, database, "executionStats", options, null)).ConfigureAwait(true); - if (result.Explain is not { } explain) + // 回来晚了:这期间又跑过一次(或手动看过执行计划),状态条上该是那一次的摘要。 + if (version != _probeVersion || result.Explain is not { } explain) { return; } @@ -391,9 +398,17 @@ internal async Task ExplainAsync(ShellCommand command, string database) // (那本来就跑过了,不额外花服务器的时间),而候选计划列表的 works / score 只有它给得出来。 string verbosity = Explain.Verbosity == "executionStats" ? "allPlansExecution" : Explain.Verbosity; var options = new ShellRunOptions { MaxTimeMs = _maxTimeMs }; + int version = ++_explainVersion; + // 手动看执行计划:后台的计划摘要回来了也别盖掉这一份。 + _probeVersion++; try { ShellResult result = await Task.Run(() => _executor.ExplainAsync(command, database, verbosity, options, null)).ConfigureAwait(true); + if (version != _explainVersion) + { + // 连按两次 F6、或中途又跑了一次:页签上已经是更新的那一份。 + return; + } if (result.Explain is { } explain) { ShowExplain(explain); @@ -403,6 +418,10 @@ internal async Task ExplainAsync(ShellCommand command, string database) } catch (Exception ex) when (ex is MongoException or TimeoutException or ShellExecutionException) { + if (version != _explainVersion) + { + return; + } string message = ex is ShellExecutionException ? ex.Message : MongoConnector.Describe(ex); Explain.Fail(message); Messages.Messages.Add(new QueryMessage(DateTime.Now, QueryMessageKind.Error, message, OneLine(command.Statement.Text), null)); diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.cs index f72255a..1ab30a9 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Query/QueryTabViewModel.cs @@ -403,7 +403,13 @@ public override void Dispose() { _diagnosticTimer.Stop(); _helperTimer.Stop(); - _runCts?.Cancel(); + if (_runCts is { } run) + { + run.Cancel(); + // 关标签页时还在跑的语句:服务器那边也停下(不等它)。 + KillOnServer(_runComment); + } + _probeVersion++; base.Dispose(); } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Query/ResultGrid.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Query/ResultGrid.cs index 22e97cf..67cf87c 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Query/ResultGrid.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Query/ResultGrid.cs @@ -44,6 +44,15 @@ public sealed class ResultGrid : Control private double _resizeStartX; private double _resizeStartWidth; + // 排版缓存:滚动、悬停每一帧都重画视口里的几百格,每格新建一个 FormattedText(还要逐格查一次字号资源) + // 是纯浪费 —— 内容不变时复用。键里带列宽(截断省略号随宽度变);数据、层、列宽、主题一变就整个清掉。 + private const int CellCacheLimit = 6000; + private readonly Dictionary<(int Index, int Column, double Width), (FormattedText Text, bool Numeric)> _cellCache = []; + private readonly Dictionary _numberCache = new(StringComparer.Ordinal); + private readonly Dictionary _fontSizes = []; + private Typeface? _mono; + private Typeface? _ui; + static ResultGrid() { AffectsMeasure(SourceProperty); @@ -51,6 +60,23 @@ static ResultGrid() FocusableProperty.OverrideDefaultValue(true); } + /// 构造:换主题 / 换字号资源时丢掉排版缓存(画刷与字号都烤在 FormattedText 里)。 + public ResultGrid() + { + ActualThemeVariantChanged += (_, _) => ResetCaches(); + ResourcesChanged += (_, _) => ResetCaches(); + } + + private void ResetCaches() + { + _mono = null; + _ui = null; + _fontSizes.Clear(); + _numberCache.Clear(); + _cellCache.Clear(); + InvalidateVisual(); + } + /// 数据源。 public object? Source { @@ -105,6 +131,7 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang if (change.Property == SourceProperty) { _hover = -1; + _cellCache.Clear(); _levels.Clear(); if (Set is { } set) { @@ -118,6 +145,8 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); + // 挂上树之前查不到宿主的字体资源;换了位置资源也可能不同。 + ResetCaches(); _scroller = this.FindAncestorOfType(); _scroller?.ScrollChanged += OnScrollChanged; } @@ -159,6 +188,7 @@ internal bool DrillInto(int row, int column) level.ScrollOffset = _scroller?.Offset ?? default; _levels.Add(Level.Of(set.Loc, label, path, rootIndex, value)); _hover = -1; + _cellCache.Clear(); InvalidateMeasure(); InvalidateVisual(); _scroller?.Offset = default; @@ -177,6 +207,7 @@ internal bool DrillTo(int level) } _levels.RemoveRange(level + 1, _levels.Count - level - 1); _hover = -1; + _cellCache.Clear(); InvalidateMeasure(); InvalidateVisual(); Vector restore = _levels[^1].ScrollOffset; @@ -243,6 +274,7 @@ internal void AutoFit(int column) } EnsureWidths(level); level.Widths[column] = Math.Clamp(Math.Ceiling(ContentWidth(level, column, sample: 5000, maxChars: 200)), 40, 1200); + _cellCache.Clear(); InvalidateMeasure(); InvalidateVisual(); } @@ -287,7 +319,15 @@ public override void Render(DrawingContext context) // 行号列:顶层是 1 起的行号;子表里是数组下标(与路径 items.2 同一个数)。 string numberText = level.IsArray ? index.ToString(CultureInfo.InvariantCulture) : level.Path.Length > 0 ? "" : (r + 1).ToString(CultureInfo.InvariantCulture); - FormattedText number = Text(numberText, mono, 10, Brush("VelaTextMuted")); + if (!_numberCache.TryGetValue(numberText, out FormattedText? number)) + { + number = Text(numberText, mono, 10, Brush("VelaTextMuted")); + if (_numberCache.Count >= CellCacheLimit) + { + _numberCache.Clear(); + } + _numberCache[numberText] = number; + } context.DrawText(number, new Point(NumberWidth - CellPadding - number.Width, y + (RowHeight - number.Height) / 2)); double x = NumberWidth; for (int c = 0; c < level.Columns.Count; c++) @@ -299,18 +339,27 @@ public override void Render(DrawingContext context) } if (x + w >= offset.X) { - BsonValue? value = level.ValueAt(index, level.Columns[c]); - BsonKind kind = BsonKinds.Of(value); - string text = BsonText.Cell(value); - (Typeface face, IBrush brush) = kind switch + if (!_cellCache.TryGetValue((index, c, w), out (FormattedText Text, bool Numeric) entry)) { - BsonKind.String => (ui, Brush("VelaTextPrimary")), - BsonKind.Null => (italic, Brush("VelaTextTertiary")), - BsonKind.Missing => (mono, Brush("VelaTextMuted")), - _ => (mono, Brush(BsonKinds.ColorToken(kind))) - }; - FormattedText cell = Text(text, face, 11, brush, maxWidth: w - CellPadding * 2); - double tx = BsonKinds.IsNumeric(kind) ? x + w - CellPadding - cell.Width : x + CellPadding; + BsonValue? value = level.ValueAt(index, level.Columns[c]); + BsonKind kind = BsonKinds.Of(value); + string text = BsonText.Cell(value); + (Typeface face, IBrush brush) = kind switch + { + BsonKind.String => (ui, Brush("VelaTextPrimary")), + BsonKind.Null => (italic, Brush("VelaTextTertiary")), + BsonKind.Missing => (mono, Brush("VelaTextMuted")), + _ => (mono, Brush(BsonKinds.ColorToken(kind))) + }; + entry = (Text(text, face, 11, brush, maxWidth: w - CellPadding * 2), BsonKinds.IsNumeric(kind)); + if (_cellCache.Count >= CellCacheLimit) + { + _cellCache.Clear(); + } + _cellCache[(index, c, w)] = entry; + } + FormattedText cell = entry.Text; + double tx = entry.Numeric ? x + w - CellPadding - cell.Width : x + CellPadding; context.DrawText(cell, new Point(tx, y + (RowHeight - cell.Height) / 2)); } x += w; @@ -412,6 +461,8 @@ protected override void OnPointerMoved(PointerEventArgs e) if (_resizing >= 0 && Current is { } level) { level.Widths[_resizing] = Math.Clamp(_resizeStartWidth + point.X - _resizeStartX, 40, 2000); + // 拖宽时每一帧的宽度都不一样:旧宽度的排版留着只会越攒越多。 + _cellCache.Clear(); InvalidateMeasure(); InvalidateVisual(); return; @@ -702,12 +753,20 @@ private static (string? Column, bool Descending) QueryOrder(QueryResultSet? set) private static IBrush Brush(string token) => ThemeBrushes.Get(token, Brushes.Gray); - private Typeface Mono() => new(this.TryFindResource("VelaUiMonoFont", out object? f) && f is FontFamily family ? family : FontFamily.Default); + // 字体与字号只解析一次(换主题 / 资源变了由 ResetCaches 清掉):原先每格每帧都拼一次键、查一次资源树。 + private Typeface Mono() => _mono ??= new(this.TryFindResource("VelaUiMonoFont", out object? f) && f is FontFamily family ? family : FontFamily.Default); - private Typeface Ui() => new(this.TryFindResource("VelaUiFont", out object? f) && f is FontFamily family ? family : FontFamily.Default); + private Typeface Ui() => _ui ??= new(this.TryFindResource("VelaUiFont", out object? f) && f is FontFamily family ? family : FontFamily.Default); - private double FontSizeOf(double design) => - this.TryFindResource($"VelaFontSize{design.ToString(CultureInfo.InvariantCulture)}", out object? size) && size is double d ? d : design; + private double FontSizeOf(double design) + { + if (!_fontSizes.TryGetValue(design, out double size)) + { + size = this.TryFindResource($"VelaFontSize{design.ToString(CultureInfo.InvariantCulture)}", out object? found) && found is double d ? d : design; + _fontSizes[design] = size; + } + return size; + } private FormattedText Text(string text, Typeface face, double size, IBrush? brush, FontWeight weight = FontWeight.Normal, double maxWidth = double.NaN) { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoSession.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoSession.cs index f8d5cbd..50d61d4 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoSession.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoSession.cs @@ -34,6 +34,7 @@ public MongoSession(MongoWorkspaceViewModel shell, ConnectionEntry entry, MongoL Link = link; Guard = new(Connection.Settings, Connection.Privileges); Guard.Changed += OnGuardChanged; + Guard.Relocked += OnGuardRelocked; LatencyMs = Connection.LatencyMs; _showSystemDatabases = Connection.Settings.ShowSystemDatabases; Connection.Availability += OnAvailability; @@ -490,6 +491,9 @@ internal async Task UnlockAsync() private void OnGuardChanged() => Shell.OnSessionChanged(this); + /// 限时解锁到期(计时在护栏上,与哪个标签页开着无关)。 + private void OnGuardRelocked() => Toast(new() { Title = Loc["State_Relocked"], Kind = ToastKind.Info }); + private void OnAvailability(bool available) => Dispatcher.UIThread.Post(() => { IsAvailable = available; @@ -624,6 +628,8 @@ public Task> PickOpenFilesAsync(string title, IReadOnlyLis public void Dispose() { Guard.Changed -= OnGuardChanged; + Guard.Relocked -= OnGuardRelocked; + Guard.Dispose(); Connection.Availability -= OnAvailability; Connection.LatencyChanged -= OnLatency; _registration.Dispose(); diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoWorkspaceViewModel.Connections.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoWorkspaceViewModel.Connections.cs index 16a1bff..011b105 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoWorkspaceViewModel.Connections.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/MongoWorkspaceViewModel.Connections.cs @@ -179,10 +179,12 @@ internal async Task ConnectAsync(ConnectionEntry entry, bool quiet = false) } CloseTabsWhere(t => ReferenceEquals(t, stateTab)); _ = await AttachAsync(entry, link, quiet).ConfigureAwait(true); - entry.Profile.LastConnectedAt = DateTimeOffset.Now; + DateTimeOffset connectedAt = DateTimeOffset.Now; + entry.Profile.LastConnectedAt = connectedAt; try { - await Profiles.SaveAsync(entry.Profile, null).ConfigureAwait(true); + // 只回写这一个字段:整条存回去会拿内存里的旧副本盖掉对话框刚保存的修改。 + _ = await Profiles.TouchLastConnectedAsync(entry.Profile.Id, connectedAt).ConfigureAwait(true); } catch (Exception ex) { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WorkspaceTab.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WorkspaceTab.cs index 53a0168..ebfb53a 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WorkspaceTab.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WorkspaceTab.cs @@ -196,4 +196,32 @@ public virtual async Task ConfirmCloseAsync() public virtual void Dispose() { } + + /// + /// 在服务器上按 comment 标记 killOp,不等结果(查询被新查询顶掉、标签页关了时用)。 + /// 只取消本地令牌的话,客户端不等了,服务器上的 COLLSCAN 照跑到 maxTimeMS —— 生产库上要拦的正是那种查询。 + /// 失败只记日志:操作多半已经自己结束了。 + /// + /// 发起操作时打的标记; 不做事。 + protected void KillOnServer(string? comment) + { + if (comment is null || Owner is not { } workspace) + { + return; + } + Core.MongoConnection connection = workspace.Connection; + VelaShell.PluginSdk.Logging.IPluginLogger log = workspace.Log; + _ = Task.Run(async () => + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + _ = await connection.KillByCommentAsync(comment, timeout.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is MongoDB.Driver.MongoException or TimeoutException or OperationCanceledException or ObjectDisposedException) + { + log.Info($"killOp for {comment} failed: {ex.Message}"); + } + }); + } } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WriteGuard.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WriteGuard.cs index 271cb18..e1efb72 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WriteGuard.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Shell/WriteGuard.cs @@ -1,3 +1,4 @@ +using Avalonia.Threading; using VelaShell.Plugin.Mongo.Core; namespace VelaShell.Plugin.Mongo.Ui; @@ -13,6 +14,7 @@ namespace VelaShell.Plugin.Mongo.Ui; internal sealed class WriteGuard : ObservableObject { private bool _isReadOnly; + private DispatcherTimer? _relockTimer; /// 按连接设置与探到的权限初始化。 /// 连接设置。 @@ -32,18 +34,77 @@ public WriteGuard(MongoSettings settings, PrivilegeSummary privileges) /// 是不是生产连接。 public bool IsProduction => Environment == MongoEnvironment.Production; - /// 只读模式(工具栏「读写」开关)。 + /// 只读模式(工具栏「读写」开关)。手动拨一下就作废限时解锁的计时(锁回去了,或改成了一直开着)。 public bool IsReadOnly { get => _isReadOnly; set { - if (SetProperty(ref _isReadOnly, value)) + StopRelockTimer(); + SetReadOnly(value); + } + } + + /// 限时解锁到期的时刻;没在限时解锁为 。 + public DateTimeOffset? UnlockedUntil { get; private set; } + + /// 限时解锁到期、自动恢复了只读(外壳据此提示一句)。 + public event Action? Relocked; + + /// + /// 限时解锁:关掉只读, 之后自动恢复。计时挂在护栏上(一条连接一个), + /// 而不是挂在点了「解锁」的那个标签页上 —— 标签页关了,连接照样可写,计时却跟着标签页没了, + /// "15 分钟"就成了"一直开着"。 + /// + /// 解锁多久。 + public void UnlockFor(TimeSpan duration) + { + StopRelockTimer(); + SetReadOnly(false); + var timer = new DispatcherTimer { Interval = duration }; + timer.Tick += (_, _) => Relock(); + _relockTimer = timer; + UnlockedUntil = DateTimeOffset.Now + duration; + timer.Start(); + } + + /// 连接断开:停掉计时(护栏随会话一起作废)。 + public void Dispose() => StopRelockTimer(); + + private void Relock() + { + StopRelockTimer(); + if (!_isReadOnly) + { + SetReadOnly(true); + Relocked?.Invoke(); + } + } + + private void StopRelockTimer() + { + if (_relockTimer is { } timer) + { + if (Dispatcher.UIThread.CheckAccess()) + { + timer.Stop(); + } + else { - RaisePropertyChanged(nameof(IsWritable)); - Changed?.Invoke(); + Dispatcher.UIThread.Post(timer.Stop); } } + _relockTimer = null; + UnlockedUntil = null; + } + + private void SetReadOnly(bool value) + { + if (SetProperty(ref _isReadOnly, value, nameof(IsReadOnly))) + { + RaisePropertyChanged(nameof(IsWritable)); + Changed?.Invoke(); + } } /// 可写(只读关着)。 diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ExportWizardViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ExportWizardViewModel.cs index 4395be3..b6b8167 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ExportWizardViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ExportWizardViewModel.cs @@ -736,14 +736,35 @@ private async Task RefreshCountAsync(CancellationToken cancellationToken) MongoConnection connection = Workspace.Connection; if (IsMulti) { + // 一库几十个集合:每个两次往返(估计行数 + collStats),逐个串着等太慢 —— 与对象列表一样限 6 路并发, + // 到齐后回 UI 线程一次写回。 + List rows = [.. Sources]; + using var gate = new SemaphoreSlim(6); + (long Count, long? Bytes)[] stats = await Task.WhenAll(rows.Select(async row => + { + await gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + long n = await connection.EstimatedCountAsync(Database, row.Name, cancellationToken).ConfigureAwait(false) ?? 0; + long? bytes = row.Info.Kind != CollectionKind.View + ? (await connection.GetStatsAsync(Database, row.Name, cancellationToken).ConfigureAwait(false)).Size + : null; + return (n, bytes); + } + finally + { + _ = gate.Release(); + } + })).ConfigureAwait(true); long total = 0; - foreach (ExportSourceRow row in Sources) + for (int i = 0; i < rows.Count; i++) { - row.Count = await connection.EstimatedCountAsync(Database, row.Name, cancellationToken).ConfigureAwait(true) ?? 0; + ExportSourceRow row = rows[i]; + row.Count = stats[i].Count; row.CountText = BsonText.Grouped(row.Count); - if (row.Info.Kind != CollectionKind.View) + if (stats[i].Bytes is { } size) { - row.Bytes = (await connection.GetStatsAsync(Database, row.Name, cancellationToken).ConfigureAwait(true)).Size; + row.Bytes = size; } if (row.IsChecked) { @@ -764,6 +785,8 @@ private async Task RefreshCountAsync(CancellationToken cancellationToken) { count = await connection.EstimatedCountAsync(Database, Collection!, cancellationToken).ConfigureAwait(true) ?? 0; } + // 条件已经又改了:这个数属于旧条件。 + cancellationToken.ThrowIfCancellationRequested(); SetCount(count, known: true); } @@ -777,18 +800,22 @@ private void SetCount(long count, bool known) UpdateSummaries(); } - private async Task LoadSampleAsync() + private async Task LoadSampleAsync(CancellationToken cancellationToken = default) { IMongoCollection collection = Workspace.Connection.Collection(Database, Collection!); int size = Math.Clamp(Workspace.Connection.Settings.SampleSize, 50, 1000); BsonDocument filter = Filter; - _sample = await SchemaSampler.SampleAsync(collection, filter, size, CancellationToken.None).ConfigureAwait(true); + // 防抖重来时旧的这一趟要作废:慢的 $sample 晚回来,不能拿旧条件的抽样盖掉新条件的。 + IReadOnlyList sample = await SchemaSampler.SampleAsync(collection, filter, size, cancellationToken).ConfigureAwait(true); IFindFluent head = collection.Find(filter).Limit(PreviewDocuments); if (Sort is { } sort) { head = head.Sort(sort); } - _head = await head.ToListAsync().ConfigureAwait(true); + List first = await head.ToListAsync(cancellationToken).ConfigureAwait(true); + cancellationToken.ThrowIfCancellationRequested(); + _sample = sample; + _head = first; RebuildFields(); RefreshPreview(); UpdateEstimate(); @@ -821,7 +848,7 @@ async Task DebouncedAsync(CancellationToken token) { await Task.Delay(400, token).ConfigureAwait(true); await RefreshCountAsync(token).ConfigureAwait(true); - await LoadSampleAsync().ConfigureAwait(true); + await LoadSampleAsync(token).ConfigureAwait(true); } catch (OperationCanceledException) { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardView.axaml b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardView.axaml index 4b191e2..a263cd2 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardView.axaml +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardView.axaml @@ -366,6 +366,15 @@ + + + + diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardViewModel.cs index 8c893b4..3cdfe1d 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/ImportWizardViewModel.cs @@ -46,6 +46,7 @@ internal sealed class ImportWizardViewModel : XferWizardViewModel private CancellationTokenSource? _run; private string _resultTone = "ok"; private string? _errorReport; + private string? _backupFile; private long _inserted; private long _updated; private long _skipped; @@ -89,7 +90,7 @@ public ImportWizardViewModel(IMongoWorkspace workspace, string database, string EditingDate = false; await DryRunAsync().ConfigureAwait(true); }); - StopCommand = new RelayCommand(() => _run?.Cancel(), () => IsRunning); + StopCommand = new AsyncCommand(StopAsync, () => IsRunning); OpenReportCommand = new RelayCommand(() => { if (_errorReport is { } report) @@ -97,6 +98,13 @@ public ImportWizardViewModel(IMongoWorkspace workspace, string database, string Reveal(report); } }); + OpenBackupCommand = new RelayCommand(() => + { + if (_backupFile is { } backup) + { + Reveal(backup); + } + }); SaveProfileCommand = new AsyncCommand(SaveProfileAsync); Steps[0].Summary = Loc["Imp_NoFile"]; _ready = InitializeAsync(); @@ -523,15 +531,24 @@ private set /// 有错误报告。 public bool HasErrorReport => _errorReport is not null; + /// 覆盖前备份的路径。 + public string BackupFile => _backupFile ?? ""; + + /// 有覆盖前备份。 + public bool HasBackupFile => _backupFile is not null; + /// 执行日志。 public ObservableCollection RunLog { get; } = []; /// 停止导入。 - public RelayCommand StopCommand { get; } + public AsyncCommand StopCommand { get; } /// 打开错误报告(在资源管理器中显示)。 public RelayCommand OpenReportCommand { get; } + /// 打开覆盖前备份(在资源管理器中显示)。 + public RelayCommand OpenBackupCommand { get; } + /// 保存为导入配置。 public AsyncCommand SaveProfileCommand { get; } @@ -634,7 +651,10 @@ private async Task OpenFileAsync() { return; } - BuildMappings(); + if (!await BuildMappingsAsync().ConfigureAwait(true)) + { + return; + } _ = CountAsync(current); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) @@ -708,24 +728,30 @@ private void UpdateFileInfo() // ── 映射 ──────────────────────────────────────────────────────────── - private void BuildMappings() + /// 按抽样生成映射;返回 表示读抽样期间文件又换了(结果作废)。 + private async Task BuildMappingsAsync() { if (_source is not { } source) { - return; + return false; } - var previous = Mappings.GroupBy(static m => m.Source, StringComparer.Ordinal).ToDictionary(static g => g.Key, static g => g.First(), StringComparer.Ordinal); - Mappings.Clear(); - var samples = new List(); - IReadOnlyList header; - using (IImportReader reader = source.Open()) + // 读开头 200 条要解码 / 解析(大 JSON 文档、GBK 解码):放到线程池,别卡 UI 线程。 + (IReadOnlyList header, List samples) = await Task.Run(() => { - header = reader.Header; - while (samples.Count < SampleRows && reader.TryRead(out ImportRecord record)) + var rows = new List(); + using IImportReader reader = source.Open(); + while (rows.Count < SampleRows && reader.TryRead(out ImportRecord record)) { - samples.Add(record); + rows.Add(record); } + return (reader.Header, rows); + }).ConfigureAwait(true); + if (!ReferenceEquals(source, _source)) + { + return false; } + var previous = Mappings.GroupBy(static m => m.Source, StringComparer.Ordinal).ToDictionary(static g => g.Key, static g => g.First(), StringComparer.Ordinal); + Mappings.Clear(); if (source.Format == ImportFormat.Csv) { for (int i = 0; i < header.Count; i++) @@ -765,6 +791,7 @@ private void BuildMappings() } RefreshMatchKeys(); UpdateMappingSummary(); + return true; } private void AddMapping(string source, int index, string sample, string target, XferOption kind, Dictionary previous) @@ -1162,8 +1189,10 @@ protected override async Task StartAsync() EnterRunStep(); RunLog.Clear(); _errorReport = null; + _backupFile = null; _inserted = _updated = _skipped = 0; - RaisePropertiesChanged(nameof(InsertedText), nameof(UpdatedText), nameof(SkippedText), nameof(ErrorReport), nameof(HasErrorReport)); + RaisePropertiesChanged(nameof(InsertedText), nameof(UpdatedText), nameof(SkippedText), nameof(ErrorReport), nameof(HasErrorReport), + nameof(BackupFile), nameof(HasBackupFile)); ResultText = ""; Progress = 0; StopCommand.RaiseCanExecuteChanged(); @@ -1171,12 +1200,31 @@ protected override async Task StartAsync() AddLog(Loc.Format("Imp_LogStart", Path.GetFileName(source.Path), TargetNamespace, ModeName(_mode)), XferTone.Normal); _run = new CancellationTokenSource(); CancellationToken token = _run.Token; - var progress = new Progress(OnProgress); + // 进度是投递过来的:结果落定之后才到的那一条(最多晚一批)不许把精确计数盖回去。 + bool settled = false; + var progress = new Progress(p => + { + if (!settled) + { + OnProgress(p); + } + }); try { ImportResult result = await Task.Run(() => ImportRunner.RunAsync(Workspace.Connection, job, Loc, progress, token), token).ConfigureAwait(true); + settled = true; _errorReport = result.ErrorReport; - RaisePropertiesChanged(nameof(ErrorReport), nameof(HasErrorReport)); + _backupFile = result.BackupFile; + _inserted = result.Inserted; + _updated = result.Updated; + _skipped = result.Skipped; + RaisePropertiesChanged(nameof(ErrorReport), nameof(HasErrorReport), nameof(BackupFile), nameof(HasBackupFile), + nameof(InsertedText), nameof(UpdatedText), nameof(SkippedText)); + if (result.Cancelled || result.Failure is not null) + { + await FinishPartialAsync(result).ConfigureAwait(true); + return; + } _resultTone = result.Stopped ? "warn" : "ok"; Progress = 100; PercentText = "100%"; @@ -1194,23 +1242,13 @@ protected override async Task StartAsync() AddLog(Loc.Format("Imp_LogBackup", backup), XferTone.Muted); } await Workspace.RefreshTreeAsync(Database).ConfigureAwait(true); - FinishRun(new ToastRequest - { - Title = Loc.Format("Imp_ToastDone", BsonText.Grouped(result.Inserted + result.Updated)), - Detail = Loc.Format("Imp_ToastDetail", BsonText.Grouped(result.Inserted), BsonText.Grouped(result.Updated), BsonText.Grouped(result.Skipped)), - Kind = result.Skipped > 0 ? ToastKind.Warning : ToastKind.Success, - ActionLabel = result.ErrorReport is not null ? Loc["Imp_OpenReport"] : null, - Action = result.ErrorReport is { } path ? () => - { - Reveal(path); - return Task.CompletedTask; - } - : null, - Duration = TimeSpan.FromSeconds(8) - }); + FinishRun(ResultToast(result, Loc.Format("Imp_ToastDone", BsonText.Grouped(result.Inserted + result.Updated)), + result.Skipped > 0 ? ToastKind.Warning : ToastKind.Success)); } catch (OperationCanceledException) { + // 只剩"还没开跑就取消"这一种:跑起来之后的取消由 ImportRunner 收成部分结果。 + settled = true; _resultTone = "warn"; ResultText = Loc.Format("Imp_Cancelled", InsertedText, UpdatedText); RaisePropertiesChanged(nameof(ResultOk), nameof(ResultFailed)); @@ -1222,6 +1260,7 @@ protected override async Task StartAsync() catch (Exception ex) { // 任何失败都要让执行页落到"失败"(而不是永远停在"进行中"),原因写进日志。 + settled = true; Workspace.Log.Error("Import failed.", ex); string reason = MongoConnector.Describe(ex); _resultTone = "err"; @@ -1239,6 +1278,81 @@ protected override async Task StartAsync() } } + /// 停止导入:与数据传输一样先确认 —— 停下来的导入不能"继续",只能重导。 + private async Task StopAsync() + { + if (_run is null) + { + return; + } + if (!await Workspace.ConfirmAsync(new() + { + Title = Loc["Imp_StopTitle"], + Message = Loc["Imp_StopBody"], + ConfirmLabel = Loc["Imp_Stop"], + IconKey = "Mongo.octagon-x" + }).ConfigureAwait(true)) + { + return; + } + _run?.Cancel(); + } + + /// 取消或中途失败:计数是服务器已确认的那些,错误报告与备份照样给出路径。 + private async Task FinishPartialAsync(ImportResult result) + { + bool cancelled = result.Failure is null; + if (result.Failure is { } ex) + { + Workspace.Log.Error("Import failed.", ex); + } + _resultTone = cancelled ? "warn" : "err"; + ResultText = cancelled + ? Loc.Format("Imp_Cancelled", BsonText.Grouped(result.Inserted), BsonText.Grouped(result.Updated)) + : Loc.Format("Imp_FailedPartial", MongoConnector.Describe(result.Failure!), BsonText.Grouped(result.Inserted), BsonText.Grouped(result.Updated)); + RaisePropertiesChanged(nameof(ResultOk), nameof(ResultFailed)); + Steps[RunStep].Summary = Loc[cancelled ? "Xfer_Cancelled" : "Xfer_Failed"]; + AddLog(ResultText, cancelled ? XferTone.Warn : XferTone.Error); + if (result.ErrorReport is { } report) + { + AddLog(Loc.Format("Imp_LogReport", report), XferTone.Warn); + } + if (result.BackupFile is { } backup) + { + AddLog(Loc.Format("Imp_LogBackup", backup), XferTone.Muted); + } + if (result.Inserted + result.Updated > 0) + { + await Workspace.RefreshTreeAsync(Database).ConfigureAwait(true); + } + FinishRun(ResultToast(result, ResultText, cancelled ? ToastKind.Info : ToastKind.Error)); + } + + /// 结束提示:计数 + 备份路径;有错误报告时动作是打开它,否则是打开备份。 + private ToastRequest ResultToast(ImportResult result, string title, ToastKind kind) + { + string detail = Loc.Format("Imp_ToastDetail", BsonText.Grouped(result.Inserted), BsonText.Grouped(result.Updated), BsonText.Grouped(result.Skipped)); + if (result.BackupFile is { } backup) + { + detail += Environment.NewLine + Loc.Format("Imp_LogBackup", backup); + } + string? reveal = result.ErrorReport ?? result.BackupFile; + return new ToastRequest + { + Title = title, + Detail = detail, + Kind = kind, + ActionLabel = reveal is null ? null : Loc[result.ErrorReport is not null ? "Imp_OpenReport" : "Imp_OpenBackup"], + Action = reveal is { } path ? () => + { + Reveal(path); + return Task.CompletedTask; + } + : null, + Duration = TimeSpan.FromSeconds(8) + }; + } + private void OnProgress(ImportProgress p) { _inserted = p.Inserted; diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferRows.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferRows.cs index 27a64c6..88a3355 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferRows.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferRows.cs @@ -63,6 +63,7 @@ internal sealed class TransferObjectRow : ObservableObject private readonly Action _changed; private XferOption _action; private long _done; + private int _doneDirty; /// 构造。 public TransferObjectRow(string name, XferObjectKind kind, CollectionInfo? info, IReadOnlyList actions, Loc loc, Action changed) @@ -214,11 +215,23 @@ public long Done } } - /// 加一批(线程池线程上调)。 + /// + /// 加一批(线程池线程上调)。只记数、不通知 —— 每批三次 Dispatcher.Post 在小批次高吞吐时会把 UI 队列塞满; + /// 向导自己的 500 ms 节拍调 统一刷新。 + /// public void Add(long count) { _ = Interlocked.Add(ref _done, count); - RaisePropertiesChanged(nameof(Done), nameof(CountText), nameof(Fraction)); + _ = Interlocked.Exchange(ref _doneDirty, 1); + } + + /// 上次刷新以来有新进度就通知一次(UI 线程上的节拍调)。 + public void FlushProgress() + { + if (Interlocked.Exchange(ref _doneDirty, 0) == 1) + { + RaisePropertiesChanged(nameof(Done), nameof(CountText), nameof(Fraction)); + } } /// 进度 0–1。 diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferWizardViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferWizardViewModel.cs index 9d3528b..b47be5e 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferWizardViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/TransferWizardViewModel.cs @@ -32,6 +32,7 @@ internal sealed class TransferWizardViewModel : XferWizardViewModel private DispatcherTimer? _ticker; private Stopwatch? _watch; private bool _objectsLoaded; + private bool _closed; private string _objectsFor = ""; /// 构造。 @@ -426,6 +427,12 @@ private async Task ConnectUriAsync() try { MongoConnection connection = await MongoConnection.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(true); + if (_closed) + { + // 连着的时候向导已经关了:没人会再释放它,这里就放掉。 + await connection.DisposeAsync().ConfigureAwait(true); + return; + } var target = new TransferTarget(MongoConnection.RedactUri(uri), connection, owned: true); _selectedSession = null; RaisePropertyChanged(nameof(SelectedSession)); @@ -474,25 +481,52 @@ private async Task LoadObjectsAsync() var previous = Objects.ToDictionary(static o => $"{o.Kind}:{o.Name}", StringComparer.Ordinal); Objects.Clear(); IEnumerable plain = all.Where(c => c.Kind != CollectionKind.System && !bucketCollections.Contains(c.Name)); - foreach (CollectionInfo info in plain.OrderBy(static c => c.Kind == CollectionKind.View ? 1 : 0)) + MongoConnection source = Workspace.Connection; + // 每个对象一到三次往返:限 6 路并发(与对象列表同一个数),全部到齐再按原顺序挂上去。 + using var gate = new SemaphoreSlim(6); + async Task Gated(Func> work) + { + await gate.WaitAsync().ConfigureAwait(false); + try + { + return await work().ConfigureAwait(false); + } + finally + { + _ = gate.Release(); + } + } + List infos = [.. plain.OrderBy(static c => c.Kind == CollectionKind.View ? 1 : 0)]; + Task[] totals = [.. infos.Select(info => info.Kind == CollectionKind.View + ? Task.FromResult(0L) + : Gated(async () => await source.EstimatedCountAsync(Database, info.Name).ConfigureAwait(false) ?? 0))]; + Task<(long Files, long Chunks, long Bytes)>[] bucketStats = [.. buckets.Select(bucket => Gated(async () => + ( + await source.EstimatedCountAsync(Database, bucket.FilesCollection).ConfigureAwait(false) ?? 0, + await source.EstimatedCountAsync(Database, bucket.ChunksCollection).ConfigureAwait(false) ?? 0, + (await source.GetStatsAsync(Database, bucket.ChunksCollection).ConfigureAwait(false)).Size + )))]; + await Task.WhenAll([.. totals.Cast(), .. bucketStats]).ConfigureAwait(true); + for (int i = 0; i < infos.Count; i++) { + CollectionInfo info = infos[i]; XferObjectKind kind = info.Kind == CollectionKind.View ? XferObjectKind.View : XferObjectKind.Collection; var row = new TransferObjectRow(info.Name, kind, info, _actions, Loc, OnObjectsChanged); Apply(row, existing.Contains(info.Name), previous); if (kind == XferObjectKind.Collection) { - row.Total = await Workspace.Connection.EstimatedCountAsync(Database, info.Name).ConfigureAwait(true) ?? 0; + row.Total = await totals[i].ConfigureAwait(true); } Objects.Add(row); } - foreach (GridFsBucketInfo bucket in buckets) + for (int i = 0; i < buckets.Count; i++) { + GridFsBucketInfo bucket = buckets[i]; var row = new TransferObjectRow(bucket.Name, XferObjectKind.Bucket, null, _actions, Loc, OnObjectsChanged); Apply(row, existing.Contains(bucket.FilesCollection) || existing.Contains(bucket.ChunksCollection), previous); - long files = await Workspace.Connection.EstimatedCountAsync(Database, bucket.FilesCollection).ConfigureAwait(true) ?? 0; - long chunks = await Workspace.Connection.EstimatedCountAsync(Database, bucket.ChunksCollection).ConfigureAwait(true) ?? 0; + (long files, long chunks, long bytes) = await bucketStats[i].ConfigureAwait(true); row.Files = files; - row.Bytes = (await Workspace.Connection.GetStatsAsync(Database, bucket.ChunksCollection).ConfigureAwait(true)).Size; + row.Bytes = bytes; row.Total = files + chunks; Objects.Add(row); } @@ -677,6 +711,16 @@ protected override async Task StartAsync() }; AddLog(Loc.Format("Xfer_LogSource", SourceName, Workspace.Connection.Endpoint, (string)_readPreference.Value), XferTone.Normal); AddLog(Loc.Format("Xfer_LogTarget", target.Name, targetDb), XferTone.Normal); + // 整批只列一次目标库的名字(复制器建了新集合会自己补进来);列不出就传 null,复制器退回逐个查。 + ISet? existingNames; + try + { + existingNames = await CollectionCopier.ExistingNamesAsync(target.Connection, targetDb, token).ConfigureAwait(true); + } + catch (Exception ex) when (ex is MongoException or TimeoutException) + { + existingNames = null; + } int done = 0, failed = 0; bool stopped = false; foreach (TransferObjectRow row in rows) @@ -704,7 +748,7 @@ protected override async Task StartAsync() XferItem item = row.ToItem(); XferOutcome outcome = await Task.Run(() => CollectionCopier.CopyAsync( Workspace.Connection, Database, target.Connection, targetDb, item, options, _gate, - row.Add, (text, tone) => AddLog(text, tone), Loc, token), token).ConfigureAwait(true); + row.Add, (text, tone) => AddLog(text, tone), Loc, token, existingNames), token).ConfigureAwait(true); row.Done = outcome.Copied; row.State = TransferObjectState.Done; done++; @@ -784,6 +828,10 @@ private void Tick(long total) { return; } + foreach (TransferObjectRow row in Objects) + { + row.FlushProgress(); + } long copied = Objects.Where(static o => o.IsChecked && o.ActionValue != XferAction.Skip).Sum(static o => o.Done); TimeSpan now = _watch.Elapsed; _rateWindow.Add((now, copied)); @@ -878,9 +926,13 @@ private string RoleText(MongoConnection connection) _ => "muted" }; + /// + protected override void OnReopened() => _closed = false; + /// internal override void OnClosed() { + _closed = true; // 手填连接串开的目标连接:向导关掉且没有任务在跑时就释放(跑着的话等跑完、对话框再关时释放)。 if (!IsRunning && _target is { Owned: true } owned) { diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/XferWizardViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/XferWizardViewModel.cs index 6806899..b480360 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/XferWizardViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Transfer/XferWizardViewModel.cs @@ -377,9 +377,15 @@ protected void FinishRun(ToastRequest toast) public void Reopen() { IsBackground = false; + OnReopened(); Workspace.ShowDialog(this); } + /// 对话框被叫回来之前(子类撤销 里记下的"已关闭")。 + protected virtual void OnReopened() + { + } + private void MoveToBackground() { if (!IsRunning) @@ -444,16 +450,16 @@ internal static void Reveal(string path) { if (OperatingSystem.IsWindows()) { - _ = Process.Start(new ProcessStartInfo("explorer.exe", File.Exists(path) ? $"/select,\"{path}\"" : $"\"{path}\"") { UseShellExecute = false }); + using Process? started = Process.Start(new ProcessStartInfo("explorer.exe", File.Exists(path) ? $"/select,\"{path}\"" : $"\"{path}\"") { UseShellExecute = false }); } else if (OperatingSystem.IsMacOS()) { - _ = Process.Start(new ProcessStartInfo("open", File.Exists(path) ? $"-R \"{path}\"" : $"\"{path}\"") { UseShellExecute = false }); + using Process? started = Process.Start(new ProcessStartInfo("open", File.Exists(path) ? $"-R \"{path}\"" : $"\"{path}\"") { UseShellExecute = false }); } else { string folder = Directory.Exists(path) ? path : Path.GetDirectoryName(path) ?? path; - _ = Process.Start(new ProcessStartInfo("xdg-open", $"\"{folder}\"") { UseShellExecute = false }); + using Process? started = Process.Start(new ProcessStartInfo("xdg-open", $"\"{folder}\"") { UseShellExecute = false }); } } catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserAdmin.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserAdmin.cs index a3f3ab7..873144c 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserAdmin.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserAdmin.cs @@ -494,17 +494,15 @@ public static BsonArray BuildRestrictions(string clientSource, string serverAddr { foreach (string item in SplitList(text)) { - string host = item; int slash = item.IndexOf('/'); - if (slash >= 0) + string host = slash >= 0 ? item[..slash] : item; + if (!System.Net.IPAddress.TryParse(host, out System.Net.IPAddress? address)) { - host = item[..slash]; - if (!int.TryParse(item[(slash + 1)..], NumberStyles.None, CultureInfo.InvariantCulture, out int bits) || bits > 128) - { - return item; - } + return item; } - if (!System.Net.IPAddress.TryParse(host, out _)) + // 前缀长度上限按地址族:IPv4 32 位,IPv6 128 位(10.0.0.0/33 服务器会拒)。 + int maxBits = address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128; + if (slash >= 0 && (!int.TryParse(item[(slash + 1)..], NumberStyles.None, CultureInfo.InvariantCulture, out int bits) || bits > maxBits)) { return item; } diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserEditorViewModel.cs b/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserEditorViewModel.cs index 968610c..b1e4318 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserEditorViewModel.cs +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Users/UserEditorViewModel.cs @@ -23,6 +23,7 @@ internal sealed class UserEditorViewModel : ObservableObject, IDisposable // 新用户默认建在 admin:那是认证库的惯例,应用连接串里 authSource=admin 也是驱动的默认。 private string _password = ""; + private string _passwordConfirm = ""; private bool _revealPassword; private MechanismOption _mechanism; private string _clientSource = ""; @@ -60,7 +61,9 @@ public UserEditorViewModel(UsersTabViewModel owner, MongoUser? user) CopyCommandsCommand = new(() => Owner.Workspace.CopyAsync(string.Join(Environment.NewLine, Commands.Select(static c => c.Shell)))); GenerateCommand = new(() => { - Password = UserAdmin.GeneratePassword(); + string generated = UserAdmin.GeneratePassword(); + Password = generated; + PasswordConfirm = generated; RevealPassword = true; PasswordGenerated = true; }); @@ -179,11 +182,29 @@ public string Password if (SetProperty(ref _password, value)) { PasswordGenerated = false; + RaisePropertyChanged(nameof(PasswordMismatch)); OnChanged(); } } } + /// 密码再输一遍(与重置密码对话框一样:掩码框里打错一个字符,建出来的账号就没人登得上)。 + public string PasswordConfirm + { + get => _passwordConfirm; + set + { + if (SetProperty(ref _passwordConfirm, value)) + { + RaisePropertyChanged(nameof(PasswordMismatch)); + OnChanged(); + } + } + } + + /// 确认框已经填了、但与密码不一致(标红)。 + public bool PasswordMismatch => _passwordConfirm.Length > 0 && !string.Equals(_password, _passwordConfirm, StringComparison.Ordinal); + /// 明文显示密码。 public bool RevealPassword { @@ -364,7 +385,13 @@ public string ValidationError { return Loc.Format("Users_NameTaken", $"{_newName}@{NewDb}"); } - return _password.Length == 0 ? Loc["Users_NeedPassword"] : ""; + if (_password.Length == 0) + { + return Loc["Users_NeedPassword"]; + } + return string.Equals(_password, _passwordConfirm, StringComparison.Ordinal) + ? "" + : Loc[_passwordConfirm.Length == 0 ? "Users_NeedConfirmPassword" : "Users_PasswordMismatch"]; } } @@ -452,8 +479,10 @@ private void Discard() { _newName = ""; _password = ""; + _passwordConfirm = ""; _revealPassword = false; - RaisePropertiesChanged(nameof(NewName), nameof(Password), nameof(RevealPassword), nameof(PasswordChar), nameof(DisplayName)); + RaisePropertiesChanged(nameof(NewName), nameof(Password), nameof(PasswordConfirm), nameof(PasswordMismatch), nameof(RevealPassword), + nameof(PasswordChar), nameof(DisplayName)); } Roles.Reset(); _clientSource = _originalClientSource; diff --git a/plugins/VelaShell.Plugin.Mongo/Ui/Users/UsersTabView.axaml b/plugins/VelaShell.Plugin.Mongo/Ui/Users/UsersTabView.axaml index e4b29b6..abf966d 100644 --- a/plugins/VelaShell.Plugin.Mongo/Ui/Users/UsersTabView.axaml +++ b/plugins/VelaShell.Plugin.Mongo/Ui/Users/UsersTabView.axaml @@ -385,7 +385,7 @@ - + @@ -412,6 +412,12 @@ + + + + + !_showRoles && UserEditor is { IsNew: false }); + ResetPasswordCommand = new(ResetPasswordAsync, () => !_showRoles && UserEditor is { IsNew: false }); DeleteCommand = new(DeleteAsync, () => _showRoles ? _selectedRole is not null : _selectedUser is not null); } @@ -250,7 +250,7 @@ public RoleEditorViewModel? RoleEditor public RelayCommand NewRoleCommand { get; } /// 重置密码。 - public RelayCommand ResetPasswordCommand { get; } + public AsyncCommand ResetPasswordCommand { get; } /// 删除(用户模式删用户,角色模式删角色)。 public AsyncCommand DeleteCommand { get; } @@ -1005,12 +1005,17 @@ private async Task DeleteRoleAsync() await ReloadAsync(keepDrafts: true, selectRoleId: "").ConfigureAwait(true); } - private void ResetPassword() + private async Task ResetPasswordAsync() { if (UserEditor?.User is not { } user) { return; } + // 改的是这条连接自己登录用的账号:先把后果讲清楚(在弹重置框之前问,免得两个对话框叠着)。 + if (IsSelf(user) && !await ConfirmSelfPasswordAsync(user, null).ConfigureAwait(true)) + { + return; + } Workspace.ShowDialog(new ResetPasswordDialogViewModel(Workspace, user, async (password, generated) => { if (!await ChangePasswordAsync(user, password).ConfigureAwait(true)) @@ -1035,7 +1040,14 @@ internal async Task RotatePasswordAsync(UserEditorViewModel editor) { return; } - if (!await Workspace.ConfirmAsync(new() + if (IsSelf(user)) + { + if (!await ConfirmSelfPasswordAsync(user, Workspace.Guard.ConfirmWrites ? user.Name : null).ConfigureAwait(true)) + { + return; + } + } + else if (!await Workspace.ConfirmAsync(new() { Title = Loc.Format("Users_RotateTitle", user.Name), Message = Loc.Format("Users_RotateBody", $"{user.Name}@{user.Db}"), @@ -1083,6 +1095,10 @@ private async Task ChangePasswordAsync(MongoUser user, string password, bo return false; } Workspace.Toast(new() { Title = Loc.Format("Users_PasswordChanged", $"{user.Name}@{user.Db}"), Kind = ToastKind.Success }); + if (IsSelf(user)) + { + await UpdateSavedPasswordAsync(user, password).ConfigureAwait(true); + } if (_userDrafts.TryGetValue(user.Id, out UserEditorViewModel? draft) && !draft.IsModified) { await RefreshUserAsync(draft).ConfigureAwait(true); @@ -1090,6 +1106,50 @@ private async Task ChangePasswordAsync(MongoUser user, string password, bo return true; } + /// 改当前连接自己登录用的账号的密码之前:连接池新开的连接与重连会被拒,要明说。 + private Task ConfirmSelfPasswordAsync(MongoUser user, string? typeToConfirm) => Workspace.ConfirmAsync(new() + { + Title = Loc["Users_SelfPasswordTitle"], + Message = Loc.Format("Users_SelfPasswordBody", $"{user.Name}@{user.Db}"), + ConfirmLabel = Loc["Users_SelfPasswordContinue"], + IconKey = "Mongo.triangle-alert", + Danger = true, + TypeToConfirm = typeToConfirm + }); + + /// + /// 当前连接自己的账号改了密码:宿主密钥库里这条连接保存的口令跟着换(与连接对话框保存时同一条路径 + /// ),否则下次连接 / 重连就拿旧口令去认证。 + /// 只在这条连接本来就存了口令、且用户名对得上时才写 —— 没存口令的连接不替用户存。 + /// + private async Task UpdateSavedPasswordAsync(MongoUser user, string password) + { + if (Workspace is not MongoSession session) + { + return; + } + MongoProfile profile = session.Entry.Profile; + if (!string.Equals(profile.Username, user.Name, StringComparison.Ordinal)) + { + return; + } + try + { + string stored = await session.Shell.Profiles.GetPasswordAsync(profile.Id).ConfigureAwait(true); + if (stored.Length == 0) + { + return; + } + await session.Shell.Profiles.SaveAsync(profile, password).ConfigureAwait(true); + Workspace.Toast(new() { Title = Loc["Users_SavedPasswordUpdated"], Kind = ToastKind.Info, Duration = TimeSpan.FromSeconds(8) }); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Workspace.Log.Error("Updating the saved password failed.", ex); + Workspace.Toast(new() { Title = Loc.Format("Users_SavedPasswordFailed", ex.Message), Kind = ToastKind.Warning, Duration = TimeSpan.FromSeconds(10) }); + } + } + /// public override void Dispose() { diff --git a/tests/VelaShell.Plugin.DockerPanel.Tests/DockerCoreFixTests.cs b/tests/VelaShell.Plugin.DockerPanel.Tests/DockerCoreFixTests.cs new file mode 100644 index 0000000..e617485 --- /dev/null +++ b/tests/VelaShell.Plugin.DockerPanel.Tests/DockerCoreFixTests.cs @@ -0,0 +1,749 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using System.Formats.Tar; +using System.Text; +using System.Text.Json; +using VelaShell.Plugin.DockerPanel.Docker; + +namespace VelaShell.Plugin.DockerPanel.Tests; + +/// +/// Docker 层几处真机才会撞上的问题:凭据头的填充、仓库键的写法、写回文件丢属主与权限、 +/// 长文件名、符号链接、BusyBox 的 ls、连接池被长连接吃光、帧解码的内存上限、大文件差异。 +/// +[TestClass] +public class DockerCoreFixTests +{ + // ── X-Registry-Auth ───────────────────────────────────────── + + [TestMethod] + public void RegistryAuthHeader_KeepsBase64PaddingForEveryCredentialLength() + { + // daemon 用 Go 的 base64.URLEncoding(带填充)严格解码。去掉 = 的话, + // JSON 长度不是 3 的倍数的那三分之二凭据会解出 "unexpected EOF"。 + for (int length = 1; length <= 12; length++) + { + var entry = new DockerAuthEntry { Username = new string('u', length), Password = "p+/?" + new string('x', length) }; + string? header = RegistryAuthProvider.BuildAuthHeader(entry, "ghcr.io"); + + Assert.IsNotNull(header); + Assert.AreEqual(0, header.Length % 4, $"长度 {length}:带填充的 base64 长度必须是 4 的倍数"); + Assert.IsFalse(header.Contains('+') || header.Contains('/'), "必须是 URL 安全字母表"); + // 严格解码:还原成标准字母表后交给不容忍缺填充的 Convert.FromBase64String。 + byte[] decoded = Convert.FromBase64String(header.Replace('-', '+').Replace('_', '/')); + using var doc = JsonDocument.Parse(decoded); + Assert.AreEqual(entry.Username, doc.RootElement.GetProperty("username").GetString()); + Assert.AreEqual(entry.Password, doc.RootElement.GetProperty("password").GetString()); + } + } + + [TestMethod] + public void RegistryAuth_TreatsExplicitDockerIoAsDockerHub() + { + Assert.AreEqual(RegistryAuthProvider.DockerHub, RegistryAuthProvider.ResolveRegistry("docker.io/library/nginx")); + Assert.AreEqual(RegistryAuthProvider.DockerHub, RegistryAuthProvider.ResolveRegistry("index.docker.io/acme/api")); + Assert.AreEqual(RegistryAuthProvider.DockerHub, RegistryAuthProvider.ResolveRegistry("registry-1.docker.io/acme/api")); + } + + [TestMethod] + public void RegistryAuth_MatchesConfigKeysByNormalisedHostname() + { + Dictionary auths = new() + { + ["https://ghcr.io"] = "ghcr", + ["https://index.docker.io/v1/"] = "hub", + ["http://registry.example.com:5000/v2/"] = "private" + }; + + Assert.IsTrue(RegistryAuthProvider.TryFindRegistryEntry(auths, "ghcr.io", out string? ghcr)); + Assert.AreEqual("ghcr", ghcr); + Assert.IsTrue(RegistryAuthProvider.TryFindRegistryEntry(auths, + RegistryAuthProvider.ResolveRegistry("docker.io/acme/api"), out string? hub)); + Assert.AreEqual("hub", hub); + Assert.IsTrue(RegistryAuthProvider.TryFindRegistryEntry(auths, "registry.example.com:5000", out string? priv)); + Assert.AreEqual("private", priv); + Assert.IsFalse(RegistryAuthProvider.TryFindRegistryEntry(auths, "quay.io", out _)); + } + + // ── tar:属主、权限、长名字、链接 ───────────────────────────── + + [TestMethod] + public async Task Tar_RoundTripsModeOwnerAndNames() + { + byte[] archive = TarUtil.CreateSingleFile("entrypoint.sh", "#!/bin/sh\n"u8, 0b111_101_101, null, + 1000, 1001, "app", "appgroup"); + + TarEntryInfo? entry = await TarUtil.ReadFirstEntryAsync(new MemoryStream(archive), 1 << 20, readContent: true, + CancellationToken.None); + + Assert.IsNotNull(entry); + Assert.AreEqual(0b111_101_101, entry.Mode); + Assert.AreEqual(1000, entry.Uid); + Assert.AreEqual(1001, entry.Gid); + Assert.AreEqual("app", entry.UserName); + Assert.AreEqual("appgroup", entry.GroupName); + } + + [TestMethod] + public void Tar_WritesLongUtf8NamesThroughAPaxHeader() + { + // 150 多字节、带多字节字符 —— ustar 的 100 字节名字段放不下,以前会被静默截断、 + // 甚至劈开一个 UTF-8 字符,写到另一个文件名上去。 + string name = new string('a', 90) + "配置文件-非常长的名字-" + new string('b', 40) + ".conf"; + Assert.IsGreaterThan(100, Encoding.UTF8.GetByteCount(name)); + byte[] archive = TarUtil.CreateSingleFile(name, "x"u8); + + // 用 BCL 的读取器独立校验(Docker 那边是 Go 的 archive/tar,同样认 PAX)。 + using var reader = new TarReader(new MemoryStream(archive)); + TarEntry? entry = reader.GetNextEntry(); + Assert.IsNotNull(entry); + Assert.AreEqual(name, entry.Name); + Assert.AreEqual(TarEntryType.RegularFile, entry.EntryType); + } + + [TestMethod] + public async Task Tar_ReportsSymlinksInsteadOfPretendingTheyAreMissing() + { + byte[] archive = SymlinkTar("nginx.conf", "../nginx-real/nginx.conf"); + + TarEntryInfo? entry = await TarUtil.ReadFirstEntryAsync(new MemoryStream(archive), 1 << 20, readContent: true, + CancellationToken.None); + + Assert.IsNotNull(entry); + Assert.IsTrue(entry.IsLink); + Assert.AreEqual("../nginx-real/nginx.conf", entry.LinkName); + } + + [TestMethod] + public void ResolveLinkTarget_HandlesRelativeAndAbsoluteTargets() + { + Assert.AreEqual("/etc/nginx-real/nginx.conf", + DockerClient.ResolveLinkTarget("/etc/nginx/nginx.conf", "../nginx-real/nginx.conf")); + Assert.AreEqual("/usr/share/zoneinfo/UTC", DockerClient.ResolveLinkTarget("/etc/localtime", "/usr/share/zoneinfo/UTC")); + Assert.AreEqual("/etc/a/b", DockerClient.ResolveLinkTarget("/etc/a/link", "./b")); + Assert.AreEqual("/x", DockerClient.ResolveLinkTarget("/link", "../../x")); + } + + private static byte[] SymlinkTar(string name, string target) + { + var output = new MemoryStream(); + using (var writer = new TarWriter(output, TarEntryFormat.Pax, leaveOpen: true)) + { + writer.WriteEntry(new PaxTarEntry(TarEntryType.SymbolicLink, name) { LinkName = target }); + } + return output.ToArray(); + } + + // ── 经假 daemon 的文件读写 ─────────────────────────────────── + + private static FakeResponse Tar(byte[] archive) => new(200, archive, "application/x-tar"); + + private static FakeResponse NotFound(string message) => FakeResponse.Json(404, $$"""{"message":"{{message}}"}"""); + + private static TarEntry ReadPutEntry(FakeRequest put) + { + using var reader = new TarReader(new MemoryStream(put.Body)); + return reader.GetNextEntry() ?? throw new AssertFailedException("PUT 的 tar 里没有条目"); + } + + [TestMethod] + public async Task ReadFile_FollowsSymlinksAndReturnsOwnerAndMode() + { + byte[] real = TarUtil.CreateSingleFile("nginx.conf", "worker_processes 1;\n"u8, 0b110_100_000, null, 101, 101, + "nginx", "nginx"); + var transport = new FakeDockerTransport(r => r.QueryValue("path") switch + { + "/etc/nginx/nginx.conf" => Tar(SymlinkTar("nginx.conf", "../nginx-real/nginx.conf")), + "/etc/nginx-real/nginx.conf" => Tar(real), + _ => NotFound("not found") + }); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + ContainerFile file = await client.ReadFileWithMetadataAsync("c1", "/etc/nginx/nginx.conf"); + + Assert.AreEqual("/etc/nginx-real/nginx.conf", file.Path); + Assert.AreEqual("worker_processes 1;\n", Encoding.UTF8.GetString(file.Content)); + Assert.AreEqual(new ContainerFileMetadata(0b110_100_000, 101, 101, "nginx", "nginx"), file.Metadata); + byte[] plain = await client.ReadFileAsync("c1", "/etc/nginx/nginx.conf"); + Assert.HasCount(file.Content.Length, plain); + } + + [TestMethod] + public async Task ReadFile_GivesUpOnSymlinkLoops() + { + var transport = new FakeDockerTransport(r => r.QueryValue("path") switch + { + "/a" => Tar(SymlinkTar("a", "b")), + "/b" => Tar(SymlinkTar("b", "a")), + _ => NotFound("not found") + }); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + DockerApiException ex = await Assert.ThrowsExactlyAsync(() => client.ReadFileAsync("c1", "/a")); + Assert.Contains("符号链接", ex.Message); + } + + [TestMethod] + public async Task WriteFile_KeepsTheOriginalOwnerAndModeAndWritesThroughTheSymlink() + { + // entrypoint.sh 0755、属主 app(1000):写回之后还得是这样,否则容器下次启动就起不来。 + byte[] original = TarUtil.CreateSingleFile("entrypoint.sh", "#!/bin/sh\n"u8, 0b111_101_101, null, 1000, 1000, + "app", "app"); + var transport = new FakeDockerTransport(r => r.Method switch + { + "PUT" => new(200, []), + _ => r.QueryValue("path") switch + { + "/entrypoint.sh" => Tar(SymlinkTar("entrypoint.sh", "app/entrypoint.sh")), + "/app/entrypoint.sh" => Tar(original), + _ => NotFound("Could not find the file") + } + }); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + await client.WriteFileAsync("c1", "/entrypoint.sh", "#!/bin/sh\necho hi\n"u8.ToArray()); + + FakeRequest put = transport.Requests.Single(static r => r.Method == "PUT"); + // 写到链接指向的真文件所在目录 —— 链接本身不被换成普通文件。 + Assert.AreEqual("/app", put.QueryValue("path")); + TarEntry entry = ReadPutEntry(put); + Assert.AreEqual("entrypoint.sh", entry.Name); + Assert.AreEqual((UnixFileMode)0b111_101_101, entry.Mode); + Assert.AreEqual(1000, entry.Uid); + Assert.AreEqual(1000, entry.Gid); + } + + [TestMethod] + public async Task WriteFile_UsesDefaultsOnlyForNewFiles() + { + var transport = new FakeDockerTransport(r => r.Method == "PUT" ? new(200, []) : NotFound("Could not find the file")); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + await client.WriteFileAsync("c1", "/tmp/new.txt", "hello"u8.ToArray()); + + TarEntry entry = ReadPutEntry(transport.Requests.Single(static r => r.Method == "PUT")); + Assert.AreEqual((UnixFileMode)0b110_100_100, entry.Mode); + Assert.AreEqual(0, entry.Uid); + } + + [TestMethod] + public async Task WriteFile_WithExplicitMetadataSkipsTheProbe() + { + var transport = new FakeDockerTransport(static _ => new(200, [])); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + await client.WriteFileAsync("c1", "/srv/secret.key", "k"u8.ToArray(), new ContainerFileMetadata(0b110_000_000, 33, 33)); + + Assert.HasCount(1, transport.Requests); + TarEntry entry = ReadPutEntry(transport.Requests[0]); + Assert.AreEqual((UnixFileMode)0b110_000_000, entry.Mode); + Assert.AreEqual(33, entry.Uid); + } + + // ── 错误状态码不再被当成内容 ───────────────────────────────── + + [TestMethod] + public async Task RawInspect_ThrowsOnErrorStatusInsteadOfShowingTheErrorBody() + { + var transport = new FakeDockerTransport(static _ => NotFound("No such container: ghost")); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + DockerApiException ex = await Assert.ThrowsExactlyAsync(() => client.InspectContainerRawAsync("ghost")); + Assert.IsTrue(ex.IsNotFound); + Assert.AreEqual("No such container: ghost", ex.Message); + _ = await Assert.ThrowsExactlyAsync(() => client.ChangesAsync("ghost")); + _ = await Assert.ThrowsExactlyAsync(() => client.StatsSnapshotAsync("ghost")); + } + + [TestMethod] + public async Task Changes_StillTreatsJsonNullAsNoChanges() + { + var transport = new FakeDockerTransport(static _ => FakeResponse.Json(200, "null")); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + FilesystemChange[] changes = await client.ChangesAsync("c1"); + + Assert.IsEmpty(changes); + } + + // ── 连接池 ────────────────────────────────────────────────── + + [TestMethod] + public void ConnectionBudget_FitsTheTunnelQuotaAndLeavesRoomForExec() + { + Assert.IsGreaterThanOrEqualTo(2, DockerClient.DirectConnections); + Assert.IsGreaterThanOrEqualTo(4, DockerClient.MaxFollowStreams); + } + + [TestMethod] + public async Task LongLivedStreams_DoNotStarveOrdinaryRequests() + { + // 以前全部共用一个 6 条的池:事件流 + 几条跟随日志一占满,普通请求排队 30 秒后 + // 被报成"daemon 连不上"。现在长连接走自己的池子。 + var transport = new FakeDockerTransport(static r => r.Path switch + { + "/version" => FakeResponse.Json(200, """{"Version":"27.0.0","ApiVersion":"1.47"}"""), + _ => new(200, [], Hang: true) + }); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + using var cts = new CancellationTokenSource(); + List streams = []; + for (int i = 0; i < 1 + DockerClient.MaxFollowStreams; i++) + { + streams.Add(client.StreamEventsAsync(null, static _ => { }, cts.Token)); + } + // 等这些长连接真的建起来。 + Stopwatch wait = Stopwatch.StartNew(); + while (transport.Requests.Count(static r => r.Path == "/events") < streams.Count && wait.Elapsed < TimeSpan.FromSeconds(5)) + { + await Task.Delay(20); + } + + Task version = client.VersionAsync(); + Task finished = await Task.WhenAny(version, Task.Delay(TimeSpan.FromSeconds(10))); + + Assert.AreSame(version, finished, "长连接占满时普通请求也必须立刻有位子"); + SystemVersion result = await version; + Assert.AreEqual("1.47", result.ApiVersion); + Assert.IsLessThanOrEqualTo(DockerClient.TunnelQuota - DockerClient.DirectConnections, transport.PeakConnections); + await cts.CancelAsync(); + foreach (Task stream in streams) + { + try + { + await stream; + } + catch (Exception) + { + // 取消掉的流以什么异常结束都行。 + } + } + } + + // ── exec ──────────────────────────────────────────────────── + + private static byte[] Frame(byte kind, string text) + { + byte[] payload = Encoding.UTF8.GetBytes(text); + byte[] frame = new byte[8 + payload.Length]; + frame[0] = kind; + BinaryPrimitives.WriteInt32BigEndian(frame.AsSpan(4, 4), payload.Length); + payload.CopyTo(frame, 8); + return frame; + } + + private static Func ExecDaemon(Func start, bool running = false) => r => + r.Path switch + { + "/containers/c1/exec" => FakeResponse.Json(201, """{"Id":"e1"}"""), + "/exec/e1/start" => start(), + "/exec/e1/json" => FakeResponse.Json(200, $$"""{"ExitCode":3,"Running":{{(running ? "true" : "false")}}}"""), + _ => NotFound("unexpected " + r.Path) + }; + + [TestMethod] + public async Task ExecCapture_ReportsTheDaemonMessageWhenStartFails() + { + var transport = new FakeDockerTransport(ExecDaemon( + static () => FakeResponse.Json(409, """{"message":"container c1 is not running"}"""))); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + DockerApiException ex = await Assert.ThrowsExactlyAsync(() => + client.ExecCaptureAsync("c1", ["ls"])); + + Assert.IsTrue(ex.IsConflict); + Assert.Contains("container c1 is not running", ex.Message); + } + + [TestMethod] + public async Task ExecCapture_SplitsStreamsAndReadsTheExitCode() + { + byte[] frames = [.. Frame(1, "out\n"), .. Frame(2, "err\n")]; + var transport = new FakeDockerTransport(ExecDaemon(() => new(101, frames, Hijack: true))); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + ExecCapture result = await client.ExecCaptureAsync("c1", ["sh"]); + + Assert.AreEqual("out\n", result.StandardOutput); + Assert.AreEqual("err\n", result.StandardError); + Assert.AreEqual(3, result.ExitCode); + Assert.IsFalse(result.IsTruncated); + } + + [TestMethod] + public async Task ExecCapture_CapsTheCollectedOutput() + { + string line = new string('x', 1023) + "\n"; + var payload = new MemoryStream(); + for (int i = 0; i < (DockerClient.MaxExecCaptureBytes / 1024) + 512; i++) + { + payload.Write(Frame(1, line)); + } + byte[] frames = payload.ToArray(); + var transport = new FakeDockerTransport(ExecDaemon(() => new(101, frames, Hijack: true), running: true)); + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + ExecCapture result = await client.ExecCaptureAsync("c1", ["yes"]); + + Assert.IsTrue(result.IsTruncated); + Assert.IsLessThanOrEqualTo(DockerClient.MaxExecCaptureBytes, result.StandardOutput.Length); + // 截断时命令还在跑:退出码没有意义,不能报成成功。 + Assert.AreEqual(-1, result.ExitCode); + Assert.IsFalse(result.IsSuccess); + } + + [TestMethod] + public async Task ExecCapture_TimesOutEvenWhenTheStreamIgnoresCancellation() + { + // 隧道流的 ReadAsync 不理会取消令牌:只能靠释放流打断,否则这里永远等下去。 + var transport = new FakeDockerTransport(ExecDaemon(static () => new(101, [], Hijack: true, Hang: true))) + { + IgnoreReadCancellation = true + }; + await using var client = new DockerClient(DockerEndpoint.Local("t"), transport); + + Task capture = client.ExecCaptureAsync("c1", ["sleep", "infinity"], timeout: TimeSpan.FromMilliseconds(300)); + Task finished = await Task.WhenAny(capture, Task.Delay(TimeSpan.FromSeconds(10))); + + Assert.AreSame(capture, finished, "超时必须真的打断读取"); + _ = await Assert.ThrowsExactlyAsync(() => capture); + } + + // ── ls:BusyBox 与 GNU ────────────────────────────────────── + + [TestMethod] + public void ListCommand_PicksTheLsFlavourByCapabilityNotByFailure() + { + string command = DockerClient.ListCommand("/etc/my dir"); + + Assert.StartsWith("if ls --time-style=long-iso -d / >/dev/null 2>&1; then ", command); + // A || B 的写法会在 GNU 上碰到悬空链接时把两份列表一起打出来。 + Assert.DoesNotContain("||", command); + Assert.Contains("'/etc/my dir'", command); + } + + [TestMethod] + [DataRow("-rw-r--r-- 1 root root 1842 Aug 21 09:12 default.conf", "default.conf", 1842L, "Aug 21 09:12")] + [DataRow("drwxr-xr-x 2 root root 4096 Aug 21 2025 conf.d", "conf.d", 4096L, "Aug 21 2025")] + [DataRow("-rw-r--r-- 1 root root 10 Aug 21 09:12 my file.txt", "my file.txt", 10L, "Aug 21 09:12")] + [DataRow("-rw-r--r-- 1 nginx nginx 10 2026-08-21 09:12 my file.txt", "my file.txt", 10L, "2026-08-21 09:12")] + [DataRow("crw-rw-rw- 1 root root 1, 3 Aug 21 09:12 null", "null", 0L, "Aug 21 09:12")] + public void ParseLsLine_ReadsBusyBoxAndGnuDateShapes(string line, string name, long size, string modified) + { + ContainerFileEntry? entry = DockerClient.ParseLsLine(line, "/etc/nginx"); + + Assert.IsNotNull(entry); + Assert.AreEqual(name, entry.Value.Name); + Assert.AreEqual(size, entry.Value.Size); + Assert.AreEqual(modified, entry.Value.Modified); + Assert.AreEqual("/etc/nginx/" + name, entry.Value.FullPath); + } + + [TestMethod] + [DataRow("lrwxrwxrwx 1 root root 12 Aug 21 09:12 sh -> /bin/busybox")] + [DataRow("lrwxrwxrwx 1 root root 12 2026-08-21 09:12 sh -> /bin/busybox")] + public void ParseLsLine_SplitsSymlinksInBothFlavours(string line) + { + ContainerFileEntry? entry = DockerClient.ParseLsLine(line, "/bin"); + + Assert.IsNotNull(entry); + Assert.IsTrue(entry.Value.IsSymlink); + Assert.AreEqual("sh", entry.Value.Name); + Assert.AreEqual("/bin/busybox", entry.Value.LinkTarget); + } + + [TestMethod] + public void ParseLsLine_KeepsSpacesInSymlinkNamesAndTargets() + { + ContainerFileEntry? entry = DockerClient.ParseLsLine( + "lrwxrwxrwx 1 root root 10 Aug 21 2025 my link -> my target", "/srv"); + + Assert.IsNotNull(entry); + Assert.AreEqual("my link", entry.Value.Name); + Assert.AreEqual("my target", entry.Value.LinkTarget); + } + + // ── 帧解码 ────────────────────────────────────────────────── + + private static async Task> DecodeAsync(byte[] data, bool tty = false) + { + List lines = []; + await new DockerFrameDecoder(tty, timestamps: false).ReadAsync(new MemoryStream(data), lines.Add, CancellationToken.None); + return lines; + } + + private static byte[] RawFrame(byte kind, ReadOnlySpan payload) + { + byte[] frame = new byte[8 + payload.Length]; + frame[0] = kind; + BinaryPrimitives.WriteInt32BigEndian(frame.AsSpan(4, 4), payload.Length); + payload.CopyTo(frame.AsSpan(8)); + return frame; + } + + [TestMethod] + public async Task Decoder_KeepsAPerStreamUtf8Decoder() + { + // stdout 的一个三字节字符被劈开,中间夹着一帧 stderr。共用一个解码器时, + // stderr 的字节会被接到 stdout 那半个字符后面,两边一起变成乱码。 + byte[] word = Encoding.UTF8.GetBytes("容\n"); + byte[] data = [.. RawFrame(1, word.AsSpan(0, 2)), .. RawFrame(2, "err\n"u8), .. RawFrame(1, word.AsSpan(2))]; + + List lines = await DecodeAsync(data); + + Assert.AreEqual("err", lines.Single(static l => l.Kind == DockerStreamKind.StdErr).Text); + Assert.AreEqual("容", lines.Single(static l => l.Kind == DockerStreamKind.StdOut).Text); + } + + [TestMethod] + public async Task Decoder_TreatsLoneCarriageReturnAsALineBreak() + { + // 进度条靠 \r 原地重画:不当换行的话这一"行"永远不结束,缓冲无限长。 + List lines = await DecodeAsync(Encoding.UTF8.GetBytes("10%\r20%\r\ndone\n"), tty: true); + + Assert.AreSequenceEqual(["10%", "20%", "done"], [.. lines.Select(static l => l.Text)]); + } + + [TestMethod] + public async Task Decoder_KeepsCrLfSplitAcrossFramesAsOneBreak() + { + byte[] data = [.. RawFrame(1, "a\r"u8), .. RawFrame(1, "\nb\n"u8)]; + + List lines = await DecodeAsync(data); + + Assert.AreSequenceEqual(["a", "b"], [.. lines.Select(static l => l.Text)]); + } + + [TestMethod] + public async Task Decoder_ForceEmitsOverlongLines() + { + string huge = new('z', (DockerFrameDecoder.MaxLineChars * 3) + 17); + + List lines = await DecodeAsync(Encoding.UTF8.GetBytes(huge), tty: true); + + Assert.IsTrue(lines.All(static l => l.Text.Length <= DockerFrameDecoder.MaxLineChars)); + Assert.AreEqual(huge, string.Concat(lines.Select(static l => l.Text))); + } + + [TestMethod] + public async Task Decoder_RejectsABogusFrameLengthMidStream() + { + byte[] bogus = new byte[8]; + bogus[0] = 1; + BinaryPrimitives.WriteInt32BigEndian(bogus.AsSpan(4, 4), 600_000_000); + byte[] data = [.. RawFrame(1, "ok\n"u8), .. bogus]; + + // 以前会照着这个长度分配 600 MB。 + _ = await Assert.ThrowsExactlyAsync(() => DecodeAsync(data)); + } + + [TestMethod] + public async Task Decoder_FallsBackToRawTextWhenTheFirstHeaderIsNotAHeader() + { + // 第一帧就不像帧头 = 容器其实有 TTY:按裸文本读,而不是吃掉前 8 个字符。 + List lines = await DecodeAsync("hello world from a tty\n"u8.ToArray()); + + Assert.HasCount(1, lines); + Assert.AreEqual("hello world from a tty", lines[0].Text); + } + + [TestMethod] + public async Task Decoder_RoutesSystemErrorFramesToStderr() + { + List lines = await DecodeAsync(RawFrame(3, "daemon exploded\n"u8)); + + Assert.AreEqual(DockerStreamKind.StdErr, lines.Single().Kind); + } + + // ── 大文件差异 ────────────────────────────────────────────── + + [TestMethod] + public void LineDiff_HandlesAFiftyThousandLineFileWithOneEditQuicklyAndSmall() + { + string[] lines = [.. Enumerable.Range(0, 50_000).Select(static i => $"line {i} = value {i * 7}")]; + string before = string.Join('\n', lines); + lines[25_000] = "line 25000 = edited"; + string after = string.Join('\n', lines); + + long allocated = GC.GetAllocatedBytesForCurrentThread(); + Stopwatch watch = Stopwatch.StartNew(); + LineDiffResult diff = LineDiff.Compute(before, after); + watch.Stop(); + allocated = GC.GetAllocatedBytesForCurrentThread() - allocated; + + // 旧的 O(n·m) 表:50k × 50k 个 int ≈ 10 GB,直接 OOM、带走宿主。 + Assert.AreEqual(1, LineDiff.CountChanged(diff)); + Assert.IsFalse(diff.IsApproximate); + Assert.IsLessThan(64L * 1024 * 1024, allocated, $"分配了 {allocated:N0} 字节"); + Assert.IsLessThan(TimeSpan.FromSeconds(2), watch.Elapsed); + } + + [TestMethod] + public void LineDiff_FindsScatteredEditsInALargeFileExactly() + { + // 首尾各改一处:前后缀剥离之后中间还剩近五万行,靠的是 Myers 的 O((N+M)·D)。 + string[] lines = [.. Enumerable.Range(0, 50_000).Select(static i => $"row {i}")]; + string before = string.Join('\n', lines); + lines[10] = "changed near the top"; + lines[49_990] = "changed near the bottom"; + string after = string.Join('\n', lines); + + LineDiffResult diff = LineDiff.Compute(before, after); + + Assert.IsFalse(diff.IsApproximate); + Assert.AreEqual(2, LineDiff.CountChanged(diff)); + Assert.AreEqual(11, diff.Single(static l => l.Text == "changed near the top").NewNumber); + } + + [TestMethod] + public void LineDiff_DegradesToAFlaggedReplacementWhenEditsAreTooDense() + { + string before = string.Join('\n', Enumerable.Range(0, 3000).Select(static i => $"old {i}")); + string after = string.Join('\n', Enumerable.Range(0, 3000).Select(static i => $"new {i}")); + + Stopwatch watch = Stopwatch.StartNew(); + LineDiffResult diff = LineDiff.Compute(before, after); + + Assert.IsTrue(diff.IsApproximate); + Assert.IsLessThan(TimeSpan.FromSeconds(5), watch.Elapsed); + Assert.AreEqual(3000, diff.Count(static l => l.Marker == DiffMarker.Removed)); + } + + [TestMethod] + public void LineDiff_ProducesAMinimalValidEditScript() + { + // 随机小样本对照 O(n·m) 的参考 LCS:脚本既要能还原两边,长度也要最短。 + var random = new Random(20261201); + for (int round = 0; round < 300; round++) + { + string[] a = [.. Enumerable.Range(0, random.Next(0, 14)).Select(_ => ((char)('a' + random.Next(4))).ToString())]; + string[] b = [.. Enumerable.Range(0, random.Next(0, 14)).Select(_ => ((char)('a' + random.Next(4))).ToString())]; + + LineDiffResult diff = LineDiff.Compute(string.Join('\n', a), string.Join('\n', b)); + + // 空串按"零行"算,与 Split 的口径一致。 + string[] expectOld = a.Length == 1 && a[0].Length == 0 ? [] : a; + List rebuiltOld = []; + List rebuiltNew = []; + int edits = 0; + foreach (DiffLine line in diff) + { + switch (line.Marker) + { + case DiffMarker.None: + rebuiltOld.Add(line.Text); + rebuiltNew.Add(line.Text); + break; + case DiffMarker.Removed: + rebuiltOld.Add(line.Text); + edits++; + break; + case DiffMarker.Added: + rebuiltNew.Add(line.Text); + edits++; + break; + case DiffMarker.Changed: + rebuiltOld.Add(a[line.OldNumber - 1]); + rebuiltNew.Add(line.Text); + edits += 2; + break; + } + } + CollectionAssert.AreEqual(a, rebuiltOld, $"round {round}"); + CollectionAssert.AreEqual(b, rebuiltNew, $"round {round}"); + Assert.AreEqual(a.Length + b.Length - (2 * ReferenceLcs(a, b)), edits, $"round {round}"); + } + } + + private static int ReferenceLcs(string[] a, string[] b) + { + int[,] table = new int[a.Length + 1, b.Length + 1]; + for (int i = a.Length - 1; i >= 0; i--) + { + for (int j = b.Length - 1; j >= 0; j--) + { + table[i, j] = a[i] == b[j] ? table[i + 1, j + 1] + 1 : Math.Max(table[i + 1, j], table[i, j + 1]); + } + } + return table[0, 0]; + } + + // ── 显示口径 ──────────────────────────────────────────────── + + [TestMethod] + public void Prettify_KeepsChineseAndPunctuationReadable() + { + string pretty = DockerJson.Prettify("""{"Labels":{"desc":"网关 & +"}}"""); + + Assert.Contains("网关 & +", pretty); + Assert.DoesNotContain("\\u", pretty); + } + + [TestMethod] + public void Stats_PrefersCgroupV1TotalInactiveFileOverCache() + { + ContainerStats? sample = JsonSerializer.Deserialize(""" + { "memory_stats": { "usage": 1000, "limit": 4000, "stats": { "cache": 500, "total_inactive_file": 300 } } } + """, DockerJson.Options); + + // docker stats 扣的是 total_inactive_file,不是整块 cache(cache 里有活跃页,扣了会报少)。 + Assert.AreEqual(700UL, sample!.MemoryUsed); + } + + [TestMethod] + public void Reclaimable_UsesLayersSizeMinusWhatUsedImagesHoldExclusively() + { + var usage = new DiskUsage + { + Images = + [ + new() { Id = "sha256:a", Size = 300, SharedSize = 100, Containers = 2 }, + new() { Id = "sha256:b", Size = 400, SharedSize = 100, Containers = 0 } + ], + LayersSize = 600 + }; + + // CLI 口径:600 − (300 − 100) = 400。 + Assert.AreEqual(400, DiskMath.Reclaimable(usage).Images); + } + + // ── 语法高亮的注释规则 ────────────────────────────────────── + + private static string CommentBegin(string resource, out System.Xml.Linq.XDocument doc) + { + using Stream stream = typeof(DockerClient).Assembly.GetManifestResourceStream( + $"VelaShell.Plugin.DockerPanel.Syntax.{resource}.xshd") + ?? throw new AssertFailedException("找不到 " + resource); + doc = System.Xml.Linq.XDocument.Load(stream); + System.Xml.Linq.XNamespace ns = "http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"; + return doc.Descendants(ns + "Span").Single(static s => (string?)s.Attribute("color") == "Comment") + .Attribute("begin")!.Value; + } + + [TestMethod] + [DataRow("Yaml", "# 整行注释", 0)] + [DataRow("Yaml", "image: nginx # 行尾注释", 14)] + [DataRow("Yaml", "url: http://example.com/a#b", -1)] + [DataRow("Yaml", "image: repo/app#tag", -1)] + [DataRow("DotEnv", "# comment", 0)] + [DataRow("DotEnv", "PASSWORD=abc#123", -1)] + [DataRow("DotEnv", "PORT=5432 # 数据库端口", 10)] + [DataRow("DotEnv", "DSN=host;port=5432", -1)] + public void SyntaxComments_StartOnlyAtLineStartOrAfterWhitespace(string resource, string line, int expected) + { + // AvaloniaEdit 按行、从当前位置往后做正则匹配;lookbehind 看得到同一行前面的字符。 + string begin = CommentBegin(resource, out _); + System.Text.RegularExpressions.Match match = new System.Text.RegularExpressions.Regex(begin).Match(line); + + Assert.AreEqual(expected, match.Success ? match.Index : -1); + } + + [TestMethod] + public void DotEnvSyntax_HasNoSemicolonComment() + { + _ = CommentBegin("DotEnv", out System.Xml.Linq.XDocument doc); + System.Xml.Linq.XNamespace ns = "http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"; + + Assert.HasCount(1, doc.Descendants(ns + "Span").Where(static s => (string?)s.Attribute("color") == "Comment")); + } +} \ No newline at end of file diff --git a/tests/VelaShell.Plugin.DockerPanel.Tests/FakeDockerDaemon.cs b/tests/VelaShell.Plugin.DockerPanel.Tests/FakeDockerDaemon.cs new file mode 100644 index 0000000..98fd051 --- /dev/null +++ b/tests/VelaShell.Plugin.DockerPanel.Tests/FakeDockerDaemon.cs @@ -0,0 +1,358 @@ +using System.Text; +using VelaShell.Plugin.DockerPanel.Docker; + +namespace VelaShell.Plugin.DockerPanel.Tests; + +/// 假 daemon 收到的一条请求。 +internal sealed record FakeRequest(string Method, string Path, string Query, byte[] Body) +{ + /// 取一个查询参数(已解码);没有返回 null。 + public string? QueryValue(string key) + { + foreach (string pair in Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + int eq = pair.IndexOf('='); + string k = Uri.UnescapeDataString(eq < 0 ? pair : pair[..eq]); + if (k == key) + { + return eq < 0 ? "" : Uri.UnescapeDataString(pair[(eq + 1)..]); + } + } + return null; + } +} + +/// 假 daemon 的一条响应。 +/// 状态码。 +/// 响应体。 +/// 内容类型。 +/// 劫持连接:回 101,写完 后(除非 )关闭读端。 +/// 只发响应头(分块编码,一块都不发),然后永远不再出声 —— 模拟长连接或卡住的流。 +internal sealed record FakeResponse(int Status, byte[] Body, string ContentType = "application/json", + bool Hijack = false, bool Hang = false) +{ + public static FakeResponse Json(int status, string json) => new(status, Encoding.UTF8.GetBytes(json)); +} + +/// +/// 一个在内存里说 HTTP/1.1 的假 daemon:每次 给一条新"连接", +/// 请求交给 handler 决定怎么回。足够让 的连接池、 +/// 劫持端点与错误路径真的跑一遍。 +/// +internal sealed class FakeDockerTransport(Func handler) : IDockerTransport +{ + private readonly Lock _gate = new(); + private readonly List _requests = []; + private int _open; + private int _peak; + + /// + /// 为真时连接的 ReadAsync 不理会取消令牌 —— SSH 隧道流就可能这样, + /// 只能靠释放流来打断。 + /// + public bool IgnoreReadCancellation { get; init; } + + public string Description => "fake docker"; + + /// 同时打开的连接数的峰值。 + public int PeakConnections => Volatile.Read(ref _peak); + + public IReadOnlyList Requests + { + get + { + lock (_gate) + { + return [.. _requests]; + } + } + } + + public Task ConnectAsync(CancellationToken cancellationToken = default) + { + int open = Interlocked.Increment(ref _open); + int peak; + while (open > (peak = Volatile.Read(ref _peak)) && Interlocked.CompareExchange(ref _peak, open, peak) != peak) + { + } + return Task.FromResult(new FakeConnection(this)); + } + + internal FakeResponse Handle(FakeRequest request) + { + lock (_gate) + { + _requests.Add(request); + } + return handler(request); + } + + internal void Closed() => Interlocked.Decrement(ref _open); + + private sealed class FakeConnection(FakeDockerTransport owner) : Stream + { + private readonly Lock _lock = new(); + private readonly List _incoming = []; + private readonly Queue _outgoing = new(); + private readonly SemaphoreSlim _signal = new(0); + private byte[]? _current; + private int _currentOffset; + private bool _eof; + private bool _hijacked; + private bool _disposed; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + ObjectDisposedException.ThrowIf(_disposed, this); + lock (_lock) + { + if (_hijacked) + { + return; + } + _incoming.AddRange(buffer.ToArray()); + Process(); + } + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + Write(buffer.Span); + return ValueTask.CompletedTask; + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + Write(buffer.AsSpan(offset, count)); + return Task.CompletedTask; + } + + public override int Read(byte[] buffer, int offset, int count) => + ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + while (true) + { + lock (_lock) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_current is null && _outgoing.Count > 0) + { + _current = _outgoing.Dequeue(); + _currentOffset = 0; + } + if (_current is not null) + { + int n = Math.Min(buffer.Length, _current.Length - _currentOffset); + _current.AsSpan(_currentOffset, n).CopyTo(buffer.Span); + _currentOffset += n; + if (_currentOffset >= _current.Length) + { + _current = null; + } + return n; + } + if (_eof) + { + return 0; + } + } + if (owner.IgnoreReadCancellation) + { + await _signal.WaitAsync(CancellationToken.None).ConfigureAwait(false); + } + else + { + await _signal.WaitAsync(cancellationToken).ConfigureAwait(false); + } + } + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + bool first; + lock (_lock) + { + first = !_disposed; + _disposed = true; + } + if (first) + { + owner.Closed(); + _ = _signal.Release(); + } + base.Dispose(disposing); + } + + /// 请求攒齐了就交给 handler,把响应排进读队列。调用方持锁。 + private void Process() + { + while (!_hijacked) + { + int headEnd = IndexOf(_incoming, "\r\n\r\n"u8); + if (headEnd < 0) + { + return; + } + string head = Encoding.ASCII.GetString([.. _incoming.GetRange(0, headEnd)]); + string[] lines = head.Split("\r\n"); + string[] requestLine = lines[0].Split(' '); + Dictionary headers = new(StringComparer.OrdinalIgnoreCase); + foreach (string line in lines.Skip(1)) + { + int colon = line.IndexOf(':'); + if (colon > 0) + { + headers[line[..colon].Trim()] = line[(colon + 1)..].Trim(); + } + } + int bodyStart = headEnd + 4; + byte[] body; + int consumed; + if (headers.TryGetValue("Content-Length", out string? lengthText)) + { + int length = int.Parse(lengthText, System.Globalization.CultureInfo.InvariantCulture); + if (_incoming.Count < bodyStart + length) + { + return; + } + body = [.. _incoming.GetRange(bodyStart, length)]; + consumed = bodyStart + length; + } + else if (headers.TryGetValue("Transfer-Encoding", out string? te) && te.Contains("chunked")) + { + if (!TryDecodeChunked(bodyStart, out body, out consumed)) + { + return; + } + } + else + { + body = []; + consumed = bodyStart; + } + _incoming.RemoveRange(0, consumed); + + string target = requestLine[1]; + int q = target.IndexOf('?'); + var request = new FakeRequest(requestLine[0], q < 0 ? target : target[..q], q < 0 ? "" : target[q..], body); + FakeResponse response = owner.Handle(request); + Enqueue(response); + } + } + + private void Enqueue(FakeResponse response) + { + var sb = new StringBuilder(); + if (response.Hijack && response.Status == 101) + { + _ = sb.Append("HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\n") + .Append("Connection: Upgrade\r\nUpgrade: tcp\r\n\r\n"); + _hijacked = true; + } + else + { + _ = sb.Append("HTTP/1.1 ").Append(response.Status).Append(" X\r\n") + .Append("Content-Type: ").Append(response.ContentType).Append("\r\n"); + _ = response.Hang + ? sb.Append("Transfer-Encoding: chunked\r\n\r\n") + : sb.Append("Content-Length: ").Append(response.Body.Length).Append("\r\n\r\n"); + } + _outgoing.Enqueue(Encoding.ASCII.GetBytes(sb.ToString())); + if (!response.Hang || response.Hijack) + { + if (response.Body.Length > 0) + { + _outgoing.Enqueue(response.Body); + } + } + if (_hijacked && !response.Hang) + { + _eof = true; + } + _ = _signal.Release(); + } + + private bool TryDecodeChunked(int start, out byte[] body, out int consumed) + { + var output = new List(); + int pos = start; + body = []; + consumed = 0; + while (true) + { + int lineEnd = IndexOf(_incoming, "\r\n"u8, pos); + if (lineEnd < 0) + { + return false; + } + string sizeText = Encoding.ASCII.GetString([.. _incoming.GetRange(pos, lineEnd - pos)]).Split(';')[0]; + int size = int.Parse(sizeText, System.Globalization.NumberStyles.HexNumber, null); + pos = lineEnd + 2; + if (size == 0) + { + if (_incoming.Count < pos + 2) + { + return false; + } + consumed = pos + 2; + body = [.. output]; + return true; + } + if (_incoming.Count < pos + size + 2) + { + return false; + } + output.AddRange(_incoming.GetRange(pos, size)); + pos += size + 2; + } + } + + private static int IndexOf(List data, ReadOnlySpan pattern, int start = 0) + { + for (int i = start; i <= data.Count - pattern.Length; i++) + { + bool match = true; + for (int j = 0; j < pattern.Length; j++) + { + if (data[i + j] != pattern[j]) + { + match = false; + break; + } + } + if (match) + { + return i; + } + } + return -1; + } + } +} diff --git a/tests/VelaShell.Plugin.DockerPanel.Tests/InspectionTests.cs b/tests/VelaShell.Plugin.DockerPanel.Tests/InspectionTests.cs index fcc8b3e..c14a074 100644 --- a/tests/VelaShell.Plugin.DockerPanel.Tests/InspectionTests.cs +++ b/tests/VelaShell.Plugin.DockerPanel.Tests/InspectionTests.cs @@ -129,22 +129,26 @@ public void CleanInstruction_SaysSomethingWhenTheresNothingToSay() => // ── system df ───────────────────────────────────────────────── [TestMethod] - public void Reclaimable_CountsEveryUnusedImageNotJustTheDanglingOnes() + public void Reclaimable_CountsEveryUnusedImageWithoutDoubleCountingSharedLayers() { var usage = new DiskUsage { Images = [ - new() { Id = "sha256:a", Size = 100, Containers = 1, RepoTags = ["app:1"] }, - new() { Id = "sha256:b", Size = 250, Containers = 0, RepoTags = ["old:1"] }, - new() { Id = "sha256:c", Size = 50, Containers = 0, RepoTags = [":"] } - ] + new() { Id = "sha256:a", Size = 100, SharedSize = 0, Containers = 1, RepoTags = ["app:1"] }, + // b 与 c 共享一层 40 字节的基础层:磁盘上它只占一份。 + new() { Id = "sha256:b", Size = 250, SharedSize = 40, Containers = 0, RepoTags = ["old:1"] }, + new() { Id = "sha256:c", Size = 50, SharedSize = 40, Containers = 0, RepoTags = [":"] } + ], + // 去重后的层总量:a 独占 100 + b 独占 210 + c 独占 10 + 共享 40。 + LayersSize = 360 }; ReclaimBreakdown reclaim = DiskMath.Reclaimable(usage); - // 只算悬空的那 50 会把可回收量报少五倍 —— prune -a 会把 old:1 也删掉。 - Assert.AreEqual(300, reclaim.Images); + // 只算悬空的那 10 会把可回收量报少一大截 —— prune -a 会把 old:1 也删掉; + // 而把 b、c 的 Size 直接相加(300)又会把共享层算两遍。CLI 口径:360 − 100 = 260。 + Assert.AreEqual(260, reclaim.Images); Assert.AreEqual(2, reclaim.UnusedImages); } diff --git a/tests/VelaShell.Plugin.DockerPanel.Tests/UiRobustnessTests.cs b/tests/VelaShell.Plugin.DockerPanel.Tests/UiRobustnessTests.cs new file mode 100644 index 0000000..7903ab3 --- /dev/null +++ b/tests/VelaShell.Plugin.DockerPanel.Tests/UiRobustnessTests.cs @@ -0,0 +1,330 @@ +using System.ComponentModel; +using System.Reflection; +using System.Text; +using Avalonia.Headless; +using VelaShell.Plugin.DockerPanel.Docker; +using VelaShell.Plugin.DockerPanel.Ui; +using VelaShell.Plugin.DockerPanel.Ui.Pages; +using VelaShell.PluginSdk.Testing; + +namespace VelaShell.Plugin.DockerPanel.Tests; + +/// +/// 界面层的健壮性:并发、重入、释放与筛选。 +/// +/// 这些都是"单跑看不出来、用久了才出事"的毛病 —— 静态事件把整张视图模型图钉在内存里、 +/// 读流线程与 UI 线程同时碰一个字典、换主机之后还留着上一台的状态。 +/// +/// +[TestClass] +public class UiRobustnessTests +{ + // 视图模型的通知、闸门的 Ui.Post 都要一条真的在泵的 UI 线程,理由见 DockerPanelHeadlessApp。 + private static HeadlessUnitTestSession _session = null!; + + [ClassInitialize] + public static void InitSession(TestContext _) => + _session = HeadlessUnitTestSession.GetOrStartForAssembly(typeof(UiRobustnessTests).Assembly); + + /// 在 headless UI 线程上跑一段测试体(lambda 必须带返回值,理由见 PanelLogicTests.OnUi)。 + private static void OnUi(Func body) => + _session.Dispatch(async () => + { + await body(); + return true; + }, CancellationToken.None).GetAwaiter().GetResult(); + + // ── KeyedCollection ─────────────────────────────────────── + + private sealed class Item(string key, int value) + { + public string Key { get; } = key; + + public int Value { get; set; } = value; + } + + [TestMethod] + public void Merge_KeepsInstancesFollowsOrderAndDropsStale() + { + var collection = new KeyedCollection(static i => i.Key); + Item a = new("a", 1), b = new("b", 2), c = new("c", 3); + collection.Add(a); + collection.Add(b); + collection.Add(c); + + collection.Merge([new("c", 30), new("d", 4), new("a", 10)], static (current, incoming) => current.Value = incoming.Value); + + string[] keys = [.. collection.Select(static i => i.Key)]; + Assert.AreSequenceEqual(new[] { "c", "d", "a" }, keys); + // 同 key 的项保留原实例 —— 选中态、展开态都挂在实例上。 + Assert.AreSame(c, collection[0]); + Assert.AreSame(a, collection[2]); + Assert.AreEqual(30, c.Value); + Assert.AreEqual(10, a.Value); + } + + private sealed record Project(string Name, string Status); + + [TestMethod] + public void MergeReplacing_SwapsChangedRecordsAndKeepsUnchangedOnes() + { + var collection = new KeyedCollection(static p => p.Name); + Project web = new("web", "running(2)"), db = new("db", "running(1)"); + collection.Add(web); + collection.Add(db); + + collection.MergeReplacing([new("db", "running(1)"), new("web", "exited(2)")]); + + Assert.AreEqual(2, collection.Count); + Assert.AreSame(db, collection[0]); + Assert.AreEqual("exited(2)", collection[1].Status); + } + + // ── 拉取进度聚合:读流线程写、UI 线程读 ───────────────────── + + [TestMethod] + public async Task PullAggregator_SurvivesConcurrentAcceptAndRead() + { + var aggregator = new PullAggregator(); + using var stop = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); + Task writer = Task.Run(() => + { + for (int i = 0; !stop.IsCancellationRequested; i++) + { + aggregator.Accept(new PullProgressFrame + { + Id = $"layer{i % 50}", + Status = "Downloading", + ProgressDetail = new() { Current = i, Total = 1000 } + }); + } + }, TestContext.CancellationToken); + int reads = 0; + while (!stop.IsCancellationRequested) + { + // 早先这里会撞上"集合在枚举时被修改"。 + _ = aggregator.Snapshot(); + _ = aggregator.Summary; + _ = aggregator.Progress; + reads++; + } + await writer; + Assert.IsGreaterThan(0, reads); + Assert.AreEqual(50, aggregator.LayerCount); + } + + // ── 事件噪声 ────────────────────────────────────────────── + + [TestMethod] + public void HealthCheckAndPanelOwnExecsAreNotRefreshTriggers() + { + static DockerEvent Container(string action) => new() { Type = "container", Action = action }; + + // 健康检查每几秒一组,带着命令参数。 + Assert.IsTrue(DockerPanelViewModel.IsIgnorableEvent(Container("exec_start: /bin/sh -c curl -f localhost"))); + Assert.IsTrue(DockerPanelViewModel.IsIgnorableEvent(Container("exec_create: df -PB1 /var/lib/docker"))); + Assert.IsTrue(DockerPanelViewModel.IsIgnorableEvent(Container("exec_die"))); + Assert.IsTrue(DockerPanelViewModel.IsIgnorableEvent(Container("top"))); + Assert.IsTrue(DockerPanelViewModel.IsIgnorableEvent(Container("archive-path"))); + // 真正改变状态的事件必须照常刷新。 + Assert.IsFalse(DockerPanelViewModel.IsIgnorableEvent(Container("start"))); + Assert.IsFalse(DockerPanelViewModel.IsIgnorableEvent(Container("die"))); + Assert.IsFalse(DockerPanelViewModel.IsIgnorableEvent(Container("health_status: unhealthy"))); + Assert.IsFalse(DockerPanelViewModel.IsIgnorableEvent(new DockerEvent { Type = "image", Action = "pull" })); + } + + // ── Compose 项目名 ──────────────────────────────────────── + + [TestMethod] + public void ProjectName_IsDerivedFromWindowsAndPosixPathsLikeComposeDoes() + { + Assert.AreEqual("web-stack", ComposePageViewModel.DeriveProjectName("/srv/stacks/web-stack/compose.yaml")); + // 早先只按 '/' 切:本机 Windows 路径推出来是空串,下发的是 compose -p ""。 + Assert.AreEqual("web-stack", ComposePageViewModel.DeriveProjectName(@"D:\stacks\web-stack\compose.yaml")); + // compose 会把目录名转小写、去掉不合法的字符;不照做的话起出来的容器前缀和命令行不一样。 + Assert.AreEqual("mystack_v2", ComposePageViewModel.DeriveProjectName(@"D:\stacks\My Stack_v2\compose.yaml")); + Assert.AreEqual("", ComposePageViewModel.DeriveProjectName("/compose.yaml")); + } + + // ── 容器内文件:编码 ────────────────────────────────────── + + [TestMethod] + public void Utf8Bom_IsStrippedForEditingAndRestoredOnSave() + { + byte[] original = [0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes("listen 80;\n中文\n")]; + + (string text, bool bom, bool valid) = ContainerFilesViewModel.DecodeText(original); + + Assert.IsTrue(valid); + Assert.IsTrue(bom); + Assert.AreEqual("listen 80;\n中文\n", text); + byte[] written = ContainerFilesViewModel.EncodeText(text, bom); + Assert.AreSequenceEqual(original, written); + } + + [TestMethod] + public void NonUtf8File_IsReportedInvalidInsteadOfSilentlyReplaced() + { + // "中文" 的 GBK 编码:按 UTF-8 宽松解码再写回,会变成一串 EF BF BD。 + byte[] gbk = [0xD6, 0xD0, 0xCE, 0xC4, 0x0A]; + + (_, bool bom, bool valid) = ContainerFilesViewModel.DecodeText(gbk); + + Assert.IsFalse(valid); + Assert.IsFalse(bom); + } + + [TestMethod] + public void CaretLookup_FindsLineAndColumnByBinarySearch() + { + // "ab\ncd\n\nxyz":行首在 0、3、6、7。 + int[] starts = [0, 3, 6, 7]; + Assert.AreEqual((1, 1), ContainerFilesView.LocateCaret(starts, 0)); + Assert.AreEqual((1, 3), ContainerFilesView.LocateCaret(starts, 2)); + Assert.AreEqual((2, 1), ContainerFilesView.LocateCaret(starts, 3)); + Assert.AreEqual((3, 1), ContainerFilesView.LocateCaret(starts, 6)); + Assert.AreEqual((4, 4), ContainerFilesView.LocateCaret(starts, 10)); + } + + // ── 日志视图 ────────────────────────────────────────────── + + private static LogLineItem Line(string text, bool stderr = false) => new("", "", 0, stderr, text); + + [TestMethod] + public void ErrorsOnly_FiltersTheViewWithoutDroppingBufferedLines() => OnUi(async () => + { + var shell = new DockerPanelViewModel(new TestPluginContext()); + await using var logs = new LogsViewModel(shell, [new("a", "web", false), new("b", "db", false)]); + logs.AppendBatch([Line("GET / 200"), Line("panic: boom", stderr: true), Line("GET /health 200")]); + + logs.ErrorsOnly = true; + Assert.HasCount(1, logs.Lines); + Assert.AreEqual(3, logs.BufferedLineCount); + + // 早先被筛掉的行在入队时就丢了:关掉「仅错误」也回不来。 + logs.ErrorsOnly = false; + Assert.HasCount(3, logs.Lines); + await shell.DisposeAsync(); + }); + + [TestMethod] + public void SearchChange_NotifiesMatchedSoHighlightFollows() => OnUi(async () => + { + var shell = new DockerPanelViewModel(new TestPluginContext()); + await using var logs = new LogsViewModel(shell, [new("a", "web", false), new("b", "db", false)]); + LogLineItem line = Line("connection refused"); + logs.AppendBatch([line]); + List changed = []; + line.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + + logs.Search = "refused"; + + Assert.IsTrue(line.Matched); + Assert.Contains(nameof(LogLineItem.Matched), changed); + Assert.AreEqual(1, logs.MatchCount); + await shell.DisposeAsync(); + }); + + [TestMethod] + public void BrokenRegex_ShowsAHintInsteadOfThrowing() => OnUi(async () => + { + var shell = new DockerPanelViewModel(new TestPluginContext()); + await using var logs = new LogsViewModel(shell, [new("a", "web", false), new("b", "db", false)]); + logs.AppendBatch([Line("error (code 5)")]); + + logs.UseRegex = true; + logs.Search = "(code"; + + Assert.AreEqual("正则还没写完整", logs.MatchText); + Assert.AreEqual(0, logs.MatchCount); + await shell.DisposeAsync(); + }); + + [TestMethod] + public void MergedLogs_AreCappedAtTheLongStreamQuota() => OnUi(async () => + { + var shell = new DockerPanelViewModel(new TestPluginContext()); + LogSource[] sources = [.. Enumerable.Range(0, 12).Select(static i => new LogSource($"id{i}", $"c{i}", false))]; + + await using var logs = new LogsViewModel(shell, sources); + + Assert.AreEqual(LogsViewModel.MaxMergedSources, logs.SourceCount); + await shell.DisposeAsync(); + }); + + // ── 外壳的生命周期 ──────────────────────────────────────── + + [TestMethod] + public void Dispose_IsIdempotentAndReleasesTheStaticCommandErrorHook() => OnUi(async () => + { + var shell = new DockerPanelViewModel(new TestPluginContext()); + Assert.IsTrue(HooksCommandErrors(shell)); + + await shell.DisposeAsync(); + // 宿主关标签与插件停用各调一次 —— 第二次不能炸。 + await shell.DisposeAsync(); + + // 静态事件不退订,整张视图模型图就随每次开面板泄漏一份。 + Assert.IsFalse(HooksCommandErrors(shell)); + }); + + private static bool HooksCommandErrors(DockerPanelViewModel shell) + { + FieldInfo field = typeof(RelayCommand).GetField(nameof(RelayCommand.UnhandledCommandError), + BindingFlags.Static | BindingFlags.NonPublic)!; + var handler = (Delegate?)field.GetValue(null); + return handler?.GetInvocationList().Any(d => ReferenceEquals(d.Target, shell)) == true; + } + + [TestMethod] + public void ConfirmGate_SaysSoWhenASecondRequestIsRejected() => OnUi(async () => + { + var gate = new ConfirmGate(); + ConfirmRequest? rejected = null; + gate.RejectedWhileBusy += r => rejected = r; + + Task first = gate.AskAsync(new() { Title = "删除 3 个卷?", HostName = "prod", ConfirmLabel = "删除" }); + bool second = await gate.AskAsync(new() { Title = "删除容器 web?", HostName = "prod", ConfirmLabel = "删除" }); + + Assert.IsFalse(second); + Assert.AreEqual("删除容器 web?", rejected?.Title); + gate.CancelPending(); + Assert.IsFalse(await first); + }); + + [TestMethod] + public void ReloadingEndpoints_KeepsTheSameItemInstances() => OnUi(async () => + { + var context = new TestPluginContext(); + _ = context.FakeSessions.AddConnected("prod-01", 22, "deploy"); + var shell = new DockerPanelViewModel(context); + + await shell.ReloadEndpointsAsync(); + EndpointItem[] first = [.. shell.Endpoints]; + await shell.ReloadEndpointsAsync(); + EndpointItem[] second = [.. shell.Endpoints]; + + // 整表重建会让 SelectedEndpoint 指着一个不在列表里的旧实例。 + Assert.HasCount(2, second); + Assert.AreSame(first[0], second[0]); + Assert.AreSame(first[1], second[1]); + await shell.DisposeAsync(); + }); + + [TestMethod] + public void CompactRowsSetting_ReachesTheListRowHeight() => OnUi(async () => + { + var shell = new DockerPanelViewModel(new TestPluginContext()); + List changed = []; + ((INotifyPropertyChanged)shell.Containers).PropertyChanged += (_, e) => changed.Add(e.PropertyName); + Assert.AreEqual(32, shell.Containers.RowHeight); + + shell.Settings.CompactRows = false; + + Assert.AreEqual(40, shell.Images.RowHeight); + Assert.Contains(nameof(PageViewModel.RowHeight), changed); + await shell.DisposeAsync(); + }); + + public TestContext TestContext { get; set; } = null!; +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/BsonRoundTripTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/BsonRoundTripTests.cs new file mode 100644 index 0000000..0e38c98 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/BsonRoundTripTests.cs @@ -0,0 +1,134 @@ +using MongoDB.Bson; +using VelaShell.Plugin.Mongo.Bson; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// Shell 写法的往返:(Shell)写出的文本经 读回来, +/// 每个字段的值与类型都不变 —— 文档编辑器就是这么存的,没动过的字段不许被悄悄改类型或改值。 +/// +[TestClass] +public sealed class BsonRoundTripTests +{ + private static BsonDocument AllTypes() => new() + { + { "_id", ObjectId.Parse("66f5c2a1b4d3e2f1a0b9e3b7") }, + { "str", "带 \"引号\"、反斜杠 \\ 、换行\n、制表\t 与控制字符 \u0001" }, + { "int", 42 }, + { "intNeg", -7 }, + { "long", 9_007_199_254_740_993L }, + { "longSmall", new BsonInt64(5) }, + { "doubleIntegral", 5.0 }, + { "doubleZero", 0.0 }, + { "doubleFraction", 0.1 }, + { "doubleHuge", 1e300 }, + { "doubleTiny", 5e-324 }, + { "doubleNaN", double.NaN }, + { "doublePosInf", double.PositiveInfinity }, + { "doubleNegInf", double.NegativeInfinity }, + { "decimal", Decimal128.Parse("0.0035") }, + { "decimalScaled", Decimal128.Parse("8740.00") }, + { "bool", true }, + { "date", new BsonDateTime(new DateTime(2026, 8, 27, 10, 30, 5, 123, DateTimeKind.Utc)) }, + { "dateWhole", new BsonDateTime(new DateTime(2026, 8, 27, 0, 0, 0, DateTimeKind.Utc)) }, + { "dateBeforeYear1", new BsonDateTime(-62135596800001L) }, + { "dateAfterYear9999", new BsonDateTime(253402300800000L) }, + { "dateMax", new BsonDateTime(long.MaxValue) }, + { "null", BsonNull.Value }, + { "uuid", new BsonBinaryData(Guid.Parse("3b241101-e2bb-4255-8caf-4136c566a962"), GuidRepresentation.Standard) }, + { "binary", new BsonBinaryData([1, 2, 3, 250], BsonBinarySubType.Binary) }, + { "binaryUser", new BsonBinaryData([9, 8], BsonBinarySubType.UserDefined) }, + { "binaryLegacyUuid", new BsonBinaryData(new byte[16], BsonBinarySubType.UuidLegacy) }, + { "regex", new BsonRegularExpression("^a/b.*", "im") }, + { "timestamp", new BsonTimestamp(1_787_788_800, 7) }, + { "minKey", BsonMinKey.Value }, + { "maxKey", BsonMaxKey.Value }, + { "nested", new BsonDocument { { "a", 1.0 }, { "b", new BsonArray { 1, 2.0, "x", BsonMinKey.Value } } } }, + { "array", new BsonArray { new BsonDocument("t", new BsonTimestamp(1, 2)), BsonMaxKey.Value, 3.0 } }, + { "code", new BsonJavaScript("function () { return 1; }") }, + { "dotted key", "ok" } + }; + + [TestMethod] + public void ShellPretty_RoundTripsEveryType() + { + BsonDocument original = AllTypes(); + string text = BsonText.Pretty(original, EjsonMode.Shell); + BsonDocument back = ShellJson.ParseDocument(text); + AssertSame(original, back); + } + + [TestMethod] + public void ShellCompact_RoundTripsEveryType() + { + BsonDocument original = AllTypes(); + BsonDocument back = ShellJson.ParseDocument(BsonText.Compact(original, EjsonMode.Shell)); + AssertSame(original, back); + } + + [TestMethod] + public void IntegralDoubleIsWrittenWithADecimalPoint() + { + Assert.AreEqual("5.0", BsonText.Literal(new BsonDouble(5))); + Assert.AreEqual(BsonType.Double, ShellJson.ParseValue(BsonText.Literal(new BsonDouble(5))).BsonType); + } + + [TestMethod] + public void MongoshConstructorsParse() + { + BsonDocument doc = ShellJson.ParseDocument("{ ts: Timestamp({ t: 10, i: 3 }), lo: MinKey(), hi: MaxKey(), list: [MinKey(), Timestamp({t:1,i:2})], s: \"Timestamp({ t: 1, i: 2 })\" }"); + Assert.AreEqual(new BsonTimestamp(10, 3), doc["ts"]); + Assert.AreEqual(BsonMinKey.Value, doc["lo"]); + Assert.AreEqual(BsonMaxKey.Value, doc["hi"]); + Assert.AreEqual(BsonMinKey.Value, doc["list"][0]); + Assert.AreEqual(new BsonTimestamp(1, 2), doc["list"][1]); + Assert.AreEqual("Timestamp({ t: 1, i: 2 })", doc["s"].AsString, "字符串里的不动"); + Assert.AreEqual(new BsonTimestamp(4, 5), ShellJson.ParseValue("Timestamp(4, 5)"), "驱动自己的写法照旧"); + } + + [TestMethod] + public void OutOfRangeDatesDoNotThrow() + { + var early = new BsonDateTime(-62135596800001L); + Assert.AreEqual("new Date(-62135596800001)", BsonText.Literal(early)); + Assert.AreEqual("-62135596800001", BsonText.IsoDate(early)); + Assert.AreEqual("2026-08-27T00:00:00Z", BsonText.IsoDate(new BsonDateTime(new DateTime(2026, 8, 27, 0, 0, 0, DateTimeKind.Utc)))); + } + + private static void AssertSame(BsonDocument expected, BsonDocument actual) + { + Assert.AreEqual(expected.ElementCount, actual.ElementCount); + foreach (BsonElement element in expected) + { + Assert.IsTrue(actual.TryGetValue(element.Name, out BsonValue value), element.Name); + AssertSameValue(element.Value, value, element.Name); + } + } + + private static void AssertSameValue(BsonValue expected, BsonValue actual, string path) + { + Assert.AreEqual(expected.BsonType, actual.BsonType, path); + switch (expected) + { + case BsonDocument doc: + AssertSame(doc, actual.AsBsonDocument); + break; + case BsonArray array: + Assert.AreEqual(array.Count, actual.AsBsonArray.Count, path); + for (int i = 0; i < array.Count; i++) + { + AssertSameValue(array[i], actual.AsBsonArray[i], $"{path}[{i}]"); + } + break; + case BsonDouble d when double.IsNaN(d.Value): + Assert.IsTrue(double.IsNaN(actual.AsDouble), path); + break; + case BsonDecimal128 m: + Assert.AreEqual(m.Value.ToString(), actual.AsDecimal128.ToString(), path + " 小数位要保留"); + break; + default: + Assert.AreEqual(expected, actual, path); + break; + } + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/CatalogAndCopierTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/CatalogAndCopierTests.cs new file mode 100644 index 0000000..12883b7 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/CatalogAndCopierTests.cs @@ -0,0 +1,88 @@ +using MongoDB.Bson; +using MongoDB.Driver; +using VelaShell.Plugin.Mongo.Core; +using VelaShell.Plugin.Mongo.Transfer; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// 分片集合的统计合并、XLSX 列名、复制器整批共用的已有名字集合。 +[TestClass] +public sealed class CatalogAndCopierTests +{ + [TestMethod] + public void CollStatsFromEveryShardAreSummed() + { + BsonDocument Shard(string name, long count, long size, long storage, long indexes, long idIndex) => new() + { + { "shard", name }, + { + "storageStats", new BsonDocument + { + { "count", count }, { "size", size }, { "storageSize", storage }, { "totalIndexSize", indexes }, + { "nindexes", 2 }, { "avgObjSize", size / Math.Max(1, count) }, { "indexSizes", new BsonDocument { { "_id_", idIndex }, { "sku_1", indexes - idIndex } } } + } + } + }; + BsonDocument merged = MongoConnection.MergeShardStorage([Shard("rs0", 100, 10_000, 4096, 2048, 1024), Shard("rs1", 300, 30_000, 8192, 4096, 3072)]); + Assert.AreEqual(400L, merged["count"].ToInt64()); + Assert.AreEqual(40_000L, merged["size"].ToInt64()); + Assert.AreEqual(12_288L, merged["storageSize"].ToInt64()); + Assert.AreEqual(6144L, merged["totalIndexSize"].ToInt64()); + Assert.AreEqual(100L, merged["avgObjSize"].ToInt64()); + Assert.AreEqual(2L, merged["nindexes"].ToInt64()); + Assert.AreEqual(4096L, merged["indexSizes"]["_id_"].ToInt64()); + Assert.AreEqual(2, merged["shards"].AsBsonDocument.ElementCount); + + BsonDocument single = MongoConnection.MergeShardStorage([Shard("rs0", 5, 50, 4096, 100, 50)]); + Assert.AreEqual(5L, single["count"].ToInt64()); + Assert.IsFalse(single.Contains("shards"), "未分片原样返回"); + Assert.AreEqual(0, MongoConnection.MergeShardStorage([]).ElementCount); + } + + [TestMethod] + public void XlsxColumnNames() + { + Assert.AreEqual("A", XlsxWriter.ColumnName(0)); + Assert.AreEqual("Z", XlsxWriter.ColumnName(25)); + Assert.AreEqual("AA", XlsxWriter.ColumnName(26)); + Assert.AreEqual("AZ", XlsxWriter.ColumnName(51)); + Assert.AreEqual("ZZ", XlsxWriter.ColumnName(701)); + Assert.AreEqual("AAA", XlsxWriter.ColumnName(702)); + Assert.AreEqual("XFD", XlsxWriter.ColumnName(16383)); + } + + [TestMethod] + public async Task CopierUsesAndUpdatesTheBatchNameSet() + { + await TestServer.RequireAsync(); + await using MongoConnection source = await TestServer.OpenAsync(); + await using MongoConnection target = await MongoConnection.ConnectAsync(TestServer.Uri, CancellationToken.None); + string from = $"velashell_copyset_{Guid.NewGuid():N}"[..28]; + string to = from[..^2] + "to"; + try + { + await source.Collection(from, "a").InsertManyAsync(Enumerable.Range(0, 10).Select(static i => new BsonDocument("i", i))); + CollectionInfo info = (await source.ListCollectionsAsync(from)).Single(static c => c.Name == "a"); + HashSet existing = await CollectionCopier.ExistingNamesAsync(target, to, CancellationToken.None); + Assert.IsEmpty(existing); + var loc = new Loc("zh-CN"); + XferOutcome first = await CollectionCopier.CopyAsync(source, from, target, to, new XferItem("a", XferObjectKind.Collection, info, XferAction.Create), + new XferOptions(), new XferPauseGate(), static _ => { }, static (_, _) => { }, loc, CancellationToken.None, existing); + Assert.AreEqual(10, first.Copied); + Assert.Contains("a", existing, "建了新集合要补进整批的名字集合"); + _ = await Assert.ThrowsAsync(() => CollectionCopier.CopyAsync(source, from, target, to, + new XferItem("a", XferObjectKind.Collection, info, XferAction.Create), new XferOptions(), new XferPauseGate(), static _ => { }, static (_, _) => { }, + loc, CancellationToken.None, existing)); + XferOutcome appended = await CollectionCopier.CopyAsync(source, from, target, to, new XferItem("a", XferObjectKind.Collection, info, XferAction.Append), + new XferOptions(), new XferPauseGate(), static _ => { }, static (_, _) => { }, loc, CancellationToken.None); + Assert.AreEqual(10, appended.Copied + appended.Failed, "不给集合时逐个按名字问服务器:已存在,不重建,照常追加(同 _id 记失败)"); + long count = await target.Collection(to, "a").CountDocumentsAsync(FilterDefinition.Empty); + Assert.AreEqual(10L, count); + } + finally + { + await source.Client.DropDatabaseAsync(from); + await target.Client.DropDatabaseAsync(to); + } + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/CodeExportLiteralTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/CodeExportLiteralTests.cs new file mode 100644 index 0000000..e5723fa --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/CodeExportLiteralTests.cs @@ -0,0 +1,111 @@ +using MongoDB.Bson; +using VelaShell.Plugin.Mongo.Shell; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// 「导出为代码」的字面量:UUID 要求的客户端设置、Timestamp / Binary / MinKey 的构造器、Int64、NaN / ∞、越界日期, +/// 以及四种语言里字符串的转义(引号、换行、控制字符、U+2028)。 +/// +[TestClass] +public sealed class CodeExportLiteralTests +{ + private static ShellCommand Parse(string text) => ShellParser.Parse(ShellScript.Split(text)[0]); + + private static readonly ShellCommand Insert = Parse( + "db.events.insertOne({ u: UUID(\"3b241101-e2bb-4255-8caf-4136c566a962\"), b: BinData(0, \"AQID\"), ts: Timestamp(1700000000, 3), " + + "n: NumberLong(\"5\"), d: 5.0, nan: NaN, inf: Infinity, ninf: -Infinity, lo: MinKey(), hi: MaxKey() })"); + + [TestMethod] + public void Python_ConstructorsAndUuidRepresentation() + { + string code = CodeExport.Generate(Insert, "shop", CodeTarget.Python); + Assert.Contains("MongoClient(\"mongodb://localhost:27017\", uuidRepresentation=\"standard\")", code); + Assert.Contains("uuid.UUID(\"3b241101-e2bb-4255-8caf-4136c566a962\")", code); + Assert.Contains("Binary(base64.b64decode(\"AQID\"), 0)", code); + Assert.Contains("Timestamp(1700000000, 3)", code); + Assert.Contains("from bson.timestamp import Timestamp", code); + Assert.Contains("Int64(5)", code); + Assert.Contains("\"d\": 5.0", code); + Assert.Contains("float(\"nan\")", code); + Assert.Contains("float(\"inf\")", code); + Assert.Contains("float(\"-inf\")", code); + Assert.Contains("MinKey()", code); + Assert.DoesNotContain("NaN.0", code); + + string plain = CodeExport.Generate(Parse("db.events.find({ a: 1 })"), "shop", CodeTarget.Python); + Assert.DoesNotContain("uuidRepresentation", plain, "没用到 UUID 就不改客户端设置"); + } + + [TestMethod] + public void Java_ConstructorsAndUuidRepresentation() + { + string code = CodeExport.Generate(Insert, "shop", CodeTarget.Java); + Assert.Contains(".uuidRepresentation(UuidRepresentation.STANDARD)", code); + Assert.Contains("import org.bson.UuidRepresentation;", code); + Assert.Contains("UUID.fromString(\"3b241101-e2bb-4255-8caf-4136c566a962\")", code); + Assert.Contains("new Binary((byte) 0, Base64.getDecoder().decode(\"AQID\"))", code); + Assert.Contains("new BsonTimestamp(1700000000, 3)", code); + Assert.Contains("Double.NaN", code); + Assert.Contains("Double.POSITIVE_INFINITY", code); + Assert.Contains("Double.NEGATIVE_INFINITY", code); + Assert.Contains("new MaxKey()", code); + Assert.DoesNotContain("NaN.0", code); + Assert.DoesNotContain("\"Timestamp", code, "不再把 Timestamp 写成字符串"); + } + + [TestMethod] + public void Node_And_CSharp_Constructors() + { + string node = CodeExport.Generate(Insert, "shop", CodeTarget.NodeJs); + Assert.Contains("new Binary(Buffer.from(\"AQID\", \"base64\"), 0)", node); + Assert.Contains("new Timestamp({ t: 1700000000, i: 3 })", node); + Assert.Contains("new Double(5)", node); + Assert.Contains("nan: NaN", node); + Assert.Contains("inf: Infinity", node); + Assert.Contains("new MinKey()", node); + + string csharp = CodeExport.Generate(Insert, "shop", CodeTarget.CSharp); + Assert.Contains("double.NaN", csharp); + Assert.Contains("double.PositiveInfinity", csharp); + Assert.Contains("new BsonTimestamp(1700000000, 3)", csharp); + Assert.DoesNotContain("NaN.0", csharp); + } + + [TestMethod] + public void OutOfRangeDatesUseMillisecondConstructors() + { + var command = new ShellCommand + { + Statement = new ShellStatement(0, "", 0), + Kind = ShellCommandKind.Collection, + Collection = "events", + Method = new ShellCall("insertOne", 0, [new ShellArgument("", 0, new BsonDocument("at", new BsonDateTime(253402300800000L)))]) + }; + Assert.Contains("new BsonDateTime(253402300800000L)", CodeExport.Generate(command, "shop", CodeTarget.CSharp)); + Assert.Contains("DatetimeMS(253402300800000)", CodeExport.Generate(command, "shop", CodeTarget.Python)); + Assert.Contains("new Date(253402300800000)", CodeExport.Generate(command, "shop", CodeTarget.NodeJs)); + Assert.Contains("new Date(253402300800000L)", CodeExport.Generate(command, "shop", CodeTarget.Java)); + } + + [TestMethod] + [DataRow(CodeTarget.CSharp)] + [DataRow(CodeTarget.Python)] + [DataRow(CodeTarget.NodeJs)] + [DataRow(CodeTarget.Java)] + public void StringsAreEscaped(CodeTarget target) + { + var command = new ShellCommand + { + Statement = new ShellStatement(0, "", 0), + Kind = ShellCommandKind.Collection, + Collection = "c\"q", + Method = new ShellCall("find", 0, [new ShellArgument("", 0, new BsonDocument("note", "a\"b\\c\nd\re\tf\u0001g" + (char)0x2028 + "h"))]) + }; + string code = CodeExport.Generate(command, "shop", target); + Assert.Contains("\"a\\\"b\\\\c\\nd\\re\\tf\\u0001g\\u2028h\"", code, target.ToString()); + Assert.Contains("\"c\\\"q\"", code, "集合名同样转义"); + Assert.DoesNotContain(((char)0x2028).ToString(), code); + Assert.DoesNotContain("\u0001", code); + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/CollectionTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/CollectionTests.cs index e60e0e8..9596951 100644 --- a/tests/VelaShell.Plugin.Mongo.Tests/CollectionTests.cs +++ b/tests/VelaShell.Plugin.Mongo.Tests/CollectionTests.cs @@ -514,7 +514,7 @@ public void Keyboard_editing_in_the_grid_stages_the_value() => Screens.OnUi(stat }); [TestMethod] - public void Fifty_thousand_rows_stay_responsive() => Screens.OnUi(static async () => + public void A_full_page_of_ten_thousand_rows_stays_responsive() => Screens.OnUi(static async () => { await TestServer.RequireAsync(); var client = new MongoClient(TestServer.Uri); @@ -532,18 +532,21 @@ public void Fifty_thousand_rows_stay_responsive() => Screens.OnUi(static async ( await using Workbench bench = await Screens.OpenWorkbenchAsync(database); CollectionTabViewModel tab = await OpenTabAsync(bench, database, "big"); tab.LimitText = "50000"; + Assert.IsTrue(tab.LimitInvalid, "a page is capped at 10,000 documents — more means paging or exporting"); + tab.LimitText = CollectionTabViewModel.MaxPageSize.ToString(System.Globalization.CultureInfo.InvariantCulture); + Assert.IsFalse(tab.LimitInvalid); var watch = System.Diagnostics.Stopwatch.StartNew(); await tab.RunQueryAsync(resetPage: true); await Screens.PumpAsync(10); watch.Stop(); - Assert.HasCount(50_000, tab.Rows); - Assert.IsLessThan(TimeSpan.FromSeconds(8), watch.Elapsed, $"50k rows took {watch.Elapsed}"); + Assert.HasCount(CollectionTabViewModel.MaxPageSize, tab.Rows); + Assert.IsLessThan(TimeSpan.FromSeconds(8), watch.Elapsed, $"10k rows took {watch.Elapsed}"); var stage = System.Diagnostics.Stopwatch.StartNew(); _ = tab.Stage(tab.Rows[10], "name", "changed"); stage.Stop(); - Assert.IsLessThan(TimeSpan.FromMilliseconds(500), stage.Elapsed, $"staging one cell in a 50k page took {stage.Elapsed}"); - ViewOf(bench).Grid.List.ScrollIntoView(tab.Rows[40_000]); + Assert.IsLessThan(TimeSpan.FromMilliseconds(500), stage.Elapsed, $"staging one cell in a 10k page took {stage.Elapsed}"); + ViewOf(bench).Grid.List.ScrollIntoView(tab.Rows[8_000]); await Screens.PumpAsync(10); tab.Staging.Clear(); } diff --git a/tests/VelaShell.Plugin.Mongo.Tests/CsvTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/CsvTests.cs index 4c5a453..af3c33d 100644 --- a/tests/VelaShell.Plugin.Mongo.Tests/CsvTests.cs +++ b/tests/VelaShell.Plugin.Mongo.Tests/CsvTests.cs @@ -138,8 +138,8 @@ public void Export_writer_flattens_nested_fields_and_applies_conversions() Assert.IsTrue(reader.TryRead(out string[] header)); Assert.AreEqual("id,orderNo,customer.name,customer.level,total,createdAt,items,note", string.Join(",", header)); Assert.IsTrue(reader.TryRead(out string[] cells)); - string local = created.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); - Assert.AreSequenceEqual(["66f5c2a1b04e1c3a5d7e9f01", "SO2609-10400", "陈立", "VIP", "1299.50", local], cells[..6]); + // 默认无损:Decimal128 原样全精度,日期 ISO 8601 UTC(本地时间 / 保留两位要在字段表里显式选)。 + Assert.AreSequenceEqual(["66f5c2a1b04e1c3a5d7e9f01", "SO2609-10400", "陈立", "VIP", "1299.5", "2026-09-27T07:00:00Z"], cells[..6]); BsonArray items = MongoDB.Bson.Serialization.BsonSerializer.Deserialize(cells[6]); Assert.AreEqual(doc["items"], items, "arrays are written as JSON strings that parse back to the same value"); Assert.AreEqual("", cells[7], "null is left empty by default"); diff --git a/tests/VelaShell.Plugin.Mongo.Tests/DocumentEditorTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/DocumentEditorTests.cs index f21b080..d0a41b7 100644 --- a/tests/VelaShell.Plugin.Mongo.Tests/DocumentEditorTests.cs +++ b/tests/VelaShell.Plugin.Mongo.Tests/DocumentEditorTests.cs @@ -906,11 +906,11 @@ public void Command_text_follows_the_design_layout() var update = new BsonDocument("$set", new BsonDocument { ["status"] = "shipped", ["discount"] = -20.0 }); string text = DocumentEditorFormat.Command("orders", "updateOne", new BsonDocument("_id", ObjectId.Parse("66f5c2a1d38b5e1a0c7fe3b7")), update); Assert.AreEqual( - "db.orders.updateOne(\n { _id: ObjectId(\"66f5c2a1d38b5e1a0c7fe3b7\") },\n { $set: {\n status: \"shipped\",\n discount: -20\n } }\n)", + "db.orders.updateOne(\n { _id: ObjectId(\"66f5c2a1d38b5e1a0c7fe3b7\") },\n { $set: {\n status: \"shipped\",\n discount: -20.0\n } }\n)", text); update["$unset"] = new BsonDocument("note", ""); string two = DocumentEditorFormat.Command("orders", "updateOne", new BsonDocument("_id", 1), update); - Assert.Contains(" discount: -20\n },\n $unset: {\n note: \"\"\n } }\n)", two); + Assert.Contains(" discount: -20.0\n },\n $unset: {\n note: \"\"\n } }\n)", two); } [TestMethod] diff --git a/tests/VelaShell.Plugin.Mongo.Tests/ExplainPlanSbeTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/ExplainPlanSbeTests.cs new file mode 100644 index 0000000..0d62a00 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/ExplainPlanSbeTests.cs @@ -0,0 +1,116 @@ +using MongoDB.Bson; +using VelaShell.Plugin.Mongo.Analysis; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// SBE(explainVersion: "2")形态的执行计划:executionStages 是槽位执行树(project / group / ixseek), +/// 阶段树要按 winningPlan.queryPlan 建。样本取自 MongoDB 9.0.8 的真实输出(删掉了无关字段)。 +/// +[TestClass] +public sealed class ExplainPlanSbeTests +{ + /// + /// db.orders.explain("allPlansExecution").aggregate([{ $match: { status: "paid" } }, { $group: { _id: "$status", n: { $sum: 1 } } }]), + /// 两个候选索引 status_1_createdAt_-1 / status_1_total_1,$group 下推进 SBE。 + /// + private static BsonDocument SbeGroup() => BsonDocument.Parse(""" + { + "explainVersion": "2", + "queryPlanner": { + "namespace": "shop.orders", + "parsedQuery": { "status": { "$eq": "paid" } }, + "optimizedPipeline": true, + "winningPlan": { + "isCached": false, + "queryPlan": { + "stage": "GROUP", "planNodeId": 3, + "inputStage": { + "stage": "PROJECTION_COVERED", "planNodeId": 2, "transformBy": { "status": true, "_id": false }, + "inputStage": { + "stage": "IXSCAN", "planNodeId": 1, "keyPattern": { "status": 1, "createdAt": -1 }, "indexName": "status_1_createdAt_-1", + "direction": "forward", "indexBounds": { "status": [ "[\"paid\", \"paid\"]" ], "createdAt": [ "[MaxKey, MinKey]" ] } } } }, + "slotBasedPlan": { "slots": "$$RESULT=s6 env: { }", "stages": "[3] project ... [1] ixseek ..." } + }, + "rejectedPlans": [ + { "isCached": false, "stage": "PROJECTION_COVERED", "transformBy": { "status": 1, "_id": 0 }, + "inputStage": { "stage": "IXSCAN", "keyPattern": { "status": 1, "total": 1 }, "indexName": "status_1_total_1", "direction": "forward", + "indexBounds": { "status": [ "[\"paid\", \"paid\"]" ], "total": [ "[MinKey, MaxKey]" ] } } } + ] + }, + "executionStats": { + "executionSuccess": true, "nReturned": 1, "executionTimeMillis": 2, "totalKeysExamined": 100, "totalDocsExamined": 0, + "executionStages": { + "stage": "project", "planNodeId": 3, "nReturned": 1, "executionTimeMillisEstimate": 0, "opens": 1, "closes": 1, "isEOF": 1, + "inputStage": { + "stage": "group", "planNodeId": 3, "nReturned": 1, "executionTimeMillisEstimate": 0, "isEOF": 1, "groupBySlots": [ { "$numberLong": "5" } ], + "inputStage": { + "stage": "project", "planNodeId": 3, "nReturned": 100, "executionTimeMillisEstimate": 0, "isEOF": 1, + "inputStage": { + "stage": "ixseek", "planNodeId": 1, "nReturned": 100, "executionTimeMillisEstimate": 0, "isEOF": 1, + "indexName": "status_1_createdAt_-1", "keysExamined": 100, "seeks": 1, "numReads": 101 } } } }, + "allPlansExecution": [ + { "nReturned": 100, "executionTimeMillisEstimate": 0, "totalKeysExamined": 100, "totalDocsExamined": 0, "score": 2.9903990099009903, + "executionStages": { "isCached": false, "stage": "PROJECTION_COVERED", "nReturned": 100, "works": 101, "transformBy": { "status": 1, "_id": 0 }, + "inputStage": { "stage": "IXSCAN", "nReturned": 100, "works": 101, "keyPattern": { "status": 1, "createdAt": -1 }, "indexName": "status_1_createdAt_-1", "keysExamined": 100 } } }, + { "nReturned": 100, "executionTimeMillisEstimate": 0, "totalKeysExamined": 100, "totalDocsExamined": 0, "score": 2.9903990099009903, + "executionStages": { "isCached": false, "stage": "PROJECTION_COVERED", "nReturned": 100, "works": 101, "transformBy": { "status": 1, "_id": 0 }, + "inputStage": { "stage": "IXSCAN", "nReturned": 100, "works": 101, "keyPattern": { "status": 1, "total": 1 }, "indexName": "status_1_total_1", "keysExamined": 100 } } } + ] + }, + "command": { "aggregate": "orders", "pipeline": [ { "$match": { "status": "paid" } }, { "$group": { "_id": "$status", "n": { "$sum": 1 } } } ], "cursor": {}, "$db": "shop" }, + "ok": 1 + } + """); + + [TestMethod] + public void Sbe_TreeComesFromTheQueryPlanNotTheSlotTree() + { + var plan = ExplainPlan.Parse(SbeGroup()); + Assert.AreEqual("IXSCAN,PROJECTION_COVERED,GROUP", string.Join(",", plan.Stages.Select(static s => s.Name))); + Assert.AreEqual("IXSCAN status_1_createdAt_-1", plan.Summary); + Assert.IsTrue(plan.IsAggregate); + Assert.IsTrue(plan.HasExecutionStats); + Assert.IsFalse(plan.Tree.Any(static s => s.Name is "project" or "group" or "ixseek"), "槽位阶段不进树"); + } + + [TestMethod] + public void Sbe_TotalsFromTopLevelAndStageStatsByPlanNodeId() + { + var plan = ExplainPlan.Parse(SbeGroup()); + Assert.AreEqual(1L, plan.NReturned); + Assert.AreEqual(100L, plan.TotalKeysExamined); + Assert.AreEqual(0L, plan.TotalDocsExamined); + Assert.AreEqual(2L, plan.TotalMs); + ExplainStage scan = plan.Stages[0]; + Assert.AreEqual(100L, scan.NReturned, "planNodeId 1 → ixseek"); + Assert.AreEqual(100L, scan.KeysExamined); + Assert.IsNull(scan.DocsExamined, "槽位树里没有对应量,留空"); + Assert.IsNull(scan.Works); + Assert.AreEqual(1L, plan.Stages[2].NReturned, "GROUP 取 planNodeId 3 最外层的 project"); + Assert.IsNull(plan.Stages[1].NReturned, "planNodeId 2 在槽位树里没有阶段"); + } + + [TestMethod] + public void Sbe_CandidatesMatchTrialRunsBeforeTheGroupPushdown() + { + var plan = ExplainPlan.Parse(SbeGroup()); + Assert.HasCount(2, plan.Candidates); + Assert.IsTrue(plan.Candidates[0].Winner); + Assert.AreEqual("IXSCAN status_1_createdAt_-1 → PROJECTION_COVERED → GROUP", plan.Candidates[0].Chain); + Assert.AreEqual(101L, plan.Candidates[0].Works); + Assert.IsFalse(plan.Candidates[1].Winner); + Assert.AreEqual(101L, plan.Candidates[1].Works); + } + + [TestMethod] + public void Sbe_WithoutExecutionStatsStillBuildsTheTree() + { + BsonDocument explain = SbeGroup(); + explain.Remove("executionStats"); + var plan = ExplainPlan.Parse(explain); + Assert.AreEqual("IXSCAN,PROJECTION_COVERED,GROUP", string.Join(",", plan.Stages.Select(static s => s.Name))); + Assert.IsNull(plan.Stages[0].NReturned); + Assert.IsFalse(plan.HasExecutionStats); + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/ImportRunnerTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/ImportRunnerTests.cs new file mode 100644 index 0000000..ba42ccf --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/ImportRunnerTests.cs @@ -0,0 +1,133 @@ +using System.Text; +using MongoDB.Bson; +using MongoDB.Driver; +using VelaShell.Plugin.Mongo.Bson; +using VelaShell.Plugin.Mongo.Core; +using VelaShell.Plugin.Mongo.Transfer; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// 导入执行器的边界:出错即停时出错行之前的好行照样落盘、取消返回部分结果而不是抛出、 +/// 备份文件名按导出同一套规则清洗(集合名里的 : 不能落成 NTFS 备用数据流)。 +/// 写服务器的测试只碰自己建的 velashell_transfer_* 库,收尾 drop 掉。 +/// +[TestClass] +public sealed class ImportRunnerTests +{ + private static readonly ImportColumn[] Columns = + [ + new() { Source = "n", Index = 0, Target = "n", Kind = BsonKind.Int32 }, + new() { Source = "name", Index = 1, Target = "name", Kind = BsonKind.String } + ]; + + [TestMethod] + public async Task StopOnError_flushes_the_rows_before_the_bad_one() + { + await TestServer.RequireAsync(); + await using MongoConnection connection = await TestServer.OpenAsync(); + string db = $"velashell_transfer_{Guid.NewGuid():N}"[..28]; + string dir = ExportTests.TempDir(); + try + { + // 第 6 行的 n 不是整数:前 5 行还攒在批里(批大小 1000),叫停时要先写进去。 + string csv = WriteCsv(dir, 10, badRow: 6); + ImportResult result = await ImportRunner.RunAsync(connection, Job(db, "items", csv, dir) with { StopOnError = true }, + new Loc("zh-CN"), null, CancellationToken.None); + Assert.IsTrue(result.Stopped); + Assert.IsFalse(result.Cancelled); + Assert.IsNull(result.Failure); + Assert.AreEqual(6, result.Rows); + Assert.AreEqual(5, result.Inserted); + Assert.AreEqual(1, result.Skipped); + Assert.IsNotNull(result.ErrorReport); + long count = await connection.Collection(db, "items").CountDocumentsAsync(FilterDefinition.Empty); + Assert.AreEqual(5, count); + } + finally + { + await connection.Client.DropDatabaseAsync(db); + Directory.Delete(dir, recursive: true); + } + } + + [TestMethod] + public async Task Cancellation_returns_a_partial_result_instead_of_throwing() + { + await TestServer.RequireAsync(); + await using MongoConnection connection = await TestServer.OpenAsync(); + string db = $"velashell_transfer_{Guid.NewGuid():N}"[..28]; + string dir = ExportTests.TempDir(); + try + { + string csv = WriteCsv(dir, 10, badRow: 2); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + ImportResult result = await ImportRunner.RunAsync(connection, Job(db, "items", csv, dir), new Loc("zh-CN"), null, cts.Token); + Assert.IsTrue(result.Cancelled); + Assert.IsNull(result.Failure); + Assert.AreEqual(0, result.Inserted); + } + finally + { + await connection.Client.DropDatabaseAsync(db); + Directory.Delete(dir, recursive: true); + } + } + + [TestMethod] + public async Task Backup_file_name_is_sanitized() + { + await TestServer.RequireAsync(); + await using MongoConnection connection = await TestServer.OpenAsync(); + string db = $"velashell_transfer_{Guid.NewGuid():N}"[..28]; + string dir = ExportTests.TempDir(); + const string collection = "imp:bk"; + try + { + await connection.Collection(db, collection).InsertManyAsync( + [new BsonDocument { { "n", 1 }, { "name", "old" } }, new BsonDocument { { "n", 2 }, { "name", "old" } }]); + string csv = WriteCsv(dir, 3, badRow: 0); + ImportResult result = await ImportRunner.RunAsync(connection, Job(db, collection, csv, dir) with + { + Rules = new ImportRules { Mode = ImportWriteMode.Upsert, MatchKey = "n" }, + Backup = true + }, new Loc("zh-CN"), null, CancellationToken.None); + Assert.IsNull(result.Failure); + Assert.IsNotNull(result.BackupFile); + string name = Path.GetFileName(result.BackupFile); + Assert.DoesNotContain(":", name); + Assert.AreEqual(dir, Path.GetDirectoryName(result.BackupFile)); + string[] lines = await File.ReadAllLinesAsync(result.BackupFile); + Assert.HasCount(2, lines); + } + finally + { + await connection.Client.DropDatabaseAsync(db); + Directory.Delete(dir, recursive: true); + } + } + + private static ImportJob Job(string db, string collection, string csv, string dir) => new() + { + Database = db, + Collection = collection, + Source = ImportSource.Sniff(csv), + Columns = Columns, + Rules = new ImportRules(), + ReportDirectory = dir + }; + + /// n,name 两列;(从 1 数,0 = 没有)那一行的 n 不是整数。 + private static string WriteCsv(string dir, int rows, int badRow) + { + var text = new StringBuilder("n,name\r\n"); + for (int i = 1; i <= rows; i++) + { + _ = text.Append(i == badRow ? "abc" : i.ToString(System.Globalization.CultureInfo.InvariantCulture)).Append(",row").Append(i).Append("\r\n"); + } + string path = Path.Combine(dir, "items.csv"); + File.WriteAllText(path, text.ToString(), new UTF8Encoding(false)); + return path; + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorProtectionTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorProtectionTests.cs new file mode 100644 index 0000000..eac5c0e --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorProtectionTests.cs @@ -0,0 +1,65 @@ +using MongoDB.Bson; +using VelaShell.Plugin.Mongo.Analysis; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// 索引顾问不建议删的索引:TTL、分片键的支撑索引、排序规则不同的"前缀"。 +[TestClass] +public sealed class IndexAdvisorProtectionTests +{ + private static readonly DateTime Now = new(2026, 9, 27, 12, 0, 0, DateTimeKind.Utc); + + private static AdvisorIndex Index(string name, string key, long? ops = 100, BsonDocument? extra = null) + { + BsonDocument keyDoc = BsonDocument.Parse(key); + var spec = new BsonDocument { { "v", 2 }, { "key", keyDoc }, { "name", name } }; + if (extra is not null) + { + _ = spec.Merge(extra); + } + return new AdvisorIndex(name, keyDoc, spec, ops, Now.AddDays(-30), 64L << 20); + } + + [TestMethod] + public void TtlIndexIsNeverRedundantOrUnused() + { + AdvisorIndex[] indexes = + [ + Index("createdAt_1", "{ createdAt: 1 }", ops: 0, extra: new BsonDocument("expireAfterSeconds", 3600)), + Index("createdAt_1_status_1", "{ createdAt: 1, status: 1 }") + ]; + Assert.IsEmpty(IndexAdvisor.Advise([], indexes, Now), "TTL 索引删了过期文档就不再清理"); + } + + [TestMethod] + public void ShardKeyIndexIsNeverRedundantOrUnused() + { + AdvisorIndex[] indexes = + [ + Index("tenant_1", "{ tenant: 1 }", ops: 0), + Index("tenant_1_createdAt_-1", "{ tenant: 1, createdAt: -1 }") + ]; + Assert.IsNotEmpty(IndexAdvisor.Advise([], indexes, Now), "未分片时照常建议"); + IReadOnlyList sharded = IndexAdvisor.Advise([], indexes, Now, BsonDocument.Parse("{ tenant: 1 }")); + Assert.IsFalse(sharded.Any(static a => a.Index?.Name == "tenant_1"), "分片键的支撑索引不能删"); + } + + [TestMethod] + public void DifferentCollationIsNotARedundantPrefix() + { + var caseInsensitive = new BsonDocument("collation", new BsonDocument { { "locale", "en" }, { "strength", 2 } }); + AdvisorIndex[] indexes = + [ + Index("name_1", "{ name: 1 }", extra: caseInsensitive), + Index("name_1_age_1", "{ name: 1, age: 1 }") + ]; + Assert.IsFalse(IndexAdvisor.Advise([], indexes, Now).Any(static a => a.Kind == AdvisorKind.RedundantIndex)); + + AdvisorIndex[] same = + [ + Index("name_1", "{ name: 1 }", extra: caseInsensitive), + Index("name_1_age_1", "{ name: 1, age: 1 }", extra: caseInsensitive) + ]; + Assert.AreEqual("name_1", IndexAdvisor.Advise([], same, Now).Single(static a => a.Kind == AdvisorKind.RedundantIndex).Index!.Name); + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorTests.cs index 909b039..1df0117 100644 --- a/tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorTests.cs +++ b/tests/VelaShell.Plugin.Mongo.Tests/IndexAdvisorTests.cs @@ -180,7 +180,9 @@ public void Unused_needs_a_full_observation_window() Index("note_text", BsonDocument.Parse("{ _fts: 'text', _ftsx: 1 }"), ops: 0, ageDays: 30), Index("paidAt_1", BsonDocument.Parse("{ paidAt: 1 }"), ops: 0, ageDays: 2), Index("sku_1", BsonDocument.Parse("{ sku: 1 }"), ops: 5, ageDays: 30), - Index("x_1", BsonDocument.Parse("{ x: 1 }"), ops: null, ageDays: 30) + Index("x_1", BsonDocument.Parse("{ x: 1 }"), ops: null, ageDays: 30), + // 唯一索引在约束写入,ops 为 0 也不能建议删。 + Index("orderNo_1", BsonDocument.Parse("{ orderNo: 1 }"), ops: 0, ageDays: 30, extra: new BsonDocument("unique", true)) ]; AdvisorSuggestion unused = IndexAdvisor.Advise([], indexes, Now).Single(); Assert.AreEqual(AdvisorKind.UnusedIndex, unused.Kind); diff --git a/tests/VelaShell.Plugin.Mongo.Tests/ObjectsTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/ObjectsTests.cs index cf5486c..fc0fef9 100644 --- a/tests/VelaShell.Plugin.Mongo.Tests/ObjectsTests.cs +++ b/tests/VelaShell.Plugin.Mongo.Tests/ObjectsTests.cs @@ -195,11 +195,13 @@ public void Drop_and_empty_go_through_confirmation_and_hit_the_server() => Scree ObjectsTabViewModel tab = bench.ViewModel.Tabs.OfType().Single(t => t.Database == db); await tab.ReloadAsync(); - // 清空:确认框不要求手打(开发环境、未开写前确认),点确认即删光文档。 + // 清空:与删除同口径 —— 集合里有数据就要手打名称(哪怕没开写前确认),确认后删光文档。 tab.SelectedItem = tab.Items.Single(static i => i.Name == "keep"); tab.EmptyCommand.Execute(null); ConfirmDialogViewModel empty = await WaitForConfirmAsync(bench); - Assert.IsFalse(empty.RequiresTyping); + Assert.IsTrue(empty.RequiresTyping); + Assert.IsFalse(empty.CanConfirm); + empty.Typed = "keep"; empty.ConfirmCommand.Execute(null); await WaitUntilAsync(() => database.GetCollection("keep").CountDocuments(FilterDefinition.Empty) == 0); long left = await database.GetCollection("keep").CountDocumentsAsync(FilterDefinition.Empty); diff --git a/tests/VelaShell.Plugin.Mongo.Tests/ProfileStoreTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/ProfileStoreTests.cs new file mode 100644 index 0000000..5af6c77 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/ProfileStoreTests.cs @@ -0,0 +1,54 @@ +using VelaShell.Plugin.Mongo.Core; +using VelaShell.PluginSdk.Testing; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// 已保存连接的读改写互斥、只回写"最近连上"、解析缓存的失效。 +[TestClass] +public sealed class ProfileStoreTests +{ + [TestMethod] + public async Task ConcurrentSavesDoNotLoseEachOther() + { + var context = new TestPluginContext { PluginId = "velashell.mongo" }; + var stores = new[] { new MongoProfileStore(context), new MongoProfileStore(context) }; + MongoProfile[] profiles = [.. Enumerable.Range(0, 64).Select(static i => new MongoProfile { Name = $"p{i}", Host = "h" })]; + await Task.WhenAll(profiles.Select((p, i) => Task.Run(() => stores[i % 2].SaveAsync(p, null)))); + IReadOnlyList saved = await stores[0].LoadAsync(); + Assert.HasCount(64, saved, "两份 store 共用同一把锁,并发保存一条都不丢"); + } + + [TestMethod] + public async Task TouchOnlyChangesTheTimestamp() + { + var context = new TestPluginContext { PluginId = "velashell.mongo" }; + var store = new MongoProfileStore(context); + var profile = new MongoProfile { Name = "old", Host = "h" }; + await store.SaveAsync(profile, null); + MongoProfile stale = profile.Clone(); + + profile.Name = "edited in the dialog"; + await store.SaveAsync(profile, null); + var at = new DateTimeOffset(2026, 12, 1, 8, 0, 0, TimeSpan.Zero); + Assert.IsTrue(await store.TouchLastConnectedAsync(stale.Id, at)); + + MongoProfile stored = (await store.LoadAsync()).Single(); + Assert.AreEqual("edited in the dialog", stored.Name, "回写时间不能把对话框刚存的修改盖回去"); + Assert.AreEqual(at, stored.LastConnectedAt); + Assert.IsFalse(await store.TouchLastConnectedAsync("missing", at)); + } + + [TestMethod] + public void ParsedIsCachedAndInvalidatedBySet() + { + var profile = new MongoProfile(); + MongoSettings first = profile.Parsed; + Assert.AreSame(first, profile.Parsed, "不重复解析"); + Assert.AreEqual(MongoEnvironment.Development, profile.Environment); + profile.Set(MongoSettings.KeyEnvironment, "production"); + Assert.AreEqual(MongoEnvironment.Production, profile.Environment); + Assert.IsTrue(profile.Parsed.ReadOnly); + profile.Settings = []; + Assert.AreEqual(MongoEnvironment.Development, profile.Environment); + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/QueryHistoryRedactionTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/QueryHistoryRedactionTests.cs new file mode 100644 index 0000000..cfceb1b --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/QueryHistoryRedactionTests.cs @@ -0,0 +1,50 @@ +using VelaShell.PluginSdk.Testing; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// 查询历史落盘前脱敏、截断:口令只在宿主的密钥库里,不躺在明文的历史表里。 +[TestClass] +public sealed class QueryHistoryRedactionTests +{ + [TestMethod] + [DataRow("db.createUser({ user: \"ops\", pwd: \"s3cr3t\", roles: [] })", "db.createUser({ user: \"ops\", pwd: \"***\", roles: [] })")] + [DataRow("db.runCommand({ createUser: 'ops', pwd: 'it\\'s', roles: [] })", "db.runCommand({ createUser: 'ops', pwd: '***', roles: [] })")] + [DataRow("db.updateUser(\"ops\", { \"pwd\" : \"new\" })", "db.updateUser(\"ops\", { \"pwd\" : \"***\" })")] + [DataRow("db.auth({ user: \"u\", password: \"p\" })", "db.auth({ user: \"u\", password: \"***\" })")] + [DataRow("db.runCommand({ createUser: \"u\", PasswordDigest: `abc` })", "db.runCommand({ createUser: \"u\", PasswordDigest: `***` })")] + [DataRow("db.changeUserPassword(\"ops\", \"hunter2\")", "db.changeUserPassword(\"ops\", \"***\")")] + [DataRow("db.auth('ops', 'hunter2')", "db.auth('ops', '***')")] + [DataRow("// mongodb://ops:hunter2@10.0.0.1/shop", "// mongodb://ops:****@10.0.0.1/shop")] + public void PasswordsAreMasked(string input, string expected) => + Assert.AreEqual(expected, MongoStore.RedactHistoryText(input)); + + [TestMethod] + [DataRow("db.createUser({ user: \"ops\", pwd: passwordPrompt(), roles: [] })")] + [DataRow("db.orders.find({ status: \"paid\" })")] + [DataRow("db.users.find({ passwordHint: \"x\" })")] + [DataRow("db.changeUserPassword(\"ops\", passwordPrompt())")] + public void NonSecretsAreUntouched(string input) => + Assert.AreEqual(input, MongoStore.RedactHistoryText(input)); + + [TestMethod] + public void LongTextIsTruncated() + { + string text = "db.a.find({ x: \"" + new string('y', 20_000) + "\" })"; + string stored = MongoStore.PrepareHistoryText(text); + Assert.AreEqual(MongoStore.HistoryTextLimit + 1, stored.Length); + Assert.EndsWith("…", stored); + } + + [TestMethod] + public async Task AppendedHistoryIsRedactedOnDisk() + { + var context = new TestPluginContext { PluginId = "velashell.mongo" }; + var store = new MongoStore(context); + await store.AppendQueryHistoryAsync("conn", new QueryHistoryEntry(DateTimeOffset.UtcNow, "admin", + "db.createUser({ user: \"ops\", pwd: \"s3cr3t\", roles: [] })", 3, true)); + IReadOnlyList history = await store.LoadQueryHistoryAsync("conn"); + Assert.HasCount(1, history); + Assert.DoesNotContain("s3cr3t", history[0].Text); + Assert.Contains("pwd: \"***\"", history[0].Text); + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/ShellGuardTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/ShellGuardTests.cs new file mode 100644 index 0000000..fd2c858 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/ShellGuardTests.cs @@ -0,0 +1,177 @@ +using MongoDB.Bson; +using VelaShell.Plugin.Mongo.Core; +using VelaShell.Plugin.Mongo.Shell; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// 写护栏的白名单与 runCommand 后门、游标修饰落到驱动上。解析部分不连服务器;执行部分每个测试自建 +/// velashell_guard_* 库,收尾删掉。 +/// +[TestClass] +public sealed class ShellGuardTests +{ + private sealed class StubGuard : IShellGuard + { + public bool Writable { get; set; } = true; + + public bool Answer { get; set; } = true; + + public bool ConfirmWrites { get; set; } = true; + + public bool DisableDropDatabase { get; set; } = true; + + public List Asked { get; } = []; + + public int WriteChecks { get; private set; } + + public bool EnsureWritable(string database) + { + WriteChecks++; + return Writable; + } + + public Task ConfirmAsync(ShellConfirmation confirmation) + { + Asked.Add(confirmation); + return Task.FromResult(Answer); + } + } + + private static ShellCommand Parse(string text) => ShellParser.Parse(ShellScript.Split(text)[0]); + + [TestMethod] + [DataRow("db.runCommand({ aggregate: \"a\", pipeline: [{ $out: \"b\" }], cursor: {} })")] + [DataRow("db.runCommand({ aggregate: \"a\", pipeline: [{ $match: {} }, { $merge: { into: \"b\" } }], cursor: {} })")] + [DataRow("db.runCommand({ mapReduce: \"a\", map: \"function(){}\", reduce: \"function(){}\", out: \"b\" })")] + [DataRow("db.runCommand({ grantPrivilegesToRole: \"r\", privileges: [] })")] + [DataRow("db.runCommand({ revokePrivilegesFromRole: \"r\", privileges: [] })")] + [DataRow("db.runCommand({ dropAllUsersFromDatabase: 1 })")] + [DataRow("db.runCommand({ dropAllRolesFromDatabase: 1 })")] + [DataRow("db.adminCommand({ bulkWrite: 1, ops: [], nsInfo: [] })")] + [DataRow("db.adminCommand({ shardCollection: \"a.b\", key: { _id: 1 } })")] + [DataRow("db.adminCommand({ replSetStepDown: 60 })")] + [DataRow("db.runCommand({ profile: 2 })")] + [DataRow("db.runCommand({ validate: \"a\", repair: true })")] + [DataRow("db.runCommand({ explain: { delete: \"a\", deletes: [{ q: {}, limit: 0 }] } })")] + [DataRow("db.runCommand({ someFutureCommand: 1 })")] + [DataRow("db.runCommand(\"dropDatabase\")")] + [DataRow("db.aggregate([{ $documents: [{ a: 1 }] }, { $out: \"b\" }])")] + public void WriteCommandsAreRecognised(string text) => Assert.IsTrue(Parse(text).IsWrite, text); + + [TestMethod] + [DataRow("db.runCommand({ find: \"a\", filter: {} })")] + [DataRow("db.runCommand({ aggregate: \"a\", pipeline: [{ $match: {} }], cursor: {} })")] + [DataRow("db.runCommand({ mapReduce: \"a\", map: \"function(){}\", reduce: \"function(){}\", out: { inline: 1 } })")] + [DataRow("db.runCommand({ count: \"a\" })")] + [DataRow("db.runCommand({ distinct: \"a\", key: \"x\" })")] + [DataRow("db.runCommand({ listCollections: 1 })")] + [DataRow("db.runCommand({ collStats: \"a\" })")] + [DataRow("db.runCommand({ dbStats: 1 })")] + [DataRow("db.adminCommand({ serverStatus: 1 })")] + [DataRow("db.adminCommand({ hello: 1 })")] + [DataRow("db.adminCommand({ isMaster: 1 })")] + [DataRow("db.adminCommand({ buildInfo: 1 })")] + [DataRow("db.adminCommand({ ping: 1 })")] + [DataRow("db.runCommand({ connectionStatus: 1 })")] + [DataRow("db.runCommand({ usersInfo: 1 })")] + [DataRow("db.adminCommand({ getParameter: \"*\" })")] + [DataRow("db.adminCommand({ currentOp: 1 })")] + [DataRow("db.adminCommand({ replSetGetStatus: 1 })")] + [DataRow("db.adminCommand({ listDatabases: 1 })")] + [DataRow("db.runCommand({ profile: -1 })")] + [DataRow("db.runCommand({ validate: \"a\" })")] + [DataRow("db.runCommand({ explain: { find: \"a\", filter: {} }, verbosity: \"executionStats\" })")] + [DataRow("db.runCommand(\"ping\")")] + [DataRow("db.aggregate([{ $currentOp: {} }])")] + public void ReadCommandsStayReadable(string text) => Assert.IsFalse(Parse(text).IsWrite, text); + + private static async Task<(MongoConnection Connection, string Database)> OpenAsync() + { + await TestServer.RequireAsync(); + MongoConnection connection = await TestServer.OpenAsync(); + return (connection, "velashell_guard_" + Guid.NewGuid().ToString("N")[..8]); + } + + private static async Task RunAsync(ShellExecutor executor, string database, string text) => + await executor.ExecuteAsync(Parse(text), new ShellSession(database), new ShellRunOptions { MaxTimeMs = 10_000 }); + + [TestMethod] + public async Task RunCommand_HonoursTheDropGuards() + { + (MongoConnection connection, string database) = await OpenAsync(); + await using (connection) + { + try + { + await connection.Collection(database, "keep").InsertOneAsync(new BsonDocument("a", 1)); + var guard = new StubGuard { DisableDropDatabase = true }; + var executor = new ShellExecutor(connection, guard, new Loc("zh-CN")); + + _ = await Assert.ThrowsAsync(() => RunAsync(executor, database, "db.runCommand({ dropDatabase: 1 })")); + _ = await Assert.ThrowsAsync(() => RunAsync(executor, database, "db.runCommand(\"dropDatabase\")")); + Assert.AreEqual(1L, await connection.EstimatedCountAsync(database, "keep"), "禁用 dropDatabase 时 runCommand 也不能删库"); + + guard.Answer = false; + ShellResult declined = await RunAsync(executor, database, "db.runCommand({ drop: \"keep\" })"); + Assert.IsTrue(declined.Declined); + Assert.AreEqual(ShellConfirmKind.Drop, guard.Asked.Single().Kind, "与 db.c.drop() 一样要手打集合名确认"); + Assert.AreEqual("keep", guard.Asked.Single().Collection); + Assert.AreEqual(1L, await connection.EstimatedCountAsync(database, "keep")); + + guard.Writable = false; + ShellResult blocked = await RunAsync(executor, database, "db.runCommand({ aggregate: \"keep\", pipeline: [{ $out: \"copy\" }], cursor: {} })"); + Assert.IsTrue(blocked.Declined, "只读模式下 runCommand 的 $out 要拦"); + ShellResult blockedDb = await RunAsync(executor, database, "db.aggregate([{ $documents: [{ a: 1 }] }, { $out: \"copy\" }])"); + Assert.IsTrue(blockedDb.Declined, "库级 aggregate 的 $out 也要拦"); + ShellResult read = await RunAsync(executor, database, "db.runCommand({ count: \"keep\" })"); + Assert.IsFalse(read.Declined, "只读命令照常放行"); + Assert.AreEqual(1, read.Documents[0]["n"].ToInt32()); + } + finally + { + await connection.Client.DropDatabaseAsync(database); + } + } + } + + [TestMethod] + public async Task Find_CursorModifiersReachTheDriver() + { + (MongoConnection connection, string database) = await OpenAsync(); + await using (connection) + { + try + { + var orders = connection.Collection(database, "orders"); + await orders.InsertManyAsync(Enumerable.Range(0, 10).Select(static i => new BsonDocument { { "n", i }, { "s", i % 2 == 0 ? "even" : "odd" } })); + _ = await orders.Indexes.CreateOneAsync(new MongoDB.Driver.CreateIndexModel(new BsonDocument("n", 1))); + var executor = new ShellExecutor(connection, new StubGuard(), new Loc("zh-CN")); + + ShellResult range = await RunAsync(executor, database, "db.orders.find().min({ n: 3 }).max({ n: 6 }).hint({ n: 1 })"); + Assert.AreEqual("3,4,5", string.Join(",", range.Documents.Select(static d => d["n"].ToInt32()))); + + ShellResult keys = await RunAsync(executor, database, "db.orders.find({ n: { $lt: 2 } }).hint({ n: 1 }).returnKey()"); + Assert.IsTrue(keys.Documents.All(static d => d.Names.SequenceEqual(["n"])), "returnKey 只返回索引键"); + + ShellResult withRecordId = await RunAsync(executor, database, "db.orders.find({ n: 1 }).showRecordId()"); + Assert.IsTrue(withRecordId.Documents.Single().Contains("$recordId")); + + ShellResult noTimeout = await RunAsync(executor, database, "db.orders.find().noCursorTimeout().limit(2)"); + Assert.HasCount(2, noTimeout.Documents); + + ShellResult countAll = await RunAsync(executor, database, "db.orders.find().skip(2).limit(3).count()"); + Assert.AreEqual(10L, countAll.Documents[0]["count"].ToInt64()); + ShellResult countApplied = await RunAsync(executor, database, "db.orders.find().skip(2).limit(3).count(true)"); + Assert.AreEqual(3L, countApplied.Documents[0]["count"].ToInt64(), "count(true) 计 skip / limit"); + + _ = await Assert.ThrowsAsync(() => RunAsync(executor, database, "db.orders.find().readPref(\"secondary\")")); + _ = await Assert.ThrowsAsync(() => RunAsync(executor, database, "db.orders.find().readConcern(\"majority\")")); + } + finally + { + await connection.Client.DropDatabaseAsync(database); + } + } + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/ToolTabFixesTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/ToolTabFixesTests.cs new file mode 100644 index 0000000..7620b11 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/ToolTabFixesTests.cs @@ -0,0 +1,138 @@ +using System.Collections.ObjectModel; +using MongoDB.Bson; +using VelaShell.Plugin.Mongo.Core; +using VelaShell.Plugin.Mongo.Ui; +using VelaShell.Plugin.Mongo.Ui.GridFs; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// 工具类标签页的几处纯逻辑:CIDR 前缀按地址族限长、多项下载避让同名、缩略图缓存的 LRU、 +/// 当前操作表按 opid 原地同步、验证规则的"会不会拒绝"判定。不连服务器。 +/// +[TestClass] +public sealed class ToolTabFixesTests +{ + [TestMethod] + public void Cidr_prefix_is_limited_by_address_family() + { + Assert.IsNull(UserAdmin.FirstInvalidAddress("10.0.0.0/32, 10.0.0.0/0, ::1/128, fe80::/10")); + Assert.AreEqual("10.0.0.0/33", UserAdmin.FirstInvalidAddress("10.0.0.1, 10.0.0.0/33")); + Assert.AreEqual("::1/129", UserAdmin.FirstInvalidAddress("::1/129")); + Assert.AreEqual("10.0.0.0/", UserAdmin.FirstInvalidAddress("10.0.0.0/")); + } + + [TestMethod] + public void Folder_download_never_overwrites_and_uniquifies_collisions() + { + string dir = Path.Combine(Path.GetTempPath(), "velashell-gridfs-" + Guid.NewGuid().ToString("N")[..8]); + _ = Directory.CreateDirectory(dir); + try + { + File.WriteAllText(Path.Combine(dir, "photo.png"), "existing"); + _ = Directory.CreateDirectory(Path.Combine(dir, "docs")); + var taken = new HashSet(StringComparer.OrdinalIgnoreCase); + + // 本地已有同名文件 → (2);同一批里再来一个同名 → (3);与已有目录同名也避让。 + Assert.AreEqual(Path.Combine(dir, "photo (2).png"), GridFsTabViewModel.UniqueLocalPath(Path.Combine(dir, "photo.png"), taken)); + Assert.AreEqual(Path.Combine(dir, "photo (3).png"), GridFsTabViewModel.UniqueLocalPath(Path.Combine(dir, "photo.png"), taken)); + Assert.AreEqual(Path.Combine(dir, "docs (2)"), GridFsTabViewModel.UniqueLocalPath(Path.Combine(dir, "docs"), taken)); + Assert.AreEqual(Path.Combine(dir, "new.txt"), GridFsTabViewModel.UniqueLocalPath(Path.Combine(dir, "new.txt"), taken)); + Assert.AreEqual(Path.Combine(dir, "NEW (2).txt"), GridFsTabViewModel.UniqueLocalPath(Path.Combine(dir, "NEW.txt"), taken), + "names that differ only in case collide on case-insensitive file systems"); + Assert.AreEqual("existing", File.ReadAllText(Path.Combine(dir, "photo.png")), "the existing file is untouched"); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [TestMethod] + public void Thumbnail_cache_is_lru_and_keys_on_upload_date() + { + var cache = new GridFsThumbnailCache(2); + var first = new GridFsFile(ObjectId.GenerateNewId(), "a.png", 10, 255 * 1024, new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), null, null); + GridFsFile reuploaded = first with { UploadDate = first.UploadDate!.Value.AddMinutes(1) }; + Assert.AreNotEqual(GridFsThumbnailCache.Key(first), GridFsThumbnailCache.Key(reuploaded), "a re-upload under the same _id is a different image"); + + _ = cache.Add("a", null); + _ = cache.Add("b", null); + Assert.IsTrue(cache.TryGet("a", out _), "touch a → b is now the least recently used"); + _ = cache.Add("c", null); + Assert.AreEqual(2, cache.Count); + Assert.IsTrue(cache.TryGet("a", out _)); + Assert.IsFalse(cache.TryGet("b", out _), "the least recently used entry is evicted"); + Assert.IsTrue(cache.TryGet("c", out _)); + cache.Dispose(); + Assert.AreEqual(0, cache.Count); + } + + [TestMethod] + public void Current_ops_are_synced_in_place_by_opid() + { + var ops = new ObservableCollection { Op(1, 5), Op(2, 3), Op(3, 1) }; + ProfilerOpRow one = ops[0]; + ProfilerOpRow three = ops[2]; + int resets = 0; + ops.CollectionChanged += (_, e) => + { + if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset) + { + resets++; + } + }; + + // 2 结束了;3 跑得比 1 还久了;新来一个 4。 + ProfilerTabViewModel.SyncOps(ops, [Op(3, 12), Op(1, 7), Op(4, 0.5)]); + + Assert.AreEqual(0, resets, "no Clear: scroll position and hover survive"); + Assert.AreSequenceEqual(["3", "1", "4"], ops.Select(static o => o.OpIdText).ToArray()); + Assert.AreSame(three, ops[0], "a surviving op keeps its row object"); + Assert.AreSame(one, ops[1]); + Assert.AreEqual(12, three.Seconds); + Assert.IsTrue(three.IsLong); + } + + [TestMethod] + public void Only_error_actions_reject_writes() + { + Assert.IsTrue(DesignTabViewModel.IsRejecting("error")); + Assert.IsTrue(DesignTabViewModel.IsRejecting("errorAndLog")); + Assert.IsFalse(DesignTabViewModel.IsRejecting("warn")); + } + + /// 新建用户的密码要再输一遍:不一致不能保存,生成的密码两栏一起填。 + [TestMethod] + [TestCategory("Integration")] + public void New_user_password_needs_confirmation() => Screens.OnUi(async () => + { + await TestServer.RequireAsync(); + await using Workbench bench = await Screens.OpenWorkbenchAsync(); + bench.Session.OpenUsers("shop"); + var tab = (UsersTabViewModel)bench.ViewModel.ActiveTab!; + DateTime deadline = DateTime.UtcNow.AddSeconds(15); + while ((tab.IsLoading || tab.Users.Count == 0) && DateTime.UtcNow < deadline) + { + await Screens.PumpAsync(5); + } + tab.NewUserCommand.Execute(null); + UserEditorViewModel editor = tab.UserEditor!; + editor.NewName = "velashell_confirm_" + Guid.NewGuid().ToString("N")[..6]; + editor.Roles.Rows.First(static r => r.Database == "shop").Cells[0].IsChecked = true; + editor.Password = "Typed-Pass-123456"; + Assert.IsFalse(editor.CanSave, "an unconfirmed password can't be saved"); + editor.PasswordConfirm = "Typed-Pass-12345"; + Assert.IsTrue(editor.PasswordMismatch); + Assert.IsFalse(editor.CanSave); + editor.PasswordConfirm = editor.Password; + Assert.IsFalse(editor.PasswordMismatch); + Assert.IsTrue(editor.CanSave, editor.ValidationError); + editor.GenerateCommand.Execute(null); + Assert.AreEqual(editor.Password, editor.PasswordConfirm, "a generated password fills both boxes"); + Assert.IsTrue(editor.CanSave, editor.ValidationError); + }); + + private static ProfilerOpRow Op(int id, double seconds) => + new(id, id.ToString(System.Globalization.CultureInfo.InvariantCulture), "query", "shop.orders", "find {}", "10.0.0.1", seconds, 1); +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/TransferFixTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/TransferFixTests.cs new file mode 100644 index 0000000..a2c1641 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/TransferFixTests.cs @@ -0,0 +1,72 @@ +using MongoDB.Bson; +using MongoDB.Driver; +using VelaShell.Plugin.Mongo.Bson; +using VelaShell.Plugin.Mongo.Transfer; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// 导出的无损默认值、XLSX 的数值精度、导入的千分位、抽样的退路。不连服务器。 +[TestClass] +public sealed class TransferFixTests +{ + [TestMethod] + public void ExportDefaultsAreLossless() + { + Assert.AreEqual(CellConversion.None, XferField.DefaultConversionFor(BsonKind.Decimal128), "保留两位会把 0.0035 写成 0.00"); + Assert.AreEqual(CellConversion.IsoTime, XferField.DefaultConversionFor(BsonKind.Date), "本地时间不带时区、丢毫秒"); + Assert.AreEqual("0.0035", CellFormatter.Format(new BsonDecimal128(Decimal128.Parse("0.0035")), XferField.DefaultConversionFor(BsonKind.Decimal128), true)); + var at = new BsonDateTime(new DateTime(2026, 9, 27, 7, 0, 0, 123, DateTimeKind.Utc)); + Assert.AreEqual("2026-09-27T07:00:00.123Z", CellFormatter.Format(at, XferField.DefaultConversionFor(BsonKind.Date), true)); + } + + [TestMethod] + public void XlsxNumbersFallBackToTextWhenDoubleWouldChangeTheValue() + { + Assert.AreEqual(9_007_199_254_740_992d, CellFormatter.Number(new BsonInt64(1L << 53), CellConversion.None)); + Assert.IsNull(CellFormatter.Number(new BsonInt64((1L << 53) + 1), CellConversion.None), "超过 2^53 的 Int64 写成文本"); + Assert.IsNull(CellFormatter.Number(new BsonInt64(long.MinValue), CellConversion.None)); + Assert.AreEqual(0.0035, CellFormatter.Number(new BsonDecimal128(Decimal128.Parse("0.0035")), CellConversion.None)); + Assert.AreEqual(86.5, CellFormatter.Number(new BsonDecimal128(Decimal128.Parse("86.50")), CellConversion.None)); + Assert.IsNull(CellFormatter.Number(new BsonDecimal128(Decimal128.Parse("1234567890.123456789")), CellConversion.None), "有效位数超过 double"); + Assert.AreEqual(1234567890.12, CellFormatter.Number(new BsonDecimal128(Decimal128.Parse("1234567890.123456789")), CellConversion.Fixed2), + "显式选了保留两位:舍入之后能精确表示就写数字"); + Assert.AreEqual("1234567890.123456789", CellFormatter.Format(new BsonDecimal128(Decimal128.Parse("1234567890.123456789")), CellConversion.None, true)); + } + + [TestMethod] + [DataRow("1,580", "1580")] + [DataRow("-1,580.25", "-1580.25")] + [DataRow("\"12,345,678.9\"", "12345678.9")] + [DataRow("¥ 1,580.00", "1580.00")] + [DataRow("1 580", "1580")] + [DataRow("1_000_000", "1000000")] + [DataRow("$42", "42")] + public void ValidGroupingIsStripped(string input, string expected) => + Assert.AreEqual(expected, ImportValues.CleanNumber(input, out _)); + + [TestMethod] + [DataRow("1,5")] + [DataRow("12,34")] + [DataRow("1,5000")] + [DataRow("12,34,567")] + [DataRow("1,580 000")] + [DataRow(",580")] + [DataRow("1,580.")] + public void InvalidGroupingIsAnErrorNotASilentlyDifferentNumber(string input) + { + Assert.AreEqual("", ImportValues.CleanNumber(input, out _)); + ConvertOutcome outcome = ImportValues.FromText(input, BsonKind.Decimal128, null); + Assert.IsTrue(outcome.IsError, input); + Assert.AreEqual(ImportIssueKind.BadNumber, outcome.Issue); + } + + [TestMethod] + public void SampleFallbackCatchesServerTimeouts() + { + // $sample 超时报 MongoExecutionTimeoutException:它是 MongoServerException,不是 MongoCommandException —— + // SchemaSampler 只接 MongoCommandException 时退路永远走不到。 + Assert.IsTrue(typeof(MongoServerException).IsAssignableFrom(typeof(MongoExecutionTimeoutException))); + Assert.IsFalse(typeof(MongoCommandException).IsAssignableFrom(typeof(MongoExecutionTimeoutException))); + Assert.IsFalse(typeof(MongoServerException).IsAssignableFrom(typeof(OperationCanceledException)), "取消不被吞"); + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/TunnelSettingsTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/TunnelSettingsTests.cs new file mode 100644 index 0000000..00cb492 --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/TunnelSettingsTests.cs @@ -0,0 +1,323 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using MongoDB.Driver; +using MongoDB.Driver.Core.Compression; +using VelaShell.Plugin.Mongo.Core; +using VelaShell.PluginSdk; +using VelaShell.PluginSdk.RemoteTunnel; +using VelaShell.PluginSdk.Sessions; +using VelaShell.PluginSdk.Testing; +using VelaShell.PluginSdk.Workspaces; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// 跳板与驱动设置:URI 形态经隧道、URI 选项不被表单默认值覆盖、跳板会话的竞态与断线重开、隧道下的证书主机名核对。不连服务器。 +/// +[TestClass] +public sealed class TunnelSettingsTests +{ + private static WorkspaceConnectRequest Request(Dictionary settings, string host, int port = 27017, string user = "", string password = "") => + new() + { + SessionId = "s", + Host = host, + Port = port, + Username = user, + Password = password, + Settings = settings + }; + + [TestMethod] + public void UriOverTunnel_KeepsTheUriAndDialsTheLocalEndpoint() + { + WorkspaceConnectRequest original = Request(new() { ["topology"] = "uri" }, + "mongodb://10.0.0.1:27017,10.0.0.2:27017/shop?replicaSet=rs0&authSource=ops", user: "ops", password: "secret"); + WorkspaceConnectRequest rewritten = SshTunnel.RewriteTo(original, 51872, new WorkspaceTunnelInfo("10.0.0.1", 27017, "bastion")); + Assert.AreEqual(original.Host, rewritten.Host, "URI 形态的主机一栏是整条连接串,不能换成 127.0.0.1"); + Assert.AreEqual(51872, rewritten.Port); + + MongoClientSettings client = MongoConnection.BuildSettings(rewritten, MongoSettings.From(rewritten), null); + Assert.HasCount(1, client.Servers); + Assert.AreEqual("127.0.0.1", client.Servers.Single().Host); + Assert.AreEqual(51872, client.Servers.Single().Port); + Assert.IsTrue(client.DirectConnection); + Assert.AreEqual("ops", client.Credential.Username); + Assert.AreEqual("ops", client.Credential.Source, "URI 里的选项照用"); + } + + [TestMethod] + public void HostListOverTunnel_RewritesTheHostToLoopback() + { + WorkspaceConnectRequest original = Request([], "10.20.3.21"); + WorkspaceConnectRequest rewritten = SshTunnel.RewriteTo(original, 40000, new WorkspaceTunnelInfo("10.20.3.21", 27017, "bastion")); + Assert.AreEqual("127.0.0.1", rewritten.Host); + MongoClientSettings client = MongoConnection.BuildSettings(rewritten, MongoSettings.From(rewritten), null); + Assert.AreEqual("127.0.0.1:40000", $"{client.Servers.Single().Host}:{client.Servers.Single().Port}"); + } + + [TestMethod] + public void SrvUriOverTunnel_IsRejectedNotSilentlyDirect() + { + WorkspaceConnectRequest original = Request(new() { ["topology"] = "uri" }, "mongodb+srv://cluster0.example.net/shop"); + Assert.IsTrue(MongoConnector.IsSrvUri(original.Host)); + WorkspaceConnectRequest rewritten = SshTunnel.RewriteTo(original, 40000, new WorkspaceTunnelInfo("cluster0.example.net", 27017, "bastion")); + _ = Assert.Throws(() => MongoConnection.BuildSettings(rewritten, MongoSettings.From(rewritten), null)); + _ = Assert.Throws(() => SshTunnel.TargetOf(original, MongoSettings.From(original))); + } + + [TestMethod] + public void UriOptions_WinOverFormDefaults() + { + WorkspaceConnectRequest request = Request(new() { ["topology"] = "uri" }, + "mongodb://10.0.0.1:27017/?readPreference=secondary&appName=reporting&connectTimeoutMS=2500&serverSelectionTimeoutMS=4000&compressors=zlib"); + MongoClientSettings client = MongoConnection.BuildSettings(request, MongoSettings.From(request), null); + Assert.AreEqual(ReadPreferenceMode.Secondary, client.ReadPreference.ReadPreferenceMode); + Assert.AreEqual("reporting", client.ApplicationName); + Assert.AreEqual(TimeSpan.FromMilliseconds(2500), client.ConnectTimeout); + Assert.AreEqual(TimeSpan.FromMilliseconds(4000), client.ServerSelectionTimeout); + Assert.HasCount(1, client.Compressors); + Assert.AreEqual(CompressorType.Zlib, client.Compressors.Single().Type); + } + + [TestMethod] + public void UriOptions_ExplicitFormValuesStillOverride() + { + WorkspaceConnectRequest request = Request(new() { ["topology"] = "uri", ["readPreference"] = "nearest", ["appName"] = "mine", ["connectTimeout"] = "3000" }, + "mongodb://10.0.0.1:27017/?readPreference=secondary&appName=reporting&connectTimeoutMS=2500"); + MongoClientSettings client = MongoConnection.BuildSettings(request, MongoSettings.From(request), null); + Assert.AreEqual(ReadPreferenceMode.Nearest, client.ReadPreference.ReadPreferenceMode); + Assert.AreEqual("mine", client.ApplicationName); + Assert.AreEqual(TimeSpan.FromMilliseconds(3000), client.ConnectTimeout); + } + + [TestMethod] + public void UriWithoutOptions_GetsTheFormDefaults() + { + WorkspaceConnectRequest request = Request(new() { ["topology"] = "uri" }, "mongodb://10.0.0.1:27017/"); + MongoClientSettings client = MongoConnection.BuildSettings(request, MongoSettings.From(request), null); + Assert.AreEqual("velashell", client.ApplicationName); + Assert.AreEqual(TimeSpan.FromMilliseconds(10_000), client.ServerSelectionTimeout); + Assert.HasCount(3, client.Compressors); + } + + [TestMethod] + public void HostList_KeepsFormValues() + { + WorkspaceConnectRequest request = Request(new() { ["readPreference"] = "secondaryPreferred" }, "10.0.0.1"); + MongoClientSettings client = MongoConnection.BuildSettings(request, MongoSettings.From(request), null); + Assert.AreEqual(ReadPreferenceMode.SecondaryPreferred, client.ReadPreference.ReadPreferenceMode); + Assert.AreEqual("velashell", client.ApplicationName); + } + + // ── 证书:隧道下的主机名 ────────────────────────────────────────────── + + private static X509Certificate2 Certificate(string dnsName) + { + using var key = ECDsa.Create(); + var request = new CertificateRequest("CN=" + dnsName, key, HashAlgorithmName.SHA256); + var san = new SubjectAlternativeNameBuilder(); + san.AddDnsName(dnsName); + request.CertificateExtensions.Add(san.Build()); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(30)); + } + + [TestMethod] + public void TlsTrust_TunnelAcceptsTheNameMismatchOnlyWhenTheRealHostMatches() + { + using X509Certificate2 cert = Certificate("db.internal"); + Assert.IsTrue(new TlsTrust(null, "db.internal").Validate(cert, null, SslPolicyErrors.RemoteCertificateNameMismatch, null)); + var wrong = new TlsTrust(null, "evil.internal"); + Assert.IsFalse(wrong.Validate(cert, null, SslPolicyErrors.RemoteCertificateNameMismatch, null)); + Assert.AreEqual(SslPolicyErrors.RemoteCertificateNameMismatch, wrong.PolicyErrors); + Assert.IsFalse(new TlsTrust(null).Validate(cert, null, SslPolicyErrors.RemoteCertificateNameMismatch, null), "不走隧道:名字不匹配照旧是错"); + } + + [TestMethod] + public void TlsTrust_TunnelStillReportsChainErrorsAfterTheNameIsCleared() + { + using X509Certificate2 cert = Certificate("db.internal"); + var trust = new TlsTrust(null, "db.internal"); + Assert.IsFalse(trust.Validate(cert, null, SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateChainErrors, null)); + Assert.AreEqual(SslPolicyErrors.RemoteCertificateChainErrors, trust.PolicyErrors, "名字那一条抹掉了,链的错误照报"); + } + + // ── 跳板会话:竞态与断线重开 ───────────────────────────────────────── + + /// 可控的会话替身:OpenAsync 可以卡在一道闸门上,会话可以被"断掉"。 + private sealed class Sessions : ISessionsApi + { + private int _next; + + public Dictionary Live { get; } = []; + + public List Closed { get; } = []; + + public int Opens { get; private set; } + + public TaskCompletionSource? Gate { get; set; } + + public Task> ListAsync(CancellationToken cancellationToken) => + Task.FromResult>([.. Live.Values]); + + public Task GetAsync(string sessionId, CancellationToken cancellationToken) => + Task.FromResult(Live.TryGetValue(sessionId, out SessionInfo? s) ? s : null); + + public Task> ListSavedAsync(CancellationToken cancellationToken) => + Task.FromResult>([]); + + public async Task OpenAsync(string savedSessionId, SessionOpenOptions options, CancellationToken cancellationToken) + { + Opens++; + string id = $"{savedSessionId}#{Interlocked.Increment(ref _next)}"; + if (Gate is { } gate) + { + await gate.Task.ConfigureAwait(false); + } + var session = new SessionInfo(id, "jump", 22, "u", SessionState.Connected, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow); + lock (Live) + { + Live[id] = session; + } + return session; + } + + public Task CloseAsync(string sessionId, CancellationToken cancellationToken = default) + { + lock (Live) + { + Closed.Add(sessionId); + _ = Live.Remove(sessionId); + } + return Task.CompletedTask; + } + } + + /// 隧道替身:只有活着的会话开得出流。 + private sealed class Tunnels(Sessions sessions) : IRemoteTunnelApi + { + public List Attempts { get; } = []; + + public int ActiveTunnels => 0; + + public Task OpenUnixSocketAsync(string sessionId, string path, TunnelOptions? options, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task OpenTcpAsync(string sessionId, string host, int port, TunnelOptions? options, CancellationToken cancellationToken) + { + Attempts.Add(sessionId); + return sessions.Live.ContainsKey(sessionId) + ? Task.FromResult(new MemoryStream()) + : Task.FromException(new InvalidOperationException("channel open failed: session closed")); + } + } + + private static string NewSavedId() => "jump-" + Guid.NewGuid().ToString("N"); + + [TestMethod] + public async Task JumpLease_RacedOpenClosesTheExtraSession() + { + var sessions = new Sessions { Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) }; + var tunnels = new Tunnels(sessions); + var log = new TestPluginContext().Log; + string saved = NewSavedId(); + + Task first = SshJumpLease.AcquireAsync(sessions, tunnels, log, saved, "r", CancellationToken.None); + Task second = SshJumpLease.AcquireAsync(sessions, tunnels, log, saved, "r", CancellationToken.None); + sessions.Gate.SetResult(); + SshJumpLease a = await first; + SshJumpLease b = await second; + + Assert.AreEqual(2, sessions.Opens); + Assert.AreEqual(a.SessionId, b.SessionId, "两份租约共用先到的那条"); + Assert.HasCount(1, sessions.Closed, "后到的那条要关掉,不能留在宿主里没人管"); + Assert.HasCount(1, sessions.Live); + Assert.AreEqual(2, SshJumpLease.SharedCount(saved)); + + await a.DisposeAsync(); + Assert.HasCount(1, sessions.Live, "还有一份租约,会话留着"); + await b.DisposeAsync(); + Assert.IsEmpty(sessions.Live); + Assert.AreEqual(0, SshJumpLease.SharedCount(saved)); + } + + [TestMethod] + public async Task JumpLease_DeadSessionIsReopenedAndTheStreamRetriedOnce() + { + var sessions = new Sessions(); + var tunnels = new Tunnels(sessions); + string saved = NewSavedId(); + SshJumpLease lease = await SshJumpLease.AcquireAsync(sessions, tunnels, new TestPluginContext().Log, saved, "r", CancellationToken.None); + string dead = lease.SessionId; + _ = sessions.Live.Remove(dead); // 跳板会话自己断了 + + await using (Stream stream = await lease.OpenTcpAsync("10.0.0.1", 27017, CancellationToken.None)) + { + Assert.IsNotNull(stream); + } + Assert.AreNotEqual(dead, lease.SessionId, "共用表里换成了新会话"); + Assert.AreEqual(2, sessions.Opens); + Assert.HasCount(2, tunnels.Attempts); + + // 同一条跳板上新来的租约直接用新会话。 + SshJumpLease another = await SshJumpLease.AcquireAsync(sessions, tunnels, new TestPluginContext().Log, saved, "r", CancellationToken.None); + Assert.AreEqual(lease.SessionId, another.SessionId); + await another.DisposeAsync(); + await lease.DisposeAsync(); + Assert.IsEmpty(sessions.Live); + } + + [TestMethod] + public async Task JumpLease_TargetFailureOnALiveSessionDoesNotReopen() + { + var sessions = new Sessions(); + var tunnels = new FailingTunnels(); + string saved = NewSavedId(); + SshJumpLease lease = await SshJumpLease.AcquireAsync(sessions, tunnels, new TestPluginContext().Log, saved, "r", CancellationToken.None); + _ = await Assert.ThrowsAsync(() => lease.OpenTcpAsync("10.0.0.1", 27017, CancellationToken.None)); + Assert.AreEqual(1, sessions.Opens, "会话还活着:目标拒连不是重开的理由"); + await lease.DisposeAsync(); + } + + private sealed class FailingTunnels : IRemoteTunnelApi + { + public int ActiveTunnels => 0; + + public Task OpenUnixSocketAsync(string sessionId, string path, TunnelOptions? options, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task OpenTcpAsync(string sessionId, string host, int port, TunnelOptions? options, CancellationToken cancellationToken) => + Task.FromException(new IOException("connection refused")); + } + + [TestMethod] + public async Task JumpLease_SessionNotFoundCountsAsGone() + { + var sessions = new Sessions(); + var tunnels = new NotFoundOnceTunnels(); + string saved = NewSavedId(); + SshJumpLease lease = await SshJumpLease.AcquireAsync(sessions, tunnels, new TestPluginContext().Log, saved, "r", CancellationToken.None); + await using (Stream stream = await lease.OpenTcpAsync("h", 1, CancellationToken.None)) + { + Assert.IsNotNull(stream); + } + Assert.AreEqual(2, sessions.Opens); + await lease.DisposeAsync(); + } + + private sealed class NotFoundOnceTunnels : IRemoteTunnelApi + { + private int _calls; + + public int ActiveTunnels => 0; + + public Task OpenUnixSocketAsync(string sessionId, string path, TunnelOptions? options, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task OpenTcpAsync(string sessionId, string host, int port, TunnelOptions? options, CancellationToken cancellationToken) => + Interlocked.Increment(ref _calls) == 1 + ? Task.FromException(new PluginSessionNotFoundException(sessionId)) + : Task.FromResult(new MemoryStream()); + } +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/UiReviewFixesTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/UiReviewFixesTests.cs new file mode 100644 index 0000000..61f2c6c --- /dev/null +++ b/tests/VelaShell.Plugin.Mongo.Tests/UiReviewFixesTests.cs @@ -0,0 +1,444 @@ +using Avalonia.Controls; +using Avalonia.VisualTree; +using MongoDB.Bson; +using MongoDB.Driver; +using VelaShell.Plugin.Mongo.Core; +using VelaShell.Plugin.Mongo.Shell; +using VelaShell.Plugin.Mongo.Staging; +using VelaShell.Plugin.Mongo.Ui; +using VelaShell.PluginSdk.Testing; + +namespace VelaShell.Plugin.Mongo.Tests; + +/// +/// 编辑 / 查询界面的几处回归:文档编辑器带上网格暂存、URI 里的口令不落盘、限时解锁挂在连接上、 +/// JSON 卡片的编辑跨重查保留、冲突对话框排队、日期原样回车不暂存、网格水平虚拟化、示例连接串。 +/// +[TestClass] +public sealed class UiReviewFixesTests +{ + private static readonly Loc Zh = new("zh-CN"); + + private static readonly BsonDateTime Stamp = new(new DateTime(2026, 9, 26, 12, 0, 0, DateTimeKind.Utc)); + + private static async Task<(IMongoClient Client, string Database, IMongoCollection Collection)> SeedAsync() + { + var client = new MongoClient(TestServer.Uri); + string database = "velashell_uifix_" + Guid.NewGuid().ToString("N")[..8]; + IMongoCollection collection = client.GetDatabase(database).GetCollection("orders"); + await collection.InsertManyAsync( + [ + new BsonDocument { { "_id", 1 }, { "status", "paid" }, { "qty", 2 }, { "note", "a" }, { "updatedAt", Stamp } }, + new BsonDocument { { "_id", 2 }, { "status", "pending" }, { "qty", 1 }, { "note", "b" }, { "updatedAt", Stamp } } + ]); + return (client, database, collection); + } + + private static async Task OpenTabAsync(Workbench bench, string database, string collection) + { + bench.Session.OpenCollection(database, collection); + var tab = (CollectionTabViewModel)bench.ViewModel.ActiveTab!; + for (int i = 0; i < 200 && (tab.IsLoading || tab.Rows.Count == 0); i++) + { + await Screens.PumpAsync(5); + } + await Screens.PumpAsync(20); + return tab; + } + + private static CollectionRow RowOf(CollectionTabViewModel tab, int id) => tab.Rows.Single(r => r.Id?.Equals(new BsonInt32(id)) == true); + + // ── 1. 文档编辑器带上网格暂存 ─────────────────────────────────────────── + + /// + /// 网格里暂存了修改再「在文档编辑器中编辑」:编辑器的原像是服务器版本、表单里是原像 + 暂存, + /// 所以保存时暂存的修改一起写进去(而不是只写对话框里动过的、再把暂存丢掉); + /// 暂存里改过的 updatedAt 也不当乐观并发的版本去筛,不会凭空冲突。 + /// + [TestMethod] + public void Opening_a_staged_row_in_the_editor_keeps_the_staged_edits() => Screens.OnUi(static async () => + { + await TestServer.RequireAsync(); + (IMongoClient client, string database, IMongoCollection collection) = await SeedAsync(); + try + { + await using Workbench bench = await Screens.OpenWorkbenchAsync(database); + CollectionTabViewModel tab = await OpenTabAsync(bench, database, "orders"); + CollectionRow row = RowOf(tab, 1); + Assert.IsTrue(tab.Stage(row, "status", "shipped")); + Assert.IsTrue(tab.Stage(row, "updatedAt", new BsonDateTime(new DateTime(2030, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + row = RowOf(tab, 1); + + tab.OpenInEditor(row); + var editor = (DocumentEditorDialogViewModel)bench.ViewModel.Dialog!; + Assert.AreEqual("paid", editor.Original!["status"].AsString, "the editor's original is the server version"); + Assert.AreEqual(Stamp, editor.BuildFilter()!["updatedAt"], "the concurrency filter uses the server's updatedAt, not the staged one"); + Assert.IsTrue(editor.HasChanges, "the staged edits show up as changes in the editor"); + Assert.Contains("shipped", editor.CommandText); + + await editor.SaveCommand.ExecuteAsync(); + for (int i = 0; i < 100 && tab.HasPending; i++) + { + await Screens.PumpAsync(5); + } + BsonDocument stored = await collection.Find(new BsonDocument("_id", 1)).FirstAsync(); + Assert.AreEqual("shipped", stored["status"].AsString, "the staged edit was written, not silently dropped"); + Assert.IsFalse(tab.HasPending); + } + finally + { + await client.DropDatabaseAsync(database); + } + }); + + // ── 2. URI 里的口令不落盘 ────────────────────────────────────────────── + + /// URI 形态里写的 user:pass@:用户名挪进用户名栏,口令进密钥库,插件存储里只有不带凭据的 URI。 + [TestMethod] + public void Saving_a_uri_with_credentials_moves_the_password_to_the_keychain() => Screens.OnUi(static async () => + { + using var context = new TestPluginContext(); + var shell = new MongoWorkspaceViewModel(Zh, context, new MongoStore(context)); + var view = new MongoWorkspaceView(shell); + var window = new Window { Width = 1440, Height = 836, Content = view }; + window.Show(); + try + { + await shell.InitializeAsync(); + shell.NewConnection(); + var dialog = (ConnectionDialogViewModel)shell.Dialog!; + dialog.Name = "uri-conn"; + dialog.IsUriTopology = true; + dialog.Uri = "mongodb://alice:s3cret-pw@10.0.0.9:27017/shop?authSource=admin"; + await dialog.SaveCommand.ExecuteAsync(); + await Screens.PumpAsync(5); + Assert.IsTrue(string.IsNullOrEmpty(dialog.Error), dialog.Error); + + var store = new MongoProfileStore(context); + MongoProfile saved = (await store.LoadAsync()).Single(); + Assert.IsFalse(saved.Host.Contains("s3cret", StringComparison.Ordinal), saved.Host); + Assert.Contains("10.0.0.9", saved.Host); + Assert.AreEqual("alice", saved.Username); + string password = await store.GetPasswordAsync(saved.Id); + Assert.AreEqual("s3cret-pw", password); + foreach (string key in await context.Storage.GetKeysAsync()) + { + System.Text.Json.JsonElement raw = await context.Storage.GetAsync(key); + Assert.IsFalse(raw.GetRawText().Contains("s3cret", StringComparison.Ordinal), "口令绝不能落进插件存储"); + } + + // 早先存进来的(URI 里还带着口令)再打开编辑:框里不露口令,用户名回到用户名栏。 + var legacy = new MongoProfile { Name = "legacy", Host = "mongodb://bob:old-pw@10.0.0.8:27017/" }; + legacy.Set(MongoSettings.KeyTopology, "uri"); + var edit = new ConnectionDialogViewModel(shell, legacy, isNew: false); + Assert.IsFalse(edit.Uri.Contains("old-pw", StringComparison.Ordinal), edit.Uri); + Assert.IsFalse(edit.Uri.Contains("bob", StringComparison.Ordinal), edit.Uri); + Assert.AreEqual("bob", edit.Username); + } + finally + { + window.Close(); + shell.Dispose(); + } + }); + + [TestMethod] + public void Strip_credentials_leaves_uris_without_credentials_untouched() + { + (string clean, string? user, string? password) = ConnectionDialogViewModel.StripCredentials("mongodb://u:p%40ss@h1:27017,h2:27018/db?replicaSet=rs0"); + Assert.AreEqual("u", user); + Assert.AreEqual("p@ss", password); + Assert.IsFalse(clean.Contains('@'), clean); + Assert.Contains("replicaSet=rs0", clean); + + const string plain = "mongodb://h1:27017/?directConnection=true"; + Assert.AreEqual((plain, (string?)null, (string?)null), ConnectionDialogViewModel.StripCredentials(plain)); + Assert.AreEqual(("not a uri", (string?)null, (string?)null), ConnectionDialogViewModel.StripCredentials("not a uri")); + } + + // ── 4. 限时解锁挂在连接上 ────────────────────────────────────────────── + + /// 「解锁写入 15 分钟」的计时在连接的护栏上:点解锁的那个标签页关了,到点照样锁回去。 + [TestMethod] + public void Timed_unlock_relocks_even_after_the_tab_is_closed() => Screens.OnUi(static async () => + { + await TestServer.RequireAsync(); + await using Workbench bench = await Screens.OpenWorkbenchAsync(); + CollectionTabViewModel tab = await OpenTabAsync(bench, Screens.Database, "orders"); + WriteGuard guard = bench.Session.Guard; + guard.IsReadOnly = true; + + guard.UnlockFor(TimeSpan.FromMilliseconds(150)); + Assert.IsFalse(guard.IsReadOnly); + Assert.IsNotNull(guard.UnlockedUntil); + await tab.CloseCommand.ExecuteAsync(); + tab.Dispose(); + for (int i = 0; i < 100 && !guard.IsReadOnly; i++) + { + await Screens.PumpAsync(2); + } + Assert.IsTrue(guard.IsReadOnly, "the connection goes back to read-only although the tab that unlocked it is gone"); + Assert.IsNull(guard.UnlockedUntil); + Assert.Contains(static t => t.Title == Zh["State_Relocked"], bench.ViewModel.Toasts); + + // 手动锁回去(或改成一直开着)就作废计时。 + guard.UnlockFor(TimeSpan.FromMilliseconds(100)); + guard.IsReadOnly = false; + Assert.IsNull(guard.UnlockedUntil, "a manual toggle cancels the timed relock"); + await Screens.PumpAsync(30); + Assert.IsFalse(guard.IsReadOnly, "the cancelled timer does not relock"); + }); + + // ── 5. JSON 卡片的编辑跨重查保留 ─────────────────────────────────────── + + [TestMethod] + public void A_json_card_being_edited_survives_a_requery() => Screens.OnUi(static async () => + { + await TestServer.RequireAsync(); + (IMongoClient client, string database, _) = await SeedAsync(); + try + { + await using Workbench bench = await Screens.OpenWorkbenchAsync(database); + CollectionTabViewModel tab = await OpenTabAsync(bench, database, "orders"); + tab.ViewMode = CollectionViewMode.Json; + await Screens.PumpAsync(5); + JsonCardViewModel card = tab.Cards.Single(c => c.Row.Id?.Equals(new BsonInt32(2)) == true); + card.BeginEdit(); + Assert.IsTrue(card.IsEditing); + string typed = card.EditText.Replace("\"pending\"", "\"on-hold\"", StringComparison.Ordinal); + Assert.AreNotEqual(card.EditText, typed); + card.EditText = typed; + + await tab.RunQueryAsync(resetPage: false); + await Screens.PumpAsync(5); + + JsonCardViewModel again = tab.Cards.Single(c => c.Row.Id?.Equals(new BsonInt32(2)) == true); + Assert.AreNotSame(card, again, "the rows are new objects after a re-query"); + Assert.IsTrue(again.IsEditing, "the card stays in edit mode"); + Assert.AreEqual(typed, again.EditText, "the half-typed text is kept"); + Assert.AreSame(again, tab.FocusedCard); + Assert.IsTrue(again.Update()); + Assert.AreEqual("on-hold", tab.Staging.EditOf(new BsonInt32(2))!.Find("status")!.Value!.AsString); + tab.Staging.Clear(); + } + finally + { + await client.DropDatabaseAsync(database); + } + }); + + // ── 6. 冲突对话框排队 ────────────────────────────────────────────────── + + /// + /// 两份冲突逐份处理;处理第一份时的重新提交又冲突(1′),1′ 排到队尾 —— + /// 不再当场弹出来又被外层接着弹的冲突 2 顶掉。 + /// + [TestMethod] + public void Conflicts_raised_while_resolving_are_queued_not_lost() => Screens.OnUi(static async () => + { + await TestServer.RequireAsync(); + (IMongoClient client, string database, IMongoCollection collection) = await SeedAsync(); + try + { + await using Workbench bench = await Screens.OpenWorkbenchAsync(database); + CollectionTabViewModel tab = await OpenTabAsync(bench, database, "orders"); + Assert.IsTrue(tab.Stage(RowOf(tab, 1), "status", "mine-1")); + Assert.IsTrue(tab.Stage(RowOf(tab, 2), "status", "mine-2")); + _ = await collection.UpdateManyAsync(FilterDefinition.Empty, new BsonDocument("$set", new BsonDocument("status", "theirs"))); + + await tab.ApplyCommand.ExecuteAsync(); + await Screens.PumpAsync(5); + var first = (ConflictDialogViewModel)bench.ViewModel.Dialog!; + Assert.AreEqual(new BsonInt32(1), first.Conflict.Edit.Id); + Assert.AreEqual(2, tab.PendingConflictCount); + + // 我看冲突的这几秒里服务器又改了 #1:覆盖时的重新提交会再撞上。 + _ = await collection.UpdateOneAsync(new BsonDocument("_id", 1), new BsonDocument("$set", new BsonDocument("status", "theirs-again"))); + await first.OverwriteCommand.ExecuteAsync(); + await Screens.PumpAsync(5); + + var second = (ConflictDialogViewModel)bench.ViewModel.Dialog!; + Assert.AreEqual(new BsonInt32(2), second.Conflict.Edit.Id, "the outer queue goes on with conflict 2"); + Assert.AreEqual(2, tab.PendingConflictCount, "conflict 1' waits behind it"); + await second.DiscardMineCommand.ExecuteAsync(); + await Screens.PumpAsync(5); + + var third = (ConflictDialogViewModel)bench.ViewModel.Dialog!; + Assert.AreEqual(new BsonInt32(1), third.Conflict.Edit.Id, "conflict 1' is shown once 2 is resolved"); + await third.OverwriteCommand.ExecuteAsync(); + await Screens.PumpAsync(5); + Assert.AreEqual(0, tab.PendingConflictCount); + BsonDocument stored = await collection.Find(new BsonDocument("_id", 1)).FirstAsync(); + Assert.AreEqual("mine-1", stored["status"].AsString); + } + finally + { + await client.DropDatabaseAsync(database); + } + }); + + // ── 7 / 8. 顶掉查询、停止 ────────────────────────────────────────────── + + [TestMethod] + public void Interrupted_errors_are_recognised_as_a_stop() + { + Assert.IsFalse(CollectionTabViewModel.IsInterrupted(new TimeoutException())); + Assert.IsFalse(CollectionTabViewModel.IsInterrupted(new InvalidOperationException())); + } + + /// 查找不再在查询跑着的时候灰掉:新的一次顶掉旧的。 + [TestMethod] + public void Find_stays_available_while_a_query_runs() => Screens.OnUi(static async () => + { + await TestServer.RequireAsync(); + await using Workbench bench = await Screens.OpenWorkbenchAsync(); + CollectionTabViewModel tab = await OpenTabAsync(bench, Screens.Database, "orders"); + Task running = tab.RunQueryAsync(resetPage: true); + Assert.IsTrue(tab.IsLoading); + Assert.IsTrue(tab.FindCommand.CanExecute(null), "Find can supersede the running query"); + await tab.FindCommand.ExecuteAsync(); + await running; + for (int i = 0; i < 100 && tab.IsLoading; i++) + { + await Screens.PumpAsync(5); + } + Assert.IsFalse(tab.IsLoading); + Assert.DoesNotContain(static t => t.Request.Kind == ToastKind.Error, bench.ViewModel.Toasts, "a superseded query is not a failure"); + }); + + // ── 12. 日期原样回车不暂存 ───────────────────────────────────────────── + + [TestMethod] + public void Committing_an_unchanged_date_editor_stages_nothing() => Screens.OnUi(static async () => + { + await TestServer.RequireAsync(); + (IMongoClient client, string database, _) = await SeedAsync(); + try + { + await using Workbench bench = await Screens.OpenWorkbenchAsync(database); + CollectionTabViewModel tab = await OpenTabAsync(bench, database, "orders"); + CollectionRow row = RowOf(tab, 1); + CollectionCell cell = row.CellOf(tab.Columns.Single(static c => c.Name == "updatedAt"))!; + tab.BeginCellEdit(cell); + Assert.IsNotNull(cell.Editor); + Assert.AreEqual(cell.Editor.InitialText, cell.Editor.Text); + Assert.IsTrue(tab.CommitCellEdit(cell)); + Assert.IsTrue(tab.Staging.IsEmpty, "Enter on an untouched date (local time, possibly a repeated DST hour) is not an edit"); + } + finally + { + await client.DropDatabaseAsync(database); + } + }); + + // ── P1. 网格水平虚拟化 ───────────────────────────────────────────────── + + [TestMethod] + public void Cell_window_slices_the_row_and_pads_the_rest() => Screens.OnUi(static async () => + { + await TestServer.RequireAsync(); + (IMongoClient client, string database, _) = await SeedAsync(); + try + { + await using Workbench bench = await Screens.OpenWorkbenchAsync(database); + CollectionTabViewModel tab = await OpenTabAsync(bench, database, "orders"); + foreach (CollectionColumn column in tab.Columns) + { + column.Width = 700; + } + await Screens.PumpAsync(10); + CellWindow window = tab.CellWindow; + Assert.IsLessThan(tab.Columns.Count - 1, window.Last, "columns beyond the viewport get no cell controls"); + CollectionRow row = tab.Rows[0]; + Assert.HasCount(window.Last - window.First + 1, row.VisibleCells); + Assert.AreEqual(700d * (tab.Columns.Count - 1 - window.Last), row.TrailWidth); + CollectionTabView view = bench.Window.GetVisualDescendants().OfType().First(static v => v.IsEffectivelyVisible); + int realized = view.Grid.List.GetVisualDescendants().OfType() + .Count(b => b.Classes.Contains("gcell") && b.DataContext is CollectionCell c && ReferenceEquals(c.Row, row)); + Assert.AreEqual(row.VisibleCells.Count, realized); + + // 当前列挪到最后一列:横向滚过去,它的单元格建出来,内联编辑照常。 + CollectionColumn last = tab.Columns[^1]; + tab.CurrentColumn = last; + await Screens.PumpAsync(10); + Assert.AreEqual(tab.Columns.Count - 1, tab.CellWindow.Last); + Assert.IsGreaterThan(0, tab.CellWindow.First); + Assert.AreEqual(700d * tab.CellWindow.First, tab.Rows[0].LeadWidth); + CollectionCell cell = tab.Rows[0].CellOf(last)!; + tab.BeginCellEdit(cell); + await Screens.PumpAsync(5); + Assert.IsTrue(view.Grid.List.GetVisualDescendants().OfType().Any(), "the editor of an off-screen column is realized after scrolling"); + CollectionTabViewModel.CancelCellEdit(cell); + } + finally + { + await client.DropDatabaseAsync(database); + } + }); + + // ── 13. 阶段片段的占位符 ─────────────────────────────────────────────── + + [TestMethod] + public void Stage_snippet_placeholders_follow_the_ui_language() + { + var en = new Loc("en-US"); + Assert.AreEqual("", en["Query_SnipField"]); + Assert.AreEqual("<字段>", Zh["Query_SnipField"]); + Assert.AreEqual("", en["Query_SnipValue"]); + } + + // ── 14. 示例代码的连接串 ─────────────────────────────────────────────── + + [TestMethod] + public void Sample_connection_string_is_a_real_credential_free_uri() + { + var hosts = new MongoProfile { Name = "h", Host = "10.0.0.5", Port = 27018, Username = "ops" }; + hosts.Set(MongoSettings.KeyReplicaSet, "rs0"); + (string uri, string? note) = QueryTabViewModel.SampleConnection(hosts, "10.0.0.5:27018", Zh); + Assert.StartsWith("mongodb://10.0.0.5:27018", uri); + Assert.Contains("replicaSet=rs0", uri); + Assert.IsFalse(uri.Contains("ops", StringComparison.Ordinal), uri); + Assert.IsNull(note); + + var withUri = new MongoProfile { Name = "u", Host = "mongodb://bob:pw@db1:27017/shop" }; + withUri.Set(MongoSettings.KeyTopology, "uri"); + (uri, _) = QueryTabViewModel.SampleConnection(withUri, MongoConnection.RedactUri(withUri.Host), Zh); + Assert.StartsWith("mongodb://db1:27017", uri); + Assert.IsFalse(uri.Contains("mongodb://mongodb://", StringComparison.Ordinal), uri); + Assert.IsFalse(uri.Contains("bob", StringComparison.Ordinal) || uri.Contains("pw", StringComparison.Ordinal), uri); + + var srv = new MongoProfile { Name = "s", Host = "cluster0.example.net" }; + srv.Set(MongoSettings.KeyTopology, "srv"); + (uri, _) = QueryTabViewModel.SampleConnection(srv, "cluster0.example.net", Zh); + Assert.StartsWith("mongodb+srv://cluster0.example.net", uri); + + var tunnel = new MongoProfile { Name = "t", Host = "10.20.3.21", Port = 27017 }; + tunnel.Set(MongoSettings.KeyJumpSession, "bastion-1"); + (uri, note) = QueryTabViewModel.SampleConnection(tunnel, "10.20.3.21:27017 ↝ bastion", Zh); + Assert.StartsWith("mongodb://10.20.3.21:27017", uri); + Assert.IsFalse(uri.Contains('↝'), uri); + Assert.AreEqual(Zh["Query_CodeTunnelNote"], note); + string code = CodeExportDialogViewModel.WithNote("x", note, CodeTarget.Python); + Assert.StartsWith("# ", code); + } + + // ── P4. 文档编辑器的重算防抖 ─────────────────────────────────────────── + + [TestMethod] + public void Document_editor_recompute_is_debounced() => Screens.OnUi(static async () => + { + var workspace = new DocEditorWorkspace(); + var info = new CollectionInfo("shop", "orders", CollectionKind.Collection, []); + var original = new BsonDocument { { "_id", 1 }, { "status", "paid" }, { "note", "x" } }; + var vm = new DocumentEditorDialogViewModel(workspace, info, original, null); + Assert.IsFalse(vm.HasChanges); + vm.AddFieldCommand.Execute(null); + Assert.IsTrue(vm.IsRecomputePending, "an edit schedules a recompute instead of running it on the spot"); + for (int i = 0; i < 50 && vm.IsRecomputePending; i++) + { + await Screens.PumpAsync(2); + } + Assert.IsFalse(vm.IsRecomputePending, "the debounced recompute runs once typing stops"); + await Task.CompletedTask; + }); +} diff --git a/tests/VelaShell.Plugin.Mongo.Tests/UsersTests.cs b/tests/VelaShell.Plugin.Mongo.Tests/UsersTests.cs index b84d13c..eac9f2c 100644 --- a/tests/VelaShell.Plugin.Mongo.Tests/UsersTests.cs +++ b/tests/VelaShell.Plugin.Mongo.Tests/UsersTests.cs @@ -282,6 +282,7 @@ public void Users_are_created_edited_reset_and_deleted_on_the_server() => Screen Assert.IsTrue(created.IsNew); created.NewName = name; created.Password = "Init-Pass-" + Guid.NewGuid().ToString("N")[..10]; + created.PasswordConfirm = created.Password; created.Roles.Rows.First(r => r.Database == "shop").Cells[0].IsChecked = true; Assert.IsTrue(created.CanSave, created.ValidationError); await Screens.PumpAsync(30); From 5cda483d150e5d080198a08316f93d21bda97319 Mon Sep 17 00:00:00 2001 From: Joes Date: Wed, 2 Dec 2026 00:26:42 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E5=AE=BF=E4=B8=BB=E7=89=88=E6=9C=AC=E5=B9=B6=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 固定 Avalonia 测试依赖为 12.2.1,升级 AWSSDK.S3 至 4.1.3.1。 将各插件最低宿主版本提升至 1.9.4,并保留对应的最低 SDK 版本。 整理多个插件清单的贡献项、权限和激活事件格式。 --- Directory.Packages.props | 10 +++++----- plugins/VelaShell.Plugin.DockerPanel/plugin.json | 2 +- plugins/VelaShell.Plugin.Mongo/plugin.json | 2 +- plugins/VelaShell.Plugin.Rdp/plugin.json | 16 ++++++++++++---- plugins/VelaShell.Plugin.Redis/plugin.json | 8 ++++++-- plugins/VelaShell.Plugin.S3/plugin.json | 8 ++++++-- plugins/VelaShell.Plugin.Serial/plugin.json | 8 ++++++-- plugins/VelaShell.Plugin.Telnet/plugin.json | 8 ++++++-- plugins/VelaShell.Plugin.Vnc/plugin.json | 16 ++++++++++++---- 9 files changed, 55 insertions(+), 23 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 3da85d9..dc79c3c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -23,13 +23,13 @@ - - + + - + - + - + - - - - 12.2.0 - 12.0.0 - - joesdu git diff --git a/Directory.Build.targets b/Directory.Build.targets index 68083b7..d081566 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -6,48 +6,5 @@ - - - - - <_VelaAvaloniaPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia')->'%(Version)') - <_VelaAvaloniaHeadlessPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.Headless')->'%(Version)') - <_VelaAvaloniaThemesPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.Themes.Fluent')->'%(Version)') - <_VelaAvaloniaSkiaPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.Skia')->'%(Version)') - <_VelaAvaloniaEditPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.AvaloniaEdit')->'%(Version)') - - - - - - - - - - - <_VelaAvaloniaReference Include="@(ReferencePath)" Condition="'%(ReferencePath.NuGetPackageId)' == 'Avalonia'" /> - <_VelaAvaloniaEditReference Include="@(ReferencePath)" Condition="'%(ReferencePath.NuGetPackageId)' == 'Avalonia.AvaloniaEdit'" /> - - - - + From 56dc0db37291e0199baf7211877e61107b24d0d1 Mon Sep 17 00:00:00 2001 From: Joes Date: Wed, 2 Dec 2026 01:06:19 +0800 Subject: [PATCH 4/5] =?UTF-8?q?Revert=20"chore:=20=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E7=BA=A6=E6=9D=9F."?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 3137f55a476c2868f380e02210510f22573ac0b0. --- Directory.Build.props | 21 +++++++++++++++++++ Directory.Build.targets | 45 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 02be386..8cd9413 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -36,6 +36,27 @@ false + + + + + 12.2.0 + 12.0.0 + + joesdu git diff --git a/Directory.Build.targets b/Directory.Build.targets index d081566..68083b7 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -6,5 +6,48 @@ - + + + + + <_VelaAvaloniaPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia')->'%(Version)') + <_VelaAvaloniaHeadlessPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.Headless')->'%(Version)') + <_VelaAvaloniaThemesPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.Themes.Fluent')->'%(Version)') + <_VelaAvaloniaSkiaPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.Skia')->'%(Version)') + <_VelaAvaloniaEditPin>@(PackageVersion->WithMetadataValue('Identity','Avalonia.AvaloniaEdit')->'%(Version)') + + + + + + + + + + + <_VelaAvaloniaReference Include="@(ReferencePath)" Condition="'%(ReferencePath.NuGetPackageId)' == 'Avalonia'" /> + <_VelaAvaloniaEditReference Include="@(ReferencePath)" Condition="'%(ReferencePath.NuGetPackageId)' == 'Avalonia.AvaloniaEdit'" /> + + + + From c8fd10236537d06848f479951f60b4855c79e156 Mon Sep 17 00:00:00 2001 From: Joes Date: Wed, 2 Dec 2026 01:07:33 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=E5=B0=86=E7=9B=AE=E6=A0=87=E5=AE=BF?= =?UTF-8?q?=E4=B8=BB=E7=9A=84=20Avalonia=20=E9=BB=98=E8=AE=A4=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=8D=87=E8=87=B3=2012.2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 仅在未设置 VelaAvaloniaVersion 时,将默认值从 12.2.0 提升至 12.2.1。 --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 8cd9413..2a88b16 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -53,7 +53,7 @@ - 12.2.0 + 12.2.1 12.0.0