Файли
openidea/src/features/services/store.ts
T
Deng Liuтаdengliu 1602a5d010 fix(services): route Docker Services to the remote host daemon (#6379)
Docker commands moved from the desktop crate into the ide-host project_host domain, so a remote window reaches the Docker daemon on the remote host through openidea-server instead of the local one. The SSH tunnel reuses the existing resolve logic, docker_executable only caches a found path, and the Services store drops event streams, timers and in-flight requests when the host changes.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:16:20 +08:00

606 рядки
20 KiB
TypeScript

/**
* Docker state for the Services tool window: the configured connections and
* registries, per connection the last snapshot and its refresh loop (a `docker
* events` stream while the daemon is up, a slow poll while it is not, so the
* view recovers when the daemon starts).
*/
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
import type {
ComposeOp,
ContainerOp,
DockerConnection,
DockerEndpoint,
DockerEvent,
DockerObject,
DockerRegistry,
DockerSettings,
DockerSnapshot,
PruneTarget,
RequestId,
} from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { notifications } from "@/workbench/contributions";
import { DEFAULT_DOCKER_FILTERS, type DockerFilters } from "./model";
export type DetailTab = "dashboard" | "log" | "processes" | "layers" | "inspect";
const FILTERS_STORAGE_KEY = "openidea.docker.filters";
function loadStoredFilters(): DockerFilters {
try {
const raw = typeof localStorage !== "undefined" ? localStorage.getItem(FILTERS_STORAGE_KEY) : null;
if (!raw) return DEFAULT_DOCKER_FILTERS;
const parsed = JSON.parse(raw) as Partial<DockerFilters>;
return {
showStoppedContainers:
typeof parsed.showStoppedContainers === "boolean"
? parsed.showStoppedContainers
: DEFAULT_DOCKER_FILTERS.showStoppedContainers,
showUntaggedImages:
typeof parsed.showUntaggedImages === "boolean"
? parsed.showUntaggedImages
: DEFAULT_DOCKER_FILTERS.showUntaggedImages,
};
} catch {
return DEFAULT_DOCKER_FILTERS;
}
}
/** `DockerSettings` with its defaults filled in. */
export interface Settings {
connections: DockerConnection[];
registries: DockerRegistry[];
}
export interface ConnectionState {
snapshot: DockerSnapshot | null;
loading: boolean;
error: string | null;
/** Explicitly disconnected: no snapshots, events or polling until Connect. */
disconnected?: boolean;
/** Containers with a start / stop / … / remove in progress, by id: the operation. */
busy?: Record<string, ContainerOp | "remove">;
}
interface DockerState {
/** Null until loaded. */
settings: Settings | null;
/** By connection id. */
conns: Record<string, ConnectionState>;
detailTab: DetailTab;
filters: DockerFilters;
/** Long operation in progress (pull, prune, compose…): its title and last output line. */
task: { title: string; line: string; request: RequestId } | null;
}
export const useServices = create<DockerState>(() => ({
settings: null,
conns: {},
detailTab: "dashboard",
filters: loadStoredFilters(),
task: null,
}));
export function setDockerFilters(patch: Partial<DockerFilters>): void {
useServices.setState((s) => {
const filters = { ...s.filters, ...patch };
try {
if (typeof localStorage !== "undefined") {
localStorage.setItem(FILTERS_STORAGE_KEY, JSON.stringify(filters));
}
} catch {
// ignore storage quota errors
}
return { filters };
});
}
export const errorMessage = (e: unknown) => (e instanceof Error ? e.message : String(e));
const IDLE: ConnectionState = { snapshot: null, loading: false, error: null };
export function connectionState(id: string, s = useServices.getState()): ConnectionState {
return s.conns[id] ?? IDLE;
}
export function connections(s = useServices.getState()): DockerConnection[] {
return s.settings?.connections ?? [];
}
export function endpointOf(connId: string): DockerEndpoint {
return connections().find((c) => c.id === connId)?.endpoint ?? { kind: "default" };
}
function patchConn(id: string, patch: Partial<ConnectionState>) {
useServices.setState((s) => ({ conns: { ...s.conns, [id]: { ...connectionState(id, s), ...patch } } }));
}
// ---------------------------------------------------------------------------
// Settings
let sessionEpoch = 0;
let settingsLoad: Promise<void> | null = null;
export function loadSettings(): Promise<void> {
if (!isTauri()) {
useServices.setState({ settings: { connections: [], registries: [] } });
return Promise.resolve();
}
const epoch = sessionEpoch;
settingsLoad ??= call(commands.dockerSettings())
.then((s: DockerSettings) => {
if (epoch !== sessionEpoch) return;
const connections = s.connections ?? [];
useServices.setState((state) => ({
settings: { connections, registries: s.registries ?? [] },
conns: {
...state.conns,
...Object.fromEntries(
connections.filter((c) => c.disconnected).map((c) => [c.id, { ...IDLE, disconnected: true }]),
),
},
}));
})
.catch((e) => {
if (epoch !== sessionEpoch) return;
settingsLoad = null;
notifications().notify({
group: "run",
level: "error",
title: "Cannot read Docker settings",
body: errorMessage(e),
});
});
return settingsLoad;
}
let settingsWrite = Promise.resolve(true);
function saveSettings(update: (current: Settings) => Settings): Promise<boolean> {
const epoch = sessionEpoch;
// Each write replaces the settings file, so derive it after the previous save.
settingsWrite = settingsWrite.then(async () => {
if (epoch !== sessionEpoch) return false;
try {
const current = useServices.getState().settings ?? { connections: [], registries: [] };
const settings = update(current);
if (settings === current) return true;
if (isTauri()) await call(commands.dockerSaveSettings(settings));
if (epoch === sessionEpoch) useServices.setState({ settings });
return true;
} catch (e) {
if (epoch === sessionEpoch) {
notifications().notify({
group: "run",
level: "error",
title: "Cannot save Docker settings",
body: errorMessage(e),
});
}
return false;
}
});
return settingsWrite;
}
export const newId = (prefix: string) => `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
/** Adds or replaces (same id) a connection; the tree picks it up right away. */
export async function saveConnection(c: Pick<DockerConnection, "id" | "name" | "endpoint">): Promise<boolean> {
await loadSettings();
let old: DockerEndpoint | undefined;
const ok = await saveSettings((s) => {
old = s.connections.find((x) => x.id === c.id)?.endpoint;
return {
...s,
connections: old ? s.connections.map((x) => (x.id === c.id ? { ...x, ...c } : x)) : [...s.connections, c],
};
});
if (ok) {
stopEvents(c.id);
if (watchers > 0) void refresh(c.id);
if (old) closeEndpoint(c.id, old);
}
return ok;
}
export async function removeConnection(id: string): Promise<void> {
const s = useServices.getState().settings;
if (!s) return;
stopEvents(id);
const endpoint = endpointOf(id);
if (await saveSettings((s) => ({ ...s, connections: s.connections.filter((c) => c.id !== id) }))) {
useServices.setState((st) => {
const conns = { ...st.conns };
delete conns[id];
return { conns };
});
closeEndpoint(id, endpoint);
}
}
/** Adds or replaces a registry; `password` undefined keeps the saved one, null forgets it. */
export async function saveRegistry(r: DockerRegistry, password: string | null | undefined): Promise<boolean> {
await loadSettings();
const ok = await saveSettings((s) => {
const exists = s.registries.some((x) => x.id === r.id);
return {
...s,
registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r],
};
});
if (ok && password !== undefined && isTauri()) {
try {
await call(commands.dockerSetRegistryPassword(r.id, password));
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Cannot save the registry password",
body: errorMessage(e),
});
}
}
return ok;
}
export async function removeRegistry(id: string): Promise<void> {
const s = useServices.getState().settings;
if (s) await saveSettings((s) => ({ ...s, registries: s.registries.filter((r) => r.id !== id) }));
}
function saveConnectionDisconnected(id: string, disconnected: boolean): Promise<boolean> {
return saveSettings((s) => {
const existing = s.connections.find((c) => c.id === id);
if (!existing || (existing.disconnected ?? false) === disconnected) return s;
return {
...s,
connections: s.connections.map((c) => (c.id === id ? { ...c, disconnected } : c)),
};
});
}
/** Test login; resolves to docker's answer, rejects with its error. */
export function testRegistryLogin(r: DockerRegistry, password: string | null): Promise<string> {
const endpoint = connections()[0]?.endpoint ?? { kind: "default" };
return call(commands.dockerRegistryLogin(endpoint, r, password));
}
// ---------------------------------------------------------------------------
// Snapshots
const inflight = new Map<string, Promise<void>>();
const again = new Set<string>();
/** Re-reads one connection (all without `id`); concurrent calls coalesce into one follow-up refresh. */
export function refresh(id?: string): Promise<void> {
if (!isTauri()) return Promise.resolve();
if (id === undefined) return Promise.all(connections().map((c) => refresh(c.id))).then(() => undefined);
if (connectionState(id).disconnected) return Promise.resolve();
const running = inflight.get(id);
if (running) {
again.add(id);
return running;
}
patchConn(id, { loading: true });
const epoch = sessionEpoch;
const p = call(commands.dockerSnapshot(endpointOf(id)))
.then((snapshot) => {
if (epoch !== sessionEpoch) return;
if (!connections().some((c) => c.id === id) || connectionState(id).disconnected) return;
const wasReady = connectionState(id).snapshot?.availability.kind === "ready";
patchConn(id, { snapshot, error: null });
if (snapshot.availability.kind === "ready" && !wasReady) startEvents(id);
})
.catch((e) => {
if (epoch !== sessionEpoch) return;
if (!connectionState(id).disconnected) patchConn(id, { error: errorMessage(e) });
})
.finally(() => {
if (epoch !== sessionEpoch) return;
inflight.delete(id);
if (connections().some((c) => c.id === id)) patchConn(id, { loading: false });
if (again.delete(id)) void refresh(id);
});
inflight.set(id, p);
return p;
}
const debounces = new Map<string, ReturnType<typeof setTimeout>>();
function refreshSoon(id: string) {
clearTimeout(debounces.get(id));
debounces.set(
id,
setTimeout(() => void refresh(id), 250),
);
}
const events = new Map<string, RequestId>();
let pollTimer: ReturnType<typeof setInterval> | undefined;
let watchers = 0;
function startEvents(id: string) {
if (events.has(id) || watchers === 0 || connectionState(id).disconnected) return;
const epoch = sessionEpoch;
const request = nextRequestId();
events.set(id, request);
const channel = new Channel<DockerEvent>();
channel.onmessage = () => {
if (epoch === sessionEpoch) refreshSoon(id);
};
void call(commands.dockerEvents(request, endpointOf(id), channel))
.catch(() => undefined)
.finally(() => {
if (epoch !== sessionEpoch || events.get(id) !== request) return;
events.delete(id);
// The stream ended on its own (daemon stopped): re-check the state.
if (watchers > 0) refreshSoon(id);
});
}
function stopEvents(id?: string) {
for (const [conn, r] of [...events]) {
if (id !== undefined && conn !== id) continue;
events.delete(conn);
void commands.cancelRequest(r);
}
}
function resetForHostChange() {
sessionEpoch++;
for (const r of events.values()) {
void Promise.resolve(commands.cancelRequest?.(r)).catch(() => undefined);
}
events.clear();
for (const timer of debounces.values()) clearTimeout(timer);
debounces.clear();
inflight.clear();
again.clear();
closing.clear();
settingsLoad = null;
settingsWrite = Promise.resolve(true);
useServices.setState({ settings: null, conns: {}, task: null });
if (watchers > 0) void loadSettings().then(() => refresh());
}
// Switching between a local window and a remote host (or reconnecting) moves Docker to that host.
useRemote.subscribe((state, previous) => {
if (state.session !== previous.session) resetForHostChange();
});
// Trusting a Restricted Mode project unlocks `docker_snapshot` without waiting for the 10 s poll.
useProject.subscribe((state, previous) => {
if (state.project?.trusted && !previous.project?.trusted && watchers > 0) {
void loadSettings().then(() => refresh());
}
});
/**
* Keeps the snapshots live while the tree is shown: events while a daemon runs,
* a poll every 10 s while it does not (or its events stream is down).
*/
export function watch(): () => void {
watchers++;
void loadSettings().then(() => refresh());
if (watchers === 1) {
pollTimer = setInterval(() => {
for (const c of connections()) {
const state = connectionState(c.id);
if (state.disconnected) continue;
const ready = state.snapshot?.availability.kind === "ready";
if (!ready || !events.has(c.id)) void refresh(c.id);
}
}, 10_000);
}
return () => {
watchers--;
if (watchers === 0) {
clearInterval(pollTimer);
stopEvents();
}
};
}
/**
* Disconnect: stops talking to the connection's daemon (its event stream and polling; for an
* SSH connection, its tunnel and SSH connection) until Connect, even across restarts.
*/
export async function disconnectConnection(id: string): Promise<void> {
stopEvents(id);
clearTimeout(debounces.get(id));
again.delete(id);
patchConn(id, { snapshot: null, error: null, loading: false, disconnected: true });
closeEndpoint(id, endpointOf(id));
await saveConnectionDisconnected(id, true);
}
export async function connectConnection(id: string): Promise<void> {
patchConn(id, { disconnected: false });
const saving = saveConnectionDisconnected(id, false);
// A tunnel being closed would take this connection's next snapshot down with it.
await closing.get(id);
await refresh(id);
await saving;
}
/** The SSH configuration an endpoint tunnels through (as the backend keys its tunnels). */
const sshConfig = (e: DockerEndpoint) => (e.kind === "ssh" ? e.config.trim() : null);
const closing = new Map<string, Promise<void>>();
/**
* Closes the SSH tunnel connection `id` used through `endpoint` (and its SSH connection, unless
* something else holds it) once no connected Docker connection goes through that configuration.
* Other endpoints keep nothing open.
*/
function closeEndpoint(id: string, endpoint: DockerEndpoint) {
const config = sshConfig(endpoint);
if (config === null || !isTauri()) return;
const done = (async () => {
// A snapshot in flight would open the tunnel again after it was closed.
await inflight.get(id);
if (connections().some((c) => !connectionState(c.id).disconnected && sshConfig(c.endpoint) === config)) return;
await call(commands.dockerDisconnect(endpoint)).catch(() => undefined);
})();
closing.set(id, done);
void done.finally(() => closing.get(id) === done && closing.delete(id));
}
// ---------------------------------------------------------------------------
// Operations
async function guarded(connId: string, title: string, run: () => Promise<unknown>): Promise<boolean> {
try {
await run();
return true;
} catch (e) {
if (!isCancelled(e))
notifications().notify({ group: "run", level: "error", title, body: errorMessage(e), key: "docker-op" });
return false;
} finally {
refreshSoon(connId);
}
}
/** The operation in progress on any of `ids`, if one is. */
export function busyOp(connId: string, ids: readonly string[], s = useServices.getState()) {
const busy = connectionState(connId, s).busy;
for (const id of ids) if (busy?.[id]) return busy[id];
return null;
}
/**
* Runs `op` on containers no other operation holds, marking them busy until the
* snapshot after it has loaded, so their actions stay disabled meanwhile.
*/
async function holding(connId: string, ids: string[], op: ContainerOp | "remove", run: () => Promise<boolean>) {
if (busyOp(connId, ids)) return false;
const mark = (on: boolean) =>
useServices.setState((s) => {
const busy = { ...connectionState(connId, s).busy };
for (const id of ids) {
if (on) busy[id] = op;
else delete busy[id];
}
return { conns: { ...s.conns, [connId]: { ...connectionState(connId, s), busy } } };
});
mark(true);
try {
const ok = await run();
await refresh(connId).catch(() => undefined);
return ok;
} finally {
mark(false);
}
}
export function containerOp(connId: string, ids: string[], op: ContainerOp): Promise<boolean> {
const failure = {
start: tx("Could not start container"),
stop: tx("Could not stop container"),
restart: tx("Could not restart container"),
pause: tx("Could not pause container"),
unpause: tx("Could not unpause container"),
kill: tx("Could not kill container"),
}[op];
return holding(connId, ids, op, () =>
guarded(connId, failure, () => call(commands.dockerContainerOp(endpointOf(connId), ids, op))),
);
}
export function removeObjects(connId: string, object: DockerObject, ids: string[], force: boolean): Promise<boolean> {
const failure = {
container: tx("Could not remove container"),
image: tx("Could not remove image"),
volume: tx("Could not remove volume"),
network: tx("Could not remove network"),
}[object];
const run = () => guarded(connId, failure, () => call(commands.dockerRemove(endpointOf(connId), object, ids, force)));
return object === "container" ? holding(connId, ids, "remove", run) : run();
}
/** Runs a streaming operation, showing its latest output line in the view's banner. */
async function task(
connId: string,
title: string,
failure: string,
run: (request: RequestId, out: Channel<string>) => Promise<unknown>,
): Promise<boolean> {
if (useServices.getState().task) {
notifications().notify({
group: "run",
level: "info",
title: "Another Docker operation is still running",
key: "docker-op",
});
return false;
}
const request = nextRequestId();
const out = new Channel<string>();
let last = "";
out.onmessage = (line) => {
last = line;
useServices.setState((s) => (s.task ? { task: { ...s.task, line } } : s));
};
useServices.setState({ task: { title, line: "", request } });
try {
return await guarded(connId, failure, () => run(request, out));
} finally {
useServices.setState({ task: null });
if (last)
notifications().notify({
group: "run",
level: "info",
title: title.replace(/…$/, ""),
body: last,
key: "docker-task",
});
}
}
export function cancelTask() {
const t = useServices.getState().task;
if (t) void commands.cancelRequest(t.request);
}
export const pullImage = (connId: string, reference: string) =>
task(connId, `Pulling ${reference}…`, tx`Could not pull ${reference}`, (r, out) =>
call(commands.dockerPull(r, endpointOf(connId), reference, out)),
);
export function prune(connId: string, target: PruneTarget) {
const title = {
containers: tx("Pruning stopped containers…"),
images: tx("Pruning dangling images…"),
allImages: tx("Pruning unused images…"),
volumes: tx("Pruning unused volumes…"),
networks: tx("Pruning unused networks…"),
system: tx("Pruning the system…"),
}[target];
return task(connId, title, tx("Could not prune"), (r, out) =>
call(commands.dockerPrune(r, endpointOf(connId), target, out)),
);
}
export function composeOp(connId: string, project: string, files: string[], workingDir: string | null, op: ComposeOp) {
const { title, failure } = {
start: { title: tx`Starting Compose project ${project}…`, failure: tx`Could not start Compose project ${project}` },
stop: { title: tx`Stopping Compose project ${project}…`, failure: tx`Could not stop Compose project ${project}` },
restart: {
title: tx`Restarting Compose project ${project}…`,
failure: tx`Could not restart Compose project ${project}`,
},
down: {
title: tx`Taking down Compose project ${project}…`,
failure: tx`Could not take down Compose project ${project}`,
},
}[op];
return task(connId, title, failure, (r, out) =>
call(commands.dockerComposeOp(r, endpointOf(connId), project, files, workingDir, op, out)),
);
}