mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 09:01:00 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c10435b414 |
No files matched your search
@@ -143,6 +143,9 @@ pub struct DockerConnection {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub endpoint: DockerEndpoint,
|
||||
/// Whether the user explicitly disconnected this connection in Services.
|
||||
#[serde(default)]
|
||||
pub disconnected: bool,
|
||||
}
|
||||
|
||||
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
|
||||
@@ -414,6 +417,7 @@ mod tests {
|
||||
id: "c1".into(),
|
||||
name: "Build box".into(),
|
||||
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
|
||||
disconnected: true,
|
||||
}],
|
||||
registries: vec![DockerRegistry {
|
||||
id: "r1".into(),
|
||||
@@ -435,12 +439,34 @@ mod tests {
|
||||
assert!(load_settings(dir).connections.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_intent_defaults_to_connected_and_round_trips() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
std::fs::write(
|
||||
dir.join(SETTINGS_FILE),
|
||||
r#"{"connections":[{"id":"box","name":"Box","endpoint":{"kind":"ssh","config":"build"}}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut settings = load_settings(dir);
|
||||
assert!(!settings.connections[0].disconnected);
|
||||
for disconnected in [true, false] {
|
||||
settings.connections[0].disconnected = disconnected;
|
||||
save_settings(dir, &settings).unwrap();
|
||||
assert_eq!(load_settings(dir), settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_drops_the_injected_default_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let injected =
|
||||
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
|
||||
let injected = || DockerConnection {
|
||||
id: "default".into(),
|
||||
name: "Docker".into(),
|
||||
endpoint: DockerEndpoint::Default,
|
||||
disconnected: false,
|
||||
};
|
||||
let registry =
|
||||
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
|
||||
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
|
||||
|
||||
@@ -6019,6 +6019,8 @@ export type DockerConnection = {
|
||||
id: string,
|
||||
name: string,
|
||||
endpoint: DockerEndpoint,
|
||||
/** Whether the user explicitly disconnected this connection in Services. */
|
||||
disconnected?: boolean,
|
||||
};
|
||||
|
||||
export type DockerContainer = {
|
||||
|
||||
@@ -51,14 +51,41 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("Docker connections", () => {
|
||||
it("skips a saved disconnected connection on startup and during polling", async () => {
|
||||
vi.resetModules();
|
||||
const { connectionState, watch } = await import("./store");
|
||||
const paused = { id: "paused", name: "Paused", endpoint: { kind: "ssh", config: "build" }, disconnected: true };
|
||||
const active = { id: "active", name: "Active", endpoint: { kind: "tcp", host: "build:2376" } };
|
||||
backend.settings.mockResolvedValueOnce(ok({ connections: [paused, active], registries: [] }));
|
||||
backend.snapshot.mockResolvedValue(ok({ availability: { kind: "daemonDown", message: "Offline" }, errors: [] }));
|
||||
|
||||
vi.useFakeTimers();
|
||||
const stop = watch();
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(backend.snapshot.mock.calls).toEqual([[active.endpoint]]);
|
||||
expect(connectionState(paused.id)).toMatchObject({ disconnected: true, snapshot: null });
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(backend.snapshot.mock.calls).toEqual([[active.endpoint], [active.endpoint]]);
|
||||
} finally {
|
||||
stop();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("stop talking to the daemon while disconnected, and connect again on Connect", async () => {
|
||||
const stop = watch();
|
||||
await vi.waitFor(() => expect(connectionState("box").snapshot).not.toBeNull());
|
||||
expect(backend.events).toHaveBeenCalledOnce();
|
||||
|
||||
disconnectConnection("box");
|
||||
await disconnectConnection("box");
|
||||
expect(backend.cancel).toHaveBeenCalledOnce();
|
||||
expect(connectionState("box")).toMatchObject({ snapshot: null, disconnected: true });
|
||||
expect(backend.saveSettings).toHaveBeenLastCalledWith({
|
||||
connections: [expect.objectContaining({ id: "box", disconnected: true })],
|
||||
registries: [],
|
||||
});
|
||||
backend.snapshot.mockClear();
|
||||
await refresh("box");
|
||||
expect(backend.snapshot).not.toHaveBeenCalled();
|
||||
@@ -66,9 +93,22 @@ describe("Docker connections", () => {
|
||||
await connectConnection("box");
|
||||
expect(backend.snapshot).toHaveBeenCalledOnce();
|
||||
expect(connectionState("box")).toMatchObject({ disconnected: false, snapshot: ready });
|
||||
expect(backend.saveSettings).toHaveBeenLastCalledWith({
|
||||
connections: [expect.objectContaining({ id: "box", disconnected: false })],
|
||||
registries: [],
|
||||
});
|
||||
stop();
|
||||
});
|
||||
|
||||
it("preserves the saved disconnect when editing the connection concurrently", async () => {
|
||||
const edited = { id: "box", name: "Edited box", endpoint: { kind: "default" } } as const;
|
||||
await Promise.all([disconnectConnection("box"), saveConnection(edited)]);
|
||||
expect(backend.saveSettings).toHaveBeenLastCalledWith({
|
||||
connections: [{ ...edited, disconnected: true }],
|
||||
registries: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe("over SSH", () => {
|
||||
const box = { id: "box", name: "Box", endpoint: { kind: "ssh", config: "build" } };
|
||||
const twin = { id: "twin", name: "Box again", endpoint: { kind: "ssh", config: "build" } };
|
||||
@@ -81,7 +121,7 @@ describe("Docker connections", () => {
|
||||
let finish!: () => void;
|
||||
backend.snapshot.mockReturnValueOnce(new Promise((resolve) => (finish = () => resolve(ok(ready)))));
|
||||
const reading = refresh("box");
|
||||
disconnectConnection("box");
|
||||
await disconnectConnection("box");
|
||||
await Promise.resolve();
|
||||
expect(backend.disconnect).not.toHaveBeenCalled();
|
||||
finish();
|
||||
@@ -95,20 +135,20 @@ describe("Docker connections", () => {
|
||||
let finish!: () => void;
|
||||
backend.snapshot.mockReturnValueOnce(new Promise((resolve) => (finish = () => resolve(ok(ready)))));
|
||||
const reading = refresh("box");
|
||||
disconnectConnection("box");
|
||||
const disconnecting = disconnectConnection("box");
|
||||
const connecting = connectConnection("box");
|
||||
finish();
|
||||
await Promise.all([reading, connecting]);
|
||||
await Promise.all([reading, disconnecting, connecting]);
|
||||
await vi.waitFor(() => expect(connectionState("box").snapshot).toEqual(ready));
|
||||
expect(backend.disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a tunnel another connected connection uses, until that one disconnects too", async () => {
|
||||
connect(box, twin);
|
||||
disconnectConnection("box");
|
||||
await disconnectConnection("box");
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(backend.disconnect).not.toHaveBeenCalled();
|
||||
disconnectConnection("twin");
|
||||
await disconnectConnection("twin");
|
||||
await vi.waitFor(() => expect(backend.disconnect).toHaveBeenCalledExactlyOnceWith(box.endpoint));
|
||||
});
|
||||
|
||||
@@ -121,7 +161,7 @@ describe("Docker connections", () => {
|
||||
|
||||
it("leaves other endpoints alone: they keep nothing open", async () => {
|
||||
connect(local);
|
||||
disconnectConnection("local");
|
||||
await disconnectConnection("local");
|
||||
await removeConnection("local");
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(backend.disconnect).not.toHaveBeenCalled();
|
||||
@@ -129,7 +169,7 @@ describe("Docker connections", () => {
|
||||
|
||||
it("matches the configuration as the backend does, ignoring surrounding spaces", async () => {
|
||||
connect(box, { ...twin, endpoint: { kind: "ssh", config: " build " } });
|
||||
disconnectConnection("box");
|
||||
await disconnectConnection("box");
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(backend.disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -144,7 +184,7 @@ describe("Docker connections", () => {
|
||||
connect(box);
|
||||
let closed!: () => void;
|
||||
backend.disconnect.mockReturnValueOnce(new Promise((resolve) => (closed = () => resolve(ok(null)))));
|
||||
disconnectConnection("box");
|
||||
await disconnectConnection("box");
|
||||
await vi.waitFor(() => expect(backend.disconnect).toHaveBeenCalledOnce());
|
||||
backend.snapshot.mockClear();
|
||||
const connecting = connectConnection("box");
|
||||
|
||||
@@ -256,7 +256,7 @@ function menu(item: ServiceTreeItem): MenuItem[] {
|
||||
{ kind: "separator" },
|
||||
connectionState(c.id).disconnected
|
||||
? { label: "Connect", run: () => void connectConnection(c.id) }
|
||||
: { label: "Disconnect", run: () => disconnectConnection(c.id) },
|
||||
: { label: "Disconnect", run: () => void disconnectConnection(c.id) },
|
||||
{ label: "Edit Connection…", icon: "edit", run: () => openConnectionDialog(c) },
|
||||
{ label: "Remove Connection", icon: "trash", danger: true, run: () => void removeConnectionPrompt(c) },
|
||||
);
|
||||
|
||||
@@ -169,7 +169,7 @@ export function activate(): () => void {
|
||||
when: PROJECT,
|
||||
run: () => {
|
||||
const id = currentConnection();
|
||||
if (id && !connectionState(id).disconnected) disconnectConnection(id);
|
||||
if (id && !connectionState(id).disconnected) void disconnectConnection(id);
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -58,7 +58,7 @@ export interface ConnectionState {
|
||||
snapshot: DockerSnapshot | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
/** Disconnected for this session: no snapshots, events or polling until Connect. */
|
||||
/** 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">;
|
||||
@@ -128,9 +128,18 @@ export function loadSettings(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
settingsLoad ??= call(commands.dockerSettings())
|
||||
.then((s: DockerSettings) =>
|
||||
useServices.setState({ settings: { connections: s.connections ?? [], registries: s.registries ?? [] } }),
|
||||
)
|
||||
.then((s: DockerSettings) => {
|
||||
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) => {
|
||||
settingsLoad = null;
|
||||
notifications().notify({
|
||||
@@ -143,32 +152,43 @@ export function loadSettings(): Promise<void> {
|
||||
return settingsLoad;
|
||||
}
|
||||
|
||||
async function saveSettings(settings: Settings): Promise<boolean> {
|
||||
try {
|
||||
if (isTauri()) await call(commands.dockerSaveSettings(settings));
|
||||
useServices.setState({ settings });
|
||||
return true;
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
title: "Cannot save Docker settings",
|
||||
body: errorMessage(e),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
let settingsWrite = Promise.resolve(true);
|
||||
|
||||
function saveSettings(update: (current: Settings) => Settings): Promise<boolean> {
|
||||
// Each write replaces the settings file, so derive it after the previous save.
|
||||
settingsWrite = settingsWrite.then(async () => {
|
||||
try {
|
||||
const current = useServices.getState().settings ?? { connections: [], registries: [] };
|
||||
const settings = update(current);
|
||||
if (settings === current) return true;
|
||||
if (isTauri()) await call(commands.dockerSaveSettings(settings));
|
||||
useServices.setState({ settings });
|
||||
return true;
|
||||
} catch (e) {
|
||||
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: DockerConnection): Promise<boolean> {
|
||||
export async function saveConnection(c: Pick<DockerConnection, "id" | "name" | "endpoint">): Promise<boolean> {
|
||||
await loadSettings();
|
||||
const s = useServices.getState().settings ?? { connections: [], registries: [] };
|
||||
const old = s.connections.find((x) => x.id === c.id)?.endpoint;
|
||||
const ok = await saveSettings({
|
||||
...s,
|
||||
connections: old ? s.connections.map((x) => (x.id === c.id ? c : x)) : [...s.connections, c],
|
||||
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);
|
||||
@@ -183,7 +203,7 @@ export async function removeConnection(id: string): Promise<void> {
|
||||
if (!s) return;
|
||||
stopEvents(id);
|
||||
const endpoint = endpointOf(id);
|
||||
if (await saveSettings({ ...s, connections: s.connections.filter((c) => c.id !== id) })) {
|
||||
if (await saveSettings((s) => ({ ...s, connections: s.connections.filter((c) => c.id !== id) }))) {
|
||||
useServices.setState((st) => {
|
||||
const conns = { ...st.conns };
|
||||
delete conns[id];
|
||||
@@ -196,11 +216,12 @@ export async function removeConnection(id: string): Promise<void> {
|
||||
/** 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 s = useServices.getState().settings ?? { connections: [], registries: [] };
|
||||
const exists = s.registries.some((x) => x.id === r.id);
|
||||
const ok = await saveSettings({
|
||||
...s,
|
||||
registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r],
|
||||
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 {
|
||||
@@ -219,7 +240,18 @@ export async function saveRegistry(r: DockerRegistry, password: string | null |
|
||||
|
||||
export async function removeRegistry(id: string): Promise<void> {
|
||||
const s = useServices.getState().settings;
|
||||
if (s) await saveSettings({ ...s, registries: s.registries.filter((r) => r.id !== id) });
|
||||
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. */
|
||||
@@ -311,7 +343,9 @@ export function watch(): () => void {
|
||||
if (watchers === 1) {
|
||||
pollTimer = setInterval(() => {
|
||||
for (const c of connections()) {
|
||||
const ready = connectionState(c.id).snapshot?.availability.kind === "ready";
|
||||
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);
|
||||
@@ -327,21 +361,24 @@ export function watch(): () => void {
|
||||
|
||||
/**
|
||||
* Disconnect: stops talking to the connection's daemon (its event stream and polling; for an
|
||||
* SSH connection, its tunnel and SSH connection) until Connect. Not saved: a new session connects.
|
||||
* SSH connection, its tunnel and SSH connection) until Connect, even across restarts.
|
||||
*/
|
||||
export function disconnectConnection(id: string): void {
|
||||
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);
|
||||
return refresh(id);
|
||||
await refresh(id);
|
||||
await saving;
|
||||
}
|
||||
|
||||
/** The SSH configuration an endpoint tunnels through (as the backend keys its tunnels). */
|
||||
|
||||
Reference in new issue
Block a user