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 the server; returns only on installation failure or timeout. */
49 readonly commit: (
50 requestId: string,
51 onHandoffAccepted?: () => Effect.Effect<void>,
52 ) => Effect.Effect<never, ServerSelfUpdateError>;
53 }
54>()("t3/desktopUpdate/DesktopAppUpdate") {}
55
56export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* () {
57 const config = yield* ServerConfig.ServerConfig;
58 const crypto = yield* Crypto.Crypto;
59 const receiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
60 const inFlight = yield* Ref.make(false);
61
62 const available = config.mode === "desktop" && config.desktopTelemetryControlFd !== undefined;
63 const failWith = (reason: string, cause?: unknown) =>
64 cause === undefined
65 ? new ServerSelfUpdateError({ reason })
66 : new ServerSelfUpdateError({ reason, cause });
67
68 const consumeReports = Effect.fn("DesktopAppUpdate.consumeReports")(function* (
69 requestId: string,
70 changes: Stream.Stream<DesktopUpdateStatusReport>,
71 reportProgress: (
72 stage: ServerSelfUpdateProgressStage,
73 ) => Effect.Effect<void, ServerSelfUpdateError>,
74 ) {
75 const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
76 const emitStage = (
77 stage: ServerSelfUpdateProgressStage | null,
78 ): Effect.Effect<void, ServerSelfUpdateError> =>
79 stage === null
80 ? Effect.void
81 : Ref.get(lastStage).pipe(
82 Effect.flatMap((previous) =>
83 previous === stage
84 ? Effect.void
85 : Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),
86 ),
87 );
88
89 const terminal = yield* changes.pipe(
90 Stream.filter((report) => report.requestId === requestId),
91 Stream.mapEffect(
92 (report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>
93 report.outcome === undefined
94 ? emitStage(desktopUpdateProgressStage(report.state)).pipe(
95 Effect.as(Option.none<DesktopUpdateStatusReport>()),
96 )
97 : Effect.succeedSome(report),
98 ),
99 Stream.filterMap(
100 Option.match({
101 onNone: () => Result.failVoid,
102 onSome: Result.succeed,
103 }),
104 ),
105 Stream.runHead,
106 );
107 if (Option.isNone(terminal)) {
108 return yield* failWith("The desktop app stopped reporting its update.");
109 }
110
111 const report = terminal.value;
112 if (report.outcome === "ready-to-install") {
113 yield* emitStage("installing");
114 const targetVersion =
115 report.state.downloadedVersion ??
116 report.state.availableVersion ??
117 report.state.currentVersion;
118 yield* Effect.logInfo("Desktop app update prepared for install.", {
119 targetVersion,
120 });
121 yield* Ref.set(inFlight, false);
122 return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };
123 }
124 if (report.outcome === "up-to-date") {
125 return yield* failWith(
126 `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
127 );
128 }
129 return yield* failWith(
130 report.reason ?? report.state.message ?? "The desktop app update failed.",
131 );
132 });
133
134 const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
135 function* (reportProgress) {
136 if (!available) {
137 return yield* failWith(
138 "This server was not started by the T3 Code desktop app, so it cannot drive a desktop update.",
139 );
140 }
141 if (yield* Ref.getAndSet(inFlight, true)) {
142 return yield* failWith("A desktop app update is already in progress.");
143 }
144
145 return yield* Effect.scoped(
146 Effect.gen(function* () {
147 const requestId = yield* crypto
148 .randomUUIDv4()
149 .pipe(
150 Effect.mapError((error) =>
151 failWith("Could not generate a desktop update request id.", error),
152 ),
153 );
154 // Subscribe before requesting to catch fast reports.
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, onHandoffAccepted = () => Effect.void) {
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* Effect.uninterruptible(
191 receiver.commitDesktopUpdate(requestId).pipe(
192 Effect.mapError((error) => failWith("Could not reach the T3 Code desktop app.", error)),
193 Effect.tap(() => onHandoffAccepted()),
194 ),
195 );
196 return yield* reports.pipe(
197 Stream.filter((report) => report.requestId === requestId && report.outcome === "failed"),
198 Stream.runHead,
199 Effect.timeout(DESKTOP_INSTALL_TIMEOUT),
200 Effect.catchTags({
201 TimeoutError: () =>
202 failWith("The desktop app did not report an install result in time."),
203 }),
204 );
205 }),
206 );
207 if (Option.isNone(terminal)) {
208 return yield* failWith("The desktop app stopped reporting the install.");
209 }
210 return yield* failWith(
211 terminal.value.reason ??
212 terminal.value.state.message ??
213 "The desktop app failed to install the update.",
214 );
215 });
216
217 return DesktopAppUpdate.of({ available, run, commit });
218});
219
220export const layer = Layer.effect(DesktopAppUpdate, make());