Open History to see the last commit
1import {
2 ServerSelfUpdateError,
3 type DesktopUpdateState,
4 type DesktopUpdateStatusReport,
5 type ServerSelfUpdateProgressStage,
6 type ServerSelfUpdateResult,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Ref from "effect/Ref";
15import * as Result from "effect/Result";
16import * as Stream from "effect/Stream";
17
18import { ServerConfig } from "../config.ts";
19import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
20
21/** Backstop for a desktop updater that hangs without ever reporting a
22 terminal outcome. Generous: it covers a slow download of a full build. */
23const DESKTOP_UPDATE_TIMEOUT = Duration.minutes(20);
24const DESKTOP_INSTALL_TIMEOUT = Duration.minutes(2);
25
26/** Progress stage a desktop update state maps to, or null when the state
27 carries no progress worth streaming. */
28export function desktopUpdateProgressStage(
29 state: DesktopUpdateState,
30): ServerSelfUpdateProgressStage | null {
31 switch (state.status) {
32 case "checking":
33 case "available":
34 case "downloading":
35 return "downloading";
36 case "downloaded":
37 return "installing";
38 default:
39 return null;
40 }
41}
42
43export class DesktopAppUpdate extends Context.Service<
44 DesktopAppUpdate,
45 {
46 /** True when this server was spawned by a desktop app that can be
47 driven over the telemetry control channel. */
48 readonly available: boolean;
49 /** Checks and downloads through the desktop app, then returns a token
50 while this server is still connected. `commit` starts installation. */
51 readonly run: (
52 reportProgress: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
53 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
54 /** Starts the prepared install. Success stops this server, so this effect
55 returns only when installation fails or times out. */
56 readonly commit: (requestId: string) => Effect.Effect<never, ServerSelfUpdateError>;
57 }
58>()("t3/desktopUpdate/DesktopAppUpdate") {}
59
60export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* () {
61 const config = yield* ServerConfig;
62 const crypto = yield* Crypto.Crypto;
63 const receiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
64 const inFlight = yield* Ref.make(false);
65
66 const available = config.mode === "desktop" && config.desktopTelemetryControlFd !== undefined;
67 const failWith = (reason: string, cause?: unknown) =>
68 cause === undefined
69 ? new ServerSelfUpdateError({ reason })
70 : new ServerSelfUpdateError({ reason, cause });
71
72 const consumeReports = (
73 requestId: string,
74 changes: Stream.Stream<DesktopUpdateStatusReport>,
75 reportProgress: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
76 ) =>
77 Effect.gen(function* () {
78 const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
79 const emitStage = (stage: ServerSelfUpdateProgressStage | null): Effect.Effect<void> =>
80 stage === null
81 ? Effect.void
82 : Ref.get(lastStage).pipe(
83 Effect.flatMap((previous) =>
84 previous === stage
85 ? Effect.void
86 : Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),
87 ),
88 );
89
90 const terminal = yield* changes.pipe(
91 Stream.filter((report) => report.requestId === requestId),
92 Stream.mapEffect(
93 (report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>> =>
94 report.outcome === undefined
95 ? emitStage(desktopUpdateProgressStage(report.state)).pipe(
96 Effect.as(Option.none<DesktopUpdateStatusReport>()),
97 )
98 : Effect.succeed(Option.some(report)),
99 ),
100 Stream.filterMap(
101 Option.match({
102 onNone: () => Result.failVoid,
103 onSome: Result.succeed,
104 }),
105 ),
106 Stream.runHead,
107 );
108 if (Option.isNone(terminal)) {
109 return yield* failWith("The desktop app stopped reporting its update.");
110 }
111
112 const report = terminal.value;
113 if (report.outcome === "ready-to-install") {
114 yield* emitStage("installing");
115 const targetVersion =
116 report.state.downloadedVersion ??
117 report.state.availableVersion ??
118 report.state.currentVersion;
119 yield* Effect.logInfo("Desktop app update prepared for install.", {
120 targetVersion,
121 });
122 yield* Ref.set(inFlight, false);
123 return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };
124 }
125 if (report.outcome === "up-to-date") {
126 return yield* failWith(
127 `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
128 );
129 }
130 return yield* failWith(
131 report.reason ?? report.state.message ?? "The desktop app update failed.",
132 );
133 });
134
135 const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
136 function* (reportProgress) {
137 if (!available) {
138 return yield* failWith(
139 "This server was not started by the T3 Code desktop app, so it cannot drive a desktop update.",
140 );
141 }
142 if (yield* Ref.getAndSet(inFlight, true)) {
143 return yield* failWith("A desktop app update is already in progress.");
144 }
145
146 return yield* Effect.scoped(
147 Effect.gen(function* () {
148 const requestId = yield* crypto.randomUUIDv4.pipe(
149 Effect.mapError((error) =>
150 failWith("Could not generate a desktop update request id.", error),
151 ),
152 );
153 // Subscribe before sending the request so a fast first report
154 // cannot be missed.
155 const { changes } = yield* receiver.desktopUpdates;
156 yield* receiver
157 .requestDesktopUpdate(requestId)
158 .pipe(
159 Effect.mapError((error) =>
160 failWith("Could not reach the T3 Code desktop app on this machine.", error),
161 ),
162 );
163 return yield* consumeReports(requestId, changes, reportProgress).pipe(
164 Effect.onInterrupt(() => receiver.cancelDesktopUpdate(requestId).pipe(Effect.ignore)),
165 );
166 }),
167 ).pipe(
168 Effect.timeout(DESKTOP_UPDATE_TIMEOUT),
169 Effect.catchTags({
170 TimeoutError: () => failWith("The desktop app did not finish the update in time."),
171 }),
172 Effect.onError(() => Ref.set(inFlight, false)),
173 );
174 },
175 );
176
177 const commit: DesktopAppUpdate["Service"]["commit"] = Effect.fn(
178 "desktopUpdate.desktopAppUpdate.commit",
179 )(function* (requestId) {
180 if (!available) {
181 return yield* failWith("This server cannot commit a desktop app update.");
182 }
183 const terminal = yield* Effect.scoped(
184 Effect.gen(function* () {
185 const { latest, changes } = yield* receiver.desktopUpdates;
186 const reports = Option.match(latest, {
187 onNone: () => changes,
188 onSome: (report) => Stream.concat(Stream.make(report), changes),
189 });
190 yield* receiver
191 .commitDesktopUpdate(requestId)
192 .pipe(
193 Effect.mapError((error) => failWith("Could not reach the T3 Code desktop app.", error)),
194 );
195 return yield* reports.pipe(
196 Stream.filter((report) => report.requestId === requestId && report.outcome === "failed"),
197 Stream.runHead,
198 Effect.timeout(DESKTOP_INSTALL_TIMEOUT),
199 Effect.catchTags({
200 TimeoutError: () =>
201 failWith("The desktop app did not report an install result in time."),
202 }),
203 );
204 }),
205 );
206 if (Option.isNone(terminal)) {
207 return yield* failWith("The desktop app stopped reporting the install.");
208 }
209 return yield* failWith(
210 terminal.value.reason ??
211 terminal.value.state.message ??
212 "The desktop app failed to install the update.",
213 );
214 });
215
216 return DesktopAppUpdate.of({ available, run, commit });
217});
218
219export const layer = Layer.effect(DesktopAppUpdate, make());