Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion apps/web/app/admin/actions/updates.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"use server";

import { updateTag } from "next/cache";
import { revalidatePath, updateTag } from "next/cache";

import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/session";
import { SETTINGS_ID } from "@/lib/settings";
import { UPDATE_CHECK_TAG } from "@/lib/version";

import type { ActionResult } from "./infrastructure";
Expand All @@ -12,3 +14,16 @@ export const checkForUpdates = async (): Promise<ActionResult> => {
updateTag(UPDATE_CHECK_TAG);
return { ok: true };
};

export const setUpdateBeta = async (
enabled: boolean
): Promise<ActionResult> => {
await requireAdmin();
await prisma.panelSettings.upsert({
create: { id: SETTINGS_ID, updateBeta: enabled },
update: { updateBeta: enabled },
where: { id: SETTINGS_ID },
});
revalidatePath("/admin", "layout");
return { ok: true };
};
11 changes: 9 additions & 2 deletions apps/web/app/admin/nodes/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import { buildNodeDaemonConfig } from "@/lib/daemon/configuration";
import { prisma } from "@/lib/db";
import { API_URL } from "@/lib/env";
import { requireAdmin } from "@/lib/session";
import { getLatestRelease, shortSha, updateStatus } from "@/lib/version";
import {
getLatestRelease,
getUpdateBeta,
shortSha,
updateStatus,
} from "@/lib/version";

import {
PageBody,
Expand All @@ -32,7 +37,9 @@ const fetchSystem = async (node: Node) => {
};

const fetchAgentStatus = async (info: SystemInfo) => {
const latest = await getLatestRelease("agent");
const latest = await getLatestRelease("agent", {
beta: await getUpdateBeta(),
});
if (!latest.ok) {
return "unknown";
}
Expand Down
29 changes: 29 additions & 0 deletions apps/web/app/admin/updates/beta-toggle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"use client";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";

import { setUpdateBeta } from "../actions/updates";
import { useAction } from "../components/use-action";

export const BetaToggle = ({ enabled }: { enabled: boolean }) => {
const { pending, run } = useAction();
return (
<div className="flex items-center gap-2">
<Switch
checked={enabled}
disabled={pending}
id="update-beta"
onCheckedChange={(checked) =>
run(
() => setUpdateBeta(checked),
checked ? "Checking pre-releases" : "Checking stable releases only"
)
}
size="sm"
/>
<Label className="text-sm" htmlFor="update-beta">
Beta
</Label>
</div>
);
};
13 changes: 10 additions & 3 deletions apps/web/app/admin/updates/overview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import { cache } from "react";

import { DaemonClient } from "@/lib/daemon/client";
import { prisma } from "@/lib/db";
import { getLatestRelease, PANEL_BUILD, updateStatus } from "@/lib/version";
import {
getLatestRelease,
getUpdateBeta,
PANEL_BUILD,
updateStatus,
} from "@/lib/version";

const fetchAgent = async (node: Node) => {
try {
Expand All @@ -16,9 +21,10 @@ const fetchAgent = async (node: Node) => {
};

export const getUpdateOverview = cache(async () => {
const beta = await getUpdateBeta();
const [panelLatest, agentLatest, nodes] = await Promise.all([
getLatestRelease("panel"),
getLatestRelease("agent"),
getLatestRelease("panel", { beta }),
getLatestRelease("agent", { beta }),
prisma.node.findMany({ orderBy: { name: "asc" } }),
]);
const agents = await Promise.all(nodes.map((node) => fetchAgent(node)));
Expand All @@ -36,6 +42,7 @@ export const getUpdateOverview = cache(async () => {
};
}),
},
beta,
panel: {
latest: panelLatest,
status: updateStatus(
Expand Down
21 changes: 19 additions & 2 deletions apps/web/app/admin/updates/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { commitUrl, PANEL_BUILD, REPOS, shortSha } from "@/lib/version";
import type { Component, LatestRelease } from "@/lib/version";

import { PageBody, PageHeader } from "../../dashboard/components/page-header";
import { BetaToggle } from "./beta-toggle";
import { CheckForUpdatesButton } from "./check-button";
import { getUpdateOverview } from "./overview";
import { StatusBadge } from "./status-badge";
Expand Down Expand Up @@ -57,6 +58,14 @@ const LatestRows = ({
>
{latest.name}
</Link>
{latest.prerelease && (
<Badge
className="ml-2 border-violet-500/40 bg-violet-500/10 text-violet-600"
variant="outline"
>
Pre-release
</Badge>
)}
{latest.publishedAt && (
<span className="text-muted-foreground">
{" "}
Expand All @@ -77,13 +86,21 @@ const LatestRows = ({

const AdminUpdatesPage = async () => {
await requireAdmin();
const { agent, panel } = await getUpdateOverview();
const { agent, beta, panel } = await getUpdateOverview();
const panelLatest = panel.latest;
const agentLatest = agent.latest;

return (
<>
<PageHeader meta={<CheckForUpdatesButton />} title="Updates" />
<PageHeader
meta={
<div className="flex items-center gap-4">
<BetaToggle enabled={beta} />
<CheckForUpdatesButton />
</div>
}
title="Updates"
/>
<PageBody>
<div className="flex flex-col gap-4">
<Panel action={<StatusBadge status={panel.status} />} title="Panel">
Expand Down
108 changes: 72 additions & 36 deletions apps/web/lib/version.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import "server-only";
import { prisma } from "@/lib/db";
import { env } from "@/lib/env";
import { SETTINGS_ID } from "@/lib/settings";

export const UPDATE_CHECK_TAG = "update-check";
const REVALIDATE_SECONDS = 60 * 60;
Expand Down Expand Up @@ -27,9 +29,18 @@ export interface LatestRelease {
name: string;
url: string;
publishedAt: string | null;
prerelease: boolean;
commit: CommitInfo;
}

export const getUpdateBeta = async (): Promise<boolean> => {
const row = await prisma.panelSettings.findUnique({
select: { updateBeta: true },
where: { id: SETTINGS_ID },
});
return row?.updateBeta ?? false;
};

export type Result<T> = { ok: true; data: T } | { ok: false; error: string };

export type UpdateStatus = "current" | "outdated" | "ahead" | "unknown";
Expand Down Expand Up @@ -70,42 +81,6 @@ const githubJson = async <T>(path: string): Promise<T> => {
const toError = (error: unknown) =>
error instanceof Error ? error.message : "update check failed";

export const getLatestRelease = async (
component: Component
): Promise<Result<LatestRelease>> => {
const repo = REPOS[component];
try {
const release = await githubJson<{
tag_name: string;
name: string | null;
html_url: string;
published_at: string | null;
}>(`/repos/${repo}/releases/latest`);
const commit = await githubJson<{
sha: string;
html_url: string;
commit: { message: string; committer?: { date?: string } };
}>(`/repos/${repo}/commits/${encodeURIComponent(release.tag_name)}`);
return {
data: {
commit: {
date: commit.commit.committer?.date ?? null,
message: commit.commit.message.split("\n")[0] ?? "",
sha: commit.sha,
url: commit.html_url,
},
name: release.name || release.tag_name,
publishedAt: release.published_at,
url: release.html_url,
version: release.tag_name.replace(/^v/u, ""),
},
ok: true,
};
} catch (error) {
return { error: toError(error), ok: false };
}
};

const parse = (v: string) => {
const [core = "", pre] = v.trim().replace(/^v/u, "").split("-", 2);
const nums = core.split(".").map((n) => Math.trunc(Number(n)) || 0);
Expand Down Expand Up @@ -137,6 +112,67 @@ export const compareVersions = (a: string, b: string) => {
return Math.sign(comparePre(pa.pre, pb.pre));
};

interface GithubRelease {
tag_name: string;
name: string | null;
html_url: string;
published_at: string | null;
prerelease: boolean;
draft: boolean;
}

const fetchRelease = async (
repo: string,
beta: boolean
): Promise<GithubRelease> => {
if (!beta) {
return githubJson<GithubRelease>(`/repos/${repo}/releases/latest`);
}
const releases = await githubJson<GithubRelease[]>(
`/repos/${repo}/releases?per_page=30`
);
const [newest] = releases
.filter((r) => !r.draft)
.toSorted((a, b) => compareVersions(b.tag_name, a.tag_name));
if (!newest) {
throw new Error("no published release found");
}
return newest;
};

export const getLatestRelease = async (
component: Component,
{ beta = false }: { beta?: boolean } = {}
): Promise<Result<LatestRelease>> => {
const repo = REPOS[component];
try {
const release = await fetchRelease(repo, beta);
const commit = await githubJson<{
sha: string;
html_url: string;
commit: { message: string; committer?: { date?: string } };
}>(`/repos/${repo}/commits/${encodeURIComponent(release.tag_name)}`);
return {
data: {
commit: {
date: commit.commit.committer?.date ?? null,
message: commit.commit.message.split("\n")[0] ?? "",
sha: commit.sha,
url: commit.html_url,
},
name: release.name || release.tag_name,
prerelease: release.prerelease,
publishedAt: release.published_at,
url: release.html_url,
version: release.tag_name.replace(/^v/u, ""),
},
ok: true,
};
} catch (error) {
return { error: toError(error), ok: false };
}
};

export const updateStatus = (
current: { version: string },
latest: LatestRelease | null
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "panel_settings" ADD COLUMN "updateBeta" BOOLEAN NOT NULL DEFAULT false;
1 change: 1 addition & 0 deletions apps/web/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,7 @@ model PanelSettings {
currency String @default("GBP")
billingApiKeyHash String?
billingApiKeyHint String?
updateBeta Boolean @default(false)
updatedAt DateTime @updatedAt

@@map("panel_settings")
Expand Down