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