diff --git a/Directory.Build.props b/Directory.Build.props
index 8cd9413..2a88b16 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -53,7 +53,7 @@
- 12.2.0
+ 12.2.1
12.0.0
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 3da85d9..dc79c3c 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -23,13 +23,13 @@
-
-
+
+
-
+
-
+
-
+
-
-
+
+
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.DockerPanel/plugin.json b/plugins/VelaShell.Plugin.DockerPanel/plugin.json
index 4a4f956..f2643e8 100644
--- a/plugins/VelaShell.Plugin.DockerPanel/plugin.json
+++ b/plugins/VelaShell.Plugin.DockerPanel/plugin.json
@@ -7,7 +7,7 @@
"author": "Joe",
"entry": "VelaShell.Plugin.DockerPanel.dll",
"apiLevel": 2,
- "minHostVersion": "1.8.9",
+ "minHostVersion": "1.9.4",
// 面板走 Docker Engine 的 HTTP API,而这条 API 的载体是一个 unix socket。
// SDK 1.2 的 IRemoteTunnelApi 才提供到远端 socket 的**裸字节双工流**;
// 1.1 的远程执行只有"整段 UTF-8 解码"与"按 \n 切行"两种文本形态,
diff --git a/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs b/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs
index 018a21a..89f53d4 100644
--- a/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Analysis/ExplainPlan.cs
@@ -171,7 +171,8 @@ internal sealed record ExplainAdvice(string ReasonKey, string ReasonArgument, Bs
///
/// 认三种形态:find 的 queryPlanner + executionStats;aggregate 的 stages[0].$cursor 包裹
/// (其后是 $group / $sort 这些管道阶段);分片集群的 shards[](取第一个分片,尽力而为)。
-/// SBE 引擎的 queryPlan 也按经典形状读。认不出的字段一概忽略 —— 解读失败不该让原始 JSON 也看不到。
+/// SBE 引擎(explainVersion: "2")的阶段树按 winningPlan.queryPlan 建 —— 它的 executionStages 是槽位执行树,
+/// 不是查询计划的形状;各节点的统计按 planNodeId 尽力从槽位树里取,总数取 executionStats 顶层。认不出的字段一概忽略 —— 解读失败不该让原始 JSON 也看不到。
///
///
internal sealed class ExplainPlan
@@ -298,8 +299,13 @@ public static ExplainPlan Parse(BsonDocument explain)
}
BsonDocument? winning = Unwrap(queryPlanner.GetValue("winningPlan", null) as BsonDocument);
- BsonDocument? executionRoot = Unwrap(executionStats?.GetValue("executionStages", null) as BsonDocument);
+ // explainVersion "2"(SBE,7.0+ 把 $group / $lookup 下推之后):executionStages 是槽位执行树
+ // (project / group / ixseek …),不是查询计划的形状。树按 winningPlan.queryPlan 建,
+ // 每个节点的统计按 planNodeId 从槽位树里尽力取(取不到就留空),总数仍取 executionStats 顶层。
+ bool sbe = IsSbe(explain) || IsSbe(queryPlanner);
+ BsonDocument? executionRoot = sbe ? null : Unwrap(executionStats?.GetValue("executionStages", null) as BsonDocument);
BsonDocument? root = executionRoot ?? winning;
+ Dictionary? sbeStats = sbe && executionStats?.GetValue("executionStages", null) is BsonDocument slots ? CollectSbeStats(slots) : null;
// 树:管道阶段在上(最后一个是根),查询层的阶段树挂在最下面那个管道阶段之下。
var tree = new List();
@@ -316,7 +322,7 @@ public static ExplainPlan Parse(BsonDocument explain)
};
tree.Add(pipelineStages[p]);
}
- ExplainStage? rootStage = root is null ? null : Build(root, pipelineStages.Count, tree);
+ ExplainStage? rootStage = root is null ? null : Build(root, pipelineStages.Count, tree, sbeStats);
var linear = new List();
for (ExplainStage? s = rootStage; s is not null; s = s.Children.Count > 0 ? s.Children[0] : null)
{
@@ -438,7 +444,63 @@ public static ExplainPlan Parse(BsonDocument explain)
return stage;
}
- private static ExplainStage Build(BsonDocument raw, int depth, List tree)
+ /// SBE 槽位树里同一个 planNodeId 的统计:输出取最外层那个槽位阶段,扫描键数累加。
+ private sealed record SbeStats(long? NReturned, long? CumulativeMs, long? KeysExamined, bool? IsEof);
+
+ private static bool IsSbe(BsonDocument document) =>
+ document.GetValue("explainVersion", null) is BsonString { Value: "2" };
+
+ ///
+ /// 按 planNodeId 汇总 SBE 槽位树的统计。一个查询计划节点会展开成几个槽位阶段(GROUP → project / group / project),
+ /// 先序遍历遇到的第一个(最外层)就是这个节点的输出。分片时只看第一个分片(与经典形态一致)。
+ ///
+ private static Dictionary CollectSbeStats(BsonDocument root)
+ {
+ var result = new Dictionary();
+ void Walk(BsonDocument stage)
+ {
+ if (stage.GetValue("planNodeId", null) is { IsNumeric: true } id)
+ {
+ int key = id.ToInt32();
+ long? keys = Long(stage, "keysExamined");
+ if (result.TryGetValue(key, out SbeStats? seen))
+ {
+ if (keys is not null)
+ {
+ result[key] = seen with { KeysExamined = (seen.KeysExamined ?? 0) + keys };
+ }
+ }
+ else
+ {
+ result[key] = new SbeStats(Long(stage, "nReturned"), Long(stage, "executionTimeMillisEstimate"), keys,
+ stage.TryGetValue("isEOF", out BsonValue eof) ? eof.ToBoolean() : null);
+ }
+ }
+ foreach (string child in (string[])["inputStage", "outerStage", "innerStage", "thenStage", "elseStage"])
+ {
+ if (stage.GetValue(child, null) is BsonDocument next)
+ {
+ Walk(next);
+ }
+ }
+ if (stage.GetValue("inputStages", null) is BsonArray many)
+ {
+ foreach (BsonDocument next in many.OfType())
+ {
+ Walk(next);
+ }
+ }
+ if (stage.GetValue("shards", null) is BsonArray shards && shards.Count > 0 && shards[0] is BsonDocument shard
+ && shard.GetValue("executionStages", null) is BsonDocument shardStages)
+ {
+ Walk(shardStages);
+ }
+ }
+ Walk(root);
+ return result;
+ }
+
+ private static ExplainStage Build(BsonDocument raw, int depth, List tree, Dictionary? sbe = null)
{
var children = new List();
if (raw.GetValue("inputStage", null) is BsonDocument input)
@@ -459,23 +521,26 @@ private static ExplainStage Build(BsonDocument raw, int depth, List Build(c, depth + 1, tree)).ToList();
+ var built = children.Select(c => Build(c, depth + 1, tree, sbe)).ToList();
+ // SBE:queryPlan 节点本身不带统计,按 planNodeId 去槽位树里取;docsExamined / works 槽位树里没有对应量,留空。
+ SbeStats? slot = sbe is not null && raw.GetValue("planNodeId", null) is { IsNumeric: true } nodeId
+ && sbe.TryGetValue(nodeId.ToInt32(), out SbeStats? found) ? found : null;
var stage = new ExplainStage
{
Name = raw.GetValue("stage", "?").ToString() ?? "?",
Raw = raw,
Depth = depth,
- NReturned = Long(raw, "nReturned"),
- KeysExamined = Long(raw, "keysExamined"),
+ NReturned = Long(raw, "nReturned") ?? slot?.NReturned,
+ KeysExamined = Long(raw, "keysExamined") ?? slot?.KeysExamined,
DocsExamined = Long(raw, "docsExamined"),
Works = Long(raw, "works"),
- CumulativeMs = Long(raw, "executionTimeMillisEstimate"),
+ CumulativeMs = Long(raw, "executionTimeMillisEstimate") ?? slot?.CumulativeMs,
IndexName = raw.GetValue("indexName", null)?.ToString(),
KeyPattern = raw.GetValue("keyPattern", null) as BsonDocument,
Direction = raw.GetValue("direction", null)?.ToString(),
Bounds = raw.GetValue("indexBounds", null) is BsonDocument bounds ? FormatBounds(bounds) : null,
Filter = raw.GetValue("filter", null) as BsonDocument,
- IsEof = raw.TryGetValue("isEOF", out BsonValue eof) ? eof.ToBoolean() : null,
+ IsEof = raw.TryGetValue("isEOF", out BsonValue eof) ? eof.ToBoolean() : slot?.IsEof,
Children = built
};
tree[index] = stage;
@@ -531,7 +596,7 @@ private static List BuildCandidates(BsonDocument queryPlanner,
}
string winnerChain = Chain(winning);
BsonDocument? winnerStats = all?.OfType()
- .FirstOrDefault(p => p.GetValue("executionStages", null) is BsonDocument s && Chain(Unwrap(s)!) == winnerChain);
+ .FirstOrDefault(p => p.GetValue("executionStages", null) is BsonDocument s && SameChain(Chain(Unwrap(s)!), winnerChain));
candidates.Add(Candidate(true, winnerChain, winnerStats));
var used = new HashSet(ReferenceEqualityComparer.Instance);
if (winnerStats is not null)
@@ -542,7 +607,7 @@ private static List BuildCandidates(BsonDocument queryPlanner,
{
string chain = Chain(Unwrap(plan)!);
BsonDocument? stats = all?.OfType()
- .FirstOrDefault(p => !used.Contains(p) && p.GetValue("executionStages", null) is BsonDocument s && Chain(Unwrap(s)!) == chain);
+ .FirstOrDefault(p => !used.Contains(p) && p.GetValue("executionStages", null) is BsonDocument s && SameChain(Chain(Unwrap(s)!), chain));
if (stats is not null)
{
_ = used.Add(stats);
@@ -552,6 +617,13 @@ private static List BuildCandidates(BsonDocument queryPlanner,
return candidates;
}
+ ///
+ /// 试运行的阶段链与计划链对得上:相同,或试运行链是计划链的开头 —— SBE 下多计划试运行发生在下推 $group 之前
+ /// (试运行是 IXSCAN → PROJECTION_COVERED,获胜计划是 IXSCAN → PROJECTION_COVERED → GROUP)。
+ ///
+ private static bool SameChain(string trial, string plan) =>
+ trial == plan || plan.StartsWith(trial + " → ", StringComparison.Ordinal);
+
private static ExplainCandidate Candidate(bool winner, string chain, BsonDocument? stats) => new(
winner,
chain,
diff --git a/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs b/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs
index 2185ce0..78cab07 100644
--- a/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Analysis/IndexAdvisor.cs
@@ -182,6 +182,20 @@ internal sealed record AdvisorIndex(string Name, BsonDocument Key, BsonDocument
/// 部分 / 稀疏索引(只覆盖一部分文档,不能拿来替代全量索引)。
public bool Partial => Spec.Contains("partialFilterExpression") || Spec.GetValue("sparse", false).ToBoolean();
+
+ ///
+ /// TTL 索引(expireAfterSeconds)。它的活是后台按时删过期文档 —— TTL 线程的扫描不计入 $indexStats 的 ops,
+ /// "没人用"是假象;它也不能当成别的索引的冗余前缀删掉,删了过期文档就再也不会被清理。
+ ///
+ public bool Ttl => Spec.Contains("expireAfterSeconds");
+
+ /// 排序规则;用简单二进制比较时为 。
+ public BsonDocument? Collation => Spec.GetValue("collation", null) as BsonDocument;
+
+ /// 与 的排序规则相同(都没有也算)。排序规则不同的索引服务的是不同的查询,不能互相替代。
+ public bool SameCollation(AdvisorIndex other) =>
+ Equals(Collation, other.Collation) || (Collation?.GetValue("locale", null)?.ToString() == "simple" && other.Collation is null)
+ || (other.Collation?.GetValue("locale", null)?.ToString() == "simple" && Collation is null);
}
/// 建议的种类(设计稿 07「索引建议」的三种卡片)。
@@ -345,10 +359,18 @@ internal static bool TryExtract(BsonDocument entry, out BsonDocument filter, out
/// 慢查询组()。
/// 现有索引。
/// 当前时间(UTC;单测注入)。
- public static IReadOnlyList Advise(IReadOnlyList groups, IReadOnlyList indexes, DateTime now)
+ ///
+ /// 分片集合的分片键(config.collections 的 key);未分片为 。
+ /// 以分片键为前缀的索引是分片键的支撑索引,删了分片就坏了 —— 不出"冗余 / 未使用"。
+ ///
+ public static IReadOnlyList Advise(IReadOnlyList groups, IReadOnlyList indexes, DateTime now,
+ BsonDocument? shardKey = null)
{
ArgumentNullException.ThrowIfNull(groups);
ArgumentNullException.ThrowIfNull(indexes);
+ // 不能建议删的:_id、TTL、分片键的支撑索引。
+ bool Protected(AdvisorIndex index) =>
+ index.Name == "_id_" || index.Ttl || shardKey is { ElementCount: > 0 } && IsPrefix(shardKey, index.Key);
var advice = new List();
var suggested = new HashSet(StringComparer.Ordinal);
foreach (AdvisorQueryGroup group in groups)
@@ -373,13 +395,13 @@ public static IReadOnlyList Advise(IReadOnlyList
- other.Name != index.Name && !other.Hidden && !other.Partial
+ other.Name != index.Name && !other.Hidden && !other.Partial && index.SameCollation(other)
&& other.Key.ElementCount > index.Key.ElementCount && IsPrefix(index.Key, other.Key));
if (cover is not null)
{
@@ -388,7 +410,8 @@ public static IReadOnlyList Advise(IReadOnlyListISO 8601 UTC(毫秒精度),与 mongosh 的 ISODate 输出一致。
+ /// 毫秒值落在 .NET 能表示的范围里(0001-01-01 至 9999-12-31)。
+ public static bool IsRepresentableDate(long ms) => ms is >= -62135596800000L and <= 253402300799999L;
+
+ ///
+ /// ISO 8601 UTC(毫秒精度),与 mongosh 的 ISODate 输出一致。
+ /// 超出 .NET 可表示范围的毫秒值(BSON 允许)原样给毫秒数,不抛。
+ ///
public static string IsoDate(BsonValue value)
{
long ms = value.AsBsonDateTime.MillisecondsSinceEpoch;
+ if (!IsRepresentableDate(ms))
+ {
+ return ms.ToString(CultureInfo.InvariantCulture);
+ }
var at = DateTimeOffset.FromUnixTimeMilliseconds(ms);
return at.UtcDateTime.ToString(at.Millisecond == 0 ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:ss.fffZ",
CultureInfo.InvariantCulture);
diff --git a/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs b/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs
index 7b6b041..a511e75 100644
--- a/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Bson/ShellJson.cs
@@ -1,4 +1,5 @@
using System.Text;
+using System.Text.RegularExpressions;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
@@ -33,7 +34,7 @@ public sealed class ShellJsonException(string message, int offset) : FormatExcep
/// 认成**错误**而不是悄悄加引号 —— mongosh 自己就会在那里报错,设计稿 03 也把它画成了一条诊断。
///
///
-public static class ShellJson
+public static partial class ShellJson
{
/// 解析一份文档;空白文本视为空文档 {}。
/// 语法错误。
@@ -175,6 +176,14 @@ internal static string Normalize(string text, out IReadOnlyList
i++;
continue;
}
+ // mongosh 的 Timestamp({ t, i }) / MinKey() / MaxKey() 驱动读不了:换成它认的写法
+ // (BsonText 的 Shell 输出就是 mongosh 的样子,这样文档编辑器里没动过的字段才能原样存回去)。
+ if (IsIdentifierStart(c) && (i == 0 || !IsIdentifierPart(text[i - 1]) && text[i - 1] != '.')
+ && RewriteShellConstructor(text, i, output) is var consumed and > 0)
+ {
+ i += consumed;
+ continue;
+ }
if (IsIdentifierStart(c) && stack.Count > 0 && stack.Peek() == '{')
{
int start = i;
@@ -211,6 +220,33 @@ internal static string Normalize(string text, out IReadOnlyList
return output.ToString();
}
+ ///
+ /// Timestamp({ t: 1, i: 2 }) → Timestamp(1, 2);MinKey() / MaxKey() → { "$minKey" : 1 } / { "$maxKey" : 1 }。
+ /// 不是这几种写法返回 0(什么都不写)。
+ ///
+ private static int RewriteShellConstructor(string text, int start, StringBuilder output)
+ {
+ Match timestamp = ShellTimestamp().Match(text, start);
+ if (timestamp.Success && timestamp.Index == start)
+ {
+ _ = output.Append("Timestamp(").Append(timestamp.Groups["t"].Value).Append(", ").Append(timestamp.Groups["i"].Value).Append(')');
+ return timestamp.Length;
+ }
+ Match key = ShellMinMaxKey().Match(text, start);
+ if (key.Success && key.Index == start)
+ {
+ _ = output.Append(key.Groups["kind"].Value == "Min" ? "{ \"$minKey\" : 1 }" : "{ \"$maxKey\" : 1 }");
+ return key.Length;
+ }
+ return 0;
+ }
+
+ [GeneratedRegex("""\GTimestamp\s*\(\s*\{\s*["']?t["']?\s*:\s*(?\d+)\s*,\s*["']?i["']?\s*:\s*(?\d+)\s*,?\s*\}\s*\)""")]
+ private static partial Regex ShellTimestamp();
+
+ [GeneratedRegex(@"\G(?Min|Max)Key\s*\(\s*\)")]
+ private static partial Regex ShellMinMaxKey();
+
private static bool LastSignificantIsKeyPosition(StringBuilder output) => PreviousSignificant(output) is '{' or ',';
private static char PreviousSignificant(StringBuilder output)
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs b/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs
index 3b25100..1972334 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/ConnectionProbe.cs
@@ -107,9 +107,21 @@ private static Target TargetOf(WorkspaceConnectRequest request, MongoSettings se
{
options.Add(("authMechanism", uriMechanism));
}
- if (url.ReadPreference is { } preference && preference.ReadPreferenceMode != ReadPreferenceMode.Primary)
+ // 表单里显式改过的读偏好覆盖 URI 的(与 MongoConnection.BuildSettings 同一口径)。
+ ReadPreferenceMode? mode = settings.ReadPreferenceSet
+ ? MongoConnection.ParseReadPreference(settings.ReadPreference).ReadPreferenceMode
+ : url.ReadPreference?.ReadPreferenceMode;
+ if (mode is { } readMode && readMode != ReadPreferenceMode.Primary)
{
- options.Add(("readPreference", ReadPreferenceName(preference.ReadPreferenceMode)));
+ options.Add(("readPreference", ReadPreferenceName(readMode)));
+ }
+ if (settings.AppNameSet && settings.AppName is { Length: > 0 } formApp)
+ {
+ options.Add(("appName", formApp));
+ }
+ else if (url.ApplicationName is { Length: > 0 } uriApp)
+ {
+ options.Add(("appName", uriApp));
}
if (url.UseTls && !srv)
{
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs b/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs
index 41ad001..d85e294 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/GridFsService.cs
@@ -401,12 +401,18 @@ internal sealed class GridFsService(MongoConnection connection, GridFsBucketInfo
/// <bucket>.chunks。
public IMongoCollection Chunks => connection.Collection(Bucket.Database, Bucket.ChunksCollection);
+ ///
+ /// 驱动的桶对象按块大小缓存(库与桶名在这个服务上是定的)。每次操作 new 一个的话,驱动每次都要重新确认
+ /// files / chunks 上的索引(第一次写入前会查一遍 listIndexes)—— 批量上传一个文件夹时这是每个文件一次往返。
+ ///
+ private readonly System.Collections.Concurrent.ConcurrentDictionary _drivers = new();
+
private GridFSBucket Driver(int chunkSize = DefaultChunkSize) =>
- new(connection.Database(Bucket.Database), new GridFSBucketOptions
+ _drivers.GetOrAdd(chunkSize, size => new GridFSBucket(connection.Database(Bucket.Database), new GridFSBucketOptions
{
BucketName = Bucket.Name,
- ChunkSizeBytes = chunkSize
- });
+ ChunkSizeBytes = size
+ }));
// ── 读 ─────────────────────────────────────────────────────────────────
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs
index 6b3bc50..3b67e7f 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.Catalog.cs
@@ -35,12 +35,24 @@ public async Task> ListDatabasesAsync(CancellationTo
return [.. list.OrderBy(static d => d.IsSystem ? 0 : 1).ThenBy(static d => d.Name, StringComparer.Ordinal)];
}
- /// 列出一个库里的集合与视图(含 options)。
+ ///
+ /// 列出一个库里的集合与视图(含 options)。
+ /// 只授了集合级权限的用户({ db: "shop", collection: "orders" } 上的 find)没有库级的 listCollections,
+ /// 完整列表会报 Unauthorized;那时退回 nameOnly + authorizedCollections —— 服务器只回他有权限的集合(没有 options)。
+ ///
public async Task> ListCollectionsAsync(string database, CancellationToken cancellationToken = default)
{
- using IAsyncCursor cursor = await Database(database)
- .ListCollectionsAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
- List raw = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);
+ List raw;
+ try
+ {
+ using IAsyncCursor cursor = await Database(database)
+ .ListCollectionsAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
+ raw = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (MongoCommandException ex) when (IsUnauthorized(ex))
+ {
+ raw = await ListAuthorizedCollectionsAsync(database, cancellationToken).ConfigureAwait(false);
+ }
return
[
.. raw.Select(doc => ToCollectionInfo(database, doc))
@@ -48,6 +60,55 @@ .. raw.Select(doc => ToCollectionInfo(database, doc))
];
}
+ /// Unauthorized(13)。
+ internal static bool IsUnauthorized(MongoCommandException ex) => ex.Code == 13 || ex.CodeName == "Unauthorized";
+
+ /// { listCollections: 1, nameOnly: true, authorizedCollections: true },把游标取完。
+ private async Task> ListAuthorizedCollectionsAsync(string database, CancellationToken cancellationToken)
+ {
+ BsonDocument reply = await RunCommandAsync(database, new BsonDocument
+ {
+ { "listCollections", 1 },
+ { "nameOnly", true },
+ { "authorizedCollections", true },
+ { "cursor", new BsonDocument() }
+ }, cancellationToken).ConfigureAwait(false);
+ var list = new List();
+ BsonDocument cursor = reply.GetValue("cursor", new BsonDocument()).AsBsonDocument;
+ list.AddRange(cursor.GetValue("firstBatch", new BsonArray()).AsBsonArray.OfType());
+ long id = cursor.GetValue("id", 0L).ToInt64();
+ string collectionName = cursor.GetValue("ns", $"{database}.$cmd.listCollections").ToString()!;
+ collectionName = collectionName[(collectionName.IndexOf('.', StringComparison.Ordinal) + 1)..];
+ while (id != 0)
+ {
+ BsonDocument more = await RunCommandAsync(database, new BsonDocument { { "getMore", id }, { "collection", collectionName } }, cancellationToken)
+ .ConfigureAwait(false);
+ BsonDocument next = more.GetValue("cursor", new BsonDocument()).AsBsonDocument;
+ list.AddRange(next.GetValue("nextBatch", new BsonArray()).AsBsonArray.OfType());
+ id = next.GetValue("id", 0L).ToInt64();
+ }
+ return list;
+ }
+
+ ///
+ /// 分片集合的分片键(config.collections 里的 key);未分片、不是 mongos 或读不了 config 库时为 。
+ /// 索引顾问拿它排除分片键的支撑索引()。
+ ///
+ public async Task GetShardKeyAsync(string database, string collection, CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ BsonDocument? entry = await Collection("config", "collections")
+ .Find(new BsonDocument("_id", $"{database}.{collection}"))
+ .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
+ return entry?.GetValue("key", null) as BsonDocument;
+ }
+ catch (MongoException)
+ {
+ return null;
+ }
+ }
+
internal static CollectionInfo ToCollectionInfo(string database, BsonDocument doc)
{
string name = doc["name"].AsString;
@@ -95,8 +156,9 @@ public async Task GetStatsAsync(string database, string collect
];
using IAsyncCursor cursor = await Collection(database, collection)
.AggregateAsync(pipeline, cancellationToken: cancellationToken).ConfigureAwait(false);
- BsonDocument? first = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
- storage = first?.GetValue("storageStats", new BsonDocument()).AsBsonDocument ?? [];
+ // mongos 上 $collStats 每个分片回一份:只取第一份会把分片集合的文档数、大小少算成一个分片的量。
+ List perShard = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);
+ storage = MergeShardStorage(perShard);
}
catch (MongoCommandException)
{
@@ -134,6 +196,52 @@ public async Task GetStatsAsync(string database, string collect
};
}
+ /// 可以跨分片相加的量。
+ private static readonly string[] AdditiveStats = ["count", "size", "storageSize", "totalIndexSize", "totalSize", "freeStorageSize"];
+
+ ///
+ /// 把 $collStats 的各分片结果并成一份:数量与大小相加,各索引大小按名相加,索引个数取最大,
+ /// 平均文档大小按合计重算。只有一份(未分片)时原样返回;多份时原文里另挂 shards: { 分片名: storageStats }。
+ ///
+ internal static BsonDocument MergeShardStorage(IReadOnlyList perShard)
+ {
+ List storages = [.. perShard.Select(static d => d.GetValue("storageStats", new BsonDocument()) as BsonDocument ?? [])];
+ if (storages.Count <= 1)
+ {
+ return storages.Count == 1 ? storages[0] : [];
+ }
+ var merged = new BsonDocument(storages[0].Where(static e => e.Name != "indexSizes"));
+ foreach (string name in AdditiveStats)
+ {
+ if (storages.Any(s => s.Contains(name)))
+ {
+ merged[name] = storages.Sum(s => Number(s, name));
+ }
+ }
+ merged["nindexes"] = storages.Max(static s => Number(s, "nindexes"));
+ long count = Number(merged, "count");
+ merged["avgObjSize"] = count > 0 ? Number(merged, "size") / count : 0;
+ var indexSizes = new BsonDocument();
+ foreach (BsonDocument storage in storages)
+ {
+ if (storage.GetValue("indexSizes", null) is BsonDocument sizes)
+ {
+ foreach (BsonElement element in sizes)
+ {
+ indexSizes[element.Name] = (indexSizes.TryGetValue(element.Name, out BsonValue seen) ? seen.ToInt64() : 0) + element.Value.ToInt64();
+ }
+ }
+ }
+ merged["indexSizes"] = indexSizes;
+ var shards = new BsonDocument();
+ for (int i = 0; i < perShard.Count; i++)
+ {
+ shards[perShard[i].GetValue("shard", $"shard{i}").ToString()!] = storages[i];
+ }
+ merged["shards"] = shards;
+ return merged;
+ }
+
/// 数据库统计(dbStats)。
public Task GetDatabaseStatsAsync(string database, CancellationToken cancellationToken = default) =>
RunCommandAsync(database, new BsonDocument("dbStats", 1), cancellationToken);
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs
index f952c5f..6ff10b0 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnection.cs
@@ -1,4 +1,5 @@
using System.Diagnostics;
+using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using MongoDB.Bson;
@@ -89,7 +90,10 @@ public static async Task ConnectAsync(
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
- TlsTrust? trust = settings.UseTls || settings.Topology != MongoTopology.Hosts ? new(settings.TrustedThumbprint) : null;
+ // 经隧道时驱动连的是 127.0.0.1,证书上的名字永远对不上:把真实目标交给 TlsTrust 自己核对。
+ TlsTrust? trust = settings.UseTls || settings.Topology != MongoTopology.Hosts
+ ? new(settings.TrustedThumbprint, request.Tunnel?.TargetHost)
+ : null;
MongoClientSettings clientSettings = BuildSettings(request, settings, trust);
var client = new MongoClient(clientSettings);
string endpoint = DescribeEndpoint(request, settings);
@@ -148,18 +152,25 @@ public static async Task ConnectAsync(string connectionString,
internal static MongoClientSettings BuildSettings(WorkspaceConnectRequest request, MongoSettings settings, TlsTrust? trust)
{
MongoClientSettings client;
+ HashSet uriOptions = [];
switch (settings.Topology)
{
case MongoTopology.Uri:
{
// URI 写在"主机"那一栏里。凭据可以在 URI 里,也可以填在用户名/密码两栏 ——
// 后者优先:那两栏的密码是宿主加密落盘的,URI 里的密码是明文。
- var url = new MongoUrlBuilder(request.Host.Trim());
+ string uri = request.Host.Trim();
+ var url = new MongoUrlBuilder(uri);
+ uriOptions = UriOptionNames(uri);
if (request.Tunnel is not null)
{
- // 走隧道时宿主把主机改写成了本地端点 —— 但 URI 模式下"主机"一栏是整条串,
- // 宿主改写的是它解析出来的第一台。这里按宿主给的端点直连那一台。
- url.Server = new(request.Host, request.Port);
+ // 走隧道时"主机"一栏仍是整条连接串(SshTunnel.RewriteTo 不动它),本地转发端口在 Port 上:
+ // 解析原串,把服务器换成回环上的转发端口并直连 —— 其余成员的真实地址经隧道够不着。
+ if (url.Scheme == ConnectionStringScheme.MongoDBPlusSrv)
+ {
+ throw new NotSupportedException("mongodb+srv:// cannot be forwarded through an SSH jump host.");
+ }
+ url.Server = new(IPAddress.Loopback.ToString(), request.Port);
url.DirectConnection = true;
}
if (!string.IsNullOrEmpty(request.Username))
@@ -188,8 +199,8 @@ internal static MongoClientSettings BuildSettings(WorkspaceConnectRequest reques
default:
{
client = new MongoClientSettings();
- var servers = new List { new(request.Host.Trim(), request.Port) };
bool tunneled = request.Tunnel is not null;
+ var servers = new List { new(tunneled ? IPAddress.Loopback.ToString() : request.Host.Trim(), request.Port) };
if (!tunneled)
{
foreach (string extra in settings.AdditionalHosts)
@@ -211,12 +222,30 @@ internal static MongoClientSettings BuildSettings(WorkspaceConnectRequest reques
}
}
- client.ApplicationName = settings.AppName;
- client.ConnectTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs);
- client.ServerSelectionTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs);
- client.ReadPreference = ParseReadPreference(settings.ReadPreference);
+ // URI 形态:连接串里写了的选项以连接串为准,只有用户在表单里显式改过(键在)才覆盖 ——
+ // 否则预览(ConnectionProbe.Preview,照 URI 画)与实际行为对不上。
+ bool fromUri = settings.Topology == MongoTopology.Uri;
+ if (!fromUri || settings.AppNameSet || client.ApplicationName is null)
+ {
+ client.ApplicationName = settings.AppName;
+ }
+ if (!fromUri || settings.ConnectTimeoutSet || !uriOptions.Contains("connecttimeoutms"))
+ {
+ client.ConnectTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs);
+ }
+ if (!fromUri || settings.ConnectTimeoutSet || !uriOptions.Contains("serverselectiontimeoutms"))
+ {
+ client.ServerSelectionTimeout = TimeSpan.FromMilliseconds(settings.ConnectTimeoutMs);
+ }
+ if (!fromUri || settings.ReadPreferenceSet)
+ {
+ client.ReadPreference = ParseReadPreference(settings.ReadPreference);
+ }
// 压缩:服务器不支持的会在握手时被协商掉,写上没有坏处 —— 远端大结果集上能省一大半带宽。
- client.Compressors = [new(CompressorType.ZStandard), new(CompressorType.Snappy), new(CompressorType.Zlib)];
+ if (!fromUri || client.Compressors is not { Count: > 0 })
+ {
+ client.Compressors = [new(CompressorType.ZStandard), new(CompressorType.Snappy), new(CompressorType.Zlib)];
+ }
bool tls = settings.UseTls || client.UseTls;
if (tls)
@@ -264,6 +293,23 @@ private static void ApplyCredential(MongoClientSettings client, WorkspaceConnect
};
}
+ /// 连接串里写了哪些选项(小写名;?a=1&b=2 与 ; 分隔都认)。
+ internal static HashSet UriOptionNames(string uri)
+ {
+ var names = new HashSet(StringComparer.Ordinal);
+ int query = uri.IndexOf('?', StringComparison.Ordinal);
+ if (query < 0)
+ {
+ return names;
+ }
+ foreach (string pair in uri[(query + 1)..].Split(['&', ';'], StringSplitOptions.RemoveEmptyEntries))
+ {
+ int eq = pair.IndexOf('=', StringComparison.Ordinal);
+ _ = names.Add(Uri.UnescapeDataString(eq < 0 ? pair : pair[..eq]).Trim().ToLowerInvariant());
+ }
+ return names;
+ }
+
internal static MongoServerAddress ParseAddress(string text)
{
int colon = text.LastIndexOf(':');
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs
index 66f7fe5..a07c90f 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoConnector.cs
@@ -130,7 +130,16 @@ public Task ProbeAsync(MongoProfile profile, string password, IProg
return ConnectionProbe.ProbeAsync(request, Loc, (ex, s) => Translate(ex, profile.ToRequest(""), s).Message, openTunnel, progress, cancellationToken);
}
- /// SRV 没有跳板可走:它靠 DNS 解析出一组成员,一条本地转发只通得到其中一台。
+ /// 连接串是 mongodb+srv://(URI 形态下"主机"一栏的写法)。
+ /// "主机"一栏。
+ /// 是不是 SRV 连接串。
+ internal static bool IsSrvUri(string host) =>
+ host.TrimStart().StartsWith("mongodb+srv://", StringComparison.OrdinalIgnoreCase);
+
+ ///
+ /// SRV 没有跳板可走:它靠 DNS 解析出一组成员,一条本地转发只通得到其中一台。
+ /// URI 形态写的 mongodb+srv:// 仍返回 true —— 开转发那一步会以 Conn_SshNoSrv 拒绝,而不是悄悄绕过跳板直连。
+ ///
/// 设置。
/// 要不要建转发。
public static bool UsesTunnel(MongoSettings settings) =>
@@ -138,6 +147,12 @@ public static bool UsesTunnel(MongoSettings settings) =>
private async Task OpenTunnelAsync(MongoProfile profile, WorkspaceConnectRequest request, MongoSettings settings, CancellationToken cancellationToken)
{
+ // URI 形态里写的 mongodb+srv:// 与 SRV 形态同理走不了跳板;但用户明确配了跳板,
+ // 悄悄改成直连会绕过跳板 —— 报清楚原因(连接失败卡片 / 测试的 SSH 一步)。
+ if (settings.Topology == MongoTopology.Uri && IsSrvUri(request.Host))
+ {
+ throw new NotSupportedException(Loc["Conn_SshNoSrv"]);
+ }
(string host, int port) = SshTunnel.TargetOf(request, settings);
string name = profile.Name.Length > 0 ? profile.Name : $"{host}:{port}";
return await SshTunnel.OpenAsync(context, settings.JumpSessionId, host, port,
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs b/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs
index 49788ef..1ff3582 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/MongoProfile.cs
@@ -33,14 +33,31 @@ internal sealed class MongoProfile
/// 用户名;空 = 匿名。
public string Username { get; set; } = "";
- /// 其余设置(键见 )。
- public Dictionary Settings { get; set; } = [with(StringComparer.Ordinal)];
+ ///
+ /// 其余设置(键见 )。**改值走 **: 有缓存,
+ /// 只在 与整体替换时失效。
+ ///
+ public Dictionary Settings
+ {
+ get => _settings;
+ set
+ {
+ _settings = value;
+ _parsed = null;
+ }
+ }
+
+ private Dictionary _settings = [with(StringComparer.Ordinal)];
+ private MongoSettings? _parsed;
/// 最近一次连上的时间(对象树按它排,常用的在上面)。
public DateTimeOffset? LastConnectedAt { get; set; }
- /// 解析好的设置。
- public MongoSettings Parsed => MongoSettings.From(ToRequest(""));
+ ///
+ /// 解析好的设置(惰性缓存:对象树每画一行都要读 ,每次都拷一份字典重新解析太浪费)。
+ /// 只依赖 ,所以只在 与替换 时失效。
+ ///
+ public MongoSettings Parsed => _parsed ??= MongoSettings.From(ToRequest(""));
/// 环境标记(对象树上的色点、生产连接默认只读)。
public MongoEnvironment Environment => Parsed.Environment;
@@ -85,6 +102,7 @@ public string Get(string key, string fallback = "") =>
/// 值。
public void Set(string key, string? value)
{
+ _parsed = null;
if (string.IsNullOrEmpty(value))
{
_ = Settings.Remove(key);
@@ -105,6 +123,15 @@ internal sealed class MongoProfileStore(IPluginContext context)
{
private const string ProfilesKey = "connections";
+ ///
+ /// 每个存储一把锁(按存储实例取,同一插件里 new 了几个 store 也是同一把)。
+ /// 保存 / 删除都是"读整表 → 改一条 → 写整表":连上时回写 与对话框里点保存撞在一起,
+ /// 后写的那个会拿着旧表把先写的改动盖掉。
+ ///
+ private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Locks = [];
+
+ private SemaphoreSlim Gate => Locks.GetValue(context.Storage, static _ => new SemaphoreSlim(1, 1));
+
private static string SecretName(string id) => $"password:{id}";
/// 全部已保存的连接。
@@ -124,17 +151,26 @@ public async Task> LoadAsync(CancellationToken cance
public async Task SaveAsync(MongoProfile profile, string? password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(profile);
- List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)];
- int index = list.FindIndex(p => p.Id == profile.Id);
- if (index >= 0)
+ MongoProfile copy = profile.Clone();
+ await Gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
{
- list[index] = profile.Clone();
+ List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)];
+ int index = list.FindIndex(p => p.Id == copy.Id);
+ if (index >= 0)
+ {
+ list[index] = copy;
+ }
+ else
+ {
+ list.Add(copy);
+ }
+ await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false);
}
- else
+ finally
{
- list.Add(profile.Clone());
+ _ = Gate.Release();
}
- await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false);
if (password is null)
{
return;
@@ -149,16 +185,54 @@ public async Task SaveAsync(MongoProfile profile, string? password, Cancellation
}
}
+ ///
+ /// 只回写"最近连上的时间"(在锁里按 id 改存储里那一条的这一个字段)。连上时用它,而不是拿手里那份
+ /// 可能已经过时的 整条 —— 那会把对话框刚存的修改盖回去。
+ /// 存储里已经没有这条(连的时候被删了)时什么都不做。
+ ///
+ /// 连接 id。
+ /// 时间。
+ /// 取消令牌。
+ /// 存储里有没有这条。
+ public async Task TouchLastConnectedAsync(string id, DateTimeOffset at, CancellationToken cancellationToken = default)
+ {
+ await Gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)];
+ MongoProfile? stored = list.Find(p => p.Id == id);
+ if (stored is null)
+ {
+ return false;
+ }
+ stored.LastConnectedAt = at;
+ await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false);
+ return true;
+ }
+ finally
+ {
+ _ = Gate.Release();
+ }
+ }
+
/// 删掉一条(连同口令)。
/// 连接 id。
/// 取消令牌。
/// 任务。
public async Task DeleteAsync(string id, CancellationToken cancellationToken = default)
{
- List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)];
- if (list.RemoveAll(p => p.Id == id) > 0)
+ await Gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
{
- await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false);
+ List list = [.. await LoadAsync(cancellationToken).ConfigureAwait(false)];
+ if (list.RemoveAll(p => p.Id == id) > 0)
+ {
+ await context.Storage.SetAsync(ProfilesKey, list, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ finally
+ {
+ _ = Gate.Release();
}
_ = await context.Secrets.DeleteAsync(SecretName(id), cancellationToken).ConfigureAwait(false);
}
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs b/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs
index 69ed00c..b766975 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/SshTunnel.cs
@@ -3,7 +3,9 @@
using System.Net;
using System.Net.Sockets;
using MongoDB.Driver;
+using MongoDB.Driver.Core.Configuration;
using VelaShell.PluginSdk;
+using VelaShell.PluginSdk.Logging;
using VelaShell.PluginSdk.RemoteTunnel;
using VelaShell.PluginSdk.Sessions;
using VelaShell.PluginSdk.Workspaces;
@@ -30,7 +32,11 @@ internal interface IMongoTunnel : IAsyncDisposable
/// 毫秒。
Task CheckTargetAsync(CancellationToken cancellationToken);
- /// 把请求改写成连本地端点( 记下真实目标)。
+ ///
+ /// 把请求改写成连本地端点( 记下真实目标)。
+ /// 本地端点 = 回环 + ;主机列表形态的"主机"一栏改成回环,
+ /// URI 形态的"主机"一栏是整条连接串,原样保留(见 )。
+ ///
/// 原请求。
/// 改写后的请求。
WorkspaceConnectRequest Rewrite(WorkspaceConnectRequest request);
@@ -43,7 +49,7 @@ internal interface IMongoTunnel : IAsyncDisposable
internal sealed class SshTunnel : IMongoTunnel
{
private readonly IPluginContext _context;
- private readonly JumpLease _lease;
+ private readonly SshJumpLease _lease;
private readonly TcpListener _listener;
private readonly CancellationTokenSource _lifetime = new();
private readonly ConcurrentDictionary _pumps = new();
@@ -52,7 +58,7 @@ internal sealed class SshTunnel : IMongoTunnel
private int _nextPump;
private int _disposed;
- private SshTunnel(IPluginContext context, JumpLease lease, string host, int port)
+ private SshTunnel(IPluginContext context, SshJumpLease lease, string host, int port)
{
_context = context;
_lease = lease;
@@ -91,7 +97,8 @@ public static async Task OpenAsync(
string reason,
CancellationToken cancellationToken)
{
- JumpLease lease = await JumpLease.AcquireAsync(context, savedSessionId, reason, cancellationToken).ConfigureAwait(false);
+ SshJumpLease lease = await SshJumpLease.AcquireAsync(context.Sessions, context.RemoteTunnel, context.Log, savedSessionId, reason, cancellationToken)
+ .ConfigureAwait(false);
try
{
return new SshTunnel(context, lease, host, port);
@@ -111,28 +118,56 @@ public static (string Host, int Port) TargetOf(WorkspaceConnectRequest request,
{
if (settings.Topology == MongoTopology.Uri)
{
- MongoServerAddress first = new MongoUrlBuilder(request.Host.Trim()).Servers.First();
+ var url = new MongoUrlBuilder(request.Host.Trim());
+ if (url.Scheme == ConnectionStringScheme.MongoDBPlusSrv)
+ {
+ // SRV 连接串经 DNS 解析出一组成员,一条转发只通得到其中一台;SRV 记录里的名字本身也不是 mongod。
+ throw new NotSupportedException("mongodb+srv:// cannot be forwarded through an SSH jump host.");
+ }
+ MongoServerAddress first = url.Servers.First();
return (first.Host, first.Port);
}
return (request.Host.Trim(), request.Port);
}
+ /// "主机"一栏写的是整条连接串(URI 形态)。
+ /// "主机"一栏。
+ /// 是不是连接串。
+ internal static bool IsUriHost(string host)
+ {
+ string trimmed = host.TrimStart();
+ return trimmed.StartsWith("mongodb://", StringComparison.OrdinalIgnoreCase)
+ || trimmed.StartsWith("mongodb+srv://", StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// 改写成连本地端点。URI 形态下"主机"一栏是整条连接串(库名、选项、凭据都在里面),**不能**换成 127.0.0.1 ——
+ /// 那样 拿到的就不是连接串了;本地端点只记在 Port 上,
+ /// 拼设置时解析原串再把服务器换成回环 + Port。
+ ///
+ /// 原请求。
+ /// 本机回环上的转发端口。
+ /// 真实目标与跳板名。
+ /// 改写后的请求。
+ internal static WorkspaceConnectRequest RewriteTo(WorkspaceConnectRequest request, int localPort, WorkspaceTunnelInfo tunnel) => request with
+ {
+ Host = IsUriHost(request.Host) ? request.Host : IPAddress.Loopback.ToString(),
+ Port = localPort,
+ Tunnel = tunnel
+ };
+
///
public async Task CheckTargetAsync(CancellationToken cancellationToken)
{
var watch = Stopwatch.StartNew();
- Stream stream = await _context.RemoteTunnel.OpenTcpAsync(_lease.SessionId, _host, _port, null, cancellationToken).ConfigureAwait(false);
+ Stream stream = await _lease.OpenTcpAsync(_host, _port, cancellationToken).ConfigureAwait(false);
await stream.DisposeAsync().ConfigureAwait(false);
return (int)watch.ElapsedMilliseconds;
}
///
- public WorkspaceConnectRequest Rewrite(WorkspaceConnectRequest request) => request with
- {
- Host = IPAddress.Loopback.ToString(),
- Port = LocalPort,
- Tunnel = new WorkspaceTunnelInfo(_host, _port, JumpName)
- };
+ public WorkspaceConnectRequest Rewrite(WorkspaceConnectRequest request) =>
+ RewriteTo(request, LocalPort, new WorkspaceTunnelInfo(_host, _port, JumpName));
private async Task AcceptLoopAsync()
{
@@ -160,7 +195,7 @@ private async Task PumpAsync(int id, TcpClient client)
Stream? remote = null;
try
{
- remote = await _context.RemoteTunnel.OpenTcpAsync(_lease.SessionId, _host, _port, null, _lifetime.Token).ConfigureAwait(false);
+ remote = await _lease.OpenTcpAsync(_host, _port, _lifetime.Token).ConfigureAwait(false);
_pumps[id] = (client, remote);
NetworkStream local = client.GetStream();
Task up = local.CopyToAsync(remote, _lifetime.Token);
@@ -169,7 +204,7 @@ private async Task PumpAsync(int id, TcpClient client)
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
- // 跳板上开不出流(目标拒连、会话断了):关掉本地这一头,驱动会当成一次普通的连接失败处理。
+ // 跳板上开不出流(目标拒连、会话断了且重开失败):关掉本地这一头,驱动会当成一次普通的连接失败处理。
if (!_lifetime.IsCancellationRequested)
{
_context.Log.Warn($"SSH forward to {Target} via {JumpName} failed: {ex.Message}");
@@ -207,94 +242,244 @@ public async ValueTask DisposeAsync()
_lifetime.Dispose();
await _lease.DisposeAsync().ConfigureAwait(false);
}
+}
- ///
- /// 一条跳板会话的引用计数。几个 MongoDB 连接走同一台跳板时共用一条 SSH 会话,最后一个走了才关;
- /// 而且只关**本插件开的**那条 —— 用户自己开着的终端会话宿主不让关(),那就留着。
- ///
- private sealed class JumpLease : IAsyncDisposable
+///
+/// 一条跳板会话的引用计数。几个 MongoDB 连接走同一台跳板时共用一条 SSH 会话,最后一个走了才关;
+/// 而且只关**本插件开的**那条 —— 用户自己开着的终端会话宿主不让关(),那就留着。
+///
+/// 跳板会话会自己断(网络抖、用户在宿主里关了它):共用表里记着的那个 SessionId 就成了死的。
+/// 开流失败且查实会话已不在时,就地重开一条、换掉共用表里的会话,再试一次 ——
+/// 否则这条跳板上之后的每一次连接都会永远失败。
+///
+///
+internal sealed class SshJumpLease : IAsyncDisposable
+{
+ private static readonly Lock Gate = new();
+ private static readonly Dictionary Open = [with(StringComparer.Ordinal)];
+
+ private readonly ISessionsApi _sessions;
+ private readonly IRemoteTunnelApi _tunnel;
+ private readonly IPluginLogger _log;
+ private readonly string _savedSessionId;
+ private readonly Shared _shared;
+ private int _disposed;
+
+ private SshJumpLease(ISessionsApi sessions, IRemoteTunnelApi tunnel, IPluginLogger log, string savedSessionId, Shared shared)
{
- private static readonly Lock Gate = new();
- private static readonly Dictionary Open = [with(StringComparer.Ordinal)];
+ _sessions = sessions;
+ _tunnel = tunnel;
+ _log = log;
+ _savedSessionId = savedSessionId;
+ _shared = shared;
+ }
- private readonly IPluginContext _context;
- private readonly string _savedSessionId;
- private readonly Shared _shared;
- private int _disposed;
+ /// 当前用的会话 id(断线重开后会换)。
+ public string SessionId => _shared.Session.SessionId;
- private JumpLease(IPluginContext context, string savedSessionId, Shared shared)
+ /// 跳板的显示名。
+ public string Name => _shared.Name;
+
+ /// 共用表里这条已保存连接的引用数;不在表里为 0(单测用)。
+ /// 已保存的 SSH 连接 id。
+ /// 引用数。
+ internal static int SharedCount(string savedSessionId)
+ {
+ lock (Gate)
{
- _context = context;
- _savedSessionId = savedSessionId;
- _shared = shared;
+ return Open.TryGetValue(savedSessionId, out Shared? shared) ? shared.Count : 0;
}
+ }
- public string SessionId => _shared.Session.SessionId;
-
- public string Name => _shared.Name;
-
- public static async Task AcquireAsync(IPluginContext context, string savedSessionId, string reason, CancellationToken cancellationToken)
+ /// 取一份租约:表里已有就加计数,没有就请宿主开一条。
+ /// 会话能力。
+ /// 隧道能力。
+ /// 日志。
+ /// 已保存的 SSH 连接 id。
+ /// 给用户看的理由。
+ /// 取消令牌。
+ /// 租约。
+ public static async Task AcquireAsync(
+ ISessionsApi sessions,
+ IRemoteTunnelApi tunnel,
+ IPluginLogger log,
+ string savedSessionId,
+ string reason,
+ CancellationToken cancellationToken)
+ {
+ lock (Gate)
{
- lock (Gate)
+ if (Open.TryGetValue(savedSessionId, out Shared? shared))
{
- if (Open.TryGetValue(savedSessionId, out Shared? shared))
- {
- shared.Count++;
- return new JumpLease(context, savedSessionId, shared);
- }
+ shared.Count++;
+ return new SshJumpLease(sessions, tunnel, log, savedSessionId, shared);
}
- IReadOnlyList saved = await context.Sessions.ListSavedAsync(cancellationToken).ConfigureAwait(false);
- string name = saved.FirstOrDefault(s => s.SavedSessionId == savedSessionId)?.Name ?? savedSessionId;
- SessionInfo session = await context.Sessions.OpenAsync(savedSessionId, new SessionOpenOptions(reason), cancellationToken).ConfigureAwait(false);
- lock (Gate)
+ }
+ IReadOnlyList saved = await sessions.ListSavedAsync(cancellationToken).ConfigureAwait(false);
+ string name = saved.FirstOrDefault(s => s.SavedSessionId == savedSessionId)?.Name ?? savedSessionId;
+ SessionInfo session = await sessions.OpenAsync(savedSessionId, new SessionOpenOptions(reason), cancellationToken).ConfigureAwait(false);
+ Shared? winner = null;
+ lock (Gate)
+ {
+ if (Open.TryGetValue(savedSessionId, out Shared? raced))
{
- // 等宿主连的这段时间里可能已经有别的连接开好了同一条:用先到的那条,自己这条交还计数。
- if (Open.TryGetValue(savedSessionId, out Shared? raced))
- {
- raced.Count++;
- return new JumpLease(context, savedSessionId, raced);
- }
- var fresh = new Shared(session, name) { Count = 1 };
+ raced.Count++;
+ winner = raced;
+ }
+ else
+ {
+ var fresh = new Shared(session, name, reason) { Count = 1 };
Open[savedSessionId] = fresh;
- return new JumpLease(context, savedSessionId, fresh);
+ return new SshJumpLease(sessions, tunnel, log, savedSessionId, fresh);
}
}
+ // 等宿主连的这段时间里已经有别的连接开好了同一条:用先到的那条,自己刚开的这条关掉 ——
+ // 不关就是宿主里一条没人管的 SSH 会话。宿主复用了同一条会话(id 相同)时不能关,那是先到者在用的。
+ if (!string.Equals(session.SessionId, winner.Session.SessionId, StringComparison.Ordinal))
+ {
+ await CloseQuietlyAsync(sessions, log, session.SessionId, name).ConfigureAwait(false);
+ }
+ return new SshJumpLease(sessions, tunnel, log, savedSessionId, winner);
+ }
- public async ValueTask DisposeAsync()
+ ///
+ /// 在跳板机上开一条到目标的流。失败且查实跳板会话已经不在(宿主说找不到、或状态是断开 / 出错)时,
+ /// 重开一条会话换进共用表,再试一次;只重试这一次,第二次失败原样抛。
+ ///
+ /// 目标主机(跳板机看到的)。
+ /// 目标端口。
+ /// 取消令牌。
+ /// 双工流。
+ public async Task OpenTcpAsync(string host, int port, CancellationToken cancellationToken)
+ {
+ SessionInfo session = _shared.Session;
+ try
+ {
+ return await _tunnel.OpenTcpAsync(session.SessionId, host, port, null, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException))
{
- if (Interlocked.Exchange(ref _disposed, 1) != 0)
+ if (!await IsGoneAsync(session.SessionId, ex, cancellationToken).ConfigureAwait(false))
{
- return;
+ throw;
}
+ _log.Info($"SSH jump session '{Name}' is gone ({ex.Message}); reopening it.");
+ }
+ SessionInfo fresh = await ReopenAsync(session, cancellationToken).ConfigureAwait(false);
+ return await _tunnel.OpenTcpAsync(fresh.SessionId, host, port, null, cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task IsGoneAsync(string sessionId, Exception failure, CancellationToken cancellationToken)
+ {
+ if (failure is PluginSessionNotFoundException)
+ {
+ return true;
+ }
+ try
+ {
+ SessionInfo? now = await _sessions.GetAsync(sessionId, cancellationToken).ConfigureAwait(false);
+ return now is null || now.State is SessionState.Disconnected or SessionState.Error;
+ }
+ catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException))
+ {
+ // 连查都查不了:不猜,按原来的失败报。
+ return false;
+ }
+ }
+
+ /// 重开跳板会话(同一时刻只开一条:几条泵同时发现会话断了,只有第一条去开,其余用它开好的)。
+ private async Task ReopenAsync(SessionInfo stale, CancellationToken cancellationToken)
+ {
+ await _shared.ReopenGate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ ObjectDisposedException.ThrowIf(_shared.Closed, this);
+ if (!string.Equals(_shared.Session.SessionId, stale.SessionId, StringComparison.Ordinal))
+ {
+ return _shared.Session;
+ }
+ SessionInfo fresh = await _sessions.OpenAsync(_savedSessionId, new SessionOpenOptions(_shared.Reason), cancellationToken).ConfigureAwait(false);
+ bool closed;
lock (Gate)
{
- if (--_shared.Count > 0)
+ closed = _shared.Closed;
+ if (!closed)
{
- return;
+ _shared.Session = fresh;
}
- _ = Open.Remove(_savedSessionId);
}
- try
+ if (closed)
{
- await _context.Sessions.CloseAsync(_shared.Session.SessionId).ConfigureAwait(false);
+ // 重开的这段时间里最后一个租约走了:新开的这条没人用,关掉。
+ await CloseQuietlyAsync(_sessions, _log, fresh.SessionId, Name).ConfigureAwait(false);
+ throw new ObjectDisposedException(nameof(SshJumpLease));
}
- catch (PluginPermissionDeniedException)
+ return fresh;
+ }
+ finally
+ {
+ _ = _shared.ReopenGate.Release();
+ }
+ }
+
+ ///
+ public async ValueTask DisposeAsync()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) != 0)
+ {
+ return;
+ }
+ string sessionId;
+ lock (Gate)
+ {
+ if (--_shared.Count > 0)
{
- // 宿主复用了用户自己开着的那条会话:不归插件关。
+ return;
}
- catch (Exception ex) when (ex is not OutOfMemoryException)
+ _shared.Closed = true;
+ sessionId = _shared.Session.SessionId;
+ if (Open.TryGetValue(_savedSessionId, out Shared? current) && ReferenceEquals(current, _shared))
{
- _context.Log.Warn($"Closing the SSH jump session '{_shared.Name}' failed: {ex.Message}");
+ _ = Open.Remove(_savedSessionId);
}
}
+ await CloseQuietlyAsync(_sessions, _log, sessionId, _shared.Name).ConfigureAwait(false);
+ }
- private sealed class Shared(SessionInfo session, string name)
+ private static async Task CloseQuietlyAsync(ISessionsApi sessions, IPluginLogger log, string sessionId, string name)
+ {
+ try
{
- public SessionInfo Session { get; } = session;
+ await sessions.CloseAsync(sessionId).ConfigureAwait(false);
+ }
+ catch (PluginPermissionDeniedException)
+ {
+ // 宿主复用了用户自己开着的那条会话:不归插件关。
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ log.Warn($"Closing the SSH jump session '{name}' failed: {ex.Message}");
+ }
+ }
- public string Name { get; } = name;
+ private sealed class Shared(SessionInfo session, string name, string reason)
+ {
+ private volatile SessionInfo _session = session;
- public int Count { get; set; }
+ public SessionInfo Session
+ {
+ get => _session;
+ set => _session = value;
}
+
+ public string Name { get; } = name;
+
+ public string Reason { get; } = reason;
+
+ public int Count { get; set; }
+
+ public bool Closed { get; set; }
+
+ public SemaphoreSlim ReopenGate { get; } = new(1, 1);
}
}
diff --git a/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs b/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs
index c57f835..6d7c2d3 100644
--- a/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Core/TlsTrust.cs
@@ -13,7 +13,11 @@ namespace VelaShell.Plugin.Mongo.Core;
///
///
/// 用户此前确认信任的指纹;为空表示还没信任过。
-internal sealed class TlsTrust(string? trustedThumbprint)
+///
+/// 经 SSH 跳板时的真实目标主机。驱动连的是本机回环,系统校验必报 ;
+/// 这时改由这里拿证书的 SAN / CN 对真实主机核对,对上了才把这一条错误抹掉。不走跳板为 。
+///
+internal sealed class TlsTrust(string? trustedThumbprint, string? tunnelTargetHost = null)
{
/// 最近一次校验失败时看到的证书;没失败过为 。
public X509Certificate2? SeenCertificate { get; private set; }
@@ -40,6 +44,15 @@ public bool Validate(X509Certificate? certificate, X509Chain? chain, SslPolicyEr
}
X509Certificate2 typed = certificate as X509Certificate2
?? X509CertificateLoader.LoadCertificate(certificate.GetRawCertData());
+ if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0 && MatchesTunnelTarget(typed))
+ {
+ // 名字不匹配只是因为驱动连的是 127.0.0.1;证书确实是发给真实目标的,这一条不算错。
+ errors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
+ if (errors == SslPolicyErrors.None)
+ {
+ return true;
+ }
+ }
if (!string.IsNullOrEmpty(trustedThumbprint)
&& string.Equals(typed.Thumbprint, trustedThumbprint, StringComparison.OrdinalIgnoreCase))
{
@@ -61,4 +74,21 @@ public bool Validate(X509Certificate? certificate, X509Chain? chain, SslPolicyEr
PolicyErrors = errors;
return false;
}
+
+ /// 证书的 SAN(没有 SAN 时退回 CN)覆盖跳板后面的真实主机。
+ private bool MatchesTunnelTarget(X509Certificate2 certificate)
+ {
+ if (string.IsNullOrWhiteSpace(tunnelTargetHost))
+ {
+ return false;
+ }
+ try
+ {
+ return certificate.MatchesHostname(tunnelTargetHost.Trim().Trim('[', ']'));
+ }
+ catch (ArgumentException)
+ {
+ return false;
+ }
+ }
}
diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs
index d406189..18b3963 100644
--- a/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Loc.Design.cs
@@ -259,8 +259,17 @@ private static readonly (string Key, string En, string Zh)[] DesignTexts =
("Design_ApplyTitle", "Apply validation rule", "应用验证规则"),
("Design_ApplyBody", "Run collMod on {0} with validationLevel {1} · validationAction {2}?",
"对 {0} 执行 collMod:validationLevel {1} · validationAction {2}?"),
- ("Design_ApplyRejects", "{0} existing documents fail it; updates to them will be rejected.", "有 {0} 份现有文档不符合,对它们的更新会被拒绝。"),
- ("Design_ApplyWarns", "{0} existing documents fail it; writes to them will log warnings.", "有 {0} 份现有文档不符合,对它们的写入会记录警告。"),
+ ("Design_ApplyFailCount", "{0} existing documents fail it.", "有 {0} 份现有文档不符合。"),
+ ("Design_ApplyFailSampled", "{0} of {1} sampled documents fail it.", "抽样的 {1} 份里有 {0} 份不符合。"),
+ ("Design_ApplyConseqReject", "Updates to such documents will be rejected.", "对这类文档的更新会被拒绝。"),
+ ("Design_ApplyConseqWarn", "Writes to such documents will be allowed and logged as warnings.", "对这类文档的写入照常进行,并记录警告。"),
+ ("Design_ApplyConseqModerate", "With moderate, updates to documents that already fail are not validated; inserts and updates to valid documents are.",
+ "moderate 下,对本就不符合的文档的更新不做校验;插入与对合规文档的更新照常校验。"),
+ ("Design_ApplyConseqOff", "Validation is off, so nothing is enforced.", "validationLevel 为 off,规则不生效。"),
+ ("Design_ApplyUnknown", "The pre-check hasn't finished, so it's unknown how many existing documents fail.", "预检尚未完成,现有文档有多少不符合还不知道。"),
+ ("Design_ViewAllInGrid", "View all failing in grid", "在网格中查看全部不通过"),
+ ("Design_ViewAllInGridTip", "This group is too large to list by _id: the grid shows every document that fails the rule, not only this group.",
+ "这一组太多,无法按 _id 列出:网格里显示的是全部不符合规则的文档,而不只是这一组。"),
("Design_PrecheckFailures", "Failing (pre-check)", "预检不通过"),
("Design_Applied", "Validation rule applied", "已应用验证规则"),
("Design_CompletionKeyword", "keyword", "关键字"),
diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs b/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs
index e577e71..09d81b7 100644
--- a/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Loc.GridFs.cs
@@ -77,6 +77,10 @@ private static readonly (string Key, string En, string Zh)[] GridFsTexts =
("Fs_Idle", "No transfers", "无传输任务"),
("Fs_CancelTransfers", "Cancel transfers", "取消传输"),
("Fs_TransfersCancelled", "Transfers cancelled", "已取消传输"),
+ ("Fs_CloseTransfersTitle", "Cancel transfers and close?", "取消传输并关闭?"),
+ ("Fs_CloseTransfersBody", "{0} transfers are still running or queued. Closing the tab cancels them; partly downloaded files are deleted and a cancelled upload leaves nothing behind.",
+ "还有 {0} 个传输在进行或排队。关闭标签会全部取消:下载到一半的文件会删掉,取消的上传不留残余。"),
+ ("Fs_CloseTransfersConfirm", "Cancel and close", "取消并关闭"),
("Fs_UploadDone", "Uploaded {0} files · {1}", "已上传 {0} 个文件 · {1}"),
("Fs_DownloadDone", "Downloaded {0} files · {1}", "已下载 {0} 个文件 · {1}"),
("Fs_TransferFailed", "{0} failed: {1}", "{0} 失败:{1}"),
diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs
index 08a30ca..fc19253 100644
--- a/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Loc.Objects.cs
@@ -92,6 +92,7 @@ private static readonly (string Key, string En, string Zh)[] ObjectsTexts =
("Obj_CopiedDdl", "Copied the structure of {0}", "已复制 {0} 的结构"),
("Obj_CopiedDdlDetail", "{0} lines of mongosh", "{0} 行 mongosh 脚本"),
("Obj_DropBucketTitle", "Drop GridFS bucket", "删除 GridFS 存储桶"),
+ ("Obj_DropBucketPartial", "Bucket {0} was only partly dropped: {1} is still there ({2})", "存储桶 {0} 只删掉了一半:{1} 还在({2})"),
("Obj_DropBucketBody", "This permanently deletes the bucket {0} — both .files and .chunks — and every file in it. This cannot be undone.",
"将永久删除存储桶 {0}(.files 与 .chunks 两个集合)及其中全部文件。此操作无法撤销。")
];
diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs
index f76876a..24bbe47 100644
--- a/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Loc.Query.cs
@@ -242,6 +242,10 @@ private static readonly (string Key, string En, string Zh)[] QueryTexts =
("Query_SnipMatchEqHint", "Keep documents whose field equals a value.", "保留字段等于某个值的文档。"),
("Query_SnipGroupCount", "$group count…", "$group 计数…"),
("Query_SnipGroupCountHint", "Count documents per value of a field.", "按字段取值分组计数。"),
+ ("Query_SnipField", "", "<字段>"),
+ ("Query_SnipValue", "", "<值>"),
+ ("Query_CodeTunnelNote", "VelaShell reaches this server through an SSH jump host; the address below is the real target, so this code must reach it directly (or through its own tunnel).",
+ "VelaShell 经 SSH 跳板连接这台服务器;下面是跳板后面的真实地址,运行这段代码的机器要能直接到达它(或自己建隧道)。"),
// ── 右侧面板 ──
("Query_HelperFields", "Fields", "字段"),
diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs
index 831f89a..861ac97 100644
--- a/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Loc.Transfer.cs
@@ -234,6 +234,12 @@ private static readonly (string Key, string En, string Zh)[] TransferTexts =
("Imp_OpenReport", "Show error report", "打开错误报告"),
("Imp_NotWritten", "Not written: the ordered batch stopped at row {0}", "未写入:ordered 批次在第 {0} 行出错后停止"),
("Imp_Stop", "Stop import", "停止导入"),
+ ("Imp_StopTitle", "Stop the import?", "停止导入?"),
+ ("Imp_StopBody", "Rows already written stay in the collection; the batch being written may or may not be committed. A stopped import can't be resumed — the error report and backup written so far are kept.",
+ "已写入的行留在集合里;正在写的那一批可能写进去、也可能没有。停止后不能接着导 —— 已写出的错误报告与备份会保留。"),
+ ("Imp_FailedPartial", "Import failed: {0} — {1} inserted and {2} updated before the failure", "导入失败:{0} —— 失败前已新增 {1}、更新 {2}"),
+ ("Imp_BackupFile", "Backup of overwritten documents", "覆盖前备份"),
+ ("Imp_OpenBackup", "Show backup", "打开备份"),
("Imp_SaveProfile", "Save as import profile", "保存为导入配置"),
// ── 数据传输(设计稿 21) ──
diff --git a/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs b/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs
index 353b628..f21fee1 100644
--- a/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Loc.Users.cs
@@ -70,6 +70,7 @@ private static readonly (string Key, string En, string Zh)[] UsersTexts =
("Users_BadAddress", "Not an IP address or CIDR: {0}", "不是 IP 地址或 CIDR:{0}"),
("Users_NeedName", "Enter a user name", "请填写用户名"),
("Users_NeedPassword", "Enter or generate a password", "请填写或生成密码"),
+ ("Users_NeedConfirmPassword", "Type the password again to confirm it", "请再输一遍密码以确认"),
("Users_NameTaken", "{0} already exists", "{0} 已存在"),
// ── 角色编辑器 ──
@@ -124,6 +125,13 @@ private static readonly (string Key, string En, string Zh)[] UsersTexts =
"A strong random password replaces the current one of {0}. It is copied to the clipboard and shown once. Applications still using the old password fail at their next login.",
"将为 {0} 生成一个强随机密码并立即替换当前密码;新密码复制到剪贴板并只显示一次。仍在用旧密码的应用下次登录时会失败。"),
("Users_PasswordChanged", "Password of {0} changed", "已更新 {0} 的密码"),
+ ("Users_SelfPasswordTitle", "Change the password of the current connection's user?", "修改当前连接所用账号的密码?"),
+ ("Users_SelfPasswordBody",
+ "{0} is the identity this connection logged in with. Sockets already open stay authenticated, but new pooled sockets and reconnects use the password the connection was opened with and will be rejected until you reconnect. If this connection has a saved password, it is updated to the new one.",
+ "{0} 是这条连接登录所用的身份。已打开的连接不受影响,但连接池新开的连接与重连仍用打开时的密码,会被拒绝,直到重新连接。这条连接若保存了密码,会一并更新成新密码。"),
+ ("Users_SelfPasswordContinue", "Continue", "继续"),
+ ("Users_SavedPasswordUpdated", "Saved password of this connection updated — reconnect to use it", "已更新这条连接保存的密码 —— 重新连接后生效"),
+ ("Users_SavedPasswordFailed", "The saved password of this connection could not be updated: {0}", "未能更新这条连接保存的密码:{0}"),
("Users_ResetTitle", "Reset password", "重置密码"),
("Users_NewPassword", "New password", "新密码"),
("Users_ConfirmPassword", "Type it again", "再输一遍"),
diff --git a/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs b/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs
index ea39625..b128f07 100644
--- a/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs
+++ b/plugins/VelaShell.Plugin.Mongo/MongoSettings.cs
@@ -203,10 +203,25 @@ public static MongoSettings From(WorkspaceConnectRequest request)
},
ShowSystemDatabases = request.GetBoolean(KeyShowSystemDatabases),
JumpSessionId = request.GetString(KeyJumpSession),
- TrustedThumbprint = request.GetString(KeyTrustedThumbprint)
+ TrustedThumbprint = request.GetString(KeyTrustedThumbprint),
+ ReadPreferenceSet = request.Settings.ContainsKey(KeyReadPreference),
+ AppNameSet = request.Settings.ContainsKey(KeyAppName),
+ ConnectTimeoutSet = request.Settings.ContainsKey(KeyConnectTimeout)
};
}
+ // 下面三个标记只给 URI 形态用:对话框把默认值存成"没有这个键",所以"键在"就是用户在表单里改过。
+ // URI 里写了 readPreference / appName / connectTimeoutMS 时,表单没改过就听 URI 的。
+
+ /// 读偏好是用户在表单里显式设的(不是默认值)。
+ public bool ReadPreferenceSet { get; init; }
+
+ /// appName 是用户在表单里显式设的。
+ public bool AppNameSet { get; init; }
+
+ /// 连接超时是用户在表单里显式设的。
+ public bool ConnectTimeoutSet { get; init; }
+
private static bool? ExplicitBool(WorkspaceConnectRequest request, string key) =>
request.Settings.TryGetValue(key, out string? raw) && bool.TryParse(raw, out bool parsed) ? parsed : null;
diff --git a/plugins/VelaShell.Plugin.Mongo/MongoStore.cs b/plugins/VelaShell.Plugin.Mongo/MongoStore.cs
index 704f015..db97773 100644
--- a/plugins/VelaShell.Plugin.Mongo/MongoStore.cs
+++ b/plugins/VelaShell.Plugin.Mongo/MongoStore.cs
@@ -30,7 +30,7 @@ internal sealed record SavedItem(string Name, string Content, DateTimeOffset Sav
///
///
/// 插件上下文。
-internal sealed class MongoStore(IPluginContext context)
+internal sealed partial class MongoStore(IPluginContext context)
{
private const string HistoryMeasurement = "query_history";
private const int HistoryLimit = 300;
@@ -103,7 +103,11 @@ public async Task SaveItemAsync(string kind, string connectionKey, SavedItem ite
await SetAsync(Key("saved-" + kind, connectionKey, ""), next).ConfigureAwait(false);
}
- /// 追加一条查询历史。
+ ///
+ /// 追加一条查询历史。落盘前先脱敏(:口令字面量换成星号)再截断到
+ /// —— 口令只该在宿主的密钥库里,不该躺在明文的历史表里;
+ /// 一段几兆的脚本也不该整段塞进每一条历史。
+ ///
public async Task AppendQueryHistoryAsync(string connectionKey, QueryHistoryEntry entry)
{
if (await OpenHistoryAsync().ConfigureAwait(false) is not { } series)
@@ -117,7 +121,7 @@ await series.WriteAsync(new(
new Dictionary { ["conn"] = connectionKey, ["db"] = entry.Database },
new Dictionary
{
- ["text"] = TimeSeriesValue.FromText(entry.Text),
+ ["text"] = TimeSeriesValue.FromText(PrepareHistoryText(entry.Text)),
["ms"] = TimeSeriesValue.FromInteger(entry.ElapsedMs),
["ok"] = TimeSeriesValue.FromFlag(entry.Ok)
})).ConfigureAwait(false);
@@ -193,4 +197,49 @@ public async Task> LoadQueryHistoryAsync(string
private static string Key(string kind, string connectionKey, string ns) =>
string.Create(CultureInfo.InvariantCulture, $"{kind}:{connectionKey}:{ns}");
+
+ /// 一条历史最多存多少个字符(超出截断并加省略号)。
+ internal const int HistoryTextLimit = 8 * 1024;
+
+ /// 脱敏 + 截断(先脱敏再截,免得截断把口令字面量切成半截、正则认不出来)。
+ internal static string PrepareHistoryText(string text)
+ {
+ string redacted = RedactHistoryText(text);
+ return redacted.Length > HistoryTextLimit ? redacted[..HistoryTextLimit] + "…" : redacted;
+ }
+
+ ///
+ /// 把语句里的口令换成 "***":
+ /// pwd / password / passwordDigest 键后的字符串字面量(createUser、updateUser、db.auth({…}));
+ /// changeUserPassword(user, "…") 与 db.auth(user, "…") 的第二个实参;连接串里 user:口令@ 的口令。
+ /// pwd: passwordPrompt() 之类不是字面量的值原样保留 —— 那里本来就没有口令。
+ ///
+ internal static string RedactHistoryText(string text)
+ {
+ if (string.IsNullOrEmpty(text))
+ {
+ return text;
+ }
+ string result = PasswordField().Replace(text, static m => m.Groups["key"].Value + Mask(m.Groups["quote"].Value));
+ result = PasswordArgument().Replace(result, static m => m.Groups["head"].Value + Mask(m.Groups["quote"].Value));
+ return UriPassword().Replace(result, static m => m.Groups["head"].Value + "****@");
+ }
+
+ private static string Mask(string quote) => quote + "***" + quote;
+
+ // 字符串字面量:"…" 或 '…' 或 `…`,含转义。
+ private const string Literal = """(?["'`])(?:\\.|(?!\k).)*\k""";
+
+ [System.Text.RegularExpressions.GeneratedRegex(
+ """(?(?:["']?)\b(?:pwd|password|passwordDigest)\b(?:["']?)\s*:\s*)""" + Literal,
+ System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline)]
+ private static partial System.Text.RegularExpressions.Regex PasswordField();
+
+ [System.Text.RegularExpressions.GeneratedRegex(
+ """(?\b(?:changeUserPassword|auth)\s*\(\s*(?:["'`](?:\\.|[^"'`\\])*["'`]|[\w.$]+)\s*,\s*)""" + Literal,
+ System.Text.RegularExpressions.RegexOptions.Singleline)]
+ private static partial System.Text.RegularExpressions.Regex PasswordArgument();
+
+ [System.Text.RegularExpressions.GeneratedRegex("""(?mongodb(?:\+srv)?://[^:/@\s"'`]+:)[^@\s"'`]*@""", System.Text.RegularExpressions.RegexOptions.IgnoreCase)]
+ private static partial System.Text.RegularExpressions.Regex UriPassword();
}
diff --git a/plugins/VelaShell.Plugin.Mongo/README.md b/plugins/VelaShell.Plugin.Mongo/README.md
index ea0f0d1..4274be2 100644
--- a/plugins/VelaShell.Plugin.Mongo/README.md
+++ b/plugins/VelaShell.Plugin.Mongo/README.md
@@ -37,7 +37,17 @@ Navicat 式的对象树与大图标工具栏,补齐 Compass 的聚合管道、Sc
- **连接由插件自己管**:已保存的连接进插件存储(`MongoProfileStore`,键 `connections`),**口令进宿主的加密密钥库**
(`ISecretsApi`,按连接 id),不写进连接串、不写进插件存储。SSH 跳板经宿主里已保存的 SSH 连接转发
(`ISessionsApi.OpenAsync` + `IRemoteTunnelApi.OpenTcpAsync`,本机回环上起转发端口)—— 插件一行 SSH 代码都不写,
- 也碰不到跳板机的凭据;几条连接走同一台跳板时共用一条会话,只关本插件开的那条。
+ 也碰不到跳板机的凭据;几条连接走同一台跳板时共用一条会话,只关本插件开的那条(并发连同一台跳板时后到者自己开的那条当场关掉;
+ 跳板会话断了,下一次开流时查实后重开一条再试一次)。连接串形态经跳板时"主机"一栏仍是整条连接串,驱动按串里的选项连、
+ 服务器换成本机转发端口并直连;`mongodb+srv://` 不能走跳板(报 `Conn_SshNoSrv`,不悄悄绕过跳板直连)。经跳板的 TLS 由插件拿证书的
+ SAN / CN 对真实目标主机核对(驱动连的是 127.0.0.1,系统校验的主机名必然对不上)。
+- **连接串形态的选项以连接串为准**:`readPreference` / `appName` / `connectTimeoutMS` / `serverSelectionTimeoutMS` / `compressors`
+ 写在连接串里时,只有用户在表单里显式改过(设置键存在)才覆盖 —— 与连接串预览一致。
+- **CSV / XLSX 导出默认无损**:Decimal128 原样全精度、日期写 ISO 8601 UTC(带毫秒);"保留 2 位"、"本地时间"要在字段表里显式选。
+ XLSX 里超过 2^53 的 Int64、有效位数超过 double 的 Decimal128 写成文本(写成数字 Excel 会悄悄改值)。导入时逗号只在合法千分位里才去掉,
+ `1,5` 这种报错而不是变成 15。
+- **查询历史落盘前脱敏**:`pwd` / `password` / `passwordDigest` 后的字符串字面量、`changeUserPassword` / `db.auth` 的口令实参、
+ 连接串里的口令换成星号(`passwordPrompt()` 原样),每条最多存 8 KB。
- **数据传输的"目标连接"**:本插件此刻开着的连接(`MongoSessionRegistry`)或手填一条连接串。
## 与设计稿 / DESIGN.md 的偏离(刻意的)
@@ -120,6 +130,10 @@ Navicat 式的对象树与大图标工具栏,补齐 Compass 的聚合管道、Sc
| 设计稿底部那行状态栏 | 面板自己画一条 24px 状态条:当前连接 · 范围 · 当前标签的状态(待提交数等并在标签的那一段里);没有「UTF-8」那一格 | 面板没有宿主状态栏可用(那是会话标签的);编码对 MongoDB 无意义 |
| 时序集合不能「创建后立即编辑验证规则」 | 服务器不允许给时序集合设 validator,对话框里这一项置灰 |
| 弹出层(补全、右键菜单、类型菜单)不进 headless 截图 | 它们是独立的顶层窗口;接线由单测覆盖 |
+| 查询编辑器的 `.readPref()` / `.readConcern()` 报"不支持" | 读偏好跟连接走;`.min()` / `.max()` / `.returnKey()` / `.showRecordId()` / `.noCursorTimeout()` / `.count(true)` 照常落到驱动 |
+| 只读模式下 `runCommand` 只放行白名单里的只读命令 | `ShellParser.IsWriteCommand`:黑名单永远列不全;`aggregate` 看有没有 `$out` / `$merge`,`mapReduce` 只有 `out: { inline: 1 }` 算读,`explain` 看内层 |
+| 只有集合级权限的用户,集合列表里没有选项(capped、验证规则等) | 库级 `listCollections` 被拒时退回 `nameOnly + authorizedCollections`,服务器只回名字与类型 |
+| 执行计划在 SBE(`explainVersion: "2"`)下各阶段只有返回数 / 扫描键数 | 阶段树按 `queryPlan` 建,统计按 `planNodeId` 从槽位树里取;读出文档数、works 槽位树里没有对应量 |
## 开发
diff --git a/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs b/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs
index 3564308..ebc9a6a 100644
--- a/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Shell/CodeExport.cs
@@ -243,8 +243,18 @@ private abstract class Writer(Op op, string connectionString)
protected readonly SortedSet Imports = [with(StringComparer.Ordinal)];
+ ///
+ /// 字面量里出现过 UUID(子类型 4)。PyMongo 与 Java 驱动默认的 uuidRepresentation 是 unspecified,
+ /// 直接编码 uuid.UUID / java.util.UUID 会抛错 —— 生成的客户端要设成 standard。
+ ///
+ protected bool UsesUuid { get; set; }
+
+ /// 没有对应字面量、只能写成空值的 BSON 类型(在代码前面写一行注释说明)。
+ protected readonly SortedSet Unmapped = [with(StringComparer.Ordinal)];
+
public abstract string Write();
+ /// 四种语言共用的双引号字符串字面量。\uXXXX 四种语言都认;U+0085 / U+2028 / U+2029 在 C# 源码里算换行,也转义。
protected static string Escape(string text)
{
var b = new StringBuilder(text.Length + 2);
@@ -258,7 +268,8 @@ protected static string Escape(string text)
'\n' => "\\n",
'\r' => "\\r",
'\t' => "\\t",
- _ => c < ' ' ? $"\\u{(int)c:x4}" : c.ToString()
+ (char)0x85 or (char)0x2028 or (char)0x2029 => $"\\u{(int)c:x4}",
+ _ => c < ' ' || c == (char)0x7f ? $"\\u{(int)c:x4}" : c.ToString()
});
}
_ = b.Append('"');
@@ -267,11 +278,36 @@ protected static string Escape(string text)
protected static string IsoString(BsonValue value) => BsonText.IsoDate(value);
+ /// 日期能用 .NET / ISO 8601 表示(公元 1–9999 年);否则各语言退回毫秒构造。
+ protected static bool Representable(BsonValue value) => BsonText.IsRepresentableDate(value.AsBsonDateTime.MillisecondsSinceEpoch);
+
+ protected static long Millis(BsonValue value) => value.AsBsonDateTime.MillisecondsSinceEpoch;
+
protected static DateTime Utc(BsonValue value) =>
DateTimeOffset.FromUnixTimeMilliseconds(value.AsBsonDateTime.MillisecondsSinceEpoch).UtcDateTime;
+ /// double 字面量(整数值补 .0,免得变成整型)。NaN / ±∞ 由各语言自己写。
protected static string Number(double d) => d.ToString("R", CultureInfo.InvariantCulture) is var s && (s.Contains('.') || s.Contains('E')) ? s : s + ".0";
+ /// double → 目标语言字面量;、、 是该语言的写法。
+ protected static string DoubleLiteral(double d, string nan, string positive, string negative) =>
+ double.IsNaN(d) ? nan : double.IsPositiveInfinity(d) ? positive : double.IsNegativeInfinity(d) ? negative : Number(d);
+
+ /// 二进制的 base64 文本。
+ protected static string Base64(BsonValue value) => Convert.ToBase64String(value.AsBsonBinaryData.Bytes);
+
+ /// 记一个没有字面量的类型,返回该语言的空值。
+ protected string Unsupported(BsonValue value, string nullLiteral)
+ {
+ _ = Unmapped.Add(value.BsonType.ToString());
+ return nullLiteral;
+ }
+
+ /// 代码前面的说明注释(有没有字面量可写的类型时)。
+ protected string UnmappedNote(string commentPrefix) => Unmapped.Count == 0
+ ? ""
+ : $"{commentPrefix} Note: BSON type(s) {string.Join(", ", Unmapped)} have no literal in this language; they are written as null below.\n";
+
protected static string Pad(int level) => new(' ', level * 4);
}
@@ -525,7 +561,7 @@ private static string Lit(BsonValue value, int level)
case BsonType.Int64:
return value.AsInt64.ToString(CultureInfo.InvariantCulture) + "L";
case BsonType.Double:
- return Number(value.AsDouble);
+ return DoubleLiteral(value.AsDouble, "double.NaN", "double.PositiveInfinity", "double.NegativeInfinity");
case BsonType.Decimal128:
return $"Decimal128.Parse({Escape(value.AsDecimal128.ToString())})";
case BsonType.Boolean:
@@ -534,6 +570,9 @@ private static string Lit(BsonValue value, int level)
return "BsonNull.Value";
case BsonType.ObjectId:
return $"new ObjectId({Escape(value.AsObjectId.ToString())})";
+ case BsonType.DateTime when !Representable(value):
+ // DateTime 表示不了(公元 1 年前 / 9999 年后):按毫秒构造 BsonDateTime。
+ return $"new BsonDateTime({Millis(value).ToString(CultureInfo.InvariantCulture)}L)";
case BsonType.DateTime:
{
DateTime at = Utc(value);
@@ -566,13 +605,15 @@ public override string Write()
{
_ = head.Append(import).Append('\n');
}
- _ = head.Append("\nclient = MongoClient(").Append(Escape(ConnectionString)).Append(")\n");
+ // uuid.UUID 要求客户端 uuidRepresentation=standard(PyMongo 4 默认 unspecified,编码时直接抛错)。
+ _ = head.Append("\nclient = MongoClient(").Append(Escape(ConnectionString))
+ .Append(UsesUuid ? ", uuidRepresentation=\"standard\")\n" : ")\n");
_ = head.Append("db = client[").Append(Escape(Op.Database)).Append("]\n");
if (Op.Collection is { } c)
{
_ = head.Append("collection = db[").Append(Escape(c)).Append("]\n");
}
- return head.Append('\n').Append(Body).ToString().TrimEnd() + "\n";
+ return head.Append('\n').Append(UnmappedNote("#")).Append(Body).ToString().TrimEnd() + "\n";
}
private void Var(string name, BsonValue value) => Body.Append(name).Append(" = ").Append(Lit(value, 0)).Append('\n');
@@ -745,10 +786,14 @@ private string Lit(BsonValue value, int level)
}
case BsonType.String:
return Escape(value.AsString);
- case BsonType.Int32 or BsonType.Int64:
- return value.ToInt64().ToString(CultureInfo.InvariantCulture);
+ case BsonType.Int32:
+ return value.AsInt32.ToString(CultureInfo.InvariantCulture);
+ case BsonType.Int64:
+ // 裸 int 在 PyMongo 里按大小编码:装得进 32 位就成了 Int32,类型悄悄变了。
+ _ = Imports.Add("from bson.int64 import Int64");
+ return $"Int64({value.AsInt64.ToString(CultureInfo.InvariantCulture)})";
case BsonType.Double:
- return Number(value.AsDouble);
+ return DoubleLiteral(value.AsDouble, "float(\"nan\")", "float(\"inf\")", "float(\"-inf\")");
case BsonType.Decimal128:
_ = Imports.Add("from bson.decimal128 import Decimal128");
return $"Decimal128({Escape(value.AsDecimal128.ToString())})";
@@ -759,6 +804,10 @@ private string Lit(BsonValue value, int level)
case BsonType.ObjectId:
_ = Imports.Add("from bson import ObjectId");
return $"ObjectId({Escape(value.AsObjectId.ToString())})";
+ case BsonType.DateTime when !Representable(value):
+ // Python 的 datetime 只到 1–9999 年;越界的毫秒值用 DatetimeMS(PyMongo 4.3+)。
+ _ = Imports.Add("from bson.datetime_ms import DatetimeMS");
+ return $"DatetimeMS({Millis(value).ToString(CultureInfo.InvariantCulture)})";
case BsonType.DateTime:
{
_ = Imports.Add("from datetime import datetime, timezone");
@@ -771,9 +820,32 @@ private string Lit(BsonValue value, int level)
return $"Regex({Escape(value.AsBsonRegularExpression.Pattern)}, {Escape(value.AsBsonRegularExpression.Options)})";
case BsonType.Binary when value.AsBsonBinaryData.SubType is BsonBinarySubType.UuidStandard:
_ = Imports.Add("import uuid");
+ UsesUuid = true;
return $"uuid.UUID({Escape(value.AsBsonBinaryData.ToGuid().ToString())})";
+ case BsonType.Binary:
+ _ = Imports.Add("import base64");
+ _ = Imports.Add("from bson.binary import Binary");
+ return $"Binary(base64.b64decode({Escape(Base64(value))}), {(int)value.AsBsonBinaryData.SubType})";
+ case BsonType.Timestamp:
+ _ = Imports.Add("from bson.timestamp import Timestamp");
+ return $"Timestamp({value.AsBsonTimestamp.Timestamp}, {value.AsBsonTimestamp.Increment})";
+ case BsonType.MinKey:
+ _ = Imports.Add("from bson.min_key import MinKey");
+ return "MinKey()";
+ case BsonType.MaxKey:
+ _ = Imports.Add("from bson.max_key import MaxKey");
+ return "MaxKey()";
+ case BsonType.JavaScript:
+ _ = Imports.Add("from bson.code import Code");
+ return $"Code({Escape(value.AsBsonJavaScript.Code)})";
+ case BsonType.JavaScriptWithScope:
+ _ = Imports.Add("from bson.code import Code");
+ return $"Code({Escape(value.AsBsonJavaScriptWithScope.Code)}, {Lit(value.AsBsonJavaScriptWithScope.Scope, level)})";
+ case BsonType.Symbol:
+ return Escape(value.AsBsonSymbol.Name);
default:
- return Escape(value.ToString() ?? "");
+ // Python 没有块注释,行内注释会把同一行后面的代码一起注释掉 —— 写 None,说明放在代码前面。
+ return Unsupported(value, "None");
}
}
}
@@ -969,8 +1041,12 @@ private string Lit(BsonValue value, int level)
case BsonType.Int64:
_ = Imports.Add("Long");
return $"Long.fromString({Escape(value.AsInt64.ToString(CultureInfo.InvariantCulture))})";
+ case BsonType.Double when double.IsFinite(value.AsDouble) && Math.Floor(value.AsDouble) == value.AsDouble:
+ // JS 里 5 与 5.0 是同一个数,驱动按整数存成 Int32:整数值的 double 包一层 Double 保住类型。
+ _ = Imports.Add("Double");
+ return $"new Double({value.AsDouble.ToString("R", CultureInfo.InvariantCulture)})";
case BsonType.Double:
- return value.AsDouble.ToString("R", CultureInfo.InvariantCulture);
+ return DoubleLiteral(value.AsDouble, "NaN", "Infinity", "-Infinity");
case BsonType.Decimal128:
_ = Imports.Add("Decimal128");
return $"Decimal128.fromString({Escape(value.AsDecimal128.ToString())})";
@@ -981,15 +1057,39 @@ private string Lit(BsonValue value, int level)
case BsonType.ObjectId:
_ = Imports.Add("ObjectId");
return $"new ObjectId({Escape(value.AsObjectId.ToString())})";
+ case BsonType.DateTime when !Representable(value):
+ return $"new Date({Millis(value).ToString(CultureInfo.InvariantCulture)})";
case BsonType.DateTime:
return $"new Date({Escape(IsoString(value))})";
case BsonType.RegularExpression:
- return $"/{value.AsBsonRegularExpression.Pattern.Replace("/", "\\/", StringComparison.Ordinal)}/{value.AsBsonRegularExpression.Options}";
+ _ = Imports.Add("BSONRegExp");
+ // 用 BSONRegExp 而不是 /…/ 字面量:BSON 正则的选项(x、s、u…)与 JS 正则的不完全一样,模式里的换行也写得进字符串。
+ return $"new BSONRegExp({Escape(value.AsBsonRegularExpression.Pattern)}, {Escape(value.AsBsonRegularExpression.Options)})";
case BsonType.Binary when value.AsBsonBinaryData.SubType is BsonBinarySubType.UuidStandard:
_ = Imports.Add("UUID");
return $"new UUID({Escape(value.AsBsonBinaryData.ToGuid().ToString())})";
+ case BsonType.Binary:
+ _ = Imports.Add("Binary");
+ return $"new Binary(Buffer.from({Escape(Base64(value))}, \"base64\"), {(int)value.AsBsonBinaryData.SubType})";
+ case BsonType.Timestamp:
+ _ = Imports.Add("Timestamp");
+ return $"new Timestamp({{ t: {value.AsBsonTimestamp.Timestamp}, i: {value.AsBsonTimestamp.Increment} }})";
+ case BsonType.MinKey:
+ _ = Imports.Add("MinKey");
+ return "new MinKey()";
+ case BsonType.MaxKey:
+ _ = Imports.Add("MaxKey");
+ return "new MaxKey()";
+ case BsonType.JavaScript:
+ _ = Imports.Add("Code");
+ return $"new Code({Escape(value.AsBsonJavaScript.Code)})";
+ case BsonType.JavaScriptWithScope:
+ _ = Imports.Add("Code");
+ return $"new Code({Escape(value.AsBsonJavaScriptWithScope.Code)}, {Lit(value.AsBsonJavaScriptWithScope.Scope, level)})";
+ case BsonType.Symbol:
+ return Escape(value.AsBsonSymbol.Name);
default:
- return Escape(value.ToString() ?? "");
+ return $"null /* {value.BsonType}: no literal */";
}
}
@@ -1012,12 +1112,29 @@ public override string Write()
_ = Imports.Add("com.mongodb.client.MongoCollection");
}
Statement();
+ if (UsesUuid)
+ {
+ _ = Imports.Add("com.mongodb.ConnectionString");
+ _ = Imports.Add("com.mongodb.MongoClientSettings");
+ _ = Imports.Add("org.bson.UuidRepresentation");
+ }
var head = new StringBuilder();
foreach (string import in Imports)
{
_ = head.Append("import ").Append(import).Append(";\n");
}
- _ = head.Append("\nMongoClient client = MongoClients.create(").Append(Escape(ConnectionString)).Append(");\n");
+ if (UsesUuid)
+ {
+ // UUID.fromString 编码要求 uuidRepresentation=STANDARD(Java 驱动默认 UNSPECIFIED,编码 java.util.UUID 时抛错)。
+ _ = head.Append("\nMongoClient client = MongoClients.create(MongoClientSettings.builder()\n")
+ .Append(Pad(1)).Append(".applyConnectionString(new ConnectionString(").Append(Escape(ConnectionString)).Append("))\n")
+ .Append(Pad(1)).Append(".uuidRepresentation(UuidRepresentation.STANDARD)\n")
+ .Append(Pad(1)).Append(".build());\n");
+ }
+ else
+ {
+ _ = head.Append("\nMongoClient client = MongoClients.create(").Append(Escape(ConnectionString)).Append(");\n");
+ }
_ = head.Append("MongoDatabase database = client.getDatabase(").Append(Escape(Op.Database)).Append(");\n");
if (Op.Collection is { } c)
{
@@ -1235,7 +1352,7 @@ private string Lit(BsonValue value, int level)
case BsonType.Int64:
return value.AsInt64.ToString(CultureInfo.InvariantCulture) + "L";
case BsonType.Double:
- return Number(value.AsDouble);
+ return DoubleLiteral(value.AsDouble, "Double.NaN", "Double.POSITIVE_INFINITY", "Double.NEGATIVE_INFINITY");
case BsonType.Decimal128:
_ = Imports.Add("java.math.BigDecimal");
_ = Imports.Add("org.bson.types.Decimal128");
@@ -1247,6 +1364,9 @@ private string Lit(BsonValue value, int level)
case BsonType.ObjectId:
_ = Imports.Add("org.bson.types.ObjectId");
return $"new ObjectId({Escape(value.AsObjectId.ToString())})";
+ case BsonType.DateTime when !Representable(value):
+ _ = Imports.Add("java.util.Date");
+ return $"new Date({Millis(value).ToString(CultureInfo.InvariantCulture)}L)";
case BsonType.DateTime:
_ = Imports.Add("java.time.Instant");
_ = Imports.Add("java.util.Date");
@@ -1256,9 +1376,31 @@ private string Lit(BsonValue value, int level)
return $"new BsonRegularExpression({Escape(value.AsBsonRegularExpression.Pattern)}, {Escape(value.AsBsonRegularExpression.Options)})";
case BsonType.Binary when value.AsBsonBinaryData.SubType is BsonBinarySubType.UuidStandard:
_ = Imports.Add("java.util.UUID");
+ UsesUuid = true;
return $"UUID.fromString({Escape(value.AsBsonBinaryData.ToGuid().ToString())})";
+ case BsonType.Binary:
+ _ = Imports.Add("java.util.Base64");
+ _ = Imports.Add("org.bson.types.Binary");
+ return $"new Binary((byte) {(int)value.AsBsonBinaryData.SubType}, Base64.getDecoder().decode({Escape(Base64(value))}))";
+ case BsonType.Timestamp:
+ _ = Imports.Add("org.bson.BsonTimestamp");
+ return $"new BsonTimestamp({value.AsBsonTimestamp.Timestamp}, {value.AsBsonTimestamp.Increment})";
+ case BsonType.MinKey:
+ _ = Imports.Add("org.bson.types.MinKey");
+ return "new MinKey()";
+ case BsonType.MaxKey:
+ _ = Imports.Add("org.bson.types.MaxKey");
+ return "new MaxKey()";
+ case BsonType.JavaScript:
+ _ = Imports.Add("org.bson.types.Code");
+ return $"new Code({Escape(value.AsBsonJavaScript.Code)})";
+ case BsonType.JavaScriptWithScope:
+ _ = Imports.Add("org.bson.types.CodeWithScope");
+ return $"new CodeWithScope({Escape(value.AsBsonJavaScriptWithScope.Code)}, {Lit(value.AsBsonJavaScriptWithScope.Scope, level)})";
+ case BsonType.Symbol:
+ return Escape(value.AsBsonSymbol.Name);
default:
- return Escape(value.ToString() ?? "");
+ return $"null /* {value.BsonType}: no literal */";
}
}
}
diff --git a/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs b/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs
index d7770eb..bcdb310 100644
--- a/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Shell/ShellExecutor.cs
@@ -234,17 +234,35 @@ private async Task DatabaseAsync(ShellCommand command, string datab
BsonString s => new BsonDocument(s.Value, 1),
_ => throw new ShellExecutionException(loc.Format("Query_ErrNeedsDocument", method.Name))
};
- if (body.ElementCount > 0 && ShellParser.WriteCommands.Contains(body.GetElement(0).Name))
+ if (ShellParser.IsWriteCommand(body))
{
+ // 与 db.dropDatabase() / db.c.drop() / db.c.dropIndex() 同一套护栏:runCommand 不是绕过它们的后门。
+ BsonElement head = body.GetElement(0);
+ bool dropDatabase = head.Name.Equals("dropDatabase", StringComparison.OrdinalIgnoreCase);
+ if (dropDatabase && guard.DisableDropDatabase)
+ {
+ throw new ShellExecutionException(loc["Query_ErrDropDatabaseDisabled"]);
+ }
if (!guard.EnsureWritable(target))
{
return Blocked(command, database);
}
- if (body.GetElement(0).Name.Equals("dropDatabase", StringComparison.OrdinalIgnoreCase)
- && !await ConfirmDropDatabaseAsync(target).ConfigureAwait(false))
+ if (dropDatabase && !await ConfirmDropDatabaseAsync(target).ConfigureAwait(false))
{
return Declined(command, target);
}
+ if (head.Name.Equals("drop", StringComparison.OrdinalIgnoreCase) && head.Value is BsonString dropped && guard.ConfirmWrites
+ && !await guard.ConfirmAsync(new ShellConfirmation(ShellConfirmKind.Drop, target, dropped.Value, null,
+ await connection.EstimatedCountAsync(target, dropped.Value, cancellationToken).ConfigureAwait(true))).ConfigureAwait(true))
+ {
+ return Declined(command, target, dropped.Value);
+ }
+ if (head.Name.Equals("dropIndexes", StringComparison.OrdinalIgnoreCase) && head.Value is BsonString indexed && guard.ConfirmWrites
+ && !await guard.ConfirmAsync(new ShellConfirmation(ShellConfirmKind.DropIndex, target, indexed.Value, null, null,
+ body.GetValue("index", "*").ToString())).ConfigureAwait(true))
+ {
+ return Declined(command, target, indexed.Value);
+ }
}
BsonDocument reply = await connection.RunCommandAsync(target, body, cancellationToken).ConfigureAwait(false);
bool catalog = body.ElementCount > 0 && body.GetElement(0).Name is "create" or "drop" or "renameCollection" or "dropDatabase";
@@ -317,12 +335,18 @@ private async Task DatabaseAsync(ShellCommand command, string datab
case "aggregate":
{
BsonArray pipeline = method.Arg(0) as BsonArray ?? throw new ShellExecutionException(loc.Format("Query_ErrNeedsPipeline", "aggregate"));
+ // 库级管道($currentOp / $documents …)末尾同样可以接 $out / $merge 写出。
+ bool writes = ShellParser.WritesPipeline(pipeline);
+ if (writes && !guard.EnsureWritable(database))
+ {
+ return Blocked(command, database);
+ }
var aggregateOptions = new AggregateOptions { MaxTime = MaxTime(options.MaxTimeMs), Comment = Comment(options) };
using IAsyncCursor cursor = await db.AggregateAsync(
PipelineDefinition.Create(pipeline.Select(static s => s.AsBsonDocument)),
aggregateOptions, cancellationToken).ConfigureAwait(false);
(List docs, bool truncated) = await DrainAsync(cursor, options.MaxDocuments, cancellationToken).ConfigureAwait(false);
- return Documents(command, database, null, docs, truncated) with { Pipeline = pipeline };
+ return Documents(command, database, null, docs, truncated) with { Pipeline = pipeline, ChangesCatalog = writes };
}
default:
throw new ShellExecutionException(loc.Format("Query_ErrUnsupportedMethod", "db." + method.Name));
@@ -352,7 +376,7 @@ private async Task CollectionAsync(ShellCommand command, string dat
case "aggregate":
{
BsonArray pipeline = Pipeline(method);
- bool writes = pipeline.Any(static s => s is BsonDocument d && (d.Contains("$out") || d.Contains("$merge")));
+ bool writes = ShellParser.WritesPipeline(pipeline);
if (writes && !guard.EnsureWritable(database))
{
return Blocked(command, database);
@@ -583,9 +607,22 @@ private async Task FindAsync(ShellCommand command, IMongoCollection
BsonValue? comment, ShellRunOptions options, CancellationToken cancellationToken)
{
ShellCall method = command.Method!;
+ // 解析器认得、但这里不落到驱动上的游标修饰:明说不支持,不能悄悄忽略 —— 用户以为读的是从节点 / majority,其实不是。
+ foreach (string unsupported in (string[])["readPref", "readConcern"])
+ {
+ if (command.Modifier(unsupported) is not null)
+ {
+ throw new ShellExecutionException(loc.Format("Query_ErrUnsupportedMethod", "." + unsupported));
+ }
+ }
FindRequest request = BuildFindRequest(command, database, options.MaxTimeMs);
var findOptions = new FindOptions
{
+ Min = command.Modifier("min")?.Document(0),
+ Max = command.Modifier("max")?.Document(0),
+ ReturnKey = command.Modifier("returnKey") is { } returnKey ? returnKey.Arg(0)?.ToBoolean() ?? true : null,
+ ShowRecordId = command.Modifier("showRecordId") is { } showRecordId ? showRecordId.Arg(0)?.ToBoolean() ?? true : null,
+ NoCursorTimeout = command.Modifier("noCursorTimeout") is not null ? true : null,
MaxTime = maxTime,
Comment = comment,
Hint = request.Hint,
@@ -600,10 +637,12 @@ private async Task FindAsync(ShellCommand command, IMongoCollection
// count() / size() / itcount() 接在 find 后面:变成按同一组条件计数。
if ((command.Modifier("count") ?? command.Modifier("size") ?? command.Modifier("itcount")) is { } counter)
{
+ // count() 默认不计 skip / limit;count(true)(applySkipLimit)与 size() / itcount() 一样计。
+ bool applySkipLimit = counter.Name != "count" || counter.Arg(0) is { } apply && apply.ToBoolean();
var countOptions = new CountOptions
{
- Skip = counter.Name != "count" && request.Skip > 0 ? request.Skip : null,
- Limit = counter.Name != "count" && request.Limit > 0 ? request.Limit : null,
+ Skip = applySkipLimit && request.Skip > 0 ? request.Skip : null,
+ Limit = applySkipLimit && request.Limit > 0 ? request.Limit : null,
Hint = request.Hint,
MaxTime = maxTime,
Comment = comment
diff --git a/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs b/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs
index 087c7f8..243173a 100644
--- a/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Shell/ShellParser.cs
@@ -80,10 +80,15 @@ public sealed class ShellCommand
public bool IsWrite => Kind switch
{
ShellCommandKind.Collection => Method?.Name is { } name && (ShellParser.CollectionWrites.Contains(name)
- || name == "aggregate" && Method.Arg(0) is BsonArray pipeline && pipeline.Any(static s => s is BsonDocument d && (d.Contains("$out") || d.Contains("$merge")))),
+ || name == "aggregate" && Method.Arg(0) is BsonArray pipeline && ShellParser.WritesPipeline(pipeline)),
ShellCommandKind.Database => Method?.Name is "createCollection" or "dropDatabase" or "createView"
- || Method?.Name is "runCommand" or "adminCommand" && Method.Arg(0) is BsonDocument command && command.ElementCount > 0
- && ShellParser.WriteCommands.Contains(command.GetElement(0).Name),
+ || Method?.Name == "aggregate" && Method.Arg(0) is BsonArray dbPipeline && ShellParser.WritesPipeline(dbPipeline)
+ || Method?.Name is "runCommand" or "adminCommand" && Method.Arg(0) switch
+ {
+ BsonDocument command => ShellParser.IsWriteCommand(command),
+ BsonString name => ShellParser.IsWriteCommand(new BsonDocument(name.Value, 1)),
+ _ => false
+ },
_ => false
};
}
@@ -128,7 +133,11 @@ public static class ShellParser
"dropIndexes", "drop", "renameCollection"
};
- /// 经 runCommand 发出时算写操作的命令名。
+ ///
+ /// 经 runCommand 发出时算写操作的典型命令名(只作文档与旧调用方参考)。
+ /// **判断一律走 **:那里是白名单 —— 不在只读名单里的命令都算写,
+ /// 黑名单永远列不全(grantPrivilegesToRole、dropAllUsersFromDatabase、shardCollection、replSetStepDown …)。
+ ///
public static IReadOnlySet WriteCommands { get; } = new HashSet(StringComparer.OrdinalIgnoreCase)
{
"insert", "update", "delete", "findAndModify", "drop", "dropDatabase", "create", "createIndexes", "dropIndexes",
@@ -137,6 +146,60 @@ public static class ShellParser
"applyOps", "shutdown", "killOp", "setParameter", "fsync"
};
+ ///
+ /// 确定只读的命令(白名单)。aggregate / mapReduce / explain / profile / validate
+ /// 要看参数,在 里单独判断。
+ ///
+ public static IReadOnlySet ReadOnlyCommands { get; } = new HashSet(StringComparer.OrdinalIgnoreCase)
+ {
+ "find", "getMore", "killCursors", "count", "distinct", "listCollections", "listIndexes", "listDatabases", "listSearchIndexes",
+ "collStats", "dbStats", "dataSize", "serverStatus", "hello", "isMaster", "buildInfo", "ping", "connectionStatus",
+ "usersInfo", "rolesInfo", "getParameter", "getClusterParameter", "hostInfo", "currentOp", "top", "replSetGetStatus",
+ "replSetGetConfig", "getLog", "getCmdLineOpts", "listCommands", "whatsmyuri", "lockInfo", "connPoolStats",
+ "shardConnPoolStats", "listShards", "isdbgrid", "getShardMap", "getShardVersion", "balancerStatus",
+ "getDefaultRWConcern", "dbHash", "planCacheListFilters", "features", "getFreeMonitoringStatus"
+ };
+
+ ///
+ /// runCommand / adminCommand 的命令文档会不会写库。白名单:只有确定只读的才放过,其余一律算写 ——
+ /// 只读模式的护栏宁可多拦一条,也不能被一个没列进黑名单的命令绕过去。
+ ///
+ /// 命令文档(第一个键是命令名)。
+ /// 会不会写。
+ public static bool IsWriteCommand(BsonDocument command)
+ {
+ ArgumentNullException.ThrowIfNull(command);
+ if (command.ElementCount == 0)
+ {
+ return false;
+ }
+ BsonElement first = command.GetElement(0);
+ switch (first.Name.ToLowerInvariant())
+ {
+ case "aggregate":
+ return command.GetValue("pipeline", null) is BsonArray pipeline && WritesPipeline(pipeline);
+ case "mapreduce":
+ // 只有 out: { inline: 1 } 是只读;out 写到集合(replace / merge / reduce)就是写。
+ return !(command.GetValue("out", null) is BsonDocument output && output.Contains("inline"));
+ case "explain":
+ // explain 本身不执行写,但内层命令按它自己的形状判断(与 mongosh 的只读模式口径一致,宁严勿宽)。
+ return first.Value is not BsonDocument inner || IsWriteCommand(inner);
+ case "profile":
+ // { profile: -1 } 只是读当前级别;0 / 1 / 2 会改实例的设置。
+ return !(first.Value.IsNumeric && first.Value.ToInt32() == -1);
+ case "validate":
+ return command.GetValue("repair", false).ToBoolean() || command.GetValue("fixMultikey", false).ToBoolean();
+ default:
+ return !ReadOnlyCommands.Contains(first.Name);
+ }
+ }
+
+ /// 管道里有没有写出的阶段($out / $merge)。
+ /// 管道。
+ /// 会不会写。
+ public static bool WritesPipeline(BsonArray pipeline) =>
+ pipeline.Any(static s => s is BsonDocument d && (d.Contains("$out") || d.Contains("$merge")));
+
/// 库级方法(db.xxx() 里不是集合名的那些)。
public static IReadOnlySet DatabaseMethods { get; } = new HashSet(StringComparer.Ordinal)
{
diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs
index 04aa035..e11c901 100644
--- a/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Transfer/CellFormatter.cs
@@ -70,18 +70,34 @@ public static string LocalDate(BsonValue value)
return DateTimeOffset.FromUnixTimeMilliseconds(ms).ToLocalTime().ToString(LocalFormat, CultureInfo.InvariantCulture);
}
+ /// double 能精确表示的最大整数(2^53);再大 Excel 里就变了样(9007199254740993 → …992)。
+ private const long MaxExactInteger = 1L << 53;
+
///
/// 数值单元格(Excel 里写成数字而不是文本,才能求和排序)。不是数值或换算成文本时返回 。
+ /// Excel 的数字就是 double:超过 2^53 的 Int64、有效位数超过 double 的 Decimal128 写成数字会被悄悄改值,
+ /// 这些返回 ,由调用方写成文本(原样的全精度)。
///
public static double? Number(BsonValue? value, CellConversion conversion) => BsonKinds.Of(value) switch
{
BsonKind.Int32 => value!.AsInt32,
- BsonKind.Int64 => value!.AsInt64,
+ BsonKind.Int64 when value!.AsInt64 is >= -MaxExactInteger and <= MaxExactInteger => value.AsInt64,
BsonKind.Double when double.IsFinite(value!.AsDouble) => conversion == CellConversion.Fixed2
? Math.Round(value.AsDouble, 2, MidpointRounding.AwayFromZero)
: value.AsDouble,
BsonKind.Decimal128 when decimal.TryParse(value!.AsDecimal128.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out decimal d) =>
- (double)(conversion == CellConversion.Fixed2 ? Math.Round(d, 2, MidpointRounding.AwayFromZero) : d),
+ ExactDouble(conversion == CellConversion.Fixed2 ? Math.Round(d, 2, MidpointRounding.AwayFromZero) : d),
_ => null
};
+
+ /// decimal → double,往返不变才给(0.0035 可以;1234567890.123456789 不行)。
+ private static double? ExactDouble(decimal value)
+ {
+ // 比较最短往返文本(Excel 显示的也是它):(decimal)double 会带出二进制尾数,0.0035 都对不上。
+ double converted = (double)value;
+ return decimal.TryParse(converted.ToString("R", CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture, out decimal back)
+ && back == value
+ ? converted
+ : null;
+ }
}
diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs
index 78ce03e..d318347 100644
--- a/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Transfer/CollectionCopier.cs
@@ -142,6 +142,10 @@ internal static class CollectionCopier
/// 日志。
/// 文案表(日志用)。
/// 取消令牌。
+ ///
+ /// 整批开始时目标库已有的名字( 列一次,整批共用;这里建了新集合会补进去)。
+ /// 不给就逐个按名字问服务器。
+ ///
public static async Task CopyAsync(
MongoConnection source,
string sourceDb,
@@ -153,7 +157,8 @@ public static async Task CopyAsync(
Action onDocuments,
Action log,
Loc loc,
- CancellationToken cancellationToken)
+ CancellationToken cancellationToken,
+ ISet? existingNames = null)
{
if (item.Action == XferAction.Skip)
{
@@ -162,23 +167,39 @@ public static async Task CopyAsync(
switch (item.Kind)
{
case XferObjectKind.View:
- await CopyViewAsync(target, targetDb, item, cancellationToken).ConfigureAwait(false);
+ await CopyViewAsync(target, targetDb, item, existingNames, cancellationToken).ConfigureAwait(false);
return new(0, 0, 0);
case XferObjectKind.Bucket:
{
// 先 chunks 后 files:读者从 files 找文件,files 晚到就不会看见"有文件没数据"的半截桶。
XferOutcome chunks = await CopyCollectionAsync(source, sourceDb, target, targetDb, $"{item.Name}.chunks",
- [], item.Action, options, gate, onDocuments, log, loc, cancellationToken).ConfigureAwait(false);
+ [], item.Action, options, gate, onDocuments, log, loc, existingNames, cancellationToken).ConfigureAwait(false);
XferOutcome files = await CopyCollectionAsync(source, sourceDb, target, targetDb, $"{item.Name}.files",
- [], item.Action, options, gate, onDocuments, log, loc, cancellationToken).ConfigureAwait(false);
+ [], item.Action, options, gate, onDocuments, log, loc, existingNames, cancellationToken).ConfigureAwait(false);
return new(chunks.Copied + files.Copied, chunks.Failed + files.Failed, chunks.Indexes + files.Indexes);
}
default:
return await CopyCollectionAsync(source, sourceDb, target, targetDb, item.Name, item.Info?.Options ?? [],
- item.Action, options, gate, onDocuments, log, loc, cancellationToken).ConfigureAwait(false);
+ item.Action, options, gate, onDocuments, log, loc, existingNames, cancellationToken).ConfigureAwait(false);
}
}
+ ///
+ /// 目标里有没有这个名字。调用方给了整批开始时列好的名字()就查它 —— 一批几百个集合时,
+ /// 每个集合都把目标库的集合列表整个拉一遍是 O(n²) 的往返;没给就只按名字过滤着问服务器这一个。
+ ///
+ private static async Task ExistsAsync(MongoConnection target, string database, string name, ISet? known, CancellationToken cancellationToken)
+ {
+ if (known is not null)
+ {
+ return known.Contains(name);
+ }
+ using IAsyncCursor cursor = await target.Database(database)
+ .ListCollectionNamesAsync(new ListCollectionNamesOptions { Filter = new BsonDocument("name", name) }, cancellationToken)
+ .ConfigureAwait(false);
+ return await cursor.AnyAsync(cancellationToken).ConfigureAwait(false);
+ }
+
/// 目标库里已有的集合 / 视图名。
public static async Task> ExistingNamesAsync(MongoConnection target, string database, CancellationToken cancellationToken)
{
@@ -201,10 +222,11 @@ private static async Task CopyCollectionAsync(
Action onDocuments,
Action log,
Loc loc,
+ ISet? existingNames,
CancellationToken cancellationToken)
{
IMongoDatabase targetDatabase = target.Database(targetDb);
- bool exists = (await ExistingNamesAsync(target, targetDb, cancellationToken).ConfigureAwait(false)).Contains(name);
+ bool exists = await ExistsAsync(target, targetDb, name, existingNames, cancellationToken).ConfigureAwait(false);
bool created = false;
switch (action)
{
@@ -224,6 +246,10 @@ private static async Task CopyCollectionAsync(
created = true;
break;
}
+ if (created)
+ {
+ _ = existingNames?.Add(name);
+ }
IMongoCollection from = source.Collection(sourceDb, name)
.WithReadPreference(MongoConnection.ParseReadPreference(options.ReadPreference));
@@ -385,9 +411,9 @@ private static Task CreateAsync(MongoConnection target, string dat
CancellationToken cancellationToken) =>
target.RunCommandAsync(database, CreateCommand(name, sourceOptions, options), cancellationToken);
- private static async Task CopyViewAsync(MongoConnection target, string database, XferItem item, CancellationToken cancellationToken)
+ private static async Task CopyViewAsync(MongoConnection target, string database, XferItem item, ISet? existingNames, CancellationToken cancellationToken)
{
- bool exists = (await ExistingNamesAsync(target, database, cancellationToken).ConfigureAwait(false)).Contains(item.Name);
+ bool exists = await ExistsAsync(target, database, item.Name, existingNames, cancellationToken).ConfigureAwait(false);
if (exists)
{
if (item.Action != XferAction.Overwrite)
@@ -408,6 +434,7 @@ private static async Task CopyViewAsync(MongoConnection target, string database,
command["collation"] = collation;
}
_ = await target.RunCommandAsync(database, command, cancellationToken).ConfigureAwait(false);
+ _ = existingNames?.Add(item.Name);
}
private static async Task CopyIndexesAsync(
diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs
index 095faed..e468e24 100644
--- a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportRunner.cs
@@ -52,7 +52,10 @@ internal sealed record ImportJob
/// 导入进度。
internal sealed record ImportProgress(long Rows, long Total, long Inserted, long Updated, long Skipped, TimeSpan Elapsed);
-/// 导入结果。
+///
+/// 导入结果。取消()与中途的致命失败()也返回一份部分结果,
+/// 而不是抛出 —— 错误报告与备份文件已经写了一部分,它们的路径与已确认写入的条数都要交给界面。
+///
internal sealed record ImportResult(
long Rows,
long Inserted,
@@ -61,7 +64,9 @@ internal sealed record ImportResult(
TimeSpan Elapsed,
string? ErrorReport,
string? BackupFile,
- bool Stopped);
+ bool Stopped,
+ bool Cancelled = false,
+ Exception? Failure = null);
///
/// 执行导入:读一条换算一条,攒满一批 bulkWrite 一次(默认 ordered: false ——
@@ -87,13 +92,15 @@ public static async Task RunAsync(
var report = new ReportFiles(job);
var batch = new List<(ConvertedRow Row, ImportRecord Record, WriteModel Model)>(job.BatchSize);
long rows = 0, inserted = 0, updated = 0, skipped = 0;
- bool stopped = false;
+ bool stopped = false, cancelled = false;
+ Exception? failure = null;
TimeSpan lastReport = TimeSpan.Zero;
- using IImportReader reader = job.Source.Open();
try
{
+ using IImportReader reader = job.Source.Open();
while (!stopped && reader.TryRead(out ImportRecord record))
{
+ cancellationToken.ThrowIfCancellationRequested();
rows++;
ConvertedRow row = converter.Convert(record);
if (row.Status == ImportRowStatus.Error)
@@ -102,6 +109,7 @@ public static async Task RunAsync(
report.Error(row.Line, [.. row.Issues.Where(static i => i.IsError).Select(i => ImportIssueText.Describe(i, loc))], record, reader.Header);
if (job.StopOnError)
{
+ // 出错行之前已经攒在批里的那些行是好的 —— 下面照常落盘,只是不再往后读。
stopped = true;
break;
}
@@ -120,24 +128,33 @@ public static async Task RunAsync(
{
lastReport = watch.Elapsed;
progress?.Report(new(rows, job.EstimatedTotal, inserted, updated, skipped, watch.Elapsed));
- cancellationToken.ThrowIfCancellationRequested();
}
}
- if (!stopped && batch.Count > 0)
+ // FlushAsync 叫停时批已清空;换算出错叫停时批里是出错行之前的好行,要写进去。
+ if (batch.Count > 0)
{
(long i, long u, long s, bool stop) = await FlushAsync(collection, job, batch, report, reader.Header, loc, cancellationToken).ConfigureAwait(false);
inserted += i;
updated += u;
skipped += s;
- stopped = stop;
+ stopped |= stop;
}
}
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ // 正在写的那一批写没写进去不得而知:计数只算服务器已确认的批次。
+ cancelled = true;
+ }
+ catch (Exception ex)
+ {
+ failure = ex;
+ }
finally
{
report.Dispose();
}
progress?.Report(new(rows, job.EstimatedTotal, inserted, updated, skipped, watch.Elapsed));
- return new(rows, inserted, updated, skipped, watch.Elapsed, report.ErrorPath, report.BackupPath, stopped);
+ return new(rows, inserted, updated, skipped, watch.Elapsed, report.ErrorPath, report.BackupPath, stopped, cancelled, failure);
}
/// 一份文档 → 写模型。
@@ -240,9 +257,10 @@ internal static WriteModel Model(BsonDocument document, ImportRule
{
// ordered 批次在第一个错误处停下:它之后的那些也没写进去 —— 同样记进错误报告,修好了能补导。
int firstError = ex.WriteErrors.Count > 0 ? ex.WriteErrors.Min(static e => e.Index) : batch.Count;
+ HashSet failed = [.. ex.WriteErrors.Select(static e => e.Index)];
for (int i = firstError + 1; i < batch.Count; i++)
{
- if (ex.WriteErrors.Any(e => e.Index == i))
+ if (failed.Contains(i))
{
continue;
}
@@ -310,7 +328,8 @@ public void Backup(BsonDocument document)
{
if (_backup is null)
{
- BackupPath = Path.Combine(job.ReportDirectory, $"{job.Database}.{job.Collection}.backup-{_stamp}.jsonl");
+ // 集合名可以带 ':' '/'(Windows 上 ':' 会落成 NTFS 备用数据流,'/' 是一级不存在的目录):与导出同一个清洗。
+ BackupPath = Path.Combine(job.ReportDirectory, TransferText.SafeFileName($"{job.Database}.{job.Collection}") + $".backup-{_stamp}.jsonl");
_ = Directory.CreateDirectory(job.ReportDirectory);
_backup = new StreamWriter(BackupPath, append: false, new UTF8Encoding(false));
}
diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs
index 71da425..20223fc 100644
--- a/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Transfer/ImportValues.cs
@@ -232,27 +232,57 @@ private static bool TryNumber(string text, BsonKind kind, out BsonValue? value,
}
}
- /// 去掉引号、千分位、货币符号与空白("1,580.00" → 1580.00)。
+ ///
+ /// 去掉引号、千分位、货币符号与空白("1,580.00" → 1580.00)。
+ /// 分组符只在**合法的千分位**里才去掉(同一种分组符、首段 1–3 位、其后每段恰好 3 位、小数点在最后一段之后):
+ /// "1,5" 很可能是小数逗号写法的 1.5,悄悄变成 15 是错数,宁可报错 —— 返回空串,调用方按解析失败处理。
+ ///
internal static string CleanNumber(string text, out bool grouping)
{
grouping = false;
- string t = text.Trim().Trim('"', '\'', '“', '”').Trim();
- var builder = new System.Text.StringBuilder(t.Length);
+ // 先去货币符号再修边:"¥ 1,580" 里符号后的空格不是分组符。
+ string t = new string([.. text.Where(static c => c is not ('¥' or '¥' or '$' or '€' or '£'))])
+ .Trim().Trim('"', '\'', '“', '”').Trim();
+ char? separator = null;
foreach (char c in t)
{
- switch (c)
+ // 逗号、下划线、空格、不换行空格、细空格、窄不换行空格。
+ if (c is ',' or '_' or ' ' or (char)0xA0 or (char)0x2009 or (char)0x202F)
{
- case ',' or '_' or ' ' or ' ' or ' ':
- grouping = true;
- break;
- case '¥' or '¥' or '$' or '€' or '£':
- break;
- default:
- _ = builder.Append(c);
- break;
+ if (separator is { } seen && seen != c)
+ {
+ return "";
+ }
+ separator = c;
+ grouping = true;
}
}
- return builder.ToString();
+ string kept = t;
+ if (separator is not { } sep)
+ {
+ return kept;
+ }
+ if (!ValidGrouping(kept, sep))
+ {
+ return "";
+ }
+ return kept.Replace(sep.ToString(), "", StringComparison.Ordinal);
+ }
+
+ /// ^[+-]?\d{1,3}(,\d{3})+(\.\d+)?$(逗号换成实际用的那一个分组符)。
+ private static bool ValidGrouping(string text, char separator)
+ {
+ int start = text.Length > 0 && text[0] is '+' or '-' ? 1 : 0;
+ int dot = text.IndexOf('.', start);
+ string integer = dot < 0 ? text[start..] : text[start..dot];
+ if (dot >= 0 && (dot == text.Length - 1 || !text[(dot + 1)..].All(char.IsAsciiDigit)))
+ {
+ return false;
+ }
+ string[] groups = integer.Split(separator);
+ return groups.Length >= 2
+ && groups[0].Length is >= 1 and <= 3 && groups[0].All(char.IsAsciiDigit)
+ && groups.Skip(1).All(static g => g.Length == 3 && g.All(char.IsAsciiDigit));
}
///
diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs
index 99f6f7e..71a8fc3 100644
--- a/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Transfer/SchemaSampler.cs
@@ -96,8 +96,11 @@ public static async Task> SampleAsync(
cancellationToken).ConfigureAwait(false);
return await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);
}
- catch (MongoCommandException)
+ catch (MongoServerException)
{
+ // MongoServerException 而不只是 MongoCommandException:$sample 超时报的是 MongoExecutionTimeoutException,
+ // 它不是命令异常 —— 只接命令异常的话,文档里说的"退回 find().limit()"在最常见的超时情形下根本不会发生。
+ // 取消不在此列(OperationCanceledException 不是服务器异常),照常往外抛。
return await collection.Find(filter ?? []).Limit(size).ToListAsync(cancellationToken).ConfigureAwait(false);
}
}
diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs
index d404c82..dbdc4a5 100644
--- a/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Transfer/TransferModels.cs
@@ -141,12 +141,15 @@ internal sealed record XferField(string Path, IReadOnlyList Kinds, int
/// 这个字段默认的换算。
public CellConversion DefaultConversion => DefaultConversionFor(Dominant);
- /// 某种类型默认的换算。
+ ///
+ /// 某种类型默认的换算。默认一律**无损**:Decimal128 原样全精度(保留两位会把 0.0035 写成 0.00),
+ /// 日期写 ISO 8601 UTC(带毫秒与时区;本地时间不带时区、丢毫秒,下游读回来对不上)。有损的写法留给用户在字段表里显式选。
+ ///
public static CellConversion DefaultConversionFor(BsonKind kind) => kind switch
{
BsonKind.ObjectId => CellConversion.Hex,
- BsonKind.Decimal128 => CellConversion.Fixed2,
- BsonKind.Date => CellConversion.LocalTime,
+ BsonKind.Decimal128 => CellConversion.None,
+ BsonKind.Date => CellConversion.IsoTime,
BsonKind.Array or BsonKind.Object => CellConversion.Json,
_ => CellConversion.None
};
diff --git a/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs b/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs
index 7bb4781..26b380e 100644
--- a/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs
+++ b/plugins/VelaShell.Plugin.Mongo/Transfer/XlsxWriter.cs
@@ -150,7 +150,11 @@ public void WriteRow(IReadOnlyList cells, bool header = false)
{
XlsxCell cell = cells[i];
_sheet.WriteStartElement("c", MainNs);
- _sheet.WriteAttributeString("r", ColumnName(i) + rowRef);
+ // 单元格引用分两段写(列名缓存 + 行号):每格拼一个新字符串在几十万行的导出里是实打实的分配压力。
+ _sheet.WriteStartAttribute("r");
+ _sheet.WriteString(CachedColumnName(i));
+ _sheet.WriteString(rowRef);
+ _sheet.WriteEndAttribute();
if (cell.Number is { } number)
{
if (cell.Fixed2)
@@ -278,15 +282,28 @@ public void Dispose()
/// 列号 → 列名(0 → A,26 → AA)。
public static string ColumnName(int index)
{
- var name = new StringBuilder();
+ Span buffer = stackalloc char[8];
+ int start = buffer.Length;
int n = index + 1;
while (n > 0)
{
int rem = (n - 1) % 26;
- _ = name.Insert(0, (char)('A' + rem));
+ buffer[--start] = (char)('A' + rem);
n = (n - 1) / 26;
}
- return name.ToString();
+ return new string(buffer[start..]);
+ }
+
+ /// 列名缓存(各表共用:列名与表无关)。
+ private readonly List _columnNames = [];
+
+ private string CachedColumnName(int index)
+ {
+ while (_columnNames.Count <= index)
+ {
+ _columnNames.Add(ColumnName(_columnNames.Count));
+ }
+ return _columnNames[index];
}
///