Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 68 additions & 4 deletions app/main-axios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,19 @@ function getHostBase(defaultPort: number): string {
return `http://localhost:${defaultPort}/host`;
}

function getHostApiBaseCandidates(defaultPort: number): string[] {
const rootBase = getRootBase(defaultPort).replace(/\/$/, "");
const sshBase = getSshBase(defaultPort).replace(/\/$/, "");
const candidates = [
getHostBase(defaultPort).replace(/\/$/, ""),
`${sshBase}/host`,
sshBase,
rootBase,
];

return [...new Set(candidates)];
}

function initializeApiInstances() {
sshHostApi = createApiInstance(getHostBase(8081), "SSH_HOST");

Expand Down Expand Up @@ -789,11 +802,62 @@ function normalizeSSHHost(host: SSHHost): SSHHost {
}

export async function getSSHHosts(): Promise<SSHHost[]> {
let lastError: unknown = null;
let firstEmptyHosts: { api: AxiosInstance; hosts: SSHHost[] } | null = null;

const normalizeHostResponse = (data: unknown): SSHHost[] | null => {
const hostList = Array.isArray(data)
? data
: Array.isArray((data as { hosts?: unknown })?.hosts)
? ((data as { hosts: SSHHost[] }).hosts as unknown[])
: null;

return hostList ? (hostList as SSHHost[]).map(normalizeSSHHost) : null;
};

try {
const response = await sshHostApi.get("/db/host");
return Array.isArray(response.data)
? response.data.map(normalizeSSHHost)
: response.data;
for (const baseURL of getHostApiBaseCandidates(8081)) {
try {
const candidateApi = createApiInstance(baseURL, "SSH_HOST");
const response = await candidateApi.get("/db/host", {
headers: {
Accept: "application/json",
"Cache-Control": "no-cache",
},
});
const hosts = normalizeHostResponse(response.data);
if (hosts) {
if (hosts.length === 0) {
firstEmptyHosts ??= { api: candidateApi, hosts };
continue;
}

sshHostApi = candidateApi;
return hosts;
}

lastError = new Error(
`Unexpected host list response from ${baseURL}/db/host`,
);
} catch (error: any) {
lastError = error;
const status = error?.response?.status;
if (status === 401 || status === 403) {
throw error;
}
}
}

if (firstEmptyHosts) {
sshHostApi = firstEmptyHosts.api;
return firstEmptyHosts.hosts;
}

if (lastError) {
throw lastError;
}

return [];
} catch (error) {
handleApiError(error, "fetch SSH hosts");
}
Expand Down
Loading