Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import {
7 databaseReclaimMinutes,
8 type DatabaseStorageStatus,
9 type EnvironmentId,
10} from "@t3tools/contracts";
11import * as Schema from "effect/Schema";
12import { type ReactNode, useState } from "react";
13
14import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
15import { useLocalStorage } from "../../hooks/useLocalStorage";
16import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
17import { serverEnvironment } from "../../state/server";
18import { useAtomCommand } from "../../state/use-atom-command";
19import {
20 AlertDialog,
21 AlertDialogClose,
22 AlertDialogDescription,
23 AlertDialogFooter,
24 AlertDialogHeader,
25 AlertDialogPopup,
26 AlertDialogTitle,
27} from "../ui/alert-dialog";
28import { Button } from "../ui/button";
29import { toastManager } from "../ui/toast";
30import { SettingsRow, SettingsSection } from "./settingsLayout";
31
32const DismissedEnvironmentIds = Schema.Array(Schema.String);
33const reclaimPermissionsAtom = environmentAtomList(
34 "web-database-reclaim-permissions",
35 serverEnvironment.reclaimDatabaseSpace.permissionAtom,
36);
37
38const formatGiB = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
39
40/** Offers to reclaim the space on every machine whose database still holds at least 1 GiB of freed pages. */
41export function DatabaseStorageNotice({
42 environments,
43}: {
44 environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>;
45}) {
46 const environmentIds = environments.map((environment) => environment.environmentId);
47 const recommendations = useAtomValue(
48 serverEnvironment.databaseCompactionRecommendations(JSON.stringify(environmentIds)),
49 );
50 const permissions = useAtomValue(reclaimPermissionsAtom(environmentIdsKey(environmentIds)));
51 const [dismissed, setDismissed] = useLocalStorage(
52 "database-storage-notice-dismissed",
53 [],
54 DismissedEnvironmentIds,
55 );
56 const { copyToClipboard } = useCopyToClipboard({ target: "command" });
57 const visible = recommendations
58 .filter((recommendation) => !dismissed.includes(recommendation.environmentId))
59 .map((recommendation) => ({
60 ...recommendation,
61 label:
62 environments.find(
63 (environment) => environment.environmentId === recommendation.environmentId,
64 )?.label ?? recommendation.environmentId,
65 reclaimable:
66 recommendation.status.canReclaim === true &&
67 permissions[environmentIds.indexOf(recommendation.environmentId)] === true,
68 }));
69 if (visible.length === 0) return null;
70 return (
71 <SettingsSection id="storage-database" title="Database">
72 <SettingsRow
73 title="Reclaim freed database space"
74 description={`These databases still hold space freed by history cleanup.${
75 visible.every((recommendation) => recommendation.reclaimable)
76 ? ""
77 : " Run the command on each machine to reclaim it. It restarts the background service. Quit the desktop app first if it hosts the environment."
78 }`}
79 />
80 {visible.map(({ environmentId, status, label, reclaimable }) => {
81 const dismiss = (
82 <Button
83 variant="ghost"
84 size="xs"
85 onClick={() => setDismissed((current) => [...current, environmentId])}
86 >
87 Dismiss
88 </Button>
89 );
90 return reclaimable ? (
91 <ReclaimRow
92 key={environmentId}
93 environmentId={environmentId}
94 label={label}
95 status={status}
96 dismiss={dismiss}
97 />
98 ) : (
99 <SettingsRow
100 key={environmentId}
101 title={`${formatGiB(status.reclaimableBytes)} on ${label}`}
102 description={<code className="select-text break-all">{status.compactCommand}</code>}
103 control={
104 <div className="flex flex-wrap items-center gap-1.5">
105 <Button
106 variant="outline"
107 size="xs"
108 onClick={() => copyToClipboard(status.compactCommand, undefined)}
109 >
110 Copy command
111 </Button>
112 {dismiss}
113 </div>
114 }
115 />
116 );
117 })}
118 </SettingsSection>
119 );
120}
121
122function ReclaimRow({
123 environmentId,
124 label,
125 status,
126 dismiss,
127}: {
128 readonly environmentId: EnvironmentId;
129 readonly label: string;
130 readonly status: DatabaseStorageStatus;
131 readonly dismiss: ReactNode;
132}) {
133 const reclaim = useAtomCommand(serverEnvironment.reclaimDatabaseSpace);
134 const [confirming, setConfirming] = useState(false);
135 const [requested, setRequested] = useState(false);
136 // A failed repair reports back after the restart, which ends the wait.
137 const restarting = requested && status.reclaimFailure === undefined;
138 const minutes = databaseReclaimMinutes(status);
139 const amount = formatGiB(status.reclaimableBytes);
140 const start = async () => {
141 setConfirming(false);
142 setRequested(true);
143 const result = await reclaim({ environmentId, input: {} });
144 if (result._tag === "Success") {
145 toastManager.add({
146 type: "success",
147 title: `Reclaiming ${amount} on ${label}`,
148 description: `T3 Code there restarts and is back in about ${minutes} min.`,
149 });
150 return;
151 }
152 setRequested(false);
153 if (isAtomCommandInterrupted(result)) return;
154 const error = squashAtomCommandFailure(result);
155 toastManager.add({
156 type: "error",
157 title: `Could not reclaim space on ${label}`,
158 description: error instanceof Error ? error.message : "An error occurred.",
159 });
160 };
161 return (
162 <SettingsRow
163 title={`${amount} on ${label}`}
164 description={
165 status.reclaimFailure === undefined
166 ? `Restarts T3 Code there. It will be offline for about ${minutes} min.`
167 : `The last attempt failed: ${status.reclaimFailure}`
168 }
169 control={
170 <div className="flex flex-wrap items-center gap-1.5">
171 <Button
172 variant="outline"
173 size="xs"
174 disabled={restarting}
175 onClick={() => setConfirming(true)}
176 >
177 {restarting ? "Restarting…" : "Reclaim"}
178 </Button>
179 {dismiss}
180 <AlertDialog open={confirming} onOpenChange={setConfirming}>
181 <AlertDialogPopup>
182 <AlertDialogHeader>
183 <AlertDialogTitle>
184 Reclaim {amount} on {label}?
185 </AlertDialogTitle>
186 <AlertDialogDescription>
187 T3 Code on {label} stops, rebuilds its database, and starts again. It will be
188 offline for about {minutes} min. Running agents stop when it restarts.
189 </AlertDialogDescription>
190 </AlertDialogHeader>
191 <AlertDialogFooter>
192 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
193 <Button onClick={() => void start()}>Restart and reclaim</Button>
194 </AlertDialogFooter>
195 </AlertDialogPopup>
196 </AlertDialog>
197 </div>
198 }
199 />
200 );
201}