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

DesktopAppUpdate.ts

222 lines7.9 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 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 }
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 = Effect.fn("DesktopAppUpdate.consumeReports")(function* (
70 requestId: string,
71 changes: Stream.Stream<DesktopUpdateStatusReport>,
72 reportProgress: (
73 stage: ServerSelfUpdateProgressStage,
74 ) => Effect.Effect<void, ServerSelfUpdateError>,
75 ) {
76 const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
77 const emitStage = (
78 stage: ServerSelfUpdateProgressStage | null,
79 ): Effect.Effect<void, ServerSelfUpdateError> =>
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>, ServerSelfUpdateError> =>
94 report.outcome === undefined
95 ? emitStage(desktopUpdateProgressStage(report.state)).pipe(
96 Effect.as(Option.none<DesktopUpdateStatusReport>()),
97 )
98 : Effect.succeedSome(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
149 .randomUUIDv4()
150 .pipe(
151 Effect.mapError((error) =>
152 failWith("Could not generate a desktop update request id.", error),
153 ),
154 );
155 // Subscribe before sending the request so a fast first report
156 // cannot be missed.
157 const { changes } = yield* receiver.desktopUpdates;
158 yield* receiver
159 .requestDesktopUpdate(requestId)
160 .pipe(
161 Effect.mapError((error) =>
162 failWith("Could not reach the T3 Code desktop app on this machine.", error),
163 ),
164 );
165 return yield* consumeReports(requestId, changes, reportProgress).pipe(
166 Effect.onInterrupt(() => receiver.cancelDesktopUpdate(requestId).pipe(Effect.ignore)),
167 );
168 }),
169 ).pipe(
170 Effect.timeout(DESKTOP_UPDATE_TIMEOUT),
171 Effect.catchTags({
172 TimeoutError: () => failWith("The desktop app did not finish the update in time."),
173 }),
174 Effect.onError(() => Ref.set(inFlight, false)),
175 );
176 },
177 );
178​
179 const commit: DesktopAppUpdate["Service"]["commit"] = Effect.fn(
180 "desktopUpdate.desktopAppUpdate.commit",
181 )(function* (requestId, onHandoffAccepted = () => Effect.void) {
182 if (!available) {
183 return yield* failWith("This server cannot commit a desktop app update.");
184 }
185 const terminal = yield* Effect.scoped(
186 Effect.gen(function* () {
187 const { latest, changes } = yield* receiver.desktopUpdates;
188 const reports = Option.match(latest, {
189 onNone: () => changes,
190 onSome: (report) => Stream.concat(Stream.make(report), changes),
191 });
192 yield* Effect.uninterruptible(
193 receiver.commitDesktopUpdate(requestId).pipe(
194 Effect.mapError((error) => failWith("Could not reach the T3 Code desktop app.", error)),
195 Effect.tap(() => onHandoffAccepted()),
196 ),
197 );
198 return yield* reports.pipe(
199 Stream.filter((report) => report.requestId === requestId && report.outcome === "failed"),
200 Stream.runHead,
201 Effect.timeout(DESKTOP_INSTALL_TIMEOUT),
202 Effect.catchTags({
203 TimeoutError: () =>
204 failWith("The desktop app did not report an install result in time."),
205 }),
206 );
207 }),
208 );
209 if (Option.isNone(terminal)) {
210 return yield* failWith("The desktop app stopped reporting the install.");
211 }
212 return yield* failWith(
213 terminal.value.reason ??
214 terminal.value.state.message ??
215 "The desktop app failed to install the update.",
216 );
217 });
218​
219 return DesktopAppUpdate.of({ available, run, commit });
220});
221​
222export const layer = Layer.effect(DesktopAppUpdate, make());