Open History to see the last commit
1import { useEffect, useRef, useState } from "react";
2import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7
8import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
9import { serverEnvironment } from "~/state/server";
10import { useAtomCommand } from "~/state/use-atom-command";
11import { manualServerUpdateCommand } from "~/versionSkew";
12import { Button } from "./ui/button";
13import { Spinner } from "./ui/spinner";
14import { toastManager } from "./ui/toast";
15
16/**
17 * The npm install on the server side is capped at 10 minutes; expire the
18 * spinner a bit beyond that so a dead transport never strands a disabled
19 * button, while a legitimately slow install is never cut off.
20 */
21const UPDATE_PENDING_EXPIRY_MS = 12 * 60_000;
22
23function updateFailureMessage(error: unknown): string {
24 return error instanceof Error ? error.message : "Server update failed.";
25}
26
27/**
28 * The call-to-action for a version-skewed server, matched to the update path
29 * it advertises: a one-click install-and-restart for servers that can update
30 * themselves, an update-the-desktop-app hint for desktop-managed backends
31 * (running `npx t3` there would start a second server, not update this one),
32 * and copying the manual relaunch command for everything else — so the skew
33 * warning always offers a way out.
34 */
35export function ServerUpdateAction({
36 environmentId,
37 serverLabel,
38 selfUpdate,
39 targetVersion,
40}: {
41 readonly environmentId: EnvironmentId;
42 readonly serverLabel: string;
43 readonly selfUpdate: ServerSelfUpdateCapability | null;
44 readonly targetVersion: string;
45}) {
46 const updateServer = useAtomCommand(serverEnvironment.updateServer, {
47 reportFailure: false,
48 });
49 const [pending, setPending] = useState(false);
50 const inFlightRef = useRef(false);
51 const attemptRef = useRef(0);
52 const expiryRef = useRef<ReturnType<typeof setTimeout> | null>(null);
53 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
54 target: "update command",
55 onCopy: ({ command }) => {
56 toastManager.add({
57 type: "success",
58 title: "Update command copied",
59 description: `Run \`${command}\` on ${serverLabel} to update it.`,
60 });
61 },
62 onError: (error) => {
63 toastManager.add({
64 type: "error",
65 title: "Could not copy update command",
66 description: error.message,
67 });
68 },
69 });
70
71 useEffect(
72 () => () => {
73 if (expiryRef.current !== null) {
74 clearTimeout(expiryRef.current);
75 expiryRef.current = null;
76 }
77 attemptRef.current += 1;
78 inFlightRef.current = false;
79 },
80 [],
81 );
82
83 const handleUpdate = () => {
84 // Synchronous re-entry guard: setPending is async, so a rapid
85 // double-click would otherwise dispatch two updates.
86 if (inFlightRef.current) {
87 return;
88 }
89 inFlightRef.current = true;
90 const attempt = attemptRef.current + 1;
91 attemptRef.current = attempt;
92 const ownsAttempt = () => attemptRef.current === attempt;
93 setPending(true);
94 const armExpiry = () => {
95 const expiry = setTimeout(() => {
96 if (!ownsAttempt()) return;
97 expiryRef.current = null;
98 attemptRef.current += 1;
99 inFlightRef.current = false;
100 setPending(false);
101 toastManager.add({
102 type: "error",
103 title: "Server update timed out",
104 description: "The update may still be running on the server — check again in a minute.",
105 });
106 }, UPDATE_PENDING_EXPIRY_MS);
107 expiryRef.current = expiry;
108 return expiry;
109 };
110 let expiry = armExpiry();
111 let restartAccepted = false;
112 const keepPendingForRestart = () => {
113 restartAccepted = true;
114 if (expiryRef.current === expiry) {
115 clearTimeout(expiry);
116 expiry = armExpiry();
117 }
118 };
119 void Promise.resolve()
120 .then(() =>
121 updateServer({
122 environmentId,
123 input: { targetVersion },
124 }),
125 )
126 .then((result) => {
127 if (!ownsAttempt()) return;
128 if (result._tag === "Failure") {
129 // An interrupt may be the expected boot-service disconnect, but it
130 // can also be client-side cancellation before restart was accepted.
131 // Release the action quietly; version sync will remove it when a
132 // successful replacement reconnects.
133 if (isAtomCommandInterrupted(result)) {
134 return;
135 }
136 toastManager.add({
137 type: "error",
138 title: "Server update failed",
139 description: updateFailureMessage(squashAtomCommandFailure(result)),
140 });
141 return;
142 }
143 keepPendingForRestart();
144 // Installation can legitimately consume most of the request window.
145 // Give restart/reconnect a fresh full window after the server accepts
146 // the handoff instead of expiring based on the original click time.
147 toastManager.add({
148 type: "success",
149 title: `Updating ${serverLabel}`,
150 description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,
151 });
152 })
153 .catch((error: unknown) => {
154 if (!ownsAttempt()) return;
155 toastManager.add({
156 type: "error",
157 title: "Server update failed",
158 description: updateFailureMessage(error),
159 });
160 })
161 .finally(() => {
162 // A successful RPC only acknowledges that restart is scheduled. Keep
163 // the action disabled until version sync unmounts it, or until the
164 // safety expiry reports that reconnection never arrived.
165 if (restartAccepted || !ownsAttempt() || expiryRef.current !== expiry) return;
166 expiryRef.current = null;
167 clearTimeout(expiry);
168 attemptRef.current += 1;
169 inFlightRef.current = false;
170 setPending(false);
171 });
172 };
173
174 if (selfUpdate === "desktop-managed") {
175 return (
176 <span className="text-muted-foreground text-xs">
177 Update the desktop app on that machine to update this server.
178 </span>
179 );
180 }
181
182 if (selfUpdate === null) {
183 const command = manualServerUpdateCommand(targetVersion);
184 return (
185 <Button size="xs" variant="outline" onClick={() => copyToClipboard(command, { command })}>
186 Copy update command
187 </Button>
188 );
189 }
190
191 return pending ? (
192 <Button size="xs" disabled>
193 <Spinner className="size-3.5" />
194 Updating...
195 </Button>
196 ) : (
197 <Button size="xs" onClick={() => void handleUpdate()}>
198 Update server
199 </Button>
200 );
201}