Files
radicle-explorer/explorer/http-client/lib/fetcher.ts
T
Daniel Norman d8f363ca99 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
2026-10-29 18:32:03 +01:00

186 lines
5.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// This module provides low-level capabilities to interact with a typed
// JSON HTTP API.
import type { ZodIssue, ZodType, TypeOf } from "zod";
import config from "@app/lib/config";
import {
isOutdated,
minimumSupportedVersion,
releaseNumber,
} from "./compat.js";
export interface BaseUrl {
hostname: string;
port: number;
scheme: string;
}
// Error that is thrown by `Fetcher` methods.
export class ResponseError extends Error {
public method: string;
public url: string;
public status: number;
public body: unknown;
public constructor(method: string, response: Response, body_: unknown) {
const body: unknown = body_;
if (
typeof body === "object" &&
body !== null &&
"message" in body &&
typeof body.message === "string"
) {
super(body.message);
} else {
super("Response error");
}
this.method = method;
this.body = body_;
this.status = response.status;
this.url = response.url;
}
}
// Error that is thrown by `Fetcher` methods when parsing the response
// body fails.
export class ResponseParseError extends Error {
public method: string;
public body: unknown;
public description: string;
public nodeVersion: string | undefined;
public zodIssues: ZodIssue[];
public path?: string;
public constructor(
method: string,
body: unknown,
nodeVersion: string | undefined,
zodIssues: ZodIssue[],
path?: string,
) {
super("Failed to parse response body");
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 =
`${node} sent a response that radicle-explorer can’t parse.${outdated}`.concat(
config.deploymentId
? ""
: " If you are self-hosting radicle-explorer, try to clear the browser’s localStorage and the cache.",
);
this.method = method;
this.path = path;
this.body = body;
this.zodIssues = zodIssues;
}
}
export interface RequestOptions {
abort?: AbortSignal;
}
export interface FetchParams {
method: Method;
// Path to append to the `Fetcher`s base URL to get the final URL.
path?: string;
// Object that is serialized into JSON and sent as the data.
body?: unknown;
// Query parameters to be serialized with URLSearchParams.
query?: Record<string, string | number | boolean>;
options?: RequestOptions;
headers?: Record<string, string>;
}
type Method = "DELETE" | "GET" | "PATCH" | "POST" | "PUT";
export class Fetcher {
#baseUrl: BaseUrl;
public constructor(baseUrl: BaseUrl) {
this.#baseUrl = baseUrl;
}
// Execute a fetch and parse the result with the provided schema.
// Return the parsed payload.
//
// Throws `ResponseError` if the response status code is not `200`.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async fetchOk<T extends ZodType<any>>(
params: FetchParams,
schema: T,
): Promise<TypeOf<T>> {
if (config.deploymentId) {
params.query ||= {};
params.query["deployment_id"] = config.deploymentId;
}
const response = await this.fetch(params);
if (!response.ok) {
let responseBody = await response.text();
try {
responseBody = JSON.parse(responseBody);
} catch {
// We keep the original text response body.
}
throw new ResponseError(params.method, response, responseBody);
}
const responseBody = await response.json();
const result = schema.safeParse(responseBody);
if (result.success) {
return result.data;
} else {
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,
nodeVersion,
result.error.issues,
params.path,
);
}
}
private async fetch({
method,
path,
body,
options = {},
query,
headers = {},
}: FetchParams): Promise<Response> {
if (body !== undefined && headers["content-type"] === undefined) {
headers["content-type"] = "application/json";
}
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) {
const searchparams = new URLSearchParams(query as Record<string, string>);
url = `${url}?${searchparams.toString()}`;
}
return globalThis.fetch(url, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: options.abort,
});
}
}