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