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