Open History to see the last commit
1import type {
2 DesktopTelemetryRequestDesktopUpdate,
3 DesktopUpdateRemoteOutcome,
4 DesktopUpdateState,
5} from "@t3tools/contracts";
6import * as Duration from "effect/Duration";
7import * as Clock from "effect/Clock";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Queue from "effect/Queue";
12import * as Ref from "effect/Ref";
13import type * as Scope from "effect/Scope";
14import * as Stream from "effect/Stream";
15
16import * as DesktopObservability from "../app/DesktopObservability.ts";
17import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
18import * as DesktopUpdates from "./DesktopUpdates.ts";
19import {
20 nextRemoteDesktopUpdateStep,
21 normalizeRemoteUpdateReason,
22 type RemoteDesktopUpdateAttempts,
23} from "./remoteUpdateFlow.ts";
24
25const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-remote-updates");
26
27const ACTION_RETRY_DELAY = Duration.millis(250);
28const PREPARED_UPDATE_TTL = Duration.minutes(5);
29
30interface PreparedUpdate {
31 readonly requestId: string;
32 readonly downloadedVersion: string;
33 readonly status: "prepared" | "committing" | "failed";
34 readonly failureReason?: string;
35 readonly expiresAt: number;
36}
37
38type CommitClaim =
39 | { readonly _tag: "invalid" }
40 | { readonly _tag: "failed"; readonly prepared: PreparedUpdate }
41 | { readonly _tag: "committing" }
42 | { readonly _tag: "claimed"; readonly prepared: PreparedUpdate };
43
44export const listen: Effect.Effect<
45 void,
46 never,
47 DesktopUpdates.DesktopUpdates | DesktopTelemetryPublisher.DesktopTelemetryPublisher | Scope.Scope
48> = Effect.gen(function* () {
49 const updates = yield* DesktopUpdates.DesktopUpdates;
50 const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
51 const activeRequestIdRef = yield* Ref.make(Option.none<string>());
52 const requestControlRef = yield* Ref.make<{
53 readonly active: Option.Option<{
54 readonly requestId: string;
55 readonly signal: Deferred.Deferred<void>;
56 }>;
57 readonly cancelledBeforeStart: ReadonlyArray<string>;
58 }>({ active: Option.none(), cancelledBeforeStart: [] });
59 const preparedUpdateRef = yield* Ref.make(Option.none<PreparedUpdate>());
60
61 const publishReport = (
62 state: DesktopUpdateState,
63 terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string },
64 explicitRequestId?: string,
65 ): Effect.Effect<void> => {
66 const reason = normalizeRemoteUpdateReason(terminal?.reason);
67 return Ref.get(activeRequestIdRef).pipe(
68 Effect.flatMap((requestId) =>
69 publisher.publishUpdateReport({
70 version: 1,
71 type: "desktopUpdateStatus",
72 ...(explicitRequestId !== undefined
73 ? { requestId: explicitRequestId }
74 : Option.isSome(requestId)
75 ? { requestId: requestId.value }
76 : {}),
77 ...(terminal === undefined ? {} : { outcome: terminal.outcome }),
78 ...(reason ? { reason } : {}),
79 state,
80 }),
81 ),
82 );
83 };
84
85 const recordPreparedFailure = (requestId: string, reason: string) =>
86 Ref.modify(preparedUpdateRef, (prepared) => {
87 if (
88 Option.isNone(prepared) ||
89 prepared.value.requestId !== requestId ||
90 prepared.value.status === "failed"
91 ) {
92 return [false, prepared] as const;
93 }
94 return [
95 true,
96 Option.some({ ...prepared.value, status: "failed" as const, failureReason: reason }),
97 ] as const;
98 });
99
100 const clearActiveRequest = (requestId: string) =>
101 Ref.update(activeRequestIdRef, (active) =>
102 Option.isSome(active) && active.value === requestId ? Option.none() : active,
103 );
104
105 yield* Effect.scoped(
106 Effect.gen(function* () {
107 const { latest, changes } = yield* updates.subscribe;
108 yield* publishReport(latest);
109 yield* Stream.runForEach(changes, (state) =>
110 Effect.gen(function* () {
111 yield* publishReport(state);
112 const prepared = yield* Ref.get(preparedUpdateRef);
113 if (
114 Option.isSome(prepared) &&
115 prepared.value.status === "committing" &&
116 state.errorContext === "install"
117 ) {
118 const reason = state.message ?? "The desktop app failed to install the update.";
119 if (yield* recordPreparedFailure(prepared.value.requestId, reason)) {
120 yield* publishReport(state, { outcome: "failed", reason }, prepared.value.requestId);
121 }
122 }
123 }),
124 );
125 }),
126 ).pipe(Effect.forkScoped);
127
128 const handleRequest = (request: DesktopTelemetryRequestDesktopUpdate): Effect.Effect<void> =>
129 Effect.scoped(
130 Effect.gen(function* () {
131 const cancellation = yield* Deferred.make<void>();
132 const shouldStart = yield* Ref.modify(requestControlRef, (control) => {
133 if (control.cancelledBeforeStart.includes(request.requestId)) {
134 return [
135 false,
136 {
137 ...control,
138 cancelledBeforeStart: control.cancelledBeforeStart.filter(
139 (requestId) => requestId !== request.requestId,
140 ),
141 },
142 ] as const;
143 }
144 return [
145 true,
146 {
147 ...control,
148 active: Option.some({ requestId: request.requestId, signal: cancellation }),
149 },
150 ] as const;
151 });
152 if (!shouldStart) return;
153
154 const now = yield* Clock.currentTimeMillis;
155 const prepared = yield* Ref.modify(preparedUpdateRef, (current) =>
156 Option.isSome(current) &&
157 current.value.status === "prepared" &&
158 current.value.expiresAt <= now
159 ? ([Option.none<typeof current.value>(), Option.none()] as const)
160 : ([current, current] as const),
161 );
162 if (Option.isSome(prepared) && prepared.value.status !== "failed") {
163 yield* publishReport(
164 yield* updates.getState,
165 {
166 outcome: "failed",
167 reason: "A prepared desktop update is already in progress.",
168 },
169 request.requestId,
170 );
171 return;
172 }
173 yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
174 yield* logInfo("remote update requested", { requestId: request.requestId });
175 const { latest, changes } = yield* updates.subscribe;
176 const disabledReason = Option.getOrNull(yield* updates.disabledReason);
177 let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
178 // State events can precede reservation release; re-enqueue refused actions so they retry after release.
179 const retries = yield* Queue.unbounded<DesktopUpdateState>();
180 const retryLater = (state: DesktopUpdateState) =>
181 Effect.sleep(ACTION_RETRY_DELAY).pipe(
182 Effect.andThen(Queue.offer(retries, state)),
183 Effect.asVoid,
184 Effect.forkScoped,
185 );
186
187 const step = Effect.fn("DesktopRemoteUpdates.step")(function* (
188 state: DesktopUpdateState,
189 ): Effect.fn.Return<boolean, never, Scope.Scope> {
190 const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
191 switch (next.action) {
192 case "wait":
193 return false;
194 case "check":
195 attempts = { ...attempts, checks: attempts.checks + 1 };
196 yield* updates.check("remote-update").pipe(
197 Effect.flatMap((result) => {
198 if (result.checked) return Effect.void;
199 attempts = { ...attempts, checks: attempts.checks - 1 };
200 return retryLater(state);
201 }),
202 Effect.forkScoped,
203 );
204 return false;
205 case "download":
206 attempts = { ...attempts, downloads: attempts.downloads + 1 };
207 yield* updates.download.pipe(
208 Effect.flatMap((result) => {
209 if (result.accepted) return Effect.void;
210 attempts = { ...attempts, downloads: attempts.downloads - 1 };
211 return retryLater(state);
212 }),
213 Effect.forkScoped,
214 );
215 return false;
216 case "install": {
217 // The download event fires before its action releases the
218 // updater reservation. Wait until the prepared install can
219 // be committed by the client in a separate RPC.
220 if (yield* updates.isActionActive) {
221 yield* retryLater(state);
222 return false;
223 }
224 if (state.downloadedVersion === null) {
225 yield* publishReport(
226 state,
227 {
228 outcome: "failed",
229 reason: "The desktop app lost the downloaded update.",
230 },
231 request.requestId,
232 );
233 return true;
234 }
235 yield* Ref.set(
236 preparedUpdateRef,
237 Option.some({
238 requestId: request.requestId,
239 downloadedVersion: state.downloadedVersion,
240 status: "prepared",
241 expiresAt:
242 (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),
243 }),
244 );
245 yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);
246 yield* logInfo("remote update prepared", { requestId: request.requestId });
247 return true;
248 }
249 case "done":
250 yield* publishReport(
251 state,
252 {
253 outcome: next.outcome,
254 ...(next.reason === undefined ? {} : { reason: next.reason }),
255 },
256 request.requestId,
257 );
258 yield* logInfo("remote update finished", {
259 requestId: request.requestId,
260 outcome: next.outcome,
261 reason: next.reason ?? null,
262 });
263 return true;
264 }
265 });
266
267 yield* Effect.raceFirst(
268 Effect.gen(function* () {
269 if (yield* step(latest)) return;
270 yield* Stream.merge(changes, Stream.fromQueue(retries)).pipe(
271 Stream.mapEffect(step),
272 Stream.takeUntil((done) => done),
273 Stream.runDrain,
274 );
275 }),
276 Deferred.await(cancellation),
277 );
278 }),
279 ).pipe(
280 Effect.ensuring(
281 Effect.all(
282 [
283 clearActiveRequest(request.requestId),
284 Ref.update(requestControlRef, (control) => ({
285 ...control,
286 active:
287 Option.isSome(control.active) &&
288 control.active.value.requestId === request.requestId
289 ? Option.none()
290 : control.active,
291 })),
292 ],
293 { discard: true },
294 ),
295 ),
296 Effect.catchCause((cause) =>
297 logError("remote update request failed unexpectedly", {
298 requestId: request.requestId,
299 cause: String(cause),
300 }),
301 ),
302 );
303
304 yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
305
306 yield* Stream.runForEach(publisher.updateCancellations, (cancellation) =>
307 Effect.gen(function* () {
308 const activeSignal = yield* Ref.modify(requestControlRef, (control) => {
309 if (
310 Option.isSome(control.active) &&
311 control.active.value.requestId === cancellation.requestId
312 ) {
313 return [Option.some(control.active.value.signal), control] as const;
314 }
315 return [
316 Option.none<Deferred.Deferred<void>>(),
317 {
318 ...control,
319 cancelledBeforeStart: [
320 ...control.cancelledBeforeStart.filter(
321 (requestId) => requestId !== cancellation.requestId,
322 ),
323 cancellation.requestId,
324 ],
325 },
326 ] as const;
327 });
328 if (Option.isSome(activeSignal)) {
329 yield* Deferred.succeed(activeSignal.value, undefined);
330 }
331 const matchedPrepared = yield* Ref.modify(preparedUpdateRef, (prepared) => {
332 if (Option.isNone(prepared) || prepared.value.requestId !== cancellation.requestId) {
333 return [false, prepared] as const;
334 }
335 return [true, prepared.value.status === "prepared" ? Option.none() : prepared] as const;
336 });
337 if (matchedPrepared) {
338 yield* Ref.update(requestControlRef, (control) => {
339 return {
340 ...control,
341 cancelledBeforeStart: control.cancelledBeforeStart.filter(
342 (requestId) => requestId !== cancellation.requestId,
343 ),
344 };
345 });
346 }
347 }),
348 ).pipe(Effect.forkScoped);
349
350 yield* Stream.runForEach(publisher.updateCommits, (commit) =>
351 Effect.gen(function* () {
352 const current = yield* updates.getState;
353 const now = yield* Clock.currentTimeMillis;
354 const claim = yield* Ref.modify(
355 preparedUpdateRef,
356 (prepared): readonly [CommitClaim, Option.Option<PreparedUpdate>] => {
357 if (
358 Option.isNone(prepared) ||
359 prepared.value.requestId !== commit.requestId ||
360 (prepared.value.status === "prepared" && prepared.value.expiresAt <= now)
361 ) {
362 return [{ _tag: "invalid" as const }, prepared] as const;
363 }
364 if (prepared.value.status === "failed") {
365 return [{ _tag: "failed" as const, prepared: prepared.value }, prepared] as const;
366 }
367 if (prepared.value.status === "committing") {
368 return [{ _tag: "committing" as const }, prepared] as const;
369 }
370 return [
371 { _tag: "claimed" as const, prepared: prepared.value },
372 Option.some({ ...prepared.value, status: "committing" as const }),
373 ] as const;
374 },
375 );
376 if (claim._tag === "invalid") {
377 yield* publishReport(
378 yield* updates.getState,
379 {
380 outcome: "failed",
381 reason: "This desktop update is no longer prepared.",
382 },
383 commit.requestId,
384 );
385 return;
386 }
387 if (claim._tag === "failed") {
388 yield* publishReport(
389 current,
390 {
391 outcome: "failed",
392 reason: claim.prepared.failureReason ?? "The desktop app failed to install the update.",
393 },
394 commit.requestId,
395 );
396 return;
397 }
398 if (claim._tag === "committing") {
399 return;
400 }
401 yield* Ref.set(activeRequestIdRef, Option.some(commit.requestId));
402 if (current.downloadedVersion !== claim.prepared.downloadedVersion) {
403 const reason = "This desktop update is no longer prepared.";
404 if (yield* recordPreparedFailure(commit.requestId, reason)) {
405 yield* publishReport(current, { outcome: "failed", reason }, commit.requestId);
406 }
407 return;
408 }
409 const result = yield* updates.installPrepared(claim.prepared.downloadedVersion);
410 if (
411 !result.accepted &&
412 result.state.downloadedVersion === claim.prepared.downloadedVersion &&
413 (yield* updates.isInstallActive)
414 ) {
415 // Join the existing install; reconnect and target-version checks prove its handoff.
416 yield* logInfo("remote update commit joining an in-progress install", {
417 requestId: commit.requestId,
418 });
419 return;
420 }
421 if (!result.accepted || result.failed) {
422 const reason = result.state.message ?? "The desktop app could not start the install.";
423 if (yield* recordPreparedFailure(commit.requestId, reason)) {
424 yield* publishReport(result.state, { outcome: "failed", reason }, commit.requestId);
425 }
426 return;
427 }
428 // Installation kills this backend; only transport loss followed by the target version proves handoff.
429 }).pipe(
430 Effect.ensuring(clearActiveRequest(commit.requestId)),
431 Effect.catchCause((cause) =>
432 logError("remote update commit failed unexpectedly", {
433 requestId: commit.requestId,
434 cause: String(cause),
435 }),
436 ),
437 ),
438 ).pipe(Effect.forkScoped);
439});