Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopAppUpdate.ts

236 lines8.4 KB

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 SecureRandom from "effect/crypto/SecureRandom";
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 }
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 trackSwitch?: DesktopTelemetryReceiver.DesktopTrackSwitch,
48 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
49 /** Success stops the server; returns only on installation failure or timeout. */
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 random = yield* SecureRandom.SecureRandom;
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 = Effect.fn("DesktopAppUpdate.consumeReports")(function* (
70 requestId: string,
71 changes: Stream.Stream<DesktopUpdateStatusReport>,
72 reportProgress: (
73 stage: ServerSelfUpdateProgressStage,
74 ) => Effect.Effect<void, ServerSelfUpdateError>,
75 trackSwitch: boolean,
76 ) {
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 (report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>
95 report.outcome === undefined
96 ? emitStage(desktopUpdateProgressStage(report.state)).pipe(
97 Effect.as(Option.none<DesktopUpdateStatusReport>()),
98 )
99 : Effect.succeedSome(report),
100 ),
101 Stream.filterMap(
102 Option.match({
103 onNone: () => Result.failVoid,
104 onSome: Result.succeed,
105 }),
106 ),
107 Stream.runHead,
108 );
109 if (Option.isNone(terminal)) {
110 return yield* failWith("The desktop app stopped reporting its update.");
111 }
112​
113 const report = terminal.value;
114 if (report.outcome === "ready-to-install") {
115 yield* emitStage("installing");
116 const targetVersion =
117 report.state.downloadedVersion ??
118 report.state.availableVersion ??
119 report.state.currentVersion;
120 yield* Effect.logInfo("Desktop app update prepared for install.", {
121 targetVersion,
122 });
123 yield* Ref.set(inFlight, false);
124 return {
125 targetVersion,
126 method: "desktop-app" as const,
127 desktopUpdateToken: report.preparedRequestId ?? requestId,
128 };
129 }
130 if (report.outcome === "up-to-date") {
131 // A switch's host already on the newest build of its track only saved the track.
132 if (trackSwitch) {
133 yield* Ref.set(inFlight, false);
134 return { targetVersion: report.state.currentVersion, method: "desktop-app" as const };
135 }
136 return yield* failWith(
137 `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
138 );
139 }
140 return yield* failWith(
141 report.reason ?? report.state.message ?? "The desktop app update failed.",
142 );
143 });
144​
145 const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
146 function* (reportProgress, trackSwitch) {
147 if (!available) {
148 return yield* failWith(
149 "This server was not started by the T3 Code desktop app, so it cannot drive a desktop update.",
150 );
151 }
152 if (yield* Ref.getAndSet(inFlight, true)) {
153 return yield* failWith("A desktop app update is already in progress.");
154 }
155​
156 return yield* Effect.scoped(
157 Effect.gen(function* () {
158 const requestId = yield* random
159 .uuidV4()
160 .pipe(
161 Effect.mapError((error) =>
162 failWith("Could not generate a desktop update request id.", error),
163 ),
164 );
165 // Subscribe before requesting to catch fast reports.
166 const { changes } = yield* receiver.desktopUpdates;
167 yield* receiver
168 .requestDesktopUpdate(requestId, trackSwitch)
169 .pipe(
170 Effect.mapError((error) =>
171 failWith("Could not reach the T3 Code desktop app on this machine.", error),
172 ),
173 );
174 return yield* consumeReports(
175 requestId,
176 changes,
177 reportProgress,
178 trackSwitch !== undefined,
179 ).pipe(
180 Effect.onInterrupt(() => receiver.cancelDesktopUpdate(requestId).pipe(Effect.ignore)),
181 );
182 }),
183 ).pipe(
184 Effect.timeout(DESKTOP_UPDATE_TIMEOUT),
185 Effect.catchTags({
186 TimeoutError: () => failWith("The desktop app did not finish the update in time."),
187 }),
188 Effect.onError(() => Ref.set(inFlight, false)),
189 );
190 },
191 );
192​
193 const commit: DesktopAppUpdate["Service"]["commit"] = Effect.fn(
194 "desktopUpdate.desktopAppUpdate.commit",
195 )(function* (requestId, onHandoffAccepted = () => Effect.void) {
196 if (!available) {
197 return yield* failWith("This server cannot commit a desktop app update.");
198 }
199 const terminal = yield* Effect.scoped(
200 Effect.gen(function* () {
201 const { latest, changes } = yield* receiver.desktopUpdates;
202 const reports = Option.match(latest, {
203 onNone: () => changes,
204 onSome: (report) => Stream.concat(Stream.make(report), changes),
205 });
206 yield* Effect.uninterruptible(
207 receiver.commitDesktopUpdate(requestId).pipe(
208 Effect.mapError((error) => failWith("Could not reach the T3 Code desktop app.", error)),
209 Effect.tap(() => onHandoffAccepted()),
210 ),
211 );
212 return yield* reports.pipe(
213 Stream.filter((report) => report.requestId === requestId && report.outcome === "failed"),
214 Stream.runHead,
215 Effect.timeout(DESKTOP_INSTALL_TIMEOUT),
216 Effect.catchTags({
217 TimeoutError: () =>
218 failWith("The desktop app did not report an install result in time."),
219 }),
220 );
221 }),
222 );
223 if (Option.isNone(terminal)) {
224 return yield* failWith("The desktop app stopped reporting the install.");
225 }
226 return yield* failWith(
227 terminal.value.reason ??
228 terminal.value.state.message ??
229 "The desktop app failed to install the update.",
230 );
231 });
232​
233 return DesktopAppUpdate.of({ available, run, commit });
234});
235​
236export const layer = Layer.effect(DesktopAppUpdate, make());