From 4c788dcdacfa7f05dd6700bfed369c8bcb19b1bf Mon Sep 17 00:00:00 2001 From: Tom Winnerl <29701706+Pixelplanet@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:14:39 +0100 Subject: [PATCH] frontend: upstream picker, live reachability check, health in the host status - UpstreamField replaces the plain forward host inputs of proxy hosts, custom locations and streams: a combobox with the suggestions from /api/upstreams/candidates grouped by source (used before, network DNS, Docker), their ports and the hosts that already use them. Free text still works; picking a candidate also fills in the port and scheme, unless the user already changed them. - While editing, the forward host and port are checked with /api/upstreams/check (debounced) and a badge shows whether the target is reachable, explains why not, or notes that a variable host such as $backend can't be checked. - The host status in the proxy host and stream tables includes the health monitor results: an online host with an unreachable upstream shows as a warning and the status popover lists the failing targets (a location that is already reported as unresolved isn't listed twice). Co-Authored-By: Claude Opus 5.5 --- frontend/src/App.css | 7 + frontend/src/api/backend/checkUpstreams.ts | 15 + .../src/api/backend/getUpstreamCandidates.ts | 15 + frontend/src/api/backend/getUpstreamHealth.ts | 6 + frontend/src/api/backend/index.ts | 3 + frontend/src/api/backend/models.ts | 93 ++++ .../components/Form/FormModal.drafts.test.tsx | 31 +- .../Form/ForwardHostCheckHint.test.tsx | 57 ++ .../components/Form/ForwardHostCheckHint.tsx | 26 + .../components/Form/LocationsFields.test.tsx | 87 ++- .../src/components/Form/LocationsFields.tsx | 51 +- .../components/Form/UpstreamField.test.tsx | 494 ++++++++++++++++++ .../src/components/Form/UpstreamField.tsx | 456 ++++++++++++++++ frontend/src/components/Form/index.ts | 2 + frontend/src/components/StatusBadges.test.tsx | 61 +++ frontend/src/components/StatusBadges.tsx | 118 ++++- .../Formatter/HostStatusFormatter.test.tsx | 75 ++- .../Table/Formatter/HostStatusFormatter.tsx | 31 +- frontend/src/hooks/index.ts | 3 + frontend/src/hooks/useUpstreamCandidates.ts | 46 ++ frontend/src/hooks/useUpstreamCheck.test.tsx | 43 ++ frontend/src/hooks/useUpstreamCheck.ts | 106 ++++ frontend/src/hooks/useUpstreamHealth.test.tsx | 65 +++ frontend/src/hooks/useUpstreamHealth.ts | 35 ++ .../src/locale/src/HelpDoc/de/ProxyHosts.md | 4 +- .../src/locale/src/HelpDoc/en/ProxyHosts.md | 4 +- frontend/src/locale/src/de.json | 81 +++ frontend/src/locale/src/en.json | 81 +++ frontend/src/locale/src/et.json | 81 +++ frontend/src/locale/src/vi.json | 81 +++ frontend/src/modals/ProxyHostModal.tsx | 51 +- frontend/src/modals/StreamModal.tsx | 38 +- frontend/src/modules/HostStatus.test.ts | 55 +- frontend/src/modules/HostStatus.ts | 36 +- frontend/src/pages/Nginx/ProxyHosts/Table.tsx | 8 +- .../pages/Nginx/ProxyHosts/TableWrapper.tsx | 4 +- frontend/src/pages/Nginx/Streams/Table.tsx | 21 +- .../src/pages/Nginx/Streams/TableWrapper.tsx | 4 +- 38 files changed, 2419 insertions(+), 56 deletions(-) create mode 100644 frontend/src/api/backend/checkUpstreams.ts create mode 100644 frontend/src/api/backend/getUpstreamCandidates.ts create mode 100644 frontend/src/api/backend/getUpstreamHealth.ts create mode 100644 frontend/src/components/Form/ForwardHostCheckHint.test.tsx create mode 100644 frontend/src/components/Form/ForwardHostCheckHint.tsx create mode 100644 frontend/src/components/Form/UpstreamField.test.tsx create mode 100644 frontend/src/components/Form/UpstreamField.tsx create mode 100644 frontend/src/components/StatusBadges.test.tsx create mode 100644 frontend/src/hooks/useUpstreamCandidates.ts create mode 100644 frontend/src/hooks/useUpstreamCheck.test.tsx create mode 100644 frontend/src/hooks/useUpstreamCheck.ts create mode 100644 frontend/src/hooks/useUpstreamHealth.test.tsx create mode 100644 frontend/src/hooks/useUpstreamHealth.ts diff --git a/frontend/src/App.css b/frontend/src/App.css index 894f70cc9..786e5502b 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -75,6 +75,13 @@ } } +/* The upstream picker only marks an option focused once the user moves through + the list with the keyboard (so Enter/Tab never pick one by surprise). Mouse + hover still needs a highlight. */ +.react-select-container.upstream-field .react-select__menu .react-select__option:hover:not(.react-select__option--is-focused) { + background: rgba(var(--tblr-primary-rgb), .1); +} + .textareaMono { font-family: 'Courier New', Courier, monospace !important; resize: vertical; diff --git a/frontend/src/api/backend/checkUpstreams.ts b/frontend/src/api/backend/checkUpstreams.ts new file mode 100644 index 000000000..d3d3ab6c2 --- /dev/null +++ b/frontend/src/api/backend/checkUpstreams.ts @@ -0,0 +1,15 @@ +import * as api from "./base"; +import type { UpstreamCheckResponse, UpstreamCheckTarget } from "./models"; + +export async function checkUpstreams( + targets: UpstreamCheckTarget[], + abortController?: AbortController, +): Promise { + return await api.post( + { + url: "/upstreams/check", + data: { targets }, + }, + abortController, + ); +} diff --git a/frontend/src/api/backend/getUpstreamCandidates.ts b/frontend/src/api/backend/getUpstreamCandidates.ts new file mode 100644 index 000000000..b7ff32832 --- /dev/null +++ b/frontend/src/api/backend/getUpstreamCandidates.ts @@ -0,0 +1,15 @@ +import * as api from "./base"; +import type { UpstreamCandidates } from "./models"; + +export async function getUpstreamCandidates( + refresh = false, + abortController?: AbortController, +): Promise { + return await api.get( + { + url: "/upstreams/candidates", + params: refresh ? { refresh: true } : undefined, + }, + abortController, + ); +} diff --git a/frontend/src/api/backend/getUpstreamHealth.ts b/frontend/src/api/backend/getUpstreamHealth.ts new file mode 100644 index 000000000..d6c659923 --- /dev/null +++ b/frontend/src/api/backend/getUpstreamHealth.ts @@ -0,0 +1,6 @@ +import * as api from "./base"; +import type { UpstreamHealth } from "./models"; + +export async function getUpstreamHealth(abortController?: AbortController): Promise { + return await api.get({ url: "/upstreams/health" }, abortController); +} diff --git a/frontend/src/api/backend/index.ts b/frontend/src/api/backend/index.ts index c1541ad8d..b78a9cd0c 100644 --- a/frontend/src/api/backend/index.ts +++ b/frontend/src/api/backend/index.ts @@ -1,4 +1,5 @@ export { ApiError, type ApiErrorDetails, buildApiError, isApiError } from "./base"; +export * from "./checkUpstreams"; export * from "./checkVersion"; export * from "./createAccessList"; export * from "./createCertificate"; @@ -39,6 +40,8 @@ export * from "./getSettings"; export * from "./getStream"; export * from "./getStreams"; export * from "./getToken"; +export * from "./getUpstreamCandidates"; +export * from "./getUpstreamHealth"; export * from "./getUser"; export * from "./getUsers"; export * from "./helpers"; diff --git a/frontend/src/api/backend/models.ts b/frontend/src/api/backend/models.ts index 3e46463d7..648a64ddb 100644 --- a/frontend/src/api/backend/models.ts +++ b/frontend/src/api/backend/models.ts @@ -312,3 +312,96 @@ export interface DNSProvider { name: string; credentials: string; } + +// --------------------------------------------------------------------------- +// Upstream discovery / reachability check / health (/api/upstreams/*) +// --------------------------------------------------------------------------- + +export type UpstreamSource = "docker" | "dns" | "history"; + +export interface UpstreamProviderStatus { + status: "ok" | "disabled" | "unavailable"; + message: string | null; +} + +export interface UpstreamCandidate { + host: string; + label: string; + source: UpstreamSource; + ports: number[]; + hintPort: number | null; + hintScheme: "http" | "https" | null; + network: string | null; + state: string | null; + ip: string | null; + usedBy: number; +} + +export interface UpstreamCandidates { + providers: Record; + items: UpstreamCandidate[]; + generatedAt: string; +} + +export type UpstreamCheckCode = + | "ok" + | "invalid_host" + | "dns_not_found" + | "dns_timeout" + | "resolver_mismatch" + | "tcp_refused" + | "tcp_timeout" + | "tcp_unreachable" + | "disabled"; + +export interface UpstreamCheckTarget { + host: string; + port: number; + scheme?: string; +} + +export interface UpstreamCheckResult { + host: string; + port: number; + scheme?: string; + ok: boolean; + code: UpstreamCheckCode; + message: string; + addresses?: string[]; + resolverOk?: boolean | null; + systemOk?: boolean | null; + ms?: number | null; +} + +export interface UpstreamCheckResponse { + results: UpstreamCheckResult[]; +} + +export interface UpstreamHealthTarget { + // null for the host's main destination + locationIndex: number | null; + path?: string; + host: string; + port: number; + ok: boolean; + code: UpstreamCheckCode; + message: string; + ms?: number | null; +} + +export interface UpstreamHostHealth { + checkedAt: string; + ok: boolean; + targets: UpstreamHealthTarget[]; +} + +export interface UpstreamHealth { + enabled: boolean; + interval: number; + checkedAt: string | null; + hosts: { + // Keyed by host id (as a string). `proxy_host` arrives camelized. + proxyHost?: Record; + stream?: Record; + }; +} diff --git a/frontend/src/components/Form/FormModal.drafts.test.tsx b/frontend/src/components/Form/FormModal.drafts.test.tsx index 7e1e11633..e52f2f752 100644 --- a/frontend/src/components/Form/FormModal.drafts.test.tsx +++ b/frontend/src/components/Form/FormModal.drafts.test.tsx @@ -1,3 +1,4 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { Form } from "formik"; import type { ReactNode } from "react"; @@ -10,17 +11,20 @@ vi.mock("./AccessField", () => ({ AccessField: () => null })); const renderDraft = (initialValues: Record, children: ReactNode) => { const onHide = vi.fn(); + // The location host field asks the API for upstream suggestions render( - - {({ onHide: hide }) => ( -
- {children} - -
- )} -
, + + + {({ onHide: hide }) => ( +
+ {children} + +
+ )} +
+
, ); return onHide; }; @@ -31,6 +35,11 @@ describe("FormModal local drafts", () => { "confirm", vi.fn(() => false), ); + // Suggestions never arrive, so the test makes no network requests + vi.stubGlobal( + "fetch", + vi.fn(() => new Promise(() => {})), + ); }); afterEach(() => { @@ -41,7 +50,7 @@ describe("FormModal local drafts", () => { it("protects a location draft without a path", () => { const onHide = renderDraft({ locations: [] }, ); fireEvent.click(screen.getByRole("button", { name: "Add Location" })); - fireEvent.change(screen.getByPlaceholderText("eg: 10.0.0.1/path/"), { target: { value: "example.com" } }); + fireEvent.change(screen.getByLabelText("Forward Hostname / IP"), { target: { value: "example.com" } }); fireEvent.click(screen.getByRole("button", { name: "Cancel" })); diff --git a/frontend/src/components/Form/ForwardHostCheckHint.test.tsx b/frontend/src/components/Form/ForwardHostCheckHint.test.tsx new file mode 100644 index 000000000..c7fc2766a --- /dev/null +++ b/frontend/src/components/Form/ForwardHostCheckHint.test.tsx @@ -0,0 +1,57 @@ +import { cleanup, render } from "@testing-library/react"; +import { Formik } from "formik"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ForwardHostCheckHint } from "./ForwardHostCheckHint"; + +vi.mock("src/context", () => ({ useLocaleState: () => ({ locale: "en" }) })); + +const check = vi.hoisted(() => ({ + calls: [] as unknown[], + answer: { result: null as unknown, isChecking: false }, +})); +vi.mock("src/hooks", () => ({ + useUpstreamCheck: (input: unknown) => { + check.calls.push(input); + return check.answer; + }, +})); + +const renderHint = (forwardHost: string) => + render( + {}}> + + , + ); + +describe("ForwardHostCheckHint", () => { + afterEach(() => { + cleanup(); + check.calls = []; + check.answer = { result: null, isChecking: false }; + }); + + it("shows the neutral variable hint for a main forward host that is an nginx variable", () => { + for (const host of ["$backend", " $up_2 "]) { + const { container, unmount } = renderHint(host); + const hint = container.querySelector("#forwardHost-check"); + expect(hint).toHaveAttribute("data-check", "variable"); + expect(hint).toHaveTextContent("nginx variable"); + // the main host is read by `set $server`, before the advanced config runs + expect(hint).toHaveTextContent(/map in \/data\/nginx\/custom\/http\.conf/); + unmount(); + } + }); + + it("shows the live check for anything else; the main host is not split at '/'", () => { + check.answer = { + result: { host: "app", port: 80, ok: true, code: "ok", ms: 3, message: "", addresses: [] }, + isChecking: false, + }; + for (const host of ["app", "$backend/api"]) { + const { container, unmount } = renderHint(host); + expect(container.querySelector("#forwardHost-check")).toHaveAttribute("data-check", "ok"); + unmount(); + } + expect(check.calls).toContainEqual({ host: "app", port: 80, scheme: "http" }); + }); +}); diff --git a/frontend/src/components/Form/ForwardHostCheckHint.tsx b/frontend/src/components/Form/ForwardHostCheckHint.tsx new file mode 100644 index 000000000..b7ec36991 --- /dev/null +++ b/frontend/src/components/Form/ForwardHostCheckHint.tsx @@ -0,0 +1,26 @@ +import { useFormikContext } from "formik"; +import { useUpstreamCheck } from "src/hooks"; +import { isVariableHost } from "src/modules/HostStatus"; +import { UpstreamCheckHint, VariableHostHint } from "../StatusBadges"; + +/** + * Live reachability of a proxy host's main forward host (Details tab). + * + * The backend writes the main forward host as `set $server "";`, so a + * single nginx variable works there too and is resolved per request: it gets + * the neutral variable hint and no live check (useUpstreamCheck skips it). + * Unlike a location's forward host it is never split at "/", so `$backend/api` + * is not a variable host here. + */ +export function ForwardHostCheckHint({ id = "forwardHost-check" }: { id?: string }) { + const { values } = useFormikContext(); + const { result, isChecking } = useUpstreamCheck({ + host: values.forwardHost, + port: values.forwardPort, + scheme: values.forwardScheme, + }); + if (isVariableHost(values.forwardHost)) { + return ; + } + return ; +} diff --git a/frontend/src/components/Form/LocationsFields.test.tsx b/frontend/src/components/Form/LocationsFields.test.tsx index 421e2834b..03aecc3f1 100644 --- a/frontend/src/components/Form/LocationsFields.test.tsx +++ b/frontend/src/components/Form/LocationsFields.test.tsx @@ -1,7 +1,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { Form, Formik } from "formik"; -import type { NginxLocationStatus, ProxyLocation } from "src/api/backend"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import type { NginxLocationStatus, ProxyLocation, UpstreamCheckResult } from "src/api/backend"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { cleanLocations, isBlankLocation, @@ -10,9 +10,23 @@ import { validateLocations, } from "./LocationsFields"; +const { checkState } = vi.hoisted(() => ({ + checkState: { result: null as UpstreamCheckResult | null, calls: [] as any[], candidates: undefined as any }, +})); + vi.mock("src/context", () => ({ useLocaleState: () => ({ locale: "en" }) })); vi.mock("src/hooks", () => ({ useAccessLists: () => ({ isLoading: false, isError: false, data: [] }), + useUpstreamCandidates: () => ({ + data: checkState.candidates, + isFetching: false, + refresh: vi.fn(), + isRefreshing: false, + }), + useUpstreamCheck: (input: any, enabled: boolean) => { + checkState.calls.push({ input, enabled }); + return { result: enabled ? checkState.result : null, isChecking: false }; + }, })); const loc = (l: Partial): ProxyLocation => ({ @@ -213,6 +227,11 @@ describe("validateLocations", () => { }); describe("LocationsFields", () => { + beforeEach(() => { + checkState.result = null; + checkState.calls = []; + checkState.candidates = undefined; + }); afterEach(() => cleanup()); it("shows server status badges, hiding ok", () => { @@ -254,6 +273,37 @@ describe("LocationsFields", () => { expect(card).not.toHaveTextContent("Disabled"); }); + it("a picked candidate fills in the port only while the user hasn't changed it", () => { + checkState.candidates = { + providers: {}, + items: [ + { host: "svc", label: "svc", source: "docker", ports: [3000], hintPort: 3000, hintScheme: null }, + { host: "other", label: "other", source: "docker", ports: [4000], hintPort: 4000, hintScheme: null }, + ], + generatedAt: "2026-11-04T10:00:00Z", + }; + renderFields([loc({ path: "/a", forwardHost: "", forwardPort: 80 })]); + fireEvent.click(screen.getByText("/a")); + const port = screen.getByPlaceholderText("eg: 8081") as HTMLInputElement; + const host = document.querySelector("[id^=location-forwardHost-]") as HTMLInputElement; + const pick = (name: string) => { + fireEvent.focus(host); + fireEvent.keyDown(host, { key: "ArrowDown", code: "ArrowDown" }); + fireEvent.click(screen.getByText(name)); + }; + // untouched port: filled in, and a later pick may replace what it filled in + pick("svc"); + expect(host.value).toBe("svc"); + expect(port.value).toBe("3000"); + pick("other"); + expect(port.value).toBe("4000"); + // a port the user typed stays + fireEvent.change(port, { target: { value: "8443" } }); + pick("svc"); + expect(host.value).toBe("svc"); + expect(port.value).toBe("8443"); + }); + it("blocks submit with invalid rows, expands them and shows the errors", async () => { const { onSubmit } = renderFields([loc({ path: "/a" }), loc({ path: "/a", forwardHost: "bad host" })]); // collapsed: no inputs visible yet @@ -302,6 +352,39 @@ describe("LocationsFields", () => { expect((screen.getByPlaceholderText("/path") as HTMLInputElement).value).toBe("/b"); }); + it("checks reachability once a card was opened and shows the result", () => { + checkState.result = { + host: "app", + port: 80, + ok: false, + code: "tcp_refused", + message: "Connection refused", + }; + renderFields([loc({ path: "/a" })]); + expect(checkState.calls.every((c) => !c.enabled)).toBe(true); + fireEvent.click(screen.getByText("/a")); + expect(checkState.calls.some((c) => c.enabled && c.input.host === "app" && c.input.port === 80)).toBe(true); + expect(screen.getByTestId("location-card-0").querySelector("[data-check]")).toHaveAttribute( + "data-check", + "tcp_refused", + ); + expect(screen.getByTestId("location-card-0")).toHaveTextContent("Connection refused"); + }); + + for (const forwardHost of ["$backend", "$backend/api"]) { + it(`doesn't check a forward host that is an nginx variable and says so (${forwardHost})`, () => { + checkState.result = { host: "$backend", port: 80, ok: false, code: "invalid_host", message: "bad" }; + renderFields([loc({ path: "/a", forwardHost })]); + fireEvent.click(screen.getByText("/a")); + expect(checkState.calls.every((c) => !c.enabled)).toBe(true); + const card = screen.getByTestId("location-card-0"); + expect(card.querySelector("[data-check]")).toHaveAttribute("data-check", "variable"); + expect(card).toHaveTextContent("nginx variable"); + expect(card).not.toHaveTextContent("Invalid host name"); + expect(card.querySelector(".invalid-feedback")).toBeNull(); + }); + } + it("shows the advanced config of a location only to those who may change it", () => { renderFields([loc({ path: "/a", advancedConfig: "expires 1d;" })], { highlightIndex: 0 }); fireEvent.click(screen.getByRole("button", { name: "Advanced" })); diff --git a/frontend/src/components/Form/LocationsFields.tsx b/frontend/src/components/Form/LocationsFields.tsx index c01d7b51b..c437f5989 100644 --- a/frontend/src/components/Form/LocationsFields.tsx +++ b/frontend/src/components/Form/LocationsFields.tsx @@ -13,11 +13,13 @@ import cn from "classnames"; import { useField, useFormikContext } from "formik"; import { useEffect, useRef, useState } from "react"; import type { NginxLocationStatus, ProxyLocation } from "src/api/backend"; +import { useUpstreamCheck } from "src/hooks"; import { intl, T } from "src/locale"; -import { locationDuplicateKey, locationHostPart, normaliseLocationPath } from "src/modules/HostStatus"; -import { LocationStatusBadge, LocationStatusDetail } from "../StatusBadges"; +import { isVariableHost, locationDuplicateKey, locationHostPart, normaliseLocationPath } from "src/modules/HostStatus"; +import { LocationStatusBadge, LocationStatusDetail, UpstreamCheckBadge, VariableHostBadge } from "../StatusBadges"; import { AccessField } from "./AccessField"; import styles from "./LocationsFields.module.css"; +import { UpstreamField, usePrefillGuard } from "./UpstreamField"; // Below this many locations the list is short enough to scan by eye, and the // filter would only take up space. @@ -440,9 +442,24 @@ function LocationCard({ }: CardProps) { const item = row.value; const isEnabled = item.enabled !== false; + // Port and scheme as they were when the row was loaded or added; a picked + // candidate only replaces them while the user hasn't changed them. + const [initial] = useState(() => ({ port: item.forwardPort, scheme: item.forwardScheme })); + const guardPrefill = usePrefillGuard(); const bodyId = `location-body-${row.id}`; + // Check reachability once the card has been opened, and keep showing the + // result in the header after it's collapsed again. + const [wasOpened, setWasOpened] = useState(isOpen); + useEffect(() => { + if (isOpen) setWasOpened(true); + }, [isOpen]); const hostError = errorFor("forwardHost"); + const check = useUpstreamCheck( + { host: item.forwardHost, port: item.forwardPort, scheme: item.forwardScheme }, + isEnabled && wasOpened && !hostError && !isVariableHost(locationHostPart(item.forwardHost)), + ); + const pathError = errorFor("path"); const portError = errorFor("forwardPort"); @@ -488,6 +505,15 @@ function LocationCard({ location={status} /> ) : null} + {isEnabled && isVariableHost(locationHostPart(item.forwardHost)) ? ( + + ) : isEnabled ? ( + + ) : null} {item.advancedConfig ? ( // Deliberately the same icon as the advanced-config toggle in the @@ -592,15 +618,24 @@ function LocationCard({ - onChanges({ forwardHost: e.target.value })} + placeholder="eg: 10.0.0.1/path/" + isInvalid={!!hostError} + onChange={(forwardHost) => onChanges({ forwardHost })} onBlur={() => onTouched("forwardHost")} + onSelectCandidate={(picked) => { + const prefill = guardPrefill( + picked, + { port: item.forwardPort, scheme: item.forwardScheme }, + initial, + ); + const changes: Partial = {}; + if (prefill.port) changes.forwardPort = prefill.port; + if (prefill.scheme) changes.forwardScheme = prefill.scheme; + if (Object.keys(changes).length) onChanges(changes); + }} /> {hostError ?
{hostError}
: null} diff --git a/frontend/src/components/Form/UpstreamField.test.tsx b/frontend/src/components/Form/UpstreamField.test.tsx new file mode 100644 index 000000000..1498c8ada --- /dev/null +++ b/frontend/src/components/Form/UpstreamField.test.tsx @@ -0,0 +1,494 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { useState } from "react"; +import type { UpstreamCandidate, UpstreamCandidates } from "src/api/backend"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { allowedPrefill, candidatePrefill, groupCandidates, UpstreamField } from "./UpstreamField"; + +const hookState = vi.hoisted(() => ({ data: undefined as unknown, refresh: () => {} })); +vi.mock("src/hooks", () => ({ + useUpstreamCandidates: () => ({ + data: hookState.data, + isFetching: false, + refresh: hookState.refresh, + isRefreshing: false, + }), +})); + +const candidate = (c: Partial): UpstreamCandidate => ({ + host: "x", + label: "x", + source: "history", + ports: [], + hintPort: null, + hintScheme: null, + network: null, + state: null, + ip: null, + usedBy: 0, + ...c, +}); + +const items: UpstreamCandidate[] = [ + candidate({ host: "old-app", label: "old-app", source: "history", ports: [3000], usedBy: 2 }), + candidate({ + host: "app", + label: "app (container)", + source: "docker", + ports: [8080, 9090], + hintPort: 9090, + hintScheme: "https", + state: "running", + network: "npm_default", + }), + candidate({ host: "db-ui", label: "db-ui", source: "dns", ports: [8081] }), +]; + +const data = (dockerStatus: "ok" | "disabled" = "ok"): UpstreamCandidates => ({ + providers: { + docker: { status: dockerStatus, message: null }, + dns: { status: "ok", message: null }, + history: { status: "ok", message: null }, + }, + items, + generatedAt: "2026-11-04T10:00:00Z", +}); + +function Harness({ + candidates, + onChange, + onSelectCandidate, + initial = "", +}: { + candidates?: UpstreamCandidates; + onChange?: (v: string) => void; + onSelectCandidate?: (...args: any[]) => void; + initial?: string; +}) { + const [value, setValue] = useState(initial); + return ( + <> + { + setValue(v); + onChange?.(v); + }} + onSelectCandidate={onSelectCandidate} + /> + + {value} + + ); +} + +const openMenu = () => { + const input = document.getElementById("host") as HTMLInputElement; + fireEvent.focus(input); + fireEvent.keyDown(input, { key: "ArrowDown", code: "ArrowDown" }); + return input; +}; + +describe("UpstreamField helpers", () => { + it("groups candidates by source in a fixed order and drops empty groups", () => { + const groups = groupCandidates(items); + expect(groups.map((g) => g.label)).toEqual(["Docker containers", "Discovered on network", "Used before"]); + expect(groups[0].options.map((o) => o.value)).toEqual(["app"]); + expect(groupCandidates([items[0]]).map((g) => g.label)).toEqual(["Used before"]); + expect(groupCandidates([])).toEqual([]); + }); + + it("prefills the hinted port and scheme, else a single port", () => { + expect(candidatePrefill(items[1])).toEqual({ port: 9090, scheme: "https" }); + expect(candidatePrefill(items[0])).toEqual({ port: 3000 }); + expect(candidatePrefill(candidate({ ports: [80, 443] }))).toEqual({}); + }); +}); + +describe("UpstreamField", () => { + afterEach(() => cleanup()); + + it("shows grouped options with ports and state", () => { + render(); + openMenu(); + expect(screen.getByText("Docker containers")).toBeInTheDocument(); + expect(screen.getByText("Discovered on network")).toBeInTheDocument(); + expect(screen.getByText("Used before")).toBeInTheDocument(); + expect(screen.getByText("running")).toBeInTheDocument(); + expect(screen.getByText(/Ports: 8080, 9090/)).toBeInTheDocument(); + }); + + it("selecting a candidate sets the host and reports the prefill", () => { + const onSelect = vi.fn(); + render(); + openMenu(); + fireEvent.click(screen.getByText("app")); + expect(screen.getByTestId("value")).toHaveTextContent("app"); + expect(onSelect).toHaveBeenCalledWith( + { port: 9090, scheme: "https" }, + expect.objectContaining({ host: "app" }), + ); + }); + + it("keeps the picked host visible after selecting and after leaving the field", () => { + render(); + const input = openMenu(); + fireEvent.click(screen.getByText("app")); + expect(input.value).toBe("app"); + expect(input.style.opacity).not.toBe("0"); + fireEvent.blur(input); + expect(input.value).toBe("app"); + expect(input.style.opacity).not.toBe("0"); + }); + + it("keeps a created value visible after pressing Enter", () => { + render(); + const input = openMenu(); + fireEvent.change(input, { target: { value: "my-service" } }); + fireEvent.keyDown(input, { key: "Enter", code: "Enter" }); + expect(screen.getByTestId("value")).toHaveTextContent("my-service"); + expect(input.value).toBe("my-service"); + expect(input.style.opacity).not.toBe("0"); + fireEvent.blur(input); + expect(input.value).toBe("my-service"); + expect(input.style.opacity).not.toBe("0"); + }); + + it("keeps free text verbatim, including host/path and IPs", () => { + const onChange = vi.fn(); + const onSelect = vi.fn(); + render(); + const input = openMenu(); + fireEvent.change(input, { target: { value: "10.0.0.1/sub/path" } }); + expect(onChange).toHaveBeenLastCalledWith("10.0.0.1/sub/path"); + expect(screen.getByTestId("value")).toHaveTextContent("10.0.0.1/sub/path"); + // still there after leaving the field + fireEvent.blur(input); + expect(input.value).toBe("10.0.0.1/sub/path"); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("explains how to enable Docker discovery when it's disabled", () => { + render(); + openMenu(); + expect(screen.getByTestId("docker-disabled-hint")).toHaveTextContent("NPM_DOCKER_DISCOVERY=true"); + }); + + it("doesn't show the Docker hint when discovery works", () => { + render(); + openMenu(); + expect(screen.queryByTestId("docker-disabled-hint")).toBeNull(); + }); +}); + +// Candidates whose host starts with what a user would type for something else +const prefixData: UpstreamCandidates = { + providers: data().providers, + items: [ + candidate({ host: "10.0.0.15", label: "10.0.0.15", source: "history", ports: [3000] }), + candidate({ host: "app-db", label: "app-db", source: "docker", ports: [5432] }), + candidate({ host: "web", label: "web", source: "docker", ports: [80] }), + ], + generatedAt: "2026-11-04T10:00:00Z", +}; + +const hostInput = () => document.getElementById("host") as HTMLInputElement; +const typeInto = (text: string) => { + const input = hostInput(); + fireEvent.focus(input); + fireEvent.change(input, { target: { value: text } }); + return input; +}; +const clickControl = () => { + fireEvent.mouseDown(document.querySelector(".react-select__control") as HTMLElement, { button: 0 }); + fireEvent.focus(hostInput()); +}; +const focusedOption = () => document.querySelector(".react-select__option--is-focused"); +const optionTexts = () => + Array.from(document.querySelectorAll(".react-select__option strong")).map((e) => e.textContent); + +describe("UpstreamField keyboard", () => { + afterEach(() => cleanup()); + + for (const [typed, key] of [ + ["10.0.0.1", "Tab"], + ["10.0.0.1", "Enter"], + ["app", "Tab"], + ["app", "Enter"], + ]) { + it(`typing "${typed}" and pressing ${key} keeps the typed text`, () => { + const onSelect = vi.fn(); + render(); + const input = typeInto(typed); + expect(document.querySelector(".react-select__menu")).not.toBeNull(); + fireEvent.keyDown(input, { key, code: key }); + expect(screen.getByTestId("value")).toHaveTextContent(new RegExp(`^${typed.replace(/\./g, "\\.")}$`)); + expect(input.value).toBe(typed); + expect(onSelect).not.toHaveBeenCalled(); + }); + } + + it("no option is highlighted while typing, and Enter just closes the menu", () => { + render(); + const input = typeInto("app"); + expect(document.querySelector(".react-select__menu")).not.toBeNull(); + expect(focusedOption()).toBeNull(); + fireEvent.keyDown(input, { key: "Enter", code: "Enter" }); + expect(document.querySelector(".react-select__menu")).toBeNull(); + expect(screen.getByTestId("value")).toHaveTextContent(/^app$/); + }); + + it("clicking into a filled field and pressing Tab keeps the value", () => { + const onSelect = vi.fn(); + render(); + clickControl(); + expect(document.querySelector(".react-select__menu")).not.toBeNull(); + expect(focusedOption()).toBeNull(); + fireEvent.keyDown(hostInput(), { key: "Tab", code: "Tab" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^app$/); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("pressing Enter in a filled field keeps the value", () => { + const onSelect = vi.fn(); + render(); + clickControl(); + fireEvent.keyDown(hostInput(), { key: "Enter", code: "Enter" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^app$/); + expect(hostInput().value).toBe("app"); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("arrow keys highlight an option and Enter picks it", () => { + const onSelect = vi.fn(); + render(); + const input = typeInto("app"); + fireEvent.keyDown(input, { key: "ArrowDown", code: "ArrowDown" }); + // the first press highlights the first match instead of skipping it + expect(focusedOption()).toHaveTextContent("app-db"); + fireEvent.keyDown(input, { key: "Enter", code: "Enter" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^app-db$/); + expect(onSelect).toHaveBeenCalledWith({ port: 5432 }, expect.objectContaining({ host: "app-db" })); + }); + + it("ArrowDown on a closed menu opens it with the first option highlighted", () => { + render(); + const input = hostInput(); + fireEvent.focus(input); + fireEvent.keyDown(input, { key: "ArrowDown", code: "ArrowDown" }); + expect(focusedOption()).toHaveTextContent("app-db"); + fireEvent.keyDown(input, { key: "ArrowDown", code: "ArrowDown" }); + expect(focusedOption()).toHaveTextContent("web"); + }); + + it("typing after using the arrows drops the highlight again", () => { + const onSelect = vi.fn(); + render(); + const input = typeInto("a"); + fireEvent.keyDown(input, { key: "ArrowDown", code: "ArrowDown" }); + expect(focusedOption()).not.toBeNull(); + fireEvent.change(input, { target: { value: "ap" } }); + expect(focusedOption()).toBeNull(); + fireEvent.keyDown(input, { key: "Enter", code: "Enter" }); + fireEvent.keyDown(input, { key: "Tab", code: "Tab" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^ap$/); + expect(onSelect).not.toHaveBeenCalled(); + }); + + const homeData: UpstreamCandidates = { + ...prefixData, + items: [ + candidate({ host: "myhost-db", label: "myhost-db", source: "docker", ports: [5432] }), + candidate({ host: "myhost-web", label: "myhost-web", source: "docker", ports: [80] }), + ], + }; + + for (const key of ["Home", "End"]) { + it(`${key} with the menu open moves the caret and doesn't highlight an option`, () => { + const onSelect = vi.fn(); + render(); + const input = typeInto("myhost"); + input.setSelectionRange(3, 3); + expect(document.querySelector(".react-select__menu")).not.toBeNull(); + fireEvent.keyDown(input, { key, code: key }); + expect(focusedOption()).toBeNull(); + const at = key === "Home" ? 0 : 6; + expect([input.selectionStart, input.selectionEnd]).toEqual([at, at]); + fireEvent.keyDown(input, { key: "Enter", code: "Enter" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^myhost$/); + expect(input.value).toBe("myhost"); + expect(onSelect).not.toHaveBeenCalled(); + }); + } + + it("Shift+Home / Shift+End select from the caret", () => { + render(); + const input = typeInto("myhost"); + input.setSelectionRange(2, 2); + fireEvent.keyDown(input, { key: "Home", code: "Home", shiftKey: true }); + expect([input.selectionStart, input.selectionEnd, input.selectionDirection]).toEqual([0, 2, "backward"]); + fireEvent.keyDown(input, { key: "End", code: "End", shiftKey: true }); + expect([input.selectionStart, input.selectionEnd, input.selectionDirection]).toEqual([2, 6, "forward"]); + expect(focusedOption()).toBeNull(); + }); + + it("Home after navigating keeps the highlighted option", () => { + const onSelect = vi.fn(); + render(); + const input = typeInto("myhost"); + fireEvent.keyDown(input, { key: "ArrowDown", code: "ArrowDown" }); + fireEvent.keyDown(input, { key: "ArrowDown", code: "ArrowDown" }); + const highlighted = focusedOption()?.textContent; + fireEvent.keyDown(input, { key: "Home", code: "Home" }); + expect(focusedOption()?.textContent).toBe(highlighted); + }); + + it("a click on an option still picks it", () => { + const onSelect = vi.fn(); + render(); + typeInto("app"); + fireEvent.click(screen.getByText("app-db")); + expect(screen.getByTestId("value")).toHaveTextContent(/^app-db$/); + expect(onSelect).toHaveBeenCalledTimes(1); + }); + + it("a filled field offers all candidates until the user types", () => { + render(); + clickControl(); + expect(optionTexts()).toEqual(["app-db", "web", "10.0.0.15"]); + fireEvent.change(hostInput(), { target: { value: "app-d" } }); + expect(optionTexts()).toEqual(["app-db"]); + }); +}); + +describe("allowedPrefill", () => { + it("fills empty fields", () => { + expect(allowedPrefill({ port: 3000, scheme: "https" }, { port: "", scheme: undefined }, {})).toEqual({ + port: 3000, + scheme: "https", + }); + }); + + it("replaces fields that still hold their initial value", () => { + expect( + allowedPrefill({ port: 3000, scheme: "https" }, { port: 80, scheme: "http" }, { port: 80, scheme: "http" }), + ).toEqual({ port: 3000, scheme: "https" }); + // form values may be strings while the initial ones are numbers + expect(allowedPrefill({ port: 3000 }, { port: "80" }, { port: 80 })).toEqual({ port: 3000 }); + }); + + it("keeps a port or scheme the user changed", () => { + expect( + allowedPrefill( + { port: 3000, scheme: "https" }, + { port: 8443, scheme: "http" }, + { port: 80, scheme: "http" }, + ), + ).toEqual({ scheme: "https" }); + expect( + allowedPrefill({ port: 3000, scheme: "http" }, { port: 80, scheme: "https" }, { port: 80, scheme: "http" }), + ).toEqual({ + port: 3000, + }); + }); + + it("replaces what an earlier pick filled in", () => { + expect(allowedPrefill({ port: 4000 }, { port: 3000 }, { port: 80 }, { port: 3000 })).toEqual({ port: 4000 }); + expect(allowedPrefill({ port: 4000 }, { port: 3001 }, { port: 80 }, { port: 3000 })).toEqual({}); + }); + + it("returns nothing for an empty prefill", () => { + expect(allowedPrefill({}, { port: "" }, {})).toEqual({}); + }); +}); + +// What a browser does on Tab when the keydown isn't prevented: focus the next +// element in tab order (as it is after React has handled the keydown). +const pressTab = (from: HTMLElement) => { + const notPrevented = fireEvent.keyDown(from, { key: "Tab", code: "Tab" }); + if (!notPrevented) return; + const tabbable = Array.from( + document.querySelectorAll("input, button, select, textarea, a[href], [tabindex]"), + ).filter((el) => el.tabIndex >= 0 && !(el as HTMLButtonElement).disabled); + const next = tabbable[tabbable.indexOf(from) + 1]; + from.blur(); + fireEvent.blur(from); + if (next) { + next.focus(); + fireEvent.focus(next); + } +}; + +describe("UpstreamField selection guard", () => { + afterEach(() => { + cleanup(); + hookState.data = undefined; + }); + + it("Space in an empty field with the menu open doesn't pick the focused option", () => { + const onSelect = vi.fn(); + render(); + clickControl(); + expect(document.querySelector(".react-select__menu")).not.toBeNull(); + fireEvent.keyDown(hostInput(), { key: " ", code: "Space" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^$/); + expect(hostInput().value).toBe(""); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("Space doesn't pick an option even after navigating with the arrows", () => { + const onSelect = vi.fn(); + render(); + const input = openMenu(); + expect(focusedOption()).toHaveTextContent("app-db"); + fireEvent.keyDown(input, { key: " ", code: "Space" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^$/); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("Space with a saved value and the menu open keeps the value", () => { + const onSelect = vi.fn(); + render(); + clickControl(); + // clear the text, menu stays open, then Space + fireEvent.change(hostInput(), { target: { value: "" } }); + fireEvent.keyDown(hostInput(), { key: " ", code: "Space" }); + expect(screen.getByTestId("value")).toHaveTextContent(/^$/); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("Tab with the menu open closes it and moves on to the next field, keeping the value", () => { + hookState.data = prefixData; + render(); + clickControl(); + expect(document.querySelector(".react-select__menu")).not.toBeNull(); + // the refresh button in the menu footer is shown but isn't a Tab stop + const refresh = screen.getByLabelText("Refresh suggestions"); + expect(refresh.tabIndex).toBe(-1); + pressTab(hostInput()); + expect(document.querySelector(".react-select__menu")).toBeNull(); + expect(document.activeElement).toBe(document.getElementById("port")); + expect(screen.getByTestId("value")).toHaveTextContent(/^my-host$/); + expect(hostInput().value).toBe("my-host"); + }); + + it("Tab after typing with the menu open moves on and keeps the typed text", () => { + hookState.data = prefixData; + const onSelect = vi.fn(); + render(); + const input = typeInto("app"); + expect(document.querySelector(".react-select__menu")).not.toBeNull(); + pressTab(input); + expect(document.activeElement).toBe(document.getElementById("port")); + expect(screen.getByTestId("value")).toHaveTextContent(/^app$/); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("a click on the 'use value' option still creates it", () => { + render(); + typeInto("new-host "); + fireEvent.click(screen.getByText(/new-host/, { selector: ".react-select__option" })); + expect(screen.getByTestId("value")).toHaveTextContent(/^new-host$/); + }); +}); diff --git a/frontend/src/components/Form/UpstreamField.tsx b/frontend/src/components/Form/UpstreamField.tsx new file mode 100644 index 000000000..497e6b2f8 --- /dev/null +++ b/frontend/src/components/Form/UpstreamField.tsx @@ -0,0 +1,456 @@ +import { IconBrandDocker, IconHistory, IconNetwork, IconRefresh } from "@tabler/icons-react"; +import cn from "classnames"; +import { + createContext, + type KeyboardEvent, + type ReactNode, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { + type ActionMeta, + components, + createFilter, + type GroupBase, + type InputProps, + type MenuListProps, + type OptionProps, + type SingleValue, +} from "react-select"; +import CreatableSelect from "react-select/creatable"; +import type { UpstreamCandidate, UpstreamCandidates, UpstreamSource } from "src/api/backend"; +import { useUpstreamCandidates } from "src/hooks"; +import { intl, T } from "src/locale"; + +export interface UpstreamOption { + readonly value: string; + readonly label: string; + readonly candidate?: UpstreamCandidate; + // react-select sets this on the synthetic "create" option + readonly __isNew__?: boolean; +} + +export interface UpstreamPrefill { + port?: number; + scheme?: "http" | "https"; +} + +const SOURCE_ORDER: UpstreamSource[] = ["docker", "dns", "history"]; + +const SOURCE_ICON: Record = { + docker: , + dns: , + history: , +}; + +/** Port and scheme to fill in when a candidate is picked */ +export const candidatePrefill = (c: UpstreamCandidate): UpstreamPrefill => { + const prefill: UpstreamPrefill = {}; + if (typeof c.hintPort === "number" && c.hintPort > 0) { + prefill.port = c.hintPort; + } else if (c.ports?.length === 1) { + prefill.port = c.ports[0]; + } + if (c.hintScheme === "http" || c.hintScheme === "https") { + prefill.scheme = c.hintScheme; + } + return prefill; +}; + +/** react-select option groups, one per source, in a fixed order, empty ones left out */ +export const groupCandidates = (items: UpstreamCandidate[] = []): GroupBase[] => + SOURCE_ORDER.map((source) => ({ + label: intl.formatMessage({ id: `upstream.group.${source}` }), + options: items + .filter((c) => c.source === source) + .map((c) => ({ value: c.host, label: c.label || c.host, candidate: c })), + })).filter((g) => g.options.length > 0); + +/** + * The port and scheme of a prefill that may actually be written: only fields + * that are empty, still hold their saved (initial) value, or still hold what an + * earlier pick filled in. A port or scheme the user set themselves is kept. + */ +export const allowedPrefill = ( + prefill: UpstreamPrefill, + current: { port?: unknown; scheme?: unknown }, + initial: { port?: unknown; scheme?: unknown }, + previous: UpstreamPrefill = {}, +): UpstreamPrefill => { + const same = (a: unknown, b: unknown) => typeof b !== "undefined" && b !== null && `${a}` === `${b}`; + const isFree = (key: "port" | "scheme") => { + const c = current[key]; + return c === undefined || c === null || c === "" || same(c, initial[key]) || same(c, previous[key]); + }; + const result: UpstreamPrefill = {}; + if (prefill.port && isFree("port")) result.port = prefill.port; + if (prefill.scheme && isFree("scheme")) result.scheme = prefill.scheme; + return result; +}; + +/** `allowedPrefill` that remembers what it filled in, so a later pick may replace it */ +export function usePrefillGuard() { + const previous = useRef({}); + return useCallback( + ( + prefill: UpstreamPrefill, + current: { port?: unknown; scheme?: unknown }, + initial: { port?: unknown; scheme?: unknown }, + ) => { + const result = allowedPrefill(prefill, current, initial, previous.current); + previous.current = { ...previous.current, ...result }; + return result; + }, + [], + ); +} + +/** + * Home / End in the host input: moves the caret to the start / end, or with + * Shift extends the selection from its anchor, as the browser would. + */ +export const moveCaret = (input: HTMLInputElement | null, toStart: boolean, extend: boolean) => { + if (!input || typeof input.setSelectionRange !== "function") return; + const len = input.value.length; + const target = toStart ? 0 : len; + if (!extend) { + input.setSelectionRange(target, target); + return; + } + const start = input.selectionStart ?? 0; + const end = input.selectionEnd ?? start; + const anchor = input.selectionDirection === "backward" ? end : start; + if (target < anchor) { + input.setSelectionRange(target, anchor, "backward"); + } else { + input.setSelectionRange(anchor, target, "forward"); + } +}; + +// Whether the user moved through the options with the keyboard since the last +// keystroke. Only then is an option highlighted and does Enter pick it; +// react-select would otherwise focus the first option and Enter (or Tab) would +// replace what was typed with it. +const NavigatedContext = createContext(false); + +// Called right before an option is picked by a click, so the pick is allowed +const OptionClickContext = createContext<() => void>(() => {}); + +const Option = (props: OptionProps>) => { + const navigated = useContext(NavigatedContext); + const allowClick = useContext(OptionClickContext); + const c = props.data.candidate; + const isFocused = props.isFocused && navigated; + const { onClick } = props.innerProps; + const innerProps = { + ...props.innerProps, + onClick: onClick + ? (e: Parameters[0]) => { + allowClick(); + onClick(e); + } + : undefined, + }; + if (!c) { + return ; + } + const extra = [ + c.ports?.length ? intl.formatMessage({ id: "upstream.ports" }, { ports: c.ports.join(", ") }) : null, + c.network, + c.usedBy ? intl.formatMessage({ id: "upstream.used-by" }, { count: c.usedBy }) : null, + ].filter(Boolean); + return ( + +
+ {SOURCE_ICON[c.source]} + {c.host} + {c.state ? ( + + {c.state} + + ) : null} +
+ {c.label && c.label !== c.host ?
{c.label}
: null} + {extra.length ?
{extra.join(" · ")}
: null} +
+ ); +}; + +// The input text is the only visible value (controlShouldRenderValue is off), so it +// must never be hidden. react-select hides the input after selecting an option until +// the next keystroke or focus, which would make the field look empty. +const Input = (props: InputProps>) => ( + +); + +interface MenuFooterInfo { + dockerDisabled: boolean; + onRefresh?: () => void; + isRefreshing?: boolean; +} +const MenuFooterContext = createContext({ dockerDisabled: false }); + +// Menu with a footer: a hint how to enable Docker discovery (or that free text +// works), and a button to refresh the suggestions. +function MenuList(props: MenuListProps>) { + const { dockerDisabled, onRefresh, isRefreshing } = useContext(MenuFooterContext); + return ( + <> + {props.children} +
+ + {dockerDisabled ? ( + + + + ) : ( + + )} + + {onRefresh ? ( + + ) : null} +
+ + ); +} + +interface Props { + id: string; + value: string; + onChange: (host: string) => void; + // Called after `onChange` when a discovered candidate (not free text) was picked + onSelectCandidate?: (prefill: UpstreamPrefill, candidate: UpstreamCandidate) => void; + onBlur?: () => void; + placeholder?: string; + isInvalid?: boolean; + // For tests and storybook-like usage; normally fetched lazily on first use + candidates?: UpstreamCandidates; +} + +/** + * Forward host input with suggestions from the upstream discovery API. + * + * Behaves like a text input: whatever is typed is the value, kept verbatim + * (IPs, `host/path`, anything), while discovered containers, hosts on the + * network and previously used hosts are offered grouped in the menu. + */ +export function UpstreamField({ + id, + value, + onChange, + onSelectCandidate, + onBlur, + placeholder, + isInvalid, + candidates, +}: Props) { + const [wanted, setWanted] = useState(false); + const query = useUpstreamCandidates(wanted && !candidates); + const data = candidates ?? query.data; + const [input, setInput] = useState(value || ""); + const [menuIsOpen, setMenuIsOpen] = useState(false); + const [navigated, setNavigated] = useState(false); + // Input text when the menu was opened. Until the user types, all candidates + // are offered, not only those matching the value already in the field. + const [openedWith, setOpenedWith] = useState(null); + + useEffect(() => { + setInput((current) => (current === (value || "") ? current : value || "")); + }, [value]); + + const groups = useMemo(() => groupCandidates(data?.items), [data]); + const dockerDisabled = data?.providers?.docker?.status === "disabled"; + const { refresh, isRefreshing } = query; + + const footer = useMemo( + () => ({ dockerDisabled, onRefresh: candidates ? undefined : refresh, isRefreshing }), + [dockerDisabled, candidates, refresh, isRefreshing], + ); + + const filterOption = useMemo(() => { + const byInput = createFilter(); + return (option: Parameters[0], text: string) => text === openedWith || byInput(option, text); + }, [openedWith]); + + // Whether react-select may pick an option right now. Only a click on an + // option and Enter on an option the user navigated to may; react-select + // also picks the (invisibly) focused option on Space in an empty field, on + // Tab (unless tabSelectsValue is off) and possibly in later versions on + // other keys. Those are all blocked in the onChange / onCreateOption below. + const pickAllowed = useRef(false); + const allowClick = useCallback(() => { + pickAllowed.current = true; + }, []); + const takePick = () => { + const allowed = pickAllowed.current; + pickAllowed.current = false; + return allowed; + }; + + const handleKeyDown = (e: KeyboardEvent) => { + pickAllowed.current = e.key === "Enter" && menuIsOpen && navigated; + switch (e.key) { + case "ArrowUp": + case "ArrowDown": + case "PageUp": + case "PageDown": + // react-select already focuses an option (shown only once navigated), so + // the first press just reveals it instead of skipping past it. A press + // that opens the menu focuses the first option, which is shown too. + if (menuIsOpen && !navigated) { + e.preventDefault(); + } + setNavigated(true); + break; + case "Home": + case "End": + // Caret keys in a text field, not option navigation. With the menu open + // react-select would focus the first / last option (and block the caret), + // so a later Enter would replace the typed text. preventDefault makes it + // skip that; the caret is then moved here instead. + if (menuIsOpen) { + e.preventDefault(); + moveCaret(e.target as HTMLInputElement, e.key === "Home", e.shiftKey); + } + break; + case "Enter": + // Without an option chosen by keyboard, Enter keeps the typed text and + // just closes the menu. + if (menuIsOpen && !navigated) { + e.preventDefault(); + setMenuIsOpen(false); + } + break; + case " ": + // react-select would pick the focused option on Space in an empty + // field. A leading space is no use in a host name either. + if (menuIsOpen && !input) { + e.preventDefault(); + } + break; + case "Tab": + // Close the menu before the browser moves the focus, so the focus goes + // to the next field. The typed text stays (tabSelectsValue is off). + if (menuIsOpen) { + setMenuIsOpen(false); + } + break; + } + }; + + const setValue = (v: string) => { + setInput(v); + onChange(v); + }; + + const handleChange = (opt: SingleValue, meta: ActionMeta) => { + if (meta.action === "select-option" && !takePick()) { + return; + } + if (!opt) { + setValue(""); + return; + } + setValue(opt.value); + if (opt.candidate && !opt.__isNew__) { + onSelectCandidate?.(candidatePrefill(opt.candidate), opt.candidate); + } + }; + + const selected: UpstreamOption | null = value ? { value, label: value } : null; + + return ( + + + +
+ > + inputId={id} + className={cn("react-select-container upstream-field", { "is-invalid": isInvalid })} + classNamePrefix="react-select" + options={groups} + value={selected} + inputValue={input} + // The typed text *is* the value, so it's shown as input text rather than as a + // selected chip, and stays editable. + controlShouldRenderValue={false} + isClearable + isLoading={!candidates && query.isFetching} + placeholder={placeholder} + components={{ Option, MenuList, Input }} + menuIsOpen={menuIsOpen} + onMenuOpen={() => { + setWanted(true); + setMenuIsOpen(true); + // When typing opens the menu this is the text before the keystroke + setOpenedWith(input); + }} + onMenuClose={() => { + setMenuIsOpen(false); + setNavigated(false); + setOpenedWith(null); + }} + onFocus={() => setWanted(true)} + onBlur={onBlur} + onKeyDown={handleKeyDown} + // Tab moves on to the next field and never replaces the typed text + tabSelectsValue={false} + filterOption={filterOption} + onInputChange={(v, meta) => { + // Ignore the resets react-select does on blur / menu close / select + if (meta.action === "input-change") { + setNavigated(false); + setValue(v); + } + }} + onChange={handleChange} + onCreateOption={(v) => { + if (takePick()) setValue(v.trim()); + }} + formatCreateLabel={(v) => intl.formatMessage({ id: "upstream.use-value" }, { value: v })} + isValidNewOption={(v, _selected, options) => { + const t = v.trim(); + if (!t || t === value) return false; + return !options.some( + (o: any) => o.value === t || o.options?.some((i: any) => i.value === t), + ); + }} + noOptionsMessage={() => intl.formatMessage({ id: "upstream.no-options" })} + loadingMessage={() => intl.formatMessage({ id: "upstream.loading" })} + styles={{ + option: (base) => ({ ...base, height: "100%" }), + control: (base) => + isInvalid + ? { ...base, borderColor: "var(--tblr-form-invalid-border-color)" } + : base, + }} + /> +
+
+
+
+ ); +} diff --git a/frontend/src/components/Form/index.ts b/frontend/src/components/Form/index.ts index 8530d6f6d..f8d6f3a4e 100644 --- a/frontend/src/components/Form/index.ts +++ b/frontend/src/components/Form/index.ts @@ -4,7 +4,9 @@ export * from "./BasicAuthFields"; export * from "./DNSProviderFields"; export * from "./DomainNamesField"; export * from "./FormModal"; +export * from "./ForwardHostCheckHint"; export * from "./LocationsFields"; export * from "./NginxConfigField"; export * from "./SSLCertificateField"; export * from "./SSLOptionsFields"; +export * from "./UpstreamField"; diff --git a/frontend/src/components/StatusBadges.test.tsx b/frontend/src/components/StatusBadges.test.tsx new file mode 100644 index 000000000..6e444a25a --- /dev/null +++ b/frontend/src/components/StatusBadges.test.tsx @@ -0,0 +1,61 @@ +import { cleanup, render } from "@testing-library/react"; +import type { UpstreamCheckResult } from "src/api/backend"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { UpstreamCheckBadge, UpstreamCheckHint, VariableHostHint } from "./StatusBadges"; + +vi.mock("src/context", () => ({ useLocaleState: () => ({ locale: "en" }) })); + +describe("UpstreamCheckHint", () => { + afterEach(() => cleanup()); + + it("renders the result as a hint line, not a badge", () => { + const { container } = render( + , + ); + const hint = container.querySelector("#h"); + expect(hint).toHaveClass("form-hint"); + expect(hint).toHaveAttribute("data-check", "ok"); + expect(hint).toHaveTextContent("Reachable (3 ms)"); + expect(hint).toHaveTextContent("10.0.0.2"); + expect(container.querySelector(".badge")).toBeNull(); + }); + + it("shows <1 ms for a sub-millisecond answer, in the hint and the badge", () => { + const result: UpstreamCheckResult = { + host: "app", + port: 80, + ok: true, + code: "ok", + ms: 0.3, + message: "app:80 is reachable (<1 ms).", + addresses: [], + }; + const { container, rerender } = render(); + expect(container.querySelector("#h")).toHaveTextContent("Reachable (<1 ms) – app:80 is reachable (<1 ms)."); + rerender(); + expect(container.querySelector(".badge")).toHaveTextContent("Reachable (<1 ms)"); + rerender(); + expect(container.querySelector(".badge")).toHaveTextContent("Reachable (3 ms)"); + }); + + it("shows a checking state and nothing without a result", () => { + const { container, rerender } = render(); + expect(container.querySelector("#h")).toHaveAttribute("data-check", "checking"); + rerender(); + expect(container.querySelector("#h")).toBeNull(); + }); +}); + +describe("VariableHostHint", () => { + afterEach(() => cleanup()); + + it("uses the location tip by default and another tip when given", () => { + const { container, rerender } = render(); + expect(container.querySelector("#v")).toHaveTextContent("Set in the advanced configuration"); + rerender(); + expect(container.querySelector("#v")).toHaveTextContent("a set in the advanced configuration comes too late"); + }); +}); diff --git a/frontend/src/components/StatusBadges.tsx b/frontend/src/components/StatusBadges.tsx index add4354c6..9abe4d486 100644 --- a/frontend/src/components/StatusBadges.tsx +++ b/frontend/src/components/StatusBadges.tsx @@ -1,10 +1,11 @@ +import { IconAlertTriangle, IconCheck, IconLoader2, IconX } from "@tabler/icons-react"; import cn from "classnames"; import type { ReactNode } from "react"; import OverlayTrigger from "react-bootstrap/OverlayTrigger"; import Tooltip from "react-bootstrap/Tooltip"; -import type { LocationStatusValue, NginxLocationStatus } from "src/api/backend"; -import { T } from "src/locale"; -import { locationStatusText } from "src/modules/HostStatus"; +import type { LocationStatusValue, NginxLocationStatus, UpstreamCheckResult } from "src/api/backend"; +import { intl, T } from "src/locale"; +import { isTranslatedCheckCode, locationStatusText } from "src/modules/HostStatus"; interface TipProps { id: string; @@ -67,3 +68,114 @@ export function LocationStatusBadge({ id, status, location }: LocationStatusBadg ); } + +/** Whole milliseconds, "<1" below one, as in the check's message */ +export const formatCheckMs = (ms: number): string => (ms < 1 ? "<1" : `${Math.round(ms)}`); + +/** Short translated text for a reachability check result */ +export const checkResultText = (result: UpstreamCheckResult): string => { + if (result.code === "ok") { + return typeof result.ms === "number" + ? intl.formatMessage({ id: "upstream.check.ok-ms" }, { ms: formatCheckMs(result.ms) }) + : intl.formatMessage({ id: "upstream.check.ok" }); + } + if (isTranslatedCheckCode(result.code)) { + return intl.formatMessage({ id: `upstream.check.${result.code}` }); + } + return result.message || result.code; +}; + +interface UpstreamCheckBadgeProps { + id: string; + result: UpstreamCheckResult | null; + isChecking?: boolean; +} +/** Live reachability of a forward host:port */ +export function UpstreamCheckBadge({ id, result, isChecking }: UpstreamCheckBadgeProps) { + if (isChecking) { + return ( + + + + + ); + } + if (!result || result.code === "disabled") { + return null; + } + const warn = result.code === "resolver_mismatch"; + const cls = result.ok ? (warn ? "bg-yellow-lt" : "bg-green-lt") : "bg-red-lt"; + const icon = result.ok ? ( + warn ? ( + + ) : ( + + ) + ) : ( + + ); + const tip = [result.message, result.addresses?.length ? result.addresses.join(", ") : null] + .filter(Boolean) + .join(" – "); + return ( + + + {icon} + {checkResultText(result)} + + + ); +} + +/** + * Live reachability of a forward host:port as a hint line below the field, for + * columns too narrow to fit a badge next to the label. + */ +export function UpstreamCheckHint({ id, result, isChecking }: UpstreamCheckBadgeProps) { + if (isChecking) { + return ( +
+ + +
+ ); + } + if (!result || result.code === "disabled") { + return null; + } + const warn = result.code === "resolver_mismatch"; + const cls = result.ok ? (warn ? "text-warning" : "text-success") : "text-danger"; + const Icon = result.ok ? (warn ? IconAlertTriangle : IconCheck) : IconX; + const details = [result.message, result.addresses?.length ? result.addresses.join(", ") : null] + .filter(Boolean) + .join(" – "); + return ( +
+ + + {checkResultText(result)} + {details ? – {details} : null} + +
+ ); +} + +/** In place of a reachability check for a forward host that is an nginx variable */ +export function VariableHostBadge({ id }: { id: string }) { + return ( + + + + + + ); +} + +/** `VariableHostBadge` as a hint line below the field */ +export function VariableHostHint({ id, tipId = "upstream.check.variable-tip" }: { id: string; tipId?: string }) { + return ( +
+ – +
+ ); +} diff --git a/frontend/src/components/Table/Formatter/HostStatusFormatter.test.tsx b/frontend/src/components/Table/Formatter/HostStatusFormatter.test.tsx index 4cea46d77..51fce8362 100644 --- a/frontend/src/components/Table/Formatter/HostStatusFormatter.test.tsx +++ b/frontend/src/components/Table/Formatter/HostStatusFormatter.test.tsx @@ -1,5 +1,5 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react"; -import type { HostMeta } from "src/api/backend"; +import type { HostMeta, UpstreamHostHealth } from "src/api/backend"; import { afterEach, describe, expect, it, vi } from "vitest"; import { HostStatusFormatter } from "./HostStatusFormatter"; @@ -80,6 +80,79 @@ describe("HostStatusFormatter", () => { expect(screen.queryByText("View error log")).toBeNull(); }); + it("warns about unreachable health targets", async () => { + const health: UpstreamHostHealth = { + checkedAt: "2026-11-04T10:00:00Z", + ok: false, + targets: [ + { locationIndex: null, host: "app", port: 80, ok: true, code: "ok", message: "ok" }, + { + locationIndex: 0, + path: "/api", + host: "api", + port: 8080, + ok: false, + code: "tcp_refused", + message: "Connection refused by api:8080", + }, + ], + }; + const { container } = render(); + expect(statusEl(container)).toHaveClass("status-yellow"); + + fireEvent.click(screen.getByRole("button")); + const popover = await screen.findByTestId("host-status-popover"); + expect(popover).toHaveTextContent("/api: api:8080 is not reachable"); + expect(popover).toHaveTextContent("Connection refused"); + }); + + it("doesn't list a failed health probe of a location that is already unresolved", async () => { + const meta: HostMeta = { + nginxOnline: true, + nginxLocations: [ + { index: 0, path: "/ok", status: "ok", mode: "dynamic", message: null }, + { + index: 1, + path: "/ghost", + status: "unresolved", + mode: "dynamic", + message: 'Host "ghost" can\'t be resolved', + }, + ], + }; + const health: UpstreamHostHealth = { + checkedAt: "2026-11-04T10:00:00Z", + ok: false, + targets: [ + { + locationIndex: 1, + path: "/ghost", + host: "ghost", + port: 8080, + ok: false, + code: "dns_not_found", + message: "Host not found", + }, + { + locationIndex: 0, + path: "/ok", + host: "api", + port: 81, + ok: false, + code: "tcp_refused", + message: "Connection refused", + }, + ], + }; + render(); + fireEvent.click(screen.getByRole("button")); + const popover = await screen.findByTestId("host-status-popover"); + expect(popover).toHaveTextContent("/ghost"); + expect(popover).not.toHaveTextContent("ghost:8080 is not reachable"); + expect(popover).toHaveTextContent("/ok: api:81 is not reachable"); + expect(popover.querySelectorAll("li").length).toBe(2); + }); + it("an offline host stays red even when there are also warnings", () => { const { container } = render( = { // Keeps the popover open while the pointer moves from the badge into it const HIDE_DELAY_MS = 200; +export const describeHealthTarget = (t: UpstreamHealthTarget) => { + const where = + t.locationIndex === null || typeof t.locationIndex === "undefined" + ? intl.formatMessage({ id: "host-status.main-target" }) + : t.path || `#${t.locationIndex + 1}`; + const reason = isTranslatedCheckCode(t.code) ? intl.formatMessage({ id: `upstream.check.${t.code}` }) : t.message; + return { where, target: `${t.host}:${t.port}`, reason: reason || t.message }; +}; + interface Props { enabled: boolean; meta?: HostMeta | null; + health?: UpstreamHostHealth | null; // When given, the popover offers a link to the host's error log onLogs?: () => void; } -export function HostStatusFormatter({ enabled, meta, onLogs }: Props) { +export function HostStatusFormatter({ enabled, meta, health, onLogs }: Props) { const { locale } = useLocaleState(); const [show, setShow] = useState(false); const hideTimer = useRef(null); - const status = getHostStatus(enabled, meta); + const status = getHostStatus(enabled, meta, health); const hasDetails = status.state === "error" || status.state === "warning"; useEffect( @@ -122,6 +132,17 @@ export function HostStatusFormatter({ enabled, meta, onLogs }: Props) { ))} + {status.unhealthyTargets.map((t, i) => { + const d = describeHealthTarget(t); + return ( +
  • +
    + +
    +
    {d.reason}
    +
  • + ); + })} {meta?.nginxCheckedAt ? (
    diff --git a/frontend/src/hooks/index.ts b/frontend/src/hooks/index.ts index 761c9578c..7c5b8c81d 100644 --- a/frontend/src/hooks/index.ts +++ b/frontend/src/hooks/index.ts @@ -21,5 +21,8 @@ export * from "./useSetting"; export * from "./useStream"; export * from "./useStreams"; export * from "./useTheme"; +export * from "./useUpstreamCandidates"; +export * from "./useUpstreamCheck"; +export * from "./useUpstreamHealth"; export * from "./useUser"; export * from "./useUsers"; diff --git a/frontend/src/hooks/useUpstreamCandidates.ts b/frontend/src/hooks/useUpstreamCandidates.ts new file mode 100644 index 000000000..fbab43722 --- /dev/null +++ b/frontend/src/hooks/useUpstreamCandidates.ts @@ -0,0 +1,46 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useCallback, useState } from "react"; +import { getUpstreamCandidates, type UpstreamCandidates } from "src/api/backend"; + +const QUERY_KEY = ["upstream-candidates"]; + +const fetchUpstreamCandidates = (refresh = false) => getUpstreamCandidates(refresh); + +/** + * Upstream suggestions for the forward host pickers. + * + * Only fetches while `enabled` is true (the pickers turn it on once a modal + * with them is open and the field is used). A failure (e.g. 403 for users + * without manage permission, or an older backend without the endpoint) is not + * retried; the pickers then simply behave like plain text inputs. + */ +const useUpstreamCandidates = (enabled: boolean, options = {}) => { + const queryClient = useQueryClient(); + const [isRefreshing, setIsRefreshing] = useState(false); + const query = useQuery({ + queryKey: QUERY_KEY, + queryFn: () => fetchUpstreamCandidates(), + enabled, + staleTime: 30 * 1000, + retry: false, + refetchOnWindowFocus: false, + ...options, + }); + + // Bypasses the server side cache. Rate limited by the backend, so errors are ignored. + const refresh = useCallback(async () => { + setIsRefreshing(true); + try { + const data = await fetchUpstreamCandidates(true); + queryClient.setQueryData(QUERY_KEY, data); + } catch { + // keep the previous suggestions + } finally { + setIsRefreshing(false); + } + }, [queryClient]); + + return { ...query, refresh, isRefreshing }; +}; + +export { fetchUpstreamCandidates, useUpstreamCandidates }; diff --git a/frontend/src/hooks/useUpstreamCheck.test.tsx b/frontend/src/hooks/useUpstreamCheck.test.tsx new file mode 100644 index 000000000..55c00a03e --- /dev/null +++ b/frontend/src/hooks/useUpstreamCheck.test.tsx @@ -0,0 +1,43 @@ +import { act, cleanup, renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { checkUpstreams } = vi.hoisted(() => ({ checkUpstreams: vi.fn() })); +vi.mock("src/api/backend", async (importOriginal) => ({ + ...(await importOriginal()), + checkUpstreams, +})); + +import { resetUpstreamCheckCache, useUpstreamCheck } from "./useUpstreamCheck"; + +describe("useUpstreamCheck", () => { + beforeEach(() => { + vi.useFakeTimers(); + resetUpstreamCheckCache(); + checkUpstreams.mockReset(); + checkUpstreams.mockResolvedValue({ + results: [{ host: "app", port: 80, ok: true, code: "ok", message: "" }], + }); + }); + afterEach(() => { + cleanup(); + vi.useRealTimers(); + }); + + it("never checks a forward host that is an nginx variable", async () => { + const { result } = renderHook(() => useUpstreamCheck({ host: "$backend", port: 80 })); + await act(async () => { + await vi.advanceTimersByTimeAsync(2000); + }); + expect(checkUpstreams).not.toHaveBeenCalled(); + expect(result.current).toEqual({ result: null, isChecking: false }); + }); + + it("checks an ordinary host", async () => { + const { result } = renderHook(() => useUpstreamCheck({ host: "app", port: 80 })); + await act(async () => { + await vi.advanceTimersByTimeAsync(2000); + }); + expect(checkUpstreams).toHaveBeenCalledTimes(1); + expect(result.current.result?.code).toBe("ok"); + }); +}); diff --git a/frontend/src/hooks/useUpstreamCheck.ts b/frontend/src/hooks/useUpstreamCheck.ts new file mode 100644 index 000000000..d06858326 --- /dev/null +++ b/frontend/src/hooks/useUpstreamCheck.ts @@ -0,0 +1,106 @@ +import { useEffect, useRef, useState } from "react"; +import { checkUpstreams, isApiError, type UpstreamCheckResult } from "src/api/backend"; +import { isVariableHost } from "src/modules/HostStatus"; + +const DEBOUNCE_MS = 600; +const CACHE_TTL_MS = 30 * 1000; + +interface CacheEntry { + at: number; + result: UpstreamCheckResult; +} + +// Shared between all fields, so re-opening a location card or a modal doesn't +// re-check the same target straight away. +const cache = new Map(); + +// Set once the backend told us the check isn't available to this user (403) +// or doesn't exist (404); there's no point asking again until a reload. +let unavailable = false; + +const resetUpstreamCheckCache = () => { + cache.clear(); + unavailable = false; +}; + +export interface UpstreamCheckInput { + host?: string; + port?: number | string; + scheme?: string; +} + +const normaliseTarget = ({ host, port, scheme }: UpstreamCheckInput) => { + const h = `${host ?? ""}`.trim(); + const p = Number(port); + // An nginx variable is only known at request time + if (!h || isVariableHost(h) || !Number.isInteger(p) || p < 1 || p > 65535) { + return null; + } + return { host: h, port: p, scheme: scheme || undefined }; +}; + +/** + * Debounced live reachability check of a single host:port. + * + * At most one request per field is in flight: a newer value aborts the older + * request, and results are cached for a short while. Any failure of the check + * endpoint itself (permissions, rate limit, older backend) results in `null`, + * which callers render as "no information". + */ +const useUpstreamCheck = (input: UpstreamCheckInput, enabled = true) => { + const target = enabled ? normaliseTarget(input) : null; + const key = target ? `${target.scheme ?? ""}://${target.host}:${target.port}` : ""; + const [state, setState] = useState<{ key: string; result: UpstreamCheckResult | null; checking: boolean }>({ + key: "", + result: null, + checking: false, + }); + const targetRef = useRef(target); + targetRef.current = target; + + useEffect(() => { + if (!key || unavailable) { + setState({ key, result: null, checking: false }); + return; + } + const cached = cache.get(key); + if (cached && Date.now() - cached.at < CACHE_TTL_MS) { + setState({ key, result: cached.result, checking: false }); + return; + } + + setState({ key, result: null, checking: true }); + const controller = new AbortController(); + const timer = window.setTimeout(async () => { + const t = targetRef.current; + if (!t) return; + try { + const res = await checkUpstreams([t], controller); + const result = res?.results?.[0] ?? null; + if (result) { + cache.set(key, { at: Date.now(), result }); + } + if (!controller.signal.aborted) { + setState({ key, result, checking: false }); + } + } catch (err) { + if (controller.signal.aborted) return; + if (isApiError(err) && (err.status === 403 || err.status === 404)) { + unavailable = true; + } + setState({ key, result: null, checking: false }); + } + }, DEBOUNCE_MS); + + return () => { + window.clearTimeout(timer); + controller.abort(); + }; + }, [key]); + + // Never hand out a result that belongs to a previous value of the field + const current = state.key === key ? state : { result: null, checking: false }; + return { result: current.result, isChecking: current.checking }; +}; + +export { resetUpstreamCheckCache, useUpstreamCheck }; diff --git a/frontend/src/hooks/useUpstreamHealth.test.tsx b/frontend/src/hooks/useUpstreamHealth.test.tsx new file mode 100644 index 000000000..11ce22665 --- /dev/null +++ b/frontend/src/hooks/useUpstreamHealth.test.tsx @@ -0,0 +1,65 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, cleanup, renderHook } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { getUpstreamHealth } = vi.hoisted(() => ({ getUpstreamHealth: vi.fn() })); +vi.mock("src/api/backend", async (importOriginal) => ({ + ...(await importOriginal()), + getUpstreamHealth, +})); + +import { ApiError } from "src/api/backend/base"; +import { useUpstreamHealth } from "./useUpstreamHealth"; + +const wrapper = () => { + const client = new QueryClient(); + return ({ children }: { children: ReactNode }) => ( + {children} + ); +}; + +const advance = async (ms: number) => { + await act(async () => { + await vi.advanceTimersByTimeAsync(ms); + }); +}; + +describe("useUpstreamHealth", () => { + beforeEach(() => { + vi.useFakeTimers(); + getUpstreamHealth.mockReset(); + }); + afterEach(() => { + cleanup(); + vi.useRealTimers(); + }); + + for (const status of [403, 404]) { + it(`stops polling after a ${status}`, async () => { + getUpstreamHealth.mockRejectedValue(new ApiError("nope", { status })); + const Wrapper = wrapper(); + const { result } = renderHook(() => useUpstreamHealth(), { wrapper: Wrapper }); + await advance(10); + expect(result.current.data).toBeNull(); + expect(getUpstreamHealth).toHaveBeenCalledTimes(1); + await advance(5 * 60 * 1000); + expect(getUpstreamHealth).toHaveBeenCalledTimes(1); + // another component using the hook doesn't ask again either + renderHook(() => useUpstreamHealth(), { wrapper: Wrapper }); + await advance(10); + expect(getUpstreamHealth).toHaveBeenCalledTimes(1); + }); + } + + it("keeps polling every 30s while health is available", async () => { + getUpstreamHealth.mockResolvedValue({ hosts: {} }); + renderHook(() => useUpstreamHealth(), { wrapper: wrapper() }); + await advance(10); + expect(getUpstreamHealth).toHaveBeenCalledTimes(1); + await advance(30 * 1000); + expect(getUpstreamHealth).toHaveBeenCalledTimes(2); + await advance(30 * 1000); + expect(getUpstreamHealth).toHaveBeenCalledTimes(3); + }); +}); diff --git a/frontend/src/hooks/useUpstreamHealth.ts b/frontend/src/hooks/useUpstreamHealth.ts new file mode 100644 index 000000000..deb63011a --- /dev/null +++ b/frontend/src/hooks/useUpstreamHealth.ts @@ -0,0 +1,35 @@ +import { useQuery } from "@tanstack/react-query"; +import { getUpstreamHealth, isApiError, type UpstreamHealth } from "src/api/backend"; + +/** + * Resolves to null when health information is unavailable to this user + * (403), or the backend doesn't have the endpoint (404). Status columns then + * just don't show health problems. + */ +const fetchUpstreamHealth = async (): Promise => { + try { + return await getUpstreamHealth(); + } catch (err) { + if (isApiError(err) && (err.status === 403 || err.status === 404)) { + return null; + } + throw err; + } +}; + +const useUpstreamHealth = (options = {}) => { + return useQuery({ + queryKey: ["upstream-health"], + queryFn: fetchUpstreamHealth, + refetchOnWindowFocus: false, + // null means 403/404: asking again every 30s would only produce the same + // answer (and an error log line on the server), so stop polling and don't + // refetch on mount either until a reload. + refetchInterval: (query) => (query.state.data === null ? false : 30 * 1000), + staleTime: (query) => (query.state.data === null ? Number.POSITIVE_INFINITY : 29 * 1000), + retry: 1, + ...options, + }); +}; + +export { fetchUpstreamHealth, useUpstreamHealth }; diff --git a/frontend/src/locale/src/HelpDoc/de/ProxyHosts.md b/frontend/src/locale/src/HelpDoc/de/ProxyHosts.md index 07990d012..43c29ccd3 100644 --- a/frontend/src/locale/src/HelpDoc/de/ProxyHosts.md +++ b/frontend/src/locale/src/HelpDoc/de/ProxyHosts.md @@ -11,8 +11,10 @@ Proxy-Hosts sind die häufigste Verwendung für den Nginx Proxy Manager. Die Statusspalte zeigt, ob nginx den Host tatsächlich ausliefert: - **Online**: Die Konfiguration ist aktiv. -- **Warnung**: Der Host ist online, aber eine benutzerdefinierte Location braucht Aufmerksamkeit: nginx hat sie abgelehnt, daher wurde sie beiseitegelegt (nicht ausgeliefert), oder ihr Ziel-Host kann gerade nicht aufgelöst werden (sie bleibt aktiv und antwortet mit 502, bis der Name aufgelöst wird, danach funktioniert sie von selbst wieder). Ein Klick auf den Status zeigt Details. +- **Warnung**: Der Host ist online, aber eine benutzerdefinierte Location braucht Aufmerksamkeit: nginx hat sie abgelehnt, daher wurde sie beiseitegelegt (nicht ausgeliefert), oder ihr Ziel-Host kann gerade nicht aufgelöst werden (sie bleibt aktiv und antwortet mit 502, bis der Name aufgelöst wird, danach funktioniert sie von selbst wieder), oder ein Ziel ist nicht erreichbar. Ein Klick auf den Status zeigt Details. - **Fehler**: nginx konnte die Konfiguration dieses Hosts nicht laden, daher ist er offline. Ein Klick auf den Status zeigt den Grund. - **Deaktiviert**: Der Host wurde ausgeschaltet. Eine fehlerhafte benutzerdefinierte Location nimmt nicht mehr den ganzen Host offline: Eine Location, die nginx ablehnt, wird beiseitegelegt, der Rest des Hosts bleibt online, und der Editor zeigt den Grund (beheben und den Host speichern, um sie zurückzuholen). Eine Location, deren Ziel-Host nicht aufgelöst wird, wird nicht beiseitegelegt: Sie antwortet mit 502, bis der Host aufgelöst wird; nichts muss wieder aktiviert werden. Jede Location kann außerdem einzeln ausgeschaltet werden. + +Die Felder für den Ziel-Host schlagen bereits verwendete Hosts und im Docker-Netzwerk gefundene Hosts vor. Um auch Docker-Container aufzulisten, `NPM_DOCKER_DISCOVERY=true` setzen und NPM Zugriff auf die Docker-API geben (empfohlen über einen Socket-Proxy, siehe Dokumentation). diff --git a/frontend/src/locale/src/HelpDoc/en/ProxyHosts.md b/frontend/src/locale/src/HelpDoc/en/ProxyHosts.md index c4c6bf191..731aecf22 100644 --- a/frontend/src/locale/src/HelpDoc/en/ProxyHosts.md +++ b/frontend/src/locale/src/HelpDoc/en/ProxyHosts.md @@ -11,8 +11,10 @@ Proxy Hosts are the most common use for the Nginx Proxy Manager. The status column shows whether nginx actually serves the host: - **Online**: the configuration is active. -- **Warning**: the host is online, but a custom location needs attention: nginx rejected it, so it was set aside (not served), or its forward host cannot be resolved right now (it stays enabled and answers 502 until the name resolves, then works again on its own). Click the status for details. +- **Warning**: the host is online, but a custom location needs attention: nginx rejected it, so it was set aside (not served), or its forward host cannot be resolved right now (it stays enabled and answers 502 until the name resolves, then works again on its own), or a destination is not reachable. Click the status for details. - **Error**: nginx could not load the configuration of this host, so it is offline. Click the status for the reason. - **Disabled**: the host was switched off. A broken custom location no longer takes the whole host offline: a location nginx rejects is set aside, the rest of the host stays online, and the editor shows why (fix it and save the host to bring it back). A location whose forward host doesn't resolve is not set aside: it answers 502 until the host resolves, nothing has to be enabled again. Each location can also be switched off on its own. + +The forward host fields suggest hosts that were used before and hosts found on the Docker network. To also list Docker containers, set `NPM_DOCKER_DISCOVERY=true` and give NPM access to the Docker API (a socket proxy is recommended, see the documentation). diff --git a/frontend/src/locale/src/de.json b/frontend/src/locale/src/de.json index 27a55130b..de0c235a3 100644 --- a/frontend/src/locale/src/de.json +++ b/frontend/src/locale/src/de.json @@ -455,9 +455,15 @@ "host-status.error": { "defaultMessage": "Fehler" }, + "host-status.main-target": { + "defaultMessage": "Hauptziel" + }, "host-status.previous-config-running": { "defaultMessage": "Nginx hat die neueste Konfiguration dieses Hosts nicht übernommen und verwendet weiterhin die vorherige." }, + "host-status.unreachable": { + "defaultMessage": "{where}: {target} ist nicht erreichbar" + }, "host-status.view-error-log": { "defaultMessage": "Fehlerprotokoll anzeigen" }, @@ -1055,6 +1061,81 @@ "update-available": { "defaultMessage": "Update verfügbar: {latestVersion}" }, + "upstream.check.checking": { + "defaultMessage": "Prüfe…" + }, + "upstream.check.disabled": { + "defaultMessage": "Prüfung deaktiviert" + }, + "upstream.check.dns_not_found": { + "defaultMessage": "Host nicht gefunden" + }, + "upstream.check.dns_timeout": { + "defaultMessage": "DNS-Abfrage abgelaufen" + }, + "upstream.check.invalid_host": { + "defaultMessage": "Ungültiger Hostname" + }, + "upstream.check.ok": { + "defaultMessage": "Erreichbar" + }, + "upstream.check.ok-ms": { + "defaultMessage": "Erreichbar ({ms} ms)" + }, + "upstream.check.resolver_mismatch": { + "defaultMessage": "Nur über /etc/hosts oder Suchdomänen auflösbar" + }, + "upstream.check.tcp_refused": { + "defaultMessage": "Verbindung abgelehnt" + }, + "upstream.check.tcp_timeout": { + "defaultMessage": "Zeitüberschreitung der Verbindung" + }, + "upstream.check.tcp_unreachable": { + "defaultMessage": "Host nicht erreichbar" + }, + "upstream.check.variable": { + "defaultMessage": "nginx-Variable" + }, + "upstream.check.variable-tip": { + "defaultMessage": "Wird in der erweiterten Konfiguration gesetzt und von nginx bei jeder Anfrage aufgelöst, daher wird sie hier nicht geprüft." + }, + "upstream.check.variable-tip-main": { + "defaultMessage": "Wird von nginx bei jeder Anfrage aufgelöst, daher wird sie hier nicht geprüft. Sie braucht einen Wert, bevor die erweiterte Konfiguration dieses Hosts ausgeführt wird, zum Beispiel aus einer map in /data/nginx/custom/http.conf; ein set in der erweiterten Konfiguration kommt zu spät." + }, + "upstream.docker-disabled": { + "defaultMessage": "Docker-Erkennung ist aus: NPM_DOCKER_DISCOVERY=true setzen (siehe Doku)." + }, + "upstream.free-text": { + "defaultMessage": "Es kann auch ein beliebiger Hostname oder eine IP-Adresse eingegeben werden." + }, + "upstream.group.dns": { + "defaultMessage": "Im Netzwerk gefunden" + }, + "upstream.group.docker": { + "defaultMessage": "Docker-Container" + }, + "upstream.group.history": { + "defaultMessage": "Bereits verwendet" + }, + "upstream.loading": { + "defaultMessage": "Suche nach Zielen…" + }, + "upstream.no-options": { + "defaultMessage": "Keine Vorschläge, Hostname oder IP-Adresse eingeben" + }, + "upstream.ports": { + "defaultMessage": "Ports: {ports}" + }, + "upstream.refresh": { + "defaultMessage": "Vorschläge aktualisieren" + }, + "upstream.use-value": { + "defaultMessage": "„{value}“ verwenden" + }, + "upstream.used-by": { + "defaultMessage": "von {count, plural, one {# Host} other {# Hosts}} verwendet" + }, "user": { "defaultMessage": "User" }, diff --git a/frontend/src/locale/src/en.json b/frontend/src/locale/src/en.json index 5c7a275de..b2deb7669 100644 --- a/frontend/src/locale/src/en.json +++ b/frontend/src/locale/src/en.json @@ -455,9 +455,15 @@ "host-status.error": { "defaultMessage": "Error" }, + "host-status.main-target": { + "defaultMessage": "Main destination" + }, "host-status.previous-config-running": { "defaultMessage": "Nginx did not apply this host's latest configuration and still runs its previous one." }, + "host-status.unreachable": { + "defaultMessage": "{where}: {target} is not reachable" + }, "host-status.view-error-log": { "defaultMessage": "View error log" }, @@ -1055,6 +1061,81 @@ "update-available": { "defaultMessage": "Update Available: {latestVersion}" }, + "upstream.check.checking": { + "defaultMessage": "Checking…" + }, + "upstream.check.disabled": { + "defaultMessage": "Check disabled" + }, + "upstream.check.dns_not_found": { + "defaultMessage": "Host not found" + }, + "upstream.check.dns_timeout": { + "defaultMessage": "DNS lookup timed out" + }, + "upstream.check.invalid_host": { + "defaultMessage": "Invalid host name" + }, + "upstream.check.ok": { + "defaultMessage": "Reachable" + }, + "upstream.check.ok-ms": { + "defaultMessage": "Reachable ({ms} ms)" + }, + "upstream.check.resolver_mismatch": { + "defaultMessage": "Resolves only via /etc/hosts or search domains" + }, + "upstream.check.tcp_refused": { + "defaultMessage": "Connection refused" + }, + "upstream.check.tcp_timeout": { + "defaultMessage": "Connection timed out" + }, + "upstream.check.tcp_unreachable": { + "defaultMessage": "Host unreachable" + }, + "upstream.check.variable": { + "defaultMessage": "nginx variable" + }, + "upstream.check.variable-tip": { + "defaultMessage": "Set in the advanced configuration and resolved by nginx for each request, so it isn't checked here." + }, + "upstream.check.variable-tip-main": { + "defaultMessage": "Resolved by nginx for each request, so it isn't checked here. It needs a value before this host's advanced configuration runs, for example from a map in /data/nginx/custom/http.conf; a set in the advanced configuration comes too late." + }, + "upstream.docker-disabled": { + "defaultMessage": "Docker discovery is off: set NPM_DOCKER_DISCOVERY=true (see docs)." + }, + "upstream.free-text": { + "defaultMessage": "You can also type any host name or IP address." + }, + "upstream.group.dns": { + "defaultMessage": "Discovered on network" + }, + "upstream.group.docker": { + "defaultMessage": "Docker containers" + }, + "upstream.group.history": { + "defaultMessage": "Used before" + }, + "upstream.loading": { + "defaultMessage": "Looking for upstreams…" + }, + "upstream.no-options": { + "defaultMessage": "No suggestions, type a host name or IP address" + }, + "upstream.ports": { + "defaultMessage": "Ports: {ports}" + }, + "upstream.refresh": { + "defaultMessage": "Refresh suggestions" + }, + "upstream.use-value": { + "defaultMessage": "Use \"{value}\"" + }, + "upstream.used-by": { + "defaultMessage": "used by {count, plural, one {# host} other {# hosts}}" + }, "user": { "defaultMessage": "User" }, diff --git a/frontend/src/locale/src/et.json b/frontend/src/locale/src/et.json index 3af186926..7ff41478c 100644 --- a/frontend/src/locale/src/et.json +++ b/frontend/src/locale/src/et.json @@ -455,9 +455,15 @@ "host-status.error": { "defaultMessage": "Viga" }, + "host-status.main-target": { + "defaultMessage": "Peamine sihtkoht" + }, "host-status.previous-config-running": { "defaultMessage": "Nginx ei rakendanud selle hosti uusimat seadistust ja kasutab endiselt eelmist." }, + "host-status.unreachable": { + "defaultMessage": "{where}: {target} pole kättesaadav" + }, "host-status.view-error-log": { "defaultMessage": "Näita vealogi" }, @@ -1055,6 +1061,81 @@ "update-available": { "defaultMessage": "Uuendus saadaval: {latestVersion}" }, + "upstream.check.checking": { + "defaultMessage": "Kontrollin…" + }, + "upstream.check.disabled": { + "defaultMessage": "Kontroll on välja lülitatud" + }, + "upstream.check.dns_not_found": { + "defaultMessage": "Hosti ei leitud" + }, + "upstream.check.dns_timeout": { + "defaultMessage": "DNS-päring aegus" + }, + "upstream.check.invalid_host": { + "defaultMessage": "Vigane hostinimi" + }, + "upstream.check.ok": { + "defaultMessage": "Kättesaadav" + }, + "upstream.check.ok-ms": { + "defaultMessage": "Kättesaadav ({ms} ms)" + }, + "upstream.check.resolver_mismatch": { + "defaultMessage": "Lahendub ainult /etc/hosts või otsingudomeenide kaudu" + }, + "upstream.check.tcp_refused": { + "defaultMessage": "Ühendusest keelduti" + }, + "upstream.check.tcp_timeout": { + "defaultMessage": "Ühendus aegus" + }, + "upstream.check.tcp_unreachable": { + "defaultMessage": "Host pole kättesaadav" + }, + "upstream.check.variable": { + "defaultMessage": "nginxi muutuja" + }, + "upstream.check.variable-tip": { + "defaultMessage": "Määratakse täpsemas seadistuses ja nginx lahendab selle iga päringu ajal, seega siin seda ei kontrollita." + }, + "upstream.check.variable-tip-main": { + "defaultMessage": "nginx lahendab selle iga päringu ajal, seega siin seda ei kontrollita. Sellel peab olema väärtus enne selle hosti täpsema seadistuse käivitumist, näiteks map-ist failis /data/nginx/custom/http.conf; set täpsemas seadistuses on liiga hilja." + }, + "upstream.docker-disabled": { + "defaultMessage": "Dockeri tuvastus on väljas: määra NPM_DOCKER_DISCOVERY=true (vt dokumentatsiooni)." + }, + "upstream.free-text": { + "defaultMessage": "Võid sisestada ka mis tahes hostinime või IP-aadressi." + }, + "upstream.group.dns": { + "defaultMessage": "Võrgust leitud" + }, + "upstream.group.docker": { + "defaultMessage": "Dockeri konteinerid" + }, + "upstream.group.history": { + "defaultMessage": "Varem kasutatud" + }, + "upstream.loading": { + "defaultMessage": "Otsin sihtkohti…" + }, + "upstream.no-options": { + "defaultMessage": "Soovitusi pole, sisesta hostinimi või IP-aadress" + }, + "upstream.ports": { + "defaultMessage": "Pordid: {ports}" + }, + "upstream.refresh": { + "defaultMessage": "Värskenda soovitusi" + }, + "upstream.use-value": { + "defaultMessage": "Kasuta „{value}“" + }, + "upstream.used-by": { + "defaultMessage": "kasutab {count, plural, one {# host} other {# hosti}}" + }, "user": { "defaultMessage": "Kasutaja" }, diff --git a/frontend/src/locale/src/vi.json b/frontend/src/locale/src/vi.json index 3a3f8548a..a69ca8df8 100644 --- a/frontend/src/locale/src/vi.json +++ b/frontend/src/locale/src/vi.json @@ -455,9 +455,15 @@ "host-status.error": { "defaultMessage": "Lỗi" }, + "host-status.main-target": { + "defaultMessage": "Đích chính" + }, "host-status.previous-config-running": { "defaultMessage": "Nginx chưa áp dụng cấu hình mới nhất của host này và vẫn đang chạy cấu hình trước đó." }, + "host-status.unreachable": { + "defaultMessage": "{where}: không thể kết nối tới {target}" + }, "host-status.view-error-log": { "defaultMessage": "Xem nhật ký lỗi" }, @@ -1055,6 +1061,81 @@ "update-available": { "defaultMessage": "Đã có bản cập nhật: {latestVersion}" }, + "upstream.check.checking": { + "defaultMessage": "Đang kiểm tra…" + }, + "upstream.check.disabled": { + "defaultMessage": "Đã tắt kiểm tra" + }, + "upstream.check.dns_not_found": { + "defaultMessage": "Không tìm thấy host" + }, + "upstream.check.dns_timeout": { + "defaultMessage": "Tra cứu DNS quá thời gian" + }, + "upstream.check.invalid_host": { + "defaultMessage": "Tên host không hợp lệ" + }, + "upstream.check.ok": { + "defaultMessage": "Có thể kết nối" + }, + "upstream.check.ok-ms": { + "defaultMessage": "Có thể kết nối ({ms} ms)" + }, + "upstream.check.resolver_mismatch": { + "defaultMessage": "Chỉ phân giải được qua /etc/hosts hoặc tên miền tìm kiếm" + }, + "upstream.check.tcp_refused": { + "defaultMessage": "Kết nối bị từ chối" + }, + "upstream.check.tcp_timeout": { + "defaultMessage": "Kết nối quá thời gian" + }, + "upstream.check.tcp_unreachable": { + "defaultMessage": "Không thể truy cập host" + }, + "upstream.check.variable": { + "defaultMessage": "Biến nginx" + }, + "upstream.check.variable-tip": { + "defaultMessage": "Được đặt trong cấu hình nâng cao và được nginx phân giải cho mỗi yêu cầu, nên không được kiểm tra ở đây." + }, + "upstream.check.variable-tip-main": { + "defaultMessage": "Được nginx phân giải cho mỗi yêu cầu, nên không được kiểm tra ở đây. Biến này cần có giá trị trước khi cấu hình nâng cao của host này chạy, ví dụ từ một map trong /data/nginx/custom/http.conf; lệnh set trong cấu hình nâng cao là quá muộn." + }, + "upstream.docker-disabled": { + "defaultMessage": "Tính năng phát hiện Docker đang tắt: hãy đặt NPM_DOCKER_DISCOVERY=true (xem tài liệu)." + }, + "upstream.free-text": { + "defaultMessage": "Bạn cũng có thể nhập bất kỳ tên host hoặc địa chỉ IP nào." + }, + "upstream.group.dns": { + "defaultMessage": "Phát hiện trên mạng" + }, + "upstream.group.docker": { + "defaultMessage": "Container Docker" + }, + "upstream.group.history": { + "defaultMessage": "Đã dùng trước đây" + }, + "upstream.loading": { + "defaultMessage": "Đang tìm upstream…" + }, + "upstream.no-options": { + "defaultMessage": "Không có gợi ý, hãy nhập tên host hoặc địa chỉ IP" + }, + "upstream.ports": { + "defaultMessage": "Cổng: {ports}" + }, + "upstream.refresh": { + "defaultMessage": "Làm mới gợi ý" + }, + "upstream.use-value": { + "defaultMessage": "Dùng \"{value}\"" + }, + "upstream.used-by": { + "defaultMessage": "được dùng bởi {count, plural, other {# host}}" + }, "user": { "defaultMessage": "Người dùng" }, diff --git a/frontend/src/modals/ProxyHostModal.tsx b/frontend/src/modals/ProxyHostModal.tsx index e01e59c07..0bf175db4 100644 --- a/frontend/src/modals/ProxyHostModal.tsx +++ b/frontend/src/modals/ProxyHostModal.tsx @@ -11,6 +11,7 @@ import { Button, cleanLocations, DomainNamesField, + ForwardHostCheckHint, HasPermission, Loading, LocationsFields, @@ -19,6 +20,8 @@ import { SaveWarning, SSLCertificateField, SSLOptionsFields, + UpstreamField, + usePrefillGuard, } from "src/components"; import { FormModal } from "src/components/Form"; import { useProxyHost, useSetProxyHost, useUser } from "src/hooks"; @@ -81,6 +84,7 @@ const ProxyHostModal = EasyModal.create(({ id, visible, remove }: Props) => { // Id of a host created by this modal, so that saving again updates it const [savedId, setSavedId] = useState(null); const [highlightIndex, setHighlightIndex] = useState(null); + const guardPrefill = usePrefillGuard(); const isAdmin = currentUser?.roles?.includes("admin"); // Only admins may change the advanced config, the others don't get its tab @@ -338,13 +342,49 @@ const ProxyHostModal = EasyModal.create(({ id, visible, remove }: Props) => { > - + form.setFieldValue("forwardHost", v) + } + onBlur={() => + form.setFieldTouched("forwardHost", true) + } + onSelectCandidate={(picked) => { + const prefill = guardPrefill( + picked, + { + port: form.values.forwardPort, + scheme: form.values.forwardScheme, + }, + { + port: form.initialValues + .forwardPort, + scheme: form.initialValues + .forwardScheme, + }, + ); + if (prefill.port) { + form.setFieldValue( + "forwardPort", + prefill.port, + ); + } + if (prefill.scheme) { + form.setFieldValue( + "forwardScheme", + prefill.scheme, + ); + } + }} /> {form.errors.forwardHost ? (
    @@ -354,6 +394,7 @@ const ProxyHostModal = EasyModal.create(({ id, visible, remove }: Props) => { : null}
    ) : null} +
    )} diff --git a/frontend/src/modals/StreamModal.tsx b/frontend/src/modals/StreamModal.tsx index 57c6d507d..dbc7c3e62 100644 --- a/frontend/src/modals/StreamModal.tsx +++ b/frontend/src/modals/StreamModal.tsx @@ -11,6 +11,8 @@ import { SaveWarning, SSLCertificateField, SSLOptionsFields, + UpstreamField, + usePrefillGuard, } from "src/components"; import { FormModal } from "src/components/Form"; import { useSetStream, useStream } from "src/hooks"; @@ -31,6 +33,7 @@ const StreamModal = EasyModal.create(({ id, visible, remove }: Props) => { const { mutate: setStream } = useSetStream(); const [errorMsg, setErrorMsg] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); + const guardPrefill = usePrefillGuard(); // Set when a save went through but nginx couldn't load the host const [savedMeta, setSavedMeta] = useState(null); // Id of a host created by this modal, so that saving again updates it @@ -195,15 +198,40 @@ const StreamModal = EasyModal.create(({ id, visible, remove }: Props) => { > - + form.setFieldValue("forwardingHost", v) + } + onBlur={() => + form.setFieldTouched("forwardingHost", true) + } + onSelectCandidate={(picked) => { + const prefill = guardPrefill( + picked, + { port: form.values.forwardingPort }, + { + port: form.initialValues + .forwardingPort, + }, + ); + if (prefill.port) { + form.setFieldValue( + "forwardingPort", + prefill.port, + ); + } + }} /> {form.errors.forwardingHost ? (
    diff --git a/frontend/src/modules/HostStatus.test.ts b/frontend/src/modules/HostStatus.test.ts index 987467a3b..e3c73bd6b 100644 --- a/frontend/src/modules/HostStatus.test.ts +++ b/frontend/src/modules/HostStatus.test.ts @@ -1,6 +1,6 @@ -import type { HostMeta } from "src/api/backend"; +import type { HostMeta, UpstreamHealthTarget, UpstreamHostHealth } from "src/api/backend"; import { describe, expect, it } from "vitest"; -import { hostStatusRank, isVariableHost, locationHostPart, sortByHostStatus } from "./HostStatus"; +import { getHostStatus, hostStatusRank, isVariableHost, locationHostPart, sortByHostStatus } from "./HostStatus"; const row = (name: string, enabled: boolean, meta: HostMeta | null) => ({ name, original: { enabled, meta } }); @@ -39,6 +39,57 @@ describe("sorting the status column", () => { }); }); +const target = (t: Partial): UpstreamHealthTarget => ({ + locationIndex: null, + host: "app", + port: 80, + ok: false, + code: "tcp_refused", + message: "refused", + ...t, +}); +const health = (targets: UpstreamHealthTarget[]): UpstreamHostHealth => ({ + checkedAt: "2026-11-04T10:00:00Z", + ok: false, + targets, +}); + +describe("getHostStatus", () => { + const meta: HostMeta = { + nginxOnline: true, + nginxLocations: [ + { index: 0, path: "/ghost", status: "unresolved", mode: "dynamic", message: null }, + { index: 1, path: "/bad", status: "quarantined", mode: null, message: null }, + { index: 2, path: "/fine", status: "ok", mode: "dynamic", message: null }, + ], + }; + + it("drops failed health targets of locations that are already reported", () => { + const status = getHostStatus( + true, + meta, + health([ + target({ locationIndex: 0, path: "/ghost", code: "dns_not_found" }), + target({ locationIndex: 1, path: "/bad" }), + target({ locationIndex: 2, path: "/fine" }), + target({ locationIndex: null }), + ]), + ); + expect(status.state).toBe("warning"); + expect(status.problemLocations.map((l) => l.path)).toEqual(["/ghost", "/bad"]); + expect(status.unhealthyTargets.map((t) => t.locationIndex)).toEqual([2, null]); + }); + + it("keeps a target whose path no longer matches the reported location", () => { + const status = getHostStatus(true, meta, health([target({ locationIndex: 0, path: "/other" })])); + expect(status.unhealthyTargets).toHaveLength(1); + }); + + it("is online without problems or failed targets", () => { + expect(getHostStatus(true, { nginxOnline: true }, health([target({ ok: true })])).state).toBe("online"); + }); +}); + describe("isVariableHost", () => { it("finds forward hosts with nginx variables like the backend", () => { for (const host of ["$backend", " $backend ", "app-$stage", "$svc.internal", "a$x$y"]) { diff --git a/frontend/src/modules/HostStatus.ts b/frontend/src/modules/HostStatus.ts index 60b76c4d1..8f2a5d747 100644 --- a/frontend/src/modules/HostStatus.ts +++ b/frontend/src/modules/HostStatus.ts @@ -3,6 +3,8 @@ import { isApiError, type NginxConfigErrorDetails, type NginxLocationStatus, + type UpstreamHealthTarget, + type UpstreamHostHealth, } from "src/api/backend"; import { intl } from "src/locale"; @@ -224,23 +226,47 @@ export const locationStatusText = ( return { text: hasMessage(fallback) ? intl.formatMessage({ id: fallback }) : "", detail: null }; }; +export const getUnhealthyTargets = (health?: UpstreamHostHealth | null): UpstreamHealthTarget[] => + (health?.targets || []).filter((t) => !t.ok); + export type HostState = "disabled" | "online" | "warning" | "error"; export interface HostStatusInfo { state: HostState; nginxErr: string | null; problemLocations: NginxLocationStatus[]; + unhealthyTargets: UpstreamHealthTarget[]; } -export const getHostStatus = (enabled: boolean, meta?: HostMeta | null): HostStatusInfo => { +export const getHostStatus = ( + enabled: boolean, + meta?: HostMeta | null, + health?: UpstreamHostHealth | null, +): HostStatusInfo => { if (!enabled) { - return { state: "disabled", nginxErr: null, problemLocations: [] }; + return { state: "disabled", nginxErr: null, problemLocations: [], unhealthyTargets: [] }; } const problemLocations = getProblemLocations(meta); + // A location nginx couldn't resolve or had to quarantine is already listed; + // its failed health probe would only report the same problem a second time. + const unhealthyTargets = getUnhealthyTargets(health).filter( + (t) => + typeof t.locationIndex !== "number" || + !problemLocations.some( + (l) => + l.index === t.locationIndex && + (!t.path || !l.path || normaliseLocationPath(t.path) === normaliseLocationPath(l.path)), + ), + ); if (meta?.nginxOnline === false) { - return { state: "error", nginxErr: meta.nginxErr || null, problemLocations }; + return { state: "error", nginxErr: meta.nginxErr || null, problemLocations, unhealthyTargets }; } - return { state: problemLocations.length ? "warning" : "online", nginxErr: null, problemLocations }; + return { + state: problemLocations.length || unhealthyTargets.length ? "warning" : "online", + nginxErr: null, + problemLocations, + unhealthyTargets, + }; }; // The order of the status column, ascending: the hosts that need attention first @@ -307,3 +333,5 @@ export const isVariableHost = (host?: string | null) => { * host part, so `$backend/api` is a variable host with a path. */ export const locationHostPart = (host?: string | null) => `${host ?? ""}`.trim().split("/")[0]; + +export const isTranslatedCheckCode = (code?: string) => !!code && hasMessage(`upstream.check.${code}`); diff --git a/frontend/src/pages/Nginx/ProxyHosts/Table.tsx b/frontend/src/pages/Nginx/ProxyHosts/Table.tsx index 6b95f37e8..6fabba14a 100644 --- a/frontend/src/pages/Nginx/ProxyHosts/Table.tsx +++ b/frontend/src/pages/Nginx/ProxyHosts/Table.tsx @@ -1,7 +1,7 @@ import { IconDotsVertical, IconEdit, IconFileText, IconPower, IconTrash } from "@tabler/icons-react"; import { createColumnHelper, type SortingState, useTable } from "@tanstack/react-table"; import { useMemo, useState } from "react"; -import type { ProxyHost } from "src/api/backend"; +import type { ProxyHost, UpstreamHostHealth } from "src/api/backend"; import { AccessListFormatter, CertificateFormatter, @@ -48,6 +48,8 @@ interface Props { // Opens the error log from the status popover; omitted when not permitted onErrorLogs?: (id: number) => void; onNew?: () => void; + // Upstream health by host id + health?: Record; } export default function Table({ data, @@ -59,6 +61,7 @@ export default function Table({ onErrorLogs, onNew, isFiltered, + health, }: Props) { const columnHelper = createColumnHelper(); const columns = useMemo( @@ -131,6 +134,7 @@ export default function Table({ onErrorLogs(row.id) : undefined} /> ); @@ -213,7 +217,7 @@ export default function Table({ }, }), ], - [columnHelper, onEdit, onDisableToggle, onDelete, onLogs, onErrorLogs], + [columnHelper, onEdit, onDisableToggle, onDelete, onLogs, onErrorLogs, health], ); const [sorting, setSorting] = useState([]); diff --git a/frontend/src/pages/Nginx/ProxyHosts/TableWrapper.tsx b/frontend/src/pages/Nginx/ProxyHosts/TableWrapper.tsx index 97d3cc794..8c0f63eba 100644 --- a/frontend/src/pages/Nginx/ProxyHosts/TableWrapper.tsx +++ b/frontend/src/pages/Nginx/ProxyHosts/TableWrapper.tsx @@ -4,7 +4,7 @@ import { useState } from "react"; import Alert from "react-bootstrap/Alert"; import { deleteProxyHost, toggleProxyHost } from "src/api/backend"; import { Button, HasPermission, LoadingPage } from "src/components"; -import { useProxyHosts, useUser } from "src/hooks"; +import { useProxyHosts, useUpstreamHealth, useUser } from "src/hooks"; import { T } from "src/locale"; import { showDeleteConfirmModal, showHelpModal, showHostLogsModal, showProxyHostModal } from "src/modals"; import { formatApiError } from "src/modules/HostStatus"; @@ -16,6 +16,7 @@ export default function TableWrapper() { const queryClient = useQueryClient(); const [search, setSearch] = useState(""); const { isFetching, isLoading, isError, error, data } = useProxyHosts(["owner", "access_list", "certificate"]); + const { data: health } = useUpstreamHealth(); const { data: currentUser } = useUser("me"); const canManage = hasPermission(PROXY_HOSTS, MANAGE, currentUser?.permissions, currentUser?.roles); @@ -115,6 +116,7 @@ export default function TableWrapper() { onEdit={(id: number) => showProxyHostModal(id)} onLogs={(id: number) => showHostLogsModal(id)} onErrorLogs={canManage ? (id: number) => showHostLogsModal(id, "error") : undefined} + health={health?.hosts?.proxyHost} onDelete={(id: number) => { const host = data?.find((h) => h.id === id); showDeleteConfirmModal({ diff --git a/frontend/src/pages/Nginx/Streams/Table.tsx b/frontend/src/pages/Nginx/Streams/Table.tsx index 8a9d4d730..1ec0851b4 100644 --- a/frontend/src/pages/Nginx/Streams/Table.tsx +++ b/frontend/src/pages/Nginx/Streams/Table.tsx @@ -1,7 +1,7 @@ import { IconDotsVertical, IconEdit, IconPower, IconTrash } from "@tabler/icons-react"; import { createColumnHelper, type SortingState, useTable } from "@tanstack/react-table"; import { useMemo, useState } from "react"; -import type { Stream } from "src/api/backend"; +import type { Stream, UpstreamHostHealth } from "src/api/backend"; import { CertificateFormatter, EmptyData, @@ -24,8 +24,19 @@ interface Props { onDelete?: (id: number) => void; onDisableToggle?: (id: number, enabled: boolean) => void; onNew?: () => void; + // Upstream health by stream id + health?: Record; } -export default function Table({ data, isFetching, isFiltered, onEdit, onDelete, onDisableToggle, onNew }: Props) { +export default function Table({ + data, + isFetching, + isFiltered, + onEdit, + onDelete, + onDisableToggle, + onNew, + health, +}: Props) { const columnHelper = createColumnHelper(); const columns = useMemo( () => [ @@ -98,7 +109,9 @@ export default function Table({ data, isFetching, isFiltered, onEdit, onDelete, sortFn: sortByHostStatus, cell: (info: any) => { const row: Stream = info.row.original; - return ; + return ( + + ); }, }), columnHelper.display({ @@ -167,7 +180,7 @@ export default function Table({ data, isFetching, isFiltered, onEdit, onDelete, }, }), ], - [columnHelper, onEdit, onDisableToggle, onDelete], + [columnHelper, onEdit, onDisableToggle, onDelete, health], ); const [sorting, setSorting] = useState([]); diff --git a/frontend/src/pages/Nginx/Streams/TableWrapper.tsx b/frontend/src/pages/Nginx/Streams/TableWrapper.tsx index 35710718d..ea0208b51 100644 --- a/frontend/src/pages/Nginx/Streams/TableWrapper.tsx +++ b/frontend/src/pages/Nginx/Streams/TableWrapper.tsx @@ -4,7 +4,7 @@ import { useState } from "react"; import Alert from "react-bootstrap/Alert"; import { deleteStream, toggleStream } from "src/api/backend"; import { Button, HasPermission, LoadingPage } from "src/components"; -import { useStreams } from "src/hooks"; +import { useStreams, useUpstreamHealth } from "src/hooks"; import { T } from "src/locale"; import { showDeleteConfirmModal, showHelpModal, showStreamModal } from "src/modals"; import { MANAGE, STREAMS } from "src/modules/Permissions"; @@ -17,6 +17,7 @@ export default function TableWrapper() { const [search, setSearch] = useState(""); const [_deleteId, _setDeleteIdd] = useState(0); const { isFetching, isLoading, isError, error, data } = useStreams(["owner", "certificate"]); + const { data: health } = useUpstreamHealth(); if (isLoading) { return ; @@ -102,6 +103,7 @@ export default function TableWrapper() { showStreamModal(id)} onDelete={(id: number) =>