diff --git a/explorer/config/custom-environment-variables.json b/explorer/config/custom-environment-variables.json index 48ac0f83d..0cd9c6817 100644 --- a/explorer/config/custom-environment-variables.json +++ b/explorer/config/custom-environment-variables.json @@ -1,7 +1,6 @@ { "nodes": { "fallbackPublicExplorer": "FALLBACK_PUBLIC_EXPLORER", - "requiredApiVersion": "REQUIRED_API_VERSION", "defaultHttpdPort": "DEFAULT_HTTPD_PORT", "defaultLocalHttpdPort": "DEFAULT_LOCAL_HTTPD_PORT", "defaultHttpdScheme": "DEFAULT_HTTPD_SCHEME" diff --git a/explorer/config/default.json b/explorer/config/default.json index cfbb24ec8..05a73f735 100644 --- a/explorer/config/default.json +++ b/explorer/config/default.json @@ -1,7 +1,6 @@ { "nodes": { "fallbackPublicExplorer": "https://radicle.network/nodes/$host/$rid$path", - "requiredApiVersion": "~0.18.0", "defaultHttpdPort": 443, "defaultLocalHttpdPort": 8080, "defaultHttpdScheme": "https", diff --git a/explorer/crates/radicle-httpd/src/api.rs b/explorer/crates/radicle-httpd/src/api.rs index 5e3ded448..6198d6b14 100644 --- a/explorer/crates/radicle-httpd/src/api.rs +++ b/explorer/crates/radicle-httpd/src/api.rs @@ -1,8 +1,6 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; -use axum::response::{IntoResponse, Json}; -use axum::routing::get; use axum::Router; use serde_json::{json, Value}; @@ -30,8 +28,6 @@ use crate::cache::Cache; use crate::Options; pub const RADICLE_VERSION: &str = env!("RADICLE_VERSION"); -// This version has to be updated on every breaking change to the radicle-httpd API. -pub const API_VERSION: &str = "6.2.0"; /// Prefix of a qualified branch reference. const REFS_HEADS: &str = "refs/heads/"; @@ -483,25 +479,12 @@ where Ok(canonical) } +/// Compat: explorer and the Open Graph worker call the API at `/api/v1` until +/// explorer drops httpd 0.30. Server: remove in the first major release after +/// they switch to `/api`, see docs/api-changes.md. pub fn router(ctx: Context) -> Router { - Router::new() - .route("/", get(root_handler)) - .merge(v1::router(ctx)) -} - -async fn root_handler() -> impl IntoResponse { - let response = json!({ - "path": "/api", - "links": [ - { - "href": "/v1", - "rel": "v1", - "type": "GET" - } - ] - }); - - Json(response) + let routes = v1::router(ctx); + routes.clone().nest("/v1", routes) } mod search { @@ -662,8 +645,24 @@ mod repo { #[cfg(test)] mod tests { + use axum::http::StatusCode; + use crate::test; + #[tokio::test] + async fn test_v1_serves_the_api() { + let tmp = tempfile::tempdir().unwrap(); + let app = super::router(test::seed(tmp.path())); + + for (path, v1_path) in [("/", "/v1"), ("/repos?show=all", "/v1/repos?show=all")] { + let response = test::get(&app, path).await; + let v1_response = test::get(&app, v1_path).await; + + assert_eq!(v1_response.status(), StatusCode::OK); + assert_eq!(v1_response.json().await, response.json().await); + } + } + #[tokio::test] async fn test_web_config_accessor() { let tmp = tempfile::tempdir().unwrap(); diff --git a/explorer/crates/radicle-httpd/src/api/v1.rs b/explorer/crates/radicle-httpd/src/api/v1.rs index d84037674..87a4089ec 100644 --- a/explorer/crates/radicle-httpd/src/api/v1.rs +++ b/explorer/crates/radicle-httpd/src/api/v1.rs @@ -10,22 +10,20 @@ use axum::routing::get; use axum::Router; use serde_json::json; -use crate::api::{Context, API_VERSION, RADICLE_VERSION}; +use crate::api::{Context, RADICLE_VERSION}; pub fn router(ctx: Context) -> Router { let root_router = Router::new() .route("/", get(root_handler)) .with_state(ctx.clone()); - let routes = Router::new() + Router::new() .merge(root_router) .merge(info::router(ctx.clone())) .merge(node::router(ctx.clone())) .merge(delegates::router(ctx.clone())) .merge(repos::router(ctx.clone())) - .merge(stats::router(ctx)); - - Router::new().nest("/v1", routes) + .merge(stats::router(ctx)) } async fn root_handler(State(ctx): State) -> impl IntoResponse { @@ -33,9 +31,8 @@ async fn root_handler(State(ctx): State) -> impl IntoResponse { "message": "Welcome!", "service": "radicle-httpd", "version": format!("{}-{}", RADICLE_VERSION, env!("GIT_HEAD")), - "apiVersion": API_VERSION, "nid": ctx.profile.public_key, - "path": "/api/v1", + "path": "/api", "links": [ { "href": "/repos", diff --git a/explorer/crates/radicle-httpd/src/api/v1/info.rs b/explorer/crates/radicle-httpd/src/api/v1/info.rs index ec5381ea4..2361d6263 100644 --- a/explorer/crates/radicle-httpd/src/api/v1/info.rs +++ b/explorer/crates/radicle-httpd/src/api/v1/info.rs @@ -22,6 +22,9 @@ struct HttpdInfo { /// Reflects only configuration — `true` does not guarantee the /// backend is currently reachable. search_available: bool, + /// Whether this httpd was built with release support. A repo can still + /// lack release counts, when this httpd fails to count them. + releases: bool, } #[derive(Serialize)] @@ -39,6 +42,7 @@ async fn info_handler(State(ctx): State) -> impl IntoResponse { let node = node::build_response(&ctx).await?; let httpd = HttpdInfo { search_available: ctx.search().is_some(), + releases: cfg!(feature = "artifacts"), }; Ok::<_, Error>(cached_response(Info { node, httpd }, 600)) } @@ -65,6 +69,7 @@ mod routes { assert_eq!(response.status(), StatusCode::OK); let body: Value = response.json().await; assert_eq!(body["httpd"]["searchAvailable"], false); + assert_eq!(body["httpd"]["releases"], cfg!(feature = "artifacts")); assert!(body["node"].is_object()); } } diff --git a/explorer/docs/adr/0001-expand-and-contract-api-changes.md b/explorer/docs/adr/0001-expand-and-contract-api-changes.md index 64d2194f9..e19b804c0 100644 --- a/explorer/docs/adr/0001-expand-and-contract-api-changes.md +++ b/explorer/docs/adr/0001-expand-and-contract-api-changes.md @@ -57,13 +57,8 @@ supported httpd release into one shape. Version-specific code lives in method that calls that endpoint. **Name the side and the version in every removal.** httpd and the client remove -their compatibility code at different times: - -- httpd stops sending the old fields in a major release after the expand. -- The client keeps its fallback until explorer drops the last httpd release - without the new fields. - -So each removal comment says which side it is on, and when it can go: +their compatibility code at different times, so each compat comment says what +the other side does, which side it is on, and when it can go: ```rust // Compat: older clients ... Server: remove in a major release. @@ -78,9 +73,16 @@ with its expand release, the consumers that read it, and its pending removals. A release fills its `## API changes` notes from this list. **Feature detection, not version checks.** The client learns what a seed -supports from its responses: a field that is present, or an endpoint that -answers. It never branches on the httpd version, and uses that version only to -warn about an unsupported node. +supports from the seed itself. It never branches on the httpd version, and uses +that version only to warn about an unsupported node. The signal depends on the +feature: + +- A feature that every build has: a field that is present, or an endpoint that + answers. +- A feature that a build or the config can turn off, such as search or releases: + a flag in `/info`. A missing field is not this signal, because a field is also + missing when httpd fails to compute it. The client must not hide a feature + because of such a failure. **No version but httpd's.** httpd does not report `apiVersion`, and serves the API at `/api`, with no version in the path. When a path moves, the client cannot diff --git a/explorer/docs/api-changes.md b/explorer/docs/api-changes.md index 77ed45d48..91ed9af10 100644 --- a/explorer/docs/api-changes.md +++ b/explorer/docs/api-changes.md @@ -1,75 +1,82 @@ # httpd API changes -Every breaking change to the httpd API ships in two steps, see -[ADR 0001](adr/0001-expand-and-contract-api-changes.md). Expand adds the new -shape next to the old one. Contract removes the old one later, on each side -separately. This file tracks each change from its expand release until both -sides have contracted. +Breaking changes to the httpd API that are between expand and contract. +[ADR 0001](adr/0001-expand-and-contract-api-changes.md) has the rules. -One section per change, under the httpd release that expanded it, newest first. -Each section says what the expand added and who reads it, then lists the -contract: the code each side removes, and when it may go. Delete a contract line -when its code is gone. Delete the section when its contract list is empty. A -release fills its `## API changes` notes from the sections under its heading, -and a major release from every server line. +- When a change expands, add a section under its release, newest first, and add + its removals to the table. +- When a release bumps the major, set the target date in `## Support`. Its + `## API changes` notes come from its sections and from the server removals. +- When code is removed, delete its row. When a change has no rows left, delete + its section. -- **Client contract**: the explorer client (`http-client/`) and the Open Graph - worker (`workers/open-graph/`) may stop reading the old shape when explorer - drops the last httpd release without the new shape. -- **Server contract**: httpd may stop sending the old shape in a major release - after the expand. +## Support -## Expanded in the next release (unreleased) +Explorer supports httpd 0.28.0 and newer, set by `minimumSupportedVersion` in +`http-client/lib/compat.ts`. No target dates are set yet. + +## Removals + +| When | Side | Change | Remove | +| ------------------------- | ------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Explorer drops httpd 0.26 | Client | Stats endpoints | `getCommitCountBySha` and `getDiffStats` in `http-client/lib/repo.ts` | +| Explorer drops httpd 0.30 | Client | API at `/api` | `/api/v1` in `http-client/lib/fetcher.ts`, `apiBase` in `workers/open-graph/index.js`, and in the tests under `tests/visual/desktop/` and `tests/e2e/` | +| Explorer drops httpd 0.30 | Client | Repo facts | `legacyMetaSchema`, `crefsPayloadSchema` and `legacyRepoFields` in `http-client/lib/compat.ts`; `normalizeRepo` in `workers/open-graph/index.js` | +| Explorer drops httpd 0.30 | Client | Release scope | `legacyReleasesQuery`, `legacyScopeReleases` and `legacyHasOtherReleases` in `http-client/lib/compat.ts` | +| Explorer drops httpd 0.30 | Client | Release support | `releasesSupported` in `http-client/lib/compat.ts` | +| Major after client switch | Server | API at `/api` | The `/v1` nest in `crates/radicle-httpd/src/api.rs` | +| A major release | Server | Repo facts | Legacy `meta` and `head` in `crates/radicle-httpd/src/api.rs` | +| A major release | Server | Release scope | `allAuthors` in `crates/radicle-httpd/src/api/query.rs` | + +## Next release ### API at `/api` -Expand: httpd serves the API at `/api`, and still serves it at `/api/v1`. Read -by the explorer client and the Open Graph worker. +- Added: httpd serves the API at `/api`, and still at `/api/v1`. +- Changed in place: the API root reports `path` as `/api`. The old index at + `/api`, which only linked to `/v1`, is gone. No client reads either. +- Read by: client, Open Graph worker. Both call `/api/v1` until explorer drops + httpd 0.30, because older httpd serves only that path. So httpd keeps `/v1` + until the first major release after they switch. -Contract: +### Repo facts -- Client, when explorer drops httpd 0.30: switch to `/api` in - `http-client/lib/fetcher.ts` -- Client, when explorer drops httpd 0.30: `apiBase` in - `workers/open-graph/index.js` -- Client, when explorer drops httpd 0.30: the tests that match `/api/v1` in - `tests/visual/desktop/` and `tests/e2e/` -- Server, a major release after the client lines above: the `/v1` nest in - `crates/radicle-httpd/src/api.rs` - -### Repo facts outside the project payload - -Expand: `cobs`, `releaseCount` and a qualified `defaultBranch` move out of the -project payload. The legacy `meta` (counts and `head`) stays inside it. Only -`repos/:rid` sends the release counts: counting reads every release, so repo -lists leave them out. Read by the explorer client and the Open Graph worker. - -Contract: - -- Client, when explorer drops httpd 0.30: `legacyMetaSchema`, - `crefsPayloadSchema` and `legacyRepoFields` in `http-client/lib/compat.ts` -- Client, when explorer drops httpd 0.30: `normalizeRepo` in - `workers/open-graph/index.js` -- Server, a major release: legacy `meta` and `head` in - `crates/radicle-httpd/src/api.rs` +- Added: `cobs`, with the release buckets, and a qualified `defaultBranch`, + outside the project payload. The legacy `meta` (counts and `head`) stays + inside it. +- Changed in place: `meta.releases` counts `delegate` plus `other`, not every + release object. When httpd cannot count, it leaves the field out instead of + sending 0. Older clients parse both, because the field was always optional. +- Changed in place: only `repos/:rid` sends the release buckets and + `meta.releases`. Repo lists leave both out, because counting reads every + release of each repo. +- Read by: client, Open Graph worker. ### Release scope -Expand: the releases query takes `scope` (`trusted` or `untrusted`), and the -repo reports release buckets. `allAuthors` stays. Read by the explorer client. +- Added: the releases query takes `scope` (`trusted` or `untrusted`). + `allAuthors` stays. +- Read by: client. -Contract: +### Release support -- Client, when explorer drops httpd 0.30: `legacyReleasesQuery`, - `legacyScopeReleases` and `legacyHasOtherReleases` in - `http-client/lib/compat.ts` -- Server, a major release: `allAuthors` in - `crates/radicle-httpd/src/api/query.rs` +- Added: `/info` reports `httpd.releases`, whether httpd was built with release + support. Without it, a repo with no release count could be a node without + releases or a count that failed. +- Read by: client. On older httpd, it reads a release count as support. -### Removed `apiVersion` +### Version -httpd no longer reports `apiVersion` in the API root, and explorer no longer -checks it. Explorer warns on nodes older than `minimumSupportedVersion` in -`http-client/lib/compat.ts`, from the `version` in the API root. Released -explorers do not read `apiVersion`. This is a removal, so the next release is a -major release. +- Removed: `apiVersion` in the API root. The client no longer checks it, and + released clients do not read it. +- Added: the client reads `version` in the API root, and warns on nodes older + than `minimumSupportedVersion`. +- This is a removal, so the release bumps the major. + +## 0.27.0 + +### Stats endpoints + +- Added: `stats/commits/:sha` and `diff/:base/:oid/stats`. The client falls back + to the tree stats and the full diff. +- Read by: client. diff --git a/explorer/http-client/index.ts b/explorer/http-client/index.ts index 3180366c1..1f7723949 100644 --- a/explorer/http-client/index.ts +++ b/explorer/http-client/index.ts @@ -131,6 +131,8 @@ const infoSchema = z.object({ node: nodeSchema, httpd: z.object({ searchAvailable: z.boolean(), + // Absent on older httpd, see `releasesSupported`. + releases: z.boolean().optional(), }), }); @@ -151,7 +153,6 @@ const nodeInfoSchema = z.object({ message: z.string(), service: z.string(), version: z.string(), - apiVersion: z.string(), nid: z.string(), path: z.string(), links: z.array( diff --git a/explorer/http-client/lib/compat.ts b/explorer/http-client/lib/compat.ts index 51054fb63..0027676d2 100644 --- a/explorer/http-client/lib/compat.ts +++ b/explorer/http-client/lib/compat.ts @@ -1,5 +1,6 @@ -// Shims that let this client read older httpd releases, so the app only ever -// sees one shape. See docs/adr/0001 and docs/api-changes.md. +// The minimum supported httpd version, and shims that let this client read +// older httpd releases, so the app only ever sees one shape. See docs/adr/0001 +// and docs/api-changes.md. // // Each shim has a "Compat:" comment that says what older httpd does and the // last httpd release that needs it: "Client: remove when explorer drops httpd @@ -13,6 +14,35 @@ import type { z } from "zod"; import { number, object, record, string } from "zod"; +// The minimum httpd version that explorer supports. Explorer compares only +// the major, and before 1.0, `0.y` counts as the major. See docs/adr/0001. +export const minimumSupportedVersion = "0.28.0"; + +// The release number of an httpd `version`, such as `0.31.0` for +// `0.31.0-`. Undefined for builds without one, such as +// `pre-release-` or `nix-`. +export function releaseNumber(version: string): string | undefined { + return version.match(/^\d+\.\d+\.\d+/)?.[0]; +} + +// Whether the major of an httpd `version` is older than the major of +// `minimum`. False for builds without a release number. +export function isOutdated( + version: string, + minimum: string = minimumSupportedVersion, +): boolean { + const release = releaseNumber(version); + if (release === undefined) { + return false; + } + const [major, minor] = release.split(".").map(Number); + const [minimumMajor, minimumMinor] = minimum.split(".").map(Number); + if (major !== minimumMajor) { + return major < minimumMajor; + } + return major === 0 && minor < minimumMinor; +} + // Compat: older httpd reports the issue and patch counts and the default // branch tip inside the project payload, and the release count as a single // number. Client: remove when explorer drops httpd 0.30. @@ -127,6 +157,17 @@ export function legacyReleasesQuery( return scope === "untrusted" ? { allAuthors: true } : {}; } +// Whether a node serves releases. Compat: older httpd has no `releases` flag +// in `/info`. It sends a release count unless it was built without release +// support, so a count means support. Client: remove when explorer drops httpd +// 0.30. +export function releasesSupported( + flag: boolean | undefined, + repo: { releaseCount?: number }, +): boolean { + return flag ?? repo.releaseCount !== undefined; +} + // Compat: older httpd answers the untrusted scope with every author, so // keep only the releases that no delegate created. A no-op on newer nodes. // Client: remove when explorer drops httpd 0.30. diff --git a/explorer/http-client/lib/fetcher.ts b/explorer/http-client/lib/fetcher.ts index fa1d6f797..ce61b2e05 100644 --- a/explorer/http-client/lib/fetcher.ts +++ b/explorer/http-client/lib/fetcher.ts @@ -4,7 +4,11 @@ import type { ZodIssue, ZodType, TypeOf } from "zod"; import config from "@app/lib/config"; -import { satisfies } from "compare-versions"; +import { + isOutdated, + minimumSupportedVersion, + releaseNumber, +} from "./compat.js"; export interface BaseUrl { hostname: string; @@ -45,34 +49,29 @@ export class ResponseParseError extends Error { public method: string; public body: unknown; public description: string; - public apiVersion: string | undefined; + public nodeVersion: string | undefined; public zodIssues: ZodIssue[]; public path?: string; public constructor( method: string, body: unknown, - apiVersion: string, + nodeVersion: string | undefined, zodIssues: ZodIssue[], path?: string, ) { super("Failed to parse response body"); - const explorerRequiredApiVersion = config.nodes.requiredApiVersion; - const nodeApiVersion = apiVersion; - - let description: string; - if (!satisfies(nodeApiVersion, explorerRequiredApiVersion)) { - description = `The node you are fetching from (v${nodeApiVersion}) doesn’t match the version requirements of radicle-explorer ${explorerRequiredApiVersion}.`; - } else { - description = `The node (v${nodeApiVersion}) matches the version requirement of radicle-explorer (${explorerRequiredApiVersion}), but radicle-explorer isn’t able to parse the response.`; - } - this.apiVersion = apiVersion; + const node = nodeVersion ? `The node (v${nodeVersion})` : "The node"; + this.nodeVersion = nodeVersion; + const outdated = + nodeVersion !== undefined && isOutdated(nodeVersion) + ? ` It runs radicle-httpd ${releaseNumber(nodeVersion)}, but explorer needs ${minimumSupportedVersion} or newer. Its operator should upgrade it.` + : ""; this.description = - "The response received from the seed does not match the expected schema.
".concat( - description, + `${node} sent a response that radicle-explorer can’t parse.${outdated}`.concat( config.deploymentId ? "" - : "
If you are self-hosting radicle-explorer and run into this error, try to clear the browser’s localStorage and the cache.", + : " If you are self-hosting radicle-explorer, try to clear the browser’s localStorage and the cache.", ); this.method = method; @@ -138,12 +137,15 @@ export class Fetcher { if (result.success) { return result.data; } else { - const response = await this.fetch({ method: "GET" }); - const info = await response.json(); + const info = await this.fetch({ method: "GET" }) + .then(response => response.json()) + .catch(() => undefined); + const nodeVersion = + typeof info?.version === "string" ? info.version : undefined; throw new ResponseParseError( params.method, responseBody, - info.version, + nodeVersion, result.error.issues, params.path, ); @@ -164,6 +166,9 @@ export class Fetcher { const pathSegment = path === undefined ? "" : `/${path}`; + // Compat: older httpd serves the API only at `/api/v1`, newer httpd + // serves it at both `/api` and `/api/v1`. Client: switch to `/api` when + // explorer drops httpd 0.30. let url = `${this.#baseUrl.scheme}://${this.#baseUrl.hostname}:${this.#baseUrl.port}/api/v1${pathSegment}`; if (query) { diff --git a/explorer/http-client/lib/repo.ts b/explorer/http-client/lib/repo.ts index 4d1f40000..91ffeeab2 100644 --- a/explorer/http-client/lib/repo.ts +++ b/explorer/http-client/lib/repo.ts @@ -147,7 +147,7 @@ export const repoSchema = object({ ...repo, cobs: repo.cobs, // The unredacted delegate releases, which the releases tab opens on. - // Absent when the node cannot serve releases. + // Absent when the node cannot count them, see `releasesSupported`. releaseCount: repo.cobs.releases?.delegate, }; }); @@ -431,10 +431,9 @@ export class Client { ); return commits; } catch (error) { - // Compat: httpd < 0.27.0 doesn't serve the commit-count endpoint, so fall + // Compat: older httpd doesn't serve the commit-count endpoint, so fall // back to the tree stats endpoint, which also returns the commit count. - // Outside the support window; remove once the e2e tests stop running - // against httpd 0.26.0. + // Client: remove when explorer drops httpd 0.26. if (error instanceof ResponseError && error.status === 404) { const stats = await this.getTreeStatsBySha(rid, sha, options); return stats.commits; @@ -541,10 +540,9 @@ export class Client { diffStatsSchema, ); } catch (error) { - // Compat: httpd < 0.27.0 doesn't serve the diff-stats endpoint, so fall - // back to the full diff, which also carries the stats. Outside the - // support window; remove once the e2e tests stop running against httpd - // 0.26.0. + // Compat: older httpd doesn't serve the diff-stats endpoint, so fall + // back to the full diff, which also carries the stats. Client: remove + // when explorer drops httpd 0.26. if (error instanceof ResponseError && error.status === 404) { const { diff } = await this.getDiff( rid, diff --git a/explorer/module.d.ts b/explorer/module.d.ts index 250c77576..1dc36cb0f 100644 --- a/explorer/module.d.ts +++ b/explorer/module.d.ts @@ -6,7 +6,6 @@ declare module "*.md" { declare const buildTimeConfig: { nodes: { - requiredApiVersion: string; fallbackPublicExplorer: string; defaultHttpdPort: number; defaultLocalHttpdPort: number; diff --git a/explorer/package.json b/explorer/package.json index e1a0afe92..8bb5a56d1 100644 --- a/explorer/package.json +++ b/explorer/package.json @@ -72,7 +72,6 @@ "baconjs": "^3.0.23", "bs58": "^6.0.0", "buffer": "^6.0.3", - "compare-versions": "^6.1.1", "dompurify": "^3.4.12", "fuzzysort": "^3.1.0", "hast-util-to-dom": "^4.0.1", diff --git a/explorer/src/components/Header.svelte b/explorer/src/components/Header.svelte index 3dee04a87..782ce8863 100644 --- a/explorer/src/components/Header.svelte +++ b/explorer/src/components/Header.svelte @@ -99,7 +99,7 @@ const info = await new HttpdClient(seed).getInfo(); searchAvailableCache[key] = info.httpd.searchAvailable; } catch { - // Older nodes without /info (or an unreachable seed) have no search. + // An unreachable seed has no search. searchAvailableCache[key] = false; } if (seedKey($searchSeed) === key) { diff --git a/explorer/src/components/Markdown.svelte b/explorer/src/components/Markdown.svelte index 0103b34e7..f111edb44 100644 --- a/explorer/src/components/Markdown.svelte +++ b/explorer/src/components/Markdown.svelte @@ -30,7 +30,6 @@ import ErrorModal from "@app/modals/ErrorModal.svelte"; import { activeUnloadedRouteStore } from "@app/lib/router"; import { highlight } from "@app/lib/syntax"; - import { mimes } from "@app/lib/file"; import { isUrl, twemoji, @@ -135,13 +134,6 @@ if (anchorHref && isCommit(anchorHref)) { // eslint-disable-next-line svelte/prefer-svelte-reactivity const url = new URL(rawPath); - // deprecated with httpd 0.18.1 - // For older httpd versions we still pass the mime type. - // On newer radicle-httpd instances we try to infer the file type on httpd. - const fileExtension = e.innerText.split(".").pop(); - if (fileExtension && fileExtension in mimes) { - url.search = `?mime=${mimes[fileExtension]}`; - } url.pathname = canonicalize(`blobs/${anchorHref}`, url.pathname); e.setAttribute("href", url.toString()); diff --git a/explorer/src/lib/file.ts b/explorer/src/lib/file.ts deleted file mode 100644 index 33819f1c4..000000000 --- a/explorer/src/lib/file.ts +++ /dev/null @@ -1,63 +0,0 @@ -export const mimes: Record = { - "3gp": "video/3gpp", - "7z": "application/x-7z-compressed", - aac: "audio/aac", - avi: "video/x-msvideo", - bin: "application/octet-stream", - bmp: "image/bmp", - bz: "application/x-bzip", - bz2: "application/x-bzip2", - csh: "application/x-csh", - css: "text/css", - csv: "text/csv", - doc: "application/msword", - docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - epub: "application/epub+zip", - gz: "application/gzip", - gif: "image/gif", - htm: "text/html", - html: "text/html", - ico: "image/vnd.microsoft.icon", - jar: "application/java-archive", - jpeg: "image/jpeg", - jpg: "image/jpeg", - js: "text/javascript", - json: "application/json", - mjs: "text/javascript", - mp3: "audio/mpeg", - mp4: "video/mp4", - mpeg: "video/mpeg", - mov: "video/mp4", - odp: "application/vnd.oasis.opendocument.presentation", - ods: "application/vnd.oasis.opendocument.spreadsheet", - odt: "application/vnd.oasis.opendocument.text", - oga: "audio/ogg", - ogv: "video/ogg", - ogx: "application/ogg", - otf: "font/otf", - png: "image/png", - pdf: "application/pdf", - php: "application/x-httpd-php", - ppt: "application/vnd.ms-powerpoint", - pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", - rar: "application/vnd.rar", - rtf: "application/rtf", - sh: "application/x-sh", - svg: "image/svg+xml", - tar: "application/x-tar", - tif: "image/tiff", - tiff: "image/tiff", - ttf: "font/ttf", - txt: "text/plain", - wav: "audio/wav", - weba: "audio/webm", - webm: "video/webm", - webp: "image/webp", - woff: "font/woff", - woff2: "font/woff2", - xhtml: "application/xhtml+xml", - xls: "application/vnd.ms-excel", - xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - xml: "application/xml", - zip: "application/zip", -}; diff --git a/explorer/src/lib/nodeVersion.ts b/explorer/src/lib/nodeVersion.ts new file mode 100644 index 000000000..2fd33690a --- /dev/null +++ b/explorer/src/lib/nodeVersion.ts @@ -0,0 +1,11 @@ +import type { BaseUrl } from "@http-client"; + +import { HttpdClient } from "@http-client"; +import { cached } from "@app/lib/cache"; + +// The radicle-httpd version of a node, fetched once per seed. +export const nodeVersion = cached( + async (baseUrl: BaseUrl) => + (await new HttpdClient(baseUrl).getNodeInfo()).version, + baseUrl => `${baseUrl.scheme}://${baseUrl.hostname}:${baseUrl.port}`, +); diff --git a/explorer/src/views/explore/SeedPicker.svelte b/explorer/src/views/explore/SeedPicker.svelte index b1929e1b5..323795c75 100644 --- a/explorer/src/views/explore/SeedPicker.svelte +++ b/explorer/src/views/explore/SeedPicker.svelte @@ -5,7 +5,7 @@ import { get } from "svelte/store"; import config from "@app/lib/config"; - import { HttpdClient, ResponseError } from "@http-client"; + import { HttpdClient } from "@http-client"; import { activeUnloadedRouteStore, push, @@ -13,6 +13,12 @@ withBaseUrl, } from "@app/lib/router"; import { isLocal, isOnion } from "@app/lib/utils"; + import { + isOutdated, + minimumSupportedVersion, + releaseNumber, + } from "@http-client/lib/compat"; + import { nodeVersion } from "@app/lib/nodeVersion"; import { addBookmark, bookmarkedSeeds, @@ -44,6 +50,15 @@ const VALIDATION_TIMEOUT_MS = 10000; + // The httpd version of the seed serving the current page, if explorer no + // longer supports it. Only the node picker names that seed. + $: outdatedVersion = + mode === "node" + ? nodeVersion(baseUrl) + .then(version => (isOutdated(version) ? version : undefined)) + .catch(() => undefined) + : Promise.resolve(undefined); + // The seed currently in use isn't necessarily bookmarked or a default: it // can be reached through a shared link or through failover. List it anyway, // so it is always possible to open its node view from here. @@ -85,26 +100,14 @@ } // Probe a seed to decide if it's reachable. Mirrors the reachability - // check in `tryWithFailover`: prefer `/info`, only swallow 404/405 (older - // httpd) and try `/node` instead. Any other error → not reachable. + // check in `tryWithFailover`: any error → not reachable. async function probeSeed(seed: BaseUrl): Promise { const api = new HttpdClient(seed); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), VALIDATION_TIMEOUT_MS); try { - try { - await api.getInfo({ abort: controller.signal }); - return true; - } catch (error) { - if ( - error instanceof ResponseError && - (error.status === 404 || error.status === 405) - ) { - await api.getNode({ abort: controller.signal }); - return true; - } - throw error; - } + await api.getInfo({ abort: controller.signal }); + return true; } catch (e) { console.warn(`Probe for seed ${seed.hostname} failed:`, e); return false; @@ -336,6 +339,17 @@ aria-expanded={expanded}>
{baseUrl.hostname}
+ {#await outdatedVersion then version} + {#if version !== undefined} + + + + {/if} + {/await} {#if variant !== "breadcrumb"} {/if} diff --git a/explorer/src/views/explore/router.ts b/explorer/src/views/explore/router.ts index 74e7b2941..1d4f7029a 100644 --- a/explorer/src/views/explore/router.ts +++ b/explorer/src/views/explore/router.ts @@ -4,7 +4,7 @@ import type { ErrorRoute, NotFoundRoute } from "@app/lib/router/definitions"; import isEqual from "lodash/isEqual"; import { get } from "svelte/store"; -import { HttpdClient, ResponseError } from "@http-client"; +import { HttpdClient } from "@http-client"; import { clearSeedFailure, failedSeeds, @@ -117,24 +117,10 @@ export async function loadExploreRoute(): Promise< > { const attempt = await tryWithFailover(async (seed, signal) => { const api = new HttpdClient(seed); - // Prefer /info — it tells us whether the seed has a search backend - // configured. Only fall back to /node on a 404/405 (older httpd that - // doesn't ship /info yet). Any other failure — network error, abort, - // 5xx — rethrows so the caller can mark the seed failed and try the - // next one, instead of silently masking outages as "no search". - try { - const info = await api.getInfo({ abort: signal }); - return { searchAvailable: info.httpd.searchAvailable }; - } catch (error) { - if ( - error instanceof ResponseError && - (error.status === 404 || error.status === 405) - ) { - await api.getNode({ abort: signal }); - return { searchAvailable: false }; - } - throw error; - } + // A failure rethrows, so the caller can mark the seed failed and try the + // next one, instead of masking an outage as "no search". + const info = await api.getInfo({ abort: signal }); + return { searchAvailable: info.httpd.searchAvailable }; }); if (!attempt) { @@ -163,21 +149,8 @@ export async function loadExploreReposRoute( const attempt = await tryWithFailover(async (seed, signal) => { const api = new HttpdClient(seed); const stats = await api.getStats({ abort: signal }); - // Prefer /info to learn whether the seed has a search backend. - // Only swallow 404/405 (older httpd without /info); any other - // failure rethrows so the seed gets marked failed. - try { - const info = await api.getInfo({ abort: signal }); - return { stats, searchAvailable: info.httpd.searchAvailable }; - } catch (error) { - if ( - error instanceof ResponseError && - (error.status === 404 || error.status === 405) - ) { - return { stats, searchAvailable: false }; - } - throw error; - } + const info = await api.getInfo({ abort: signal }); + return { stats, searchAvailable: info.httpd.searchAvailable }; }); if (!attempt) { diff --git a/explorer/src/views/nodes/OutdatedWarning.svelte b/explorer/src/views/nodes/OutdatedWarning.svelte new file mode 100644 index 000000000..8eb083d8e --- /dev/null +++ b/explorer/src/views/nodes/OutdatedWarning.svelte @@ -0,0 +1,33 @@ + + + + + diff --git a/explorer/src/views/nodes/View.svelte b/explorer/src/views/nodes/View.svelte index ac023b20b..c47533850 100644 --- a/explorer/src/views/nodes/View.svelte +++ b/explorer/src/views/nodes/View.svelte @@ -4,6 +4,7 @@ import { tick } from "svelte"; import dompurify from "dompurify"; + import { isOutdated } from "@http-client/lib/compat"; import { markdown, sanitizeConfig } from "@app/lib/markdown"; import Command from "@app/components/Command.svelte"; @@ -20,10 +21,12 @@ import Seeding from "./Seeding.svelte"; import UserAgent from "./UserAgent.svelte"; import NodeAddress from "./NodeAddress.svelte"; + import OutdatedWarning from "./OutdatedWarning.svelte"; export let baseUrl: BaseUrl; export let stats: NodeStats; export let node: Node; + export let version: string | undefined = undefined; let descriptionContent: HTMLDivElement | undefined = undefined; let descriptionExpanded = false; @@ -257,6 +260,9 @@ {/if} + {#if version !== undefined && isOutdated(version)} + + {/if}