Replace API version checks with feature detection

httpd:
- Serve the API at /api, not only under /v1
- Keep serving it at /api/v1, without a redirect, until the first
  major release after explorer and the Open Graph worker switch
  to /api
- Remove apiVersion: released explorers do not read it
- Add `httpd.releases` to `/info`, set by the artifacts feature

explorer:
- Remove the API version check, its config and the unused
  compare-versions dependency
- Keep the node version in a plain parse error message
- Add `minimumSupportedVersion`, set to 0.28.0, and warn on nodes
  whose major is older, treating 0.y as the major before 1.0
- Do not warn on builds without a release number
- Show a warning on the node page of an outdated node
- Mark an outdated node in the seed picker on every page
- Name the node version and the floor in parse errors
- Drop the `/node` fallback for httpd without `/info`, which
  predates the floor
- Check the status, not `ResponseError`, so the Open Graph worker
  can import compat without the fetcher
- Name the httpd release each shim serves, not a date
- Drop the mime shim for httpd 0.18.1 and the unused `lib/file.ts`
- Read the node from `/info` in repo views
- Pass the node and its features to repo views as one `node` param
- Show the releases tab and pages when the node supports releases,
  and the counter only when there is a count
- Read a release count as release support on older httpd
- Test the flag and the fallback

docs:
- Restructure docs/api-changes.md: the supported versions, one
  table of removals, fixed fields per change, and a link to ADR
  0001 for the rules
- Say in ADR 0001 that each compat comment names what the other
  side does
- Say in ADR 0001 when a capability needs a flag in /info

tests:
- Run e2e tests on httpd 0.30.0, above the floor, instead of 0.26.0
- Run the release tests on it too, so they cover the compat shims
- Skip only those that need release counts per scope on it
- Test a node without release support through a mocked `/info`
  flag, instead of an httpd that predates the floor
This commit is contained in:
Daniel Norman
2026-10-29 18:32:03 +01:00
parent b77c82151d
commit d8f363ca99
40 changed files with 480 additions and 397 deletions
@@ -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"
-1
View File
@@ -1,7 +1,6 @@
{
"nodes": {
"fallbackPublicExplorer": "https://radicle.network/nodes/$host/$rid$path",
"requiredApiVersion": "~0.18.0",
"defaultHttpdPort": 443,
"defaultLocalHttpdPort": 8080,
"defaultHttpdScheme": "https",
+21 -22
View File
@@ -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();
+4 -7
View File
@@ -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<Context>) -> impl IntoResponse {
@@ -33,9 +31,8 @@ async fn root_handler(State(ctx): State<Context>) -> 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",
@@ -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<Context>) -> 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());
}
}
@@ -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
+65 -58
View File
@@ -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.
+2 -1
View File
@@ -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(
+43 -2
View File
@@ -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-<commit>`. Undefined for builds without one, such as
// `pre-release-<commit>` or `nix-<commit>`.
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.
+24 -19
View File
@@ -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 <code>radicle-explorer</code> ${explorerRequiredApiVersion}.`;
} else {
description = `The node (v${nodeApiVersion}) matches the version requirement of <code>radicle-explorer</code> (${explorerRequiredApiVersion}), but <code>radicle-explorer</code> 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.<br/>".concat(
description,
`${node} sent a response that radicle-explorer can’t parse.${outdated}`.concat(
config.deploymentId
? ""
: "<br/>If you are self-hosting <code>radicle-explorer</code> and run into this error, try to clear the browser’s <code>localStorage</code> 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) {
+6 -8
View File
@@ -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,
-1
View File
@@ -6,7 +6,6 @@ declare module "*.md" {
declare const buildTimeConfig: {
nodes: {
requiredApiVersion: string;
fallbackPublicExplorer: string;
defaultHttpdPort: number;
defaultLocalHttpdPort: number;
-1
View File
@@ -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",
+1 -1
View File
@@ -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) {
-8
View File
@@ -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());
-63
View File
@@ -1,63 +0,0 @@
export const mimes: Record<string, string> = {
"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",
};
+11
View File
@@ -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}`,
);
+30 -16
View File
@@ -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<boolean> {
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}>
<slot name="icon"><Icon name="seed" /></slot>
<div class="hostname txt-overflow">{baseUrl.hostname}</div>
{#await outdatedVersion then version}
{#if version !== undefined}
<span
class="failed-icon"
title="This node runs radicle-httpd {releaseNumber(
version,
)}, but explorer needs {minimumSupportedVersion} or newer. Upgrade radicle-httpd to the latest release.">
<Icon name="warning" />
</span>
{/if}
{/await}
{#if variant !== "breadcrumb"}
<Icon name={expanded ? "chevron-up" : "chevron-down"} />
{/if}
+7 -34
View File
@@ -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) {
@@ -0,0 +1,33 @@
<script lang="ts">
import Icon from "@app/components/Icon.svelte";
import {
minimumSupportedVersion,
releaseNumber,
} from "@http-client/lib/compat";
export let version: string;
</script>
<style>
.banner {
display: flex;
align-items: flex-start;
gap: 0.375rem;
color: var(--color-text-secondary);
font: var(--txt-body-s-regular);
}
.icon {
display: flex;
flex-shrink: 0;
color: var(--color-feedback-warning-text);
}
</style>
<div class="banner" role="note">
<span class="icon"><Icon name="warning" /></span>
<span>
This node runs radicle-httpd {releaseNumber(version)}, but explorer needs
{minimumSupportedVersion} or newer, so some pages may not load. If you run this
node, please upgrade radicle-httpd.
</span>
</div>
+6
View File
@@ -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 @@
</div>
{/if}
</div>
{#if version !== undefined && isOutdated(version)}
<OutdatedWarning {version} />
{/if}
</div>
<div class="footer">
+8 -1
View File
@@ -5,6 +5,7 @@ import config from "@app/lib/config";
import { HttpdClient } from "@http-client";
import { ResponseError, ResponseParseError } from "@http-client/lib/fetcher";
import { handleError } from "@app/views/nodes/error";
import { nodeVersion } from "@app/lib/nodeVersion";
import { unreachableError } from "@app/views/repos/error";
import { determineSeed } from "./SeedSelector";
@@ -26,6 +27,7 @@ export interface NodesLoadedRoute {
baseUrl: BaseUrl;
stats: NodeStats;
node: Node;
version: string | undefined;
};
}
@@ -53,7 +55,11 @@ export async function loadNodeRoute(
const api = new HttpdClient(baseUrl);
try {
const [node, stats] = await Promise.all([api.getNode(), api.getStats()]);
const [node, stats, version] = await Promise.all([
api.getNode(),
api.getStats(),
nodeVersion(baseUrl).catch(() => undefined),
]);
return {
resource: "nodes",
@@ -61,6 +67,7 @@ export async function loadNodeRoute(
baseUrl,
node,
stats,
version,
},
};
} catch (error) {
+3 -3
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import type { BaseUrl, Commit, Repo } from "@http-client";
import type { RepoNode } from "./router";
import {
archiveDownloadSupported,
@@ -24,8 +25,7 @@
export let commit: Commit;
export let repo: Repo;
export let repoId: string;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
let downloading = false;
@@ -75,7 +75,7 @@
}
</style>
<Layout {nodeId} {nodeAvatarUrl} {baseUrl} {repo} {repoId}>
<Layout {node} {baseUrl} {repo} {repoId}>
<svelte:fragment slot="breadcrumb">
<Separator />
<Link
+12 -9
View File
@@ -5,6 +5,7 @@
<script lang="ts">
import type { BaseUrl, Repo } from "@http-client";
import type { RepoNode } from "./router";
import config from "@app/lib/config";
import debounce from "lodash/debounce";
@@ -20,8 +21,9 @@
export let activeTab: ActiveTab = undefined;
export let repo: Repo;
export let repoId: string;
export let node: RepoNode;
// Undefined on nodes that cannot serve releases.
// Undefined when the node cannot count the releases.
$: releaseCount = repo.releaseCount;
let shareIcon: "link" | "checkmark" = "link";
@@ -167,8 +169,7 @@
</Button>
</Link>
<!-- Only nodes that report a release count support the release API. -->
{#if releaseCount !== undefined}
{#if node.releases}
<Link
route={{
resource: "repo.releases",
@@ -181,12 +182,14 @@
<Icon name="parcel" />
<div class="title-counter">
Releases
<span
class="counter"
class:hover={hover && activeTab !== "releases"}
class:selected={activeTab === "releases"}>
{releaseCount}
</span>
{#if releaseCount !== undefined}
<span
class="counter"
class:hover={hover && activeTab !== "releases"}
class:selected={activeTab === "releases"}>
{releaseCount}
</span>
{/if}
</div>
</Button>
</Link>
+3 -4
View File
@@ -6,7 +6,7 @@
SeedingPolicy,
Tree,
} from "@http-client";
import type { RepoRoute } from "./router";
import type { RepoNode, RepoRoute } from "./router";
import config from "@app/lib/config";
import { HttpdClient } from "@http-client";
@@ -40,8 +40,7 @@
export let repoId: string;
export let revision: string | undefined;
export let tree: Tree;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
// The revision carries the encoded branch name after an in-app navigation,
// and this refname reaches the user as part of the clone popover's archive
@@ -112,7 +111,7 @@
}
</style>
<Layout {nodeId} {nodeAvatarUrl} {baseUrl} {repo} {repoId} activeTab="source">
<Layout {node} {baseUrl} {repo} {repoId} activeTab="source">
<svelte:fragment slot="breadcrumb">
<Separator />
<Link
+3 -4
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import type { BaseUrl, Issue, Repo } from "@http-client";
import type { RepoNode } from "./router";
import capitalize from "lodash/capitalize";
import uniqBy from "lodash/uniqBy";
@@ -28,8 +29,7 @@
export let repo: Repo;
export let repoId: string;
export let rawPath: (commit?: string) => string;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
$: uniqueEmbeds = uniqBy(
issue.discussion.flatMap(comment => comment.embeds),
@@ -126,8 +126,7 @@
<Layout
{baseUrl}
{nodeId}
{nodeAvatarUrl}
{node}
{repo}
{repoId}
activeTab="issues"
+3 -3
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import type { BaseUrl, Issue, IssueState, Repo } from "@http-client";
import type { RepoNode } from "./router";
import { HttpdClient } from "@http-client";
import { ISSUES_PER_PAGE } from "./router";
@@ -21,8 +22,7 @@
export let repo: Repo;
export let repoId: string;
export let status: IssueState["status"];
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
let loading = false;
let page = 0;
@@ -109,7 +109,7 @@
}
</style>
<Layout {nodeId} {nodeAvatarUrl} {baseUrl} {repo} {repoId} activeTab="issues">
<Layout {node} {baseUrl} {repo} {repoId} activeTab="issues">
<svelte:fragment slot="breadcrumb">
<Separator />
<Link
+6 -6
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import type { ActiveTab } from "./Header.svelte";
import type { BaseUrl, Repo } from "@http-client";
import type { RepoNode } from "./router";
import { onMount } from "svelte";
@@ -23,8 +24,7 @@
export let repo: Repo;
export let repoId: string;
export let stylePaddingBottom: string = "2.5rem";
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
$: route = $activeRouteStore;
$: project = repo.payloads["xyz.radicle.project"];
@@ -195,8 +195,8 @@
title="Switch the node serving this page">
<svelte:fragment slot="icon">
<NodeAvatar
{nodeId}
avatarUrl={nodeAvatarUrl}
nodeId={node.id}
avatarUrl={node.avatarUrl}
styleWidth="1rem"
size={16} />
</svelte:fragment>
@@ -238,7 +238,7 @@
</div>
<div class="tab-bar">
<RepoHeader {activeTab} {baseUrl} {repo} {repoId}>
<RepoHeader {activeTab} {baseUrl} {repo} {repoId} {node}>
<svelte:fragment slot="actions">
<slot name="actions" />
</svelte:fragment>
@@ -306,7 +306,7 @@
</Link>
</div>
{#if repo.releaseCount !== undefined}
{#if node.releases}
<div style:width="100%">
<Link
title="Releases"
+3 -5
View File
@@ -68,7 +68,7 @@
<script lang="ts">
import type { BaseUrl } from "@http-client";
import type { PatchView } from "./router";
import type { PatchView, RepoNode } from "./router";
import type { Route } from "@app/lib/router";
import type { ComponentProps } from "svelte";
@@ -107,8 +107,7 @@
export let repo: Repo;
export let repoId: string;
export let view: PatchView;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
const patchStatusLabel: Record<Patch["state"]["status"], string> = {
draft: "Draft Patches",
@@ -345,8 +344,7 @@
{baseUrl}
{repo}
{repoId}
{nodeId}
{nodeAvatarUrl}
{node}
activeTab="patches"
stylePaddingBottom="0">
<svelte:fragment slot="breadcrumb">
+3 -3
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import type { BaseUrl, Patch, PatchState, Repo } from "@http-client";
import type { RepoNode } from "./router";
import { HttpdClient } from "@http-client";
@@ -22,8 +23,7 @@
export let repo: Repo;
export let repoId: string;
export let status: PatchState["status"];
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
let loading = false;
let page = 0;
@@ -113,7 +113,7 @@
}
</style>
<Layout {nodeId} {nodeAvatarUrl} {baseUrl} {repo} {repoId} activeTab="patches">
<Layout {node} {baseUrl} {repo} {repoId} activeTab="patches">
<svelte:fragment slot="breadcrumb">
<Separator />
<Link
+9 -6
View File
@@ -6,6 +6,7 @@
ReleaseScope,
Repo,
} from "@http-client";
import type { RepoNode } from "./router";
import * as utils from "@app/lib/utils";
import {
@@ -34,8 +35,7 @@
export let repo: Repo;
export let repoId: string;
export let scope: ReleaseScope | undefined = undefined;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
const SIZE_KEY = "sizeBytes";
@@ -363,7 +363,7 @@
}
</style>
<Layout {baseUrl} {nodeId} {nodeAvatarUrl} {repo} {repoId} activeTab="releases">
<Layout {baseUrl} {node} {repo} {repoId} activeTab="releases">
<svelte:fragment slot="breadcrumb">
<Separator />
<Link
@@ -571,10 +571,13 @@
{#if artifact.attestations.length > 0}
<span class="attested">
attested by
{#each delegatesFirst(artifact.attestations, n => n.id, delegateIds) as node, i (i)}
{#each delegatesFirst(artifact.attestations, n => n.id, delegateIds) as attestor, i (i)}
<span class="attestor">
<NodeId {baseUrl} nodeId={node.id} alias={node.alias} />
{#if delegateIds.has(node.id)}
<NodeId
{baseUrl}
nodeId={attestor.id}
alias={attestor.alias} />
{#if delegateIds.has(attestor.id)}
<DelegateBadge />
{/if}{#if i < artifact.attestations.length - 1},{/if}
</span>
+3 -3
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import type { BaseUrl, Release, ReleaseScope, Repo } from "@http-client";
import type { RepoNode } from "./router";
import { HttpdClient } from "@http-client";
import { releasesQuery } from "./router";
@@ -24,8 +25,7 @@
export let repoId: string;
export let scope: ReleaseScope;
export let showFilters: boolean;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
let loading = false;
let page = 0;
@@ -127,7 +127,7 @@
}
</style>
<Layout {nodeId} {nodeAvatarUrl} {baseUrl} {repo} {repoId} activeTab="releases">
<Layout {node} {baseUrl} {repo} {repoId} activeTab="releases">
<svelte:fragment slot="breadcrumb">
<Separator />
<Link
+3 -5
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import type { BaseUrl, Repo, SeedingPolicy, Tree } from "@http-client";
import type { BlobResult, RepoRoute } from "./router";
import type { BlobResult, RepoNode, RepoRoute } from "./router";
import { HttpdClient } from "@http-client";
@@ -33,8 +33,7 @@
export let revision: string | undefined;
export let seedingPolicy: SeedingPolicy;
export let tree: Tree;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
let mobileFileTree = false;
@@ -130,8 +129,7 @@
<Layout
{baseUrl}
{nodeId}
{nodeAvatarUrl}
{node}
{repo}
{repoId}
activeTab="source"
@@ -1,5 +1,6 @@
<script lang="ts">
import type { BaseUrl, PeerRefs, Repo, SeedingPolicy } from "@http-client";
import type { RepoNode } from "./router";
import { getPeers } from "./Source/Header.svelte";
import { defaultBranchName } from "@app/lib/utils";
@@ -14,8 +15,7 @@
export let repoId: string;
export let seedingPolicy: SeedingPolicy;
export let peer: string | undefined = undefined;
export let nodeId: string;
export let nodeAvatarUrl: string | undefined;
export let node: RepoNode;
let peers: PeerRefs[] | undefined = undefined;
@@ -55,7 +55,7 @@
commit, or a peer who hasn't pushed it has nothing to open at. Keep the shell
so the issue and patch tabs stay reachable, and offer the peer branch
selector. -->
<Layout {baseUrl} {repo} {repoId} {nodeId} {nodeAvatarUrl} activeTab="source">
<Layout {baseUrl} {repo} {repoId} {node} activeTab="source">
<RepoNameHeader {repo} {repoId} {baseUrl} {seedingPolicy} slot="header" />
<div class="subheader" slot="subheader">
+70 -77
View File
@@ -13,7 +13,6 @@ import type {
DiffBlob,
Issue,
IssueState,
Node,
Patch,
PatchState,
PeerRefs,
@@ -32,6 +31,7 @@ import * as Syntax from "@app/lib/syntax";
import config from "@app/lib/config";
import { HttpdClient } from "@http-client";
import { ResponseError, ResponseParseError } from "@http-client/lib/fetcher";
import { releasesSupported } from "@http-client/lib/compat";
import { cached } from "@app/lib/cache";
import { handleError, unreachableError } from "@app/views/repos/error";
import {
@@ -200,8 +200,7 @@ export type RepoLoadedRoute =
path: string;
rawPath: (commit?: string) => string;
blobResult: BlobResult;
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -216,8 +215,7 @@ export type RepoLoadedRoute =
revision: string | undefined;
tree: Tree;
commitHeaders: CommitHeader[];
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -228,8 +226,7 @@ export type RepoLoadedRoute =
repo: Repo;
repoId: string;
peer: string | undefined;
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -239,8 +236,7 @@ export type RepoLoadedRoute =
repo: Repo;
repoId: string;
commit: Commit;
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -251,8 +247,7 @@ export type RepoLoadedRoute =
repoId: string;
rawPath: (commit?: string) => string;
issue: Issue;
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -263,8 +258,7 @@ export type RepoLoadedRoute =
repoId: string;
issues: Issue[];
status: IssueState["status"];
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -275,8 +269,7 @@ export type RepoLoadedRoute =
repoId: string;
patches: Patch[];
status: PatchState["status"];
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -289,8 +282,7 @@ export type RepoLoadedRoute =
patch: Patch;
stats: Diff["stats"];
view: PatchView;
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -303,8 +295,7 @@ export type RepoLoadedRoute =
lastPageFull: boolean;
scope: ReleaseScope;
showFilters: boolean;
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
}
| {
@@ -315,8 +306,7 @@ export type RepoLoadedRoute =
repoId: string;
release: Release;
scope?: ReleaseScope;
nodeId: string;
nodeAvatarUrl: string | undefined;
node: RepoNode;
};
};
@@ -397,7 +387,7 @@ export async function loadRepoRoute(
const [repo, commit, node] = await Promise.all([
api.repo.getByRid(route.repo),
api.repo.getCommitBySha(route.repo, route.commit),
api.getNode(),
getRepoNode(api),
]);
return {
@@ -407,8 +397,7 @@ export async function loadRepoRoute(
repoId: route.repo,
repo,
commit,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
} else if (route.resource === "repo.issue") {
@@ -453,7 +442,7 @@ async function loadPatchesView(
page: 0,
perPage: PATCHES_PER_PAGE,
}),
api.getNode(),
getRepoNode(api),
]);
return {
@@ -464,8 +453,7 @@ async function loadPatchesView(
patches,
status,
repo,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
@@ -483,7 +471,7 @@ async function loadIssuesView(
page: 0,
perPage: ISSUES_PER_PAGE,
}),
api.getNode(),
getRepoNode(api),
]);
return {
@@ -494,8 +482,7 @@ async function loadIssuesView(
issues,
status,
repo,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
@@ -507,7 +494,7 @@ function sourceUnavailable(
route: { node: BaseUrl; repo: string; peer?: string },
repo: Repo,
seedingPolicy: SeedingPolicy,
node: { id: string; avatarUrl?: string | undefined },
node: RepoNodeInfo,
): RepoLoadedRoute {
return {
resource: "repo.sourceUnavailable",
@@ -517,14 +504,35 @@ function sourceUnavailable(
repo,
seedingPolicy,
peer: route.peer,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
// A missing release count means the node cannot serve releases: it predates
// the release API or was built without release support.
// The node a repo view shows, and the features it serves.
export type RepoNode = {
id: string;
avatarUrl: string | undefined;
releases: boolean;
};
// The node as `/info` reports it. A feature is undefined on httpd without its
// flag.
type RepoNodeInfo = Omit<RepoNode, "releases"> & {
releases: boolean | undefined;
};
// `/info` carries the node and its release support in one request.
async function getRepoNode(api: HttpdClient): Promise<RepoNodeInfo> {
const { node, httpd } = await api.getInfo();
return { id: node.id, avatarUrl: node.avatarUrl, releases: httpd.releases };
}
function resolveRepoNode(node: RepoNodeInfo, repo: Repo): RepoNode {
return { ...node, releases: releasesSupported(node.releases, repo) };
}
// The node predates the release API or was built without release support.
function releasesNotSupported(node: BaseUrl): NotFoundRoute {
return {
resource: "notFound",
@@ -550,9 +558,10 @@ async function loadReleasesView(
// shows only when asked for.
const scope = route.scope ?? "trusted";
// Fetch the page alongside the repo. The repo then tells whether a failed
// fetch is a node without releases or a real error.
// Fetch the page alongside the repo and the node. They then tell whether a
// failed fetch is a node without releases or a real error.
const repoPromise = api.repo.getByRid(route.repo);
const nodePromise = getRepoNode(api);
const [repo, pageResult, showFilters, node] = await Promise.all([
repoPromise,
api.repo
@@ -568,16 +577,15 @@ async function loadReleasesView(
// Others is one click away whenever it holds releases, and Delegates is
// one click back from it.
scope === "untrusted" ||
repoPromise.then(
repo =>
repo.releaseCount !== undefined &&
Promise.all([repoPromise, nodePromise]).then(
([repo, node]) =>
releasesSupported(node.releases, repo) &&
api.repo.hasOtherReleases(repo, RELEASES_PER_PAGE),
),
api.getNode(),
nodePromise,
]);
// A missing release count means the node cannot serve releases.
if (repo.releaseCount === undefined) {
if (!releasesSupported(node.releases, repo)) {
return releasesNotSupported(route.node);
}
if ("error" in pageResult) {
@@ -595,8 +603,7 @@ async function loadReleasesView(
scope,
showFilters,
repo,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
@@ -612,10 +619,10 @@ async function loadReleaseView(
release => ({ release }),
(error: unknown) => ({ error }),
),
api.getNode(),
getRepoNode(api),
]);
if (repo.releaseCount === undefined) {
if (!releasesSupported(node.releases, repo)) {
return releasesNotSupported(route.node);
}
if ("error" in releaseResult) {
@@ -630,8 +637,7 @@ async function loadReleaseView(
repo,
release: releaseResult.release,
scope: route.scope,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
@@ -648,7 +654,7 @@ async function loadTreeView(
let repoPromise: Promise<Repo>;
let seedingPolicyPromise: Promise<SeedingPolicy>;
let nodePromise: Promise<Pick<Node, "id" | "avatarUrl">>;
let nodePromise: Promise<RepoNodeInfo>;
if (
(previousLoaded.resource === "repo.source" ||
previousLoaded.resource === "repo.history") &&
@@ -660,14 +666,11 @@ async function loadTreeView(
) {
repoPromise = Promise.resolve(previousLoaded.params.repo);
seedingPolicyPromise = Promise.resolve(previousLoaded.params.seedingPolicy);
nodePromise = Promise.resolve({
id: previousLoaded.params.nodeId,
avatarUrl: previousLoaded.params.nodeAvatarUrl,
});
nodePromise = Promise.resolve(previousLoaded.params.node);
} else {
repoPromise = api.repo.getByRid(route.repo);
seedingPolicyPromise = api.getPolicyByRid(route.repo);
nodePromise = api.getNode();
nodePromise = getRepoNode(api);
}
const [repo, seedingPolicy, node] = await Promise.all([
@@ -724,8 +727,7 @@ async function loadTreeView(
tree,
path,
blobResult,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
@@ -787,7 +789,7 @@ async function loadHistoryView(
let repoPromise: Promise<Repo>;
let seedingPolicyPromise: Promise<SeedingPolicy>;
let nodePromise: Promise<Pick<Node, "id" | "avatarUrl">>;
let nodePromise: Promise<RepoNodeInfo>;
if (
(previousLoaded.resource === "repo.source" ||
previousLoaded.resource === "repo.history") &&
@@ -799,14 +801,11 @@ async function loadHistoryView(
) {
repoPromise = Promise.resolve(previousLoaded.params.repo);
seedingPolicyPromise = Promise.resolve(previousLoaded.params.seedingPolicy);
nodePromise = Promise.resolve({
id: previousLoaded.params.nodeId,
avatarUrl: previousLoaded.params.nodeAvatarUrl,
});
nodePromise = Promise.resolve(previousLoaded.params.node);
} else {
repoPromise = api.repo.getByRid(route.repo);
seedingPolicyPromise = api.getPolicyByRid(route.repo);
nodePromise = api.getNode();
nodePromise = getRepoNode(api);
}
const [repo, seedingPolicy, node] = await Promise.all([
@@ -869,8 +868,7 @@ async function loadHistoryView(
revision: route.revision,
tree,
commitHeaders,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
@@ -885,7 +883,7 @@ async function loadIssueView(route: RepoIssueRoute): Promise<RepoLoadedRoute> {
const [repo, issue, node] = await Promise.all([
api.repo.getByRid(route.repo),
api.repo.getIssueById(route.repo, route.issue),
api.getNode(),
getRepoNode(api),
]);
return {
resource: "repo.issue",
@@ -895,8 +893,7 @@ async function loadIssueView(route: RepoIssueRoute): Promise<RepoLoadedRoute> {
repo,
rawPath,
issue,
nodeId: node.id,
nodeAvatarUrl: node.avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
@@ -913,7 +910,7 @@ async function loadPatchView(
let repoPromise: Promise<Repo>;
let patchPromise: Promise<Patch>;
let nodePromise: Promise<Pick<Node, "id" | "avatarUrl">>;
let nodePromise: Promise<RepoNodeInfo>;
if (
previousLoaded.resource === "repo.patch" &&
@@ -925,16 +922,13 @@ async function loadPatchView(
) {
repoPromise = Promise.resolve(previousLoaded.params.repo);
patchPromise = Promise.resolve(previousLoaded.params.patch);
nodePromise = Promise.resolve({
id: previousLoaded.params.nodeId,
avatarUrl: previousLoaded.params.nodeAvatarUrl,
});
nodePromise = Promise.resolve(previousLoaded.params.node);
} else {
repoPromise = api.repo.getByRid(route.repo);
patchPromise = api.repo.getPatchById(route.repo, route.patch);
nodePromise = api.getNode();
nodePromise = getRepoNode(api);
}
const [repo, patch, { id: nodeId, avatarUrl }] = await Promise.all([
const [repo, patch, node] = await Promise.all([
repoPromise,
patchPromise,
nodePromise,
@@ -1008,8 +1002,7 @@ async function loadPatchView(
patch,
stats,
view,
nodeId,
nodeAvatarUrl: avatarUrl,
node: resolveRepoNode(node, repo),
},
};
}
+20 -5
View File
@@ -1,4 +1,4 @@
import { test, cobRid, cobUrl, expect } from "@tests/support/fixtures.js";
import { test, cobUrl, expect } from "@tests/support/fixtures.js";
import {
createContributor,
createRepo,
@@ -6,6 +6,10 @@ import {
registerArtifact,
syncFrom,
} from "@tests/support/repo.js";
import {
releaseCountsOnlyLocal,
useLocalHttpd,
} from "@tests/support/support.js";
test.describe(() => {
// Release fixtures need several rad-artifact commands, which takes longer
@@ -29,6 +33,7 @@ test.describe(() => {
});
test("filter releases by author", async ({ page, peer, peerManager }) => {
test.skip(!useLocalHttpd, releaseCountsOnlyLocal);
const name = "release-authors";
const { rid, repoFolder } = await createRepo(peer, { name });
await registerArtifact(peer, repoFolder, { name: "delegate-binary" });
@@ -76,6 +81,7 @@ test.describe(() => {
peer,
peerManager,
}) => {
test.skip(!useLocalHttpd, releaseCountsOnlyLocal);
const name = "release-others-only";
const { rid, repoFolder } = await createRepo(peer, { name });
@@ -107,6 +113,7 @@ test.describe(() => {
});
test("keep a way back from empty others", async ({ page, peer }) => {
test.skip(!useLocalHttpd, releaseCountsOnlyLocal);
const { rid, repoFolder } = await createRepo(peer, {
name: "no-others-releases",
});
@@ -125,6 +132,7 @@ test.describe(() => {
});
test("hide fully redacted releases", async ({ page, peer }) => {
test.skip(!useLocalHttpd, releaseCountsOnlyLocal);
const { rid, repoFolder } = await createRepo(peer, {
name: "redacted-release",
});
@@ -151,12 +159,15 @@ test.describe(() => {
});
});
test("releases are unavailable on older nodes", async ({ page }) => {
// Older nodes don't report a release count.
await page.route(`**/api/v1/repos/${cobRid}`, async route => {
test("releases are unavailable on nodes without release support", async ({
page,
}) => {
// Report a build without release support, as httpd does without the
// artifacts feature. The flag wins over any release count.
await page.route("**/api/v1/info", async route => {
const response = await route.fetch();
const json = await response.json();
delete json.payloads["xyz.radicle.project"].meta.releases;
json.httpd.releases = false;
await route.fulfill({ response, json });
});
@@ -167,4 +178,8 @@ test("releases are unavailable on older nodes", async ({ page }) => {
await expect(
page.getByText("Releases are not available on this node"),
).toBeVisible();
// The header and seed picker also fetch /info, so a request can still be in
// the route when the test ends.
await page.unrouteAll({ behavior: "ignoreErrors" });
});
+3
View File
@@ -39,6 +39,9 @@ export const radicleArtifactRelease = (
export const useLocalHttpd = process.env.USE_LOCAL_HTTPD === "true";
export const releaseCountsOnlyLocal =
"release counts per scope only exist in the local httpd build";
// Assert that binaries are installed and are the correct version.
export async function assertBinariesInstalled(
binary: string,
+52
View File
@@ -2,9 +2,12 @@ import type { Release } from "@http-client";
import { describe, expect, test } from "vitest";
import {
isOutdated,
legacyHasOtherReleases,
legacyReleasesQuery,
legacyScopeReleases,
releaseNumber,
releasesSupported,
} from "@http-client/lib/compat";
import { repoSchema } from "@http-client/lib/repo";
@@ -314,3 +317,52 @@ describe("legacyHasOtherReleases", () => {
expect(await legacyHasOtherReleases(page, [delegate], 10)).toBe(true);
});
});
describe("releaseNumber", () => {
test("reads the release number of a release build", () => {
expect(releaseNumber("0.31.0-abc123")).toBe("0.31.0");
expect(releaseNumber("1.2.3")).toBe("1.2.3");
});
test("has none for builds without one", () => {
expect(releaseNumber("pre-release-abc123")).toBeUndefined();
expect(releaseNumber("nix-abc123-abc123")).toBeUndefined();
});
});
describe("isOutdated", () => {
test("compares 0.y as the major before 1.0", () => {
expect(isOutdated("0.27.0", "0.28.0")).toBe(true);
expect(isOutdated("0.28.0-unknown", "0.28.0")).toBe(false);
expect(isOutdated("0.31.2", "0.28.0")).toBe(false);
expect(isOutdated("1.2.0", "0.28.0")).toBe(false);
});
test("compares the major from 1.0 on", () => {
expect(isOutdated("0.40.0", "1.0.0")).toBe(true);
expect(isOutdated("1.9.0", "2.0.0")).toBe(true);
expect(isOutdated("2.0.0", "2.0.0")).toBe(false);
expect(isOutdated("2.5.1-abc123", "2.0.0")).toBe(false);
expect(isOutdated("2.0.0", "2.3.0")).toBe(false);
expect(isOutdated("1.9.0", "2.3.0")).toBe(true);
});
test("does not warn on builds without a release number", () => {
expect(isOutdated("pre-release-abc123", "2.0.0")).toBe(false);
expect(isOutdated("nix-abc123-abc123", "2.0.0")).toBe(false);
});
});
describe("releasesSupported", () => {
test("follows the node's flag, with or without a count", () => {
expect(releasesSupported(true, { releaseCount: undefined })).toBe(true);
expect(releasesSupported(false, { releaseCount: 2 })).toBe(false);
});
test("reads a count as support on older nodes", () => {
expect(releasesSupported(undefined, { releaseCount: 0 })).toBe(true);
expect(releasesSupported(undefined, { releaseCount: undefined })).toBe(
false,
);
});
});
+3
View File
@@ -100,6 +100,9 @@ function parseRoute(pathname) {
return { type: "repo", host, rid };
}
// 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.
function apiBase(host) {
const local = host.startsWith("localhost") || host.startsWith("127.");
return `${local ? "http" : "https"}://${host}/api/v1`;
-7
View File
@@ -111,7 +111,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",
@@ -2894,12 +2893,6 @@
"node": ">=22.12.0"
}
},
"node_modules/compare-versions": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz",
"integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==",
"license": "MIT"
},
"node_modules/config": {
"version": "4.4.2",
"resolved": "https://registry.npmjs.org/config/-/config-4.4.2.tgz",