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 { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
14import { compareSemverVersions } from "@t3tools/shared/semver";
15import type * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17
18import * as DesktopObservability from "../app/DesktopObservability.ts";
19import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
20import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
21import * as DesktopUpdates from "./DesktopUpdates.ts";
22import {
23 nextRemoteDesktopUpdateStep,
24 offersNotAppliedVersion,
25 normalizeRemoteUpdateReason,
26 type RemoteDesktopUpdateAttempts,
27} from "./remoteUpdateFlow.ts";
28
29const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-remote-updates");
30
31const ACTION_RETRY_DELAY = Duration.millis(250);
32const PREPARED_UPDATE_TTL = Duration.minutes(5);
33
34interface PreparedUpdate {
35 readonly requestId: string;
36 readonly channel: DesktopTelemetryRequestDesktopUpdate["channel"];
37 readonly targetVersion: DesktopTelemetryRequestDesktopUpdate["targetVersion"];
38 readonly downloadedVersion: string;
39 readonly status: "prepared" | "committing" | "failed";
40 readonly failureReason?: string;
41 readonly expiresAt: number;
42}
43
44type CommitClaim =
45 | { readonly _tag: "invalid" }
46 | { readonly _tag: "failed"; readonly prepared: PreparedUpdate }
47 | { readonly _tag: "committing" }
48 | { readonly _tag: "claimed"; readonly prepared: PreparedUpdate };
49
50export const listen: Effect.Effect<
51 void,
52 never,
53 | DesktopUpdates.DesktopUpdates
54 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
55 | DesktopBackendPool.DesktopBackendPool
56 | Scope.Scope
57> = Effect.gen(function* () {
58 const updates = yield* DesktopUpdates.DesktopUpdates;
59 const backends = yield* DesktopBackendPool.DesktopBackendPool;
60 const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
61 const activeRequestIdRef = yield* Ref.make(Option.none<string>());
62 const requestControlRef = yield* Ref.make<{
63 readonly active: Option.Option<{
64 readonly requestId: string;
65 readonly signal: Deferred.Deferred<void>;
66 }>;
67 readonly cancelledBeforeStart: ReadonlyArray<string>;
68 }>({ active: Option.none(), cancelledBeforeStart: [] });
69 const preparedUpdateRef = yield* Ref.make(Option.none<PreparedUpdate>());
70
71 const publishReport = (
72 state: DesktopUpdateState,
73 terminal?: {
74 readonly outcome: DesktopUpdateRemoteOutcome;
75 readonly reason?: string;
76 readonly preparedRequestId?: string;
77 },
78 explicitRequestId?: string,
79 ): Effect.Effect<void> => {
80 const reason = normalizeRemoteUpdateReason(terminal?.reason);
81 return Ref.get(activeRequestIdRef).pipe(
82 Effect.flatMap((requestId) =>
83 publisher.publishUpdateReport({
84 version: 1,
85 type: "desktopUpdateStatus",
86 ...(explicitRequestId !== undefined
87 ? { requestId: explicitRequestId }
88 : Option.isSome(requestId)
89 ? { requestId: requestId.value }
90 : {}),
91 ...(terminal === undefined ? {} : { outcome: terminal.outcome }),
92 ...(terminal?.preparedRequestId === undefined
93 ? {}
94 : { preparedRequestId: terminal.preparedRequestId }),
95 ...(reason ? { reason } : {}),
96 state,
97 }),
98 ),
99 );
100 };
101
102 const recordPreparedFailure = (requestId: string, reason: string) =>
103 Ref.modify(preparedUpdateRef, (prepared) => {
104 if (
105 Option.isNone(prepared) ||
106 prepared.value.requestId !== requestId ||
107 prepared.value.status === "failed"
108 ) {
109 return [false, prepared] as const;
110 }
111 return [
112 true,
113 Option.some({ ...prepared.value, status: "failed" as const, failureReason: reason }),
114 ] as const;
115 });
116
117 const clearActiveRequest = (requestId: string) =>
118 Ref.update(activeRequestIdRef, (active) =>
119 Option.isSome(active) && active.value === requestId ? Option.none() : active,
120 );
121
122 yield* Effect.scoped(
123 Effect.gen(function* () {
124 const { latest, changes } = yield* updates.subscribe;
125 yield* publishReport(latest);
126 yield* Stream.runForEach(changes, (state) =>
127 Effect.gen(function* () {
128 yield* publishReport(state);
129 const prepared = yield* Ref.get(preparedUpdateRef);
130 if (
131 Option.isSome(prepared) &&
132 prepared.value.status === "committing" &&
133 state.errorContext === "install"
134 ) {
135 const reason = state.message ?? "The desktop app failed to install the update.";
136 if (yield* recordPreparedFailure(prepared.value.requestId, reason)) {
137 yield* publishReport(state, { outcome: "failed", reason }, prepared.value.requestId);
138 }
139 }
140 }),
141 );
142 }),
143 ).pipe(Effect.forkScoped);
144
145 const handleRequest = (request: DesktopTelemetryRequestDesktopUpdate): Effect.Effect<void> =>
146 Effect.scoped(
147 Effect.gen(function* () {
148 const cancellation = yield* Deferred.make<void>();
149 const shouldStart = yield* Ref.modify(requestControlRef, (control) => {
150 if (control.cancelledBeforeStart.includes(request.requestId)) {
151 return [
152 false,
153 {
154 ...control,
155 cancelledBeforeStart: control.cancelledBeforeStart.filter(
156 (requestId) => requestId !== request.requestId,
157 ),
158 },
159 ] as const;
160 }
161 return [
162 true,
163 {
164 ...control,
165 active: Option.some({ requestId: request.requestId, signal: cancellation }),
166 },
167 ] as const;
168 });
169 if (!shouldStart) return;
170
171 const now = yield* Clock.currentTimeMillis;
172 // One snapshot decides both clearing and reuse, so a replacement download landing between
173 // two reads cannot report a stale preparation as busy.
174 const state = yield* updates.getState;
175 const prepared = yield* Ref.modify(preparedUpdateRef, (current) =>
176 Option.isSome(current) &&
177 current.value.status === "prepared" &&
178 (current.value.expiresAt <= now ||
179 current.value.downloadedVersion !== state.downloadedVersion)
180 ? ([Option.none<typeof current.value>(), Option.none()] as const)
181 : ([current, current] as const),
182 );
183 if (Option.isSome(prepared) && prepared.value.status !== "failed") {
184 if (
185 prepared.value.status === "prepared" &&
186 prepared.value.channel === request.channel &&
187 prepared.value.targetVersion === request.targetVersion &&
188 state.downloadedVersion === prepared.value.downloadedVersion
189 ) {
190 yield* publishReport(
191 state,
192 { outcome: "ready-to-install", preparedRequestId: prepared.value.requestId },
193 request.requestId,
194 );
195 return;
196 }
197 yield* publishReport(
198 state,
199 {
200 outcome: "failed",
201 reason: "A prepared desktop update is already in progress.",
202 },
203 request.requestId,
204 );
205 return;
206 }
207 yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
208 yield* logInfo("remote update requested", {
209 requestId: request.requestId,
210 channel: request.channel,
211 });
212 // A switch saves its track first, so the step machine never sees the old track's offer.
213 // The saved track is the user's intent and stays even if this request fails: a track saved
214 // toward Stable never offers an older build outside a guarded switch.
215 if (request.channel !== undefined) {
216 // A reinstall restarts every backend, but the requesting server checked only its own
217 // database. A WSL backend keeps its own, so cross tracks only where all can be checked.
218 const current = yield* updates.getState;
219 if (
220 desktopUpdateChannelOf(current.currentVersion) !== request.channel &&
221 (yield* backends.list).length > 1
222 ) {
223 yield* publishReport(
224 current,
225 {
226 outcome: "failed",
227 reason:
228 "This desktop app also runs WSL backends, whose databases a remote switch cannot check. Switch it on that machine.",
229 },
230 request.requestId,
231 );
232 return;
233 }
234 const switched = yield* Effect.raceFirst(
235 updates.setChannel(request.channel, { minimumVersion: request.targetVersion }).pipe(
236 Effect.as(true),
237 Effect.catch((error) =>
238 updates.getState.pipe(
239 Effect.flatMap((state) =>
240 publishReport(
241 state,
242 { outcome: "failed", reason: error.message },
243 request.requestId,
244 ),
245 ),
246 Effect.as(false),
247 ),
248 ),
249 ),
250 Deferred.await(cancellation).pipe(Effect.as(false)),
251 );
252 if (!switched) return;
253 // A host already running the target only needed its track saved; installing a newer
254 // build here would restart it without the dialog having said so.
255 const state = yield* updates.getState;
256 if (request.targetVersion === state.currentVersion) {
257 yield* publishReport(state, { outcome: "up-to-date" }, request.requestId);
258 return;
259 }
260 }
261 const { latest, changes } = yield* updates.subscribe;
262 const disabledReason = Option.getOrNull(yield* updates.disabledReason);
263 let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
264 // State events can precede reservation release; re-enqueue refused actions so they retry after release.
265 const retries = yield* Queue.unbounded<DesktopUpdateState>();
266 const retryLater = (state: DesktopUpdateState) =>
267 Effect.sleep(ACTION_RETRY_DELAY).pipe(
268 Effect.andThen(Queue.offer(retries, state)),
269 Effect.asVoid,
270 Effect.forkScoped,
271 );
272
273 // A host leaving its build's track may need an older build, down to the checked release;
274 // the updater offers nothing below it.
275 const crossing = (state: DesktopUpdateState) =>
276 request.channel !== undefined &&
277 request.targetVersion !== undefined &&
278 desktopUpdateChannelOf(state.currentVersion) !== request.channel;
279 const step = Effect.fn("DesktopRemoteUpdates.step")(function* (
280 state: DesktopUpdateState,
281 ): Effect.fn.Return<boolean, never, Scope.Scope> {
282 const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
283 switch (next.action) {
284 case "wait":
285 return false;
286 case "check":
287 attempts = { ...attempts, checks: attempts.checks + 1 };
288 yield* updates.check("remote-update", { allowDowngrade: crossing(state) }).pipe(
289 Effect.flatMap((result) => {
290 // A feed still offering the failed version emits no state change to step on.
291 if (result.checked) {
292 return offersNotAppliedVersion(result.state)
293 ? Queue.offer(retries, result.state).pipe(Effect.asVoid)
294 : Effect.void;
295 }
296 attempts = { ...attempts, checks: attempts.checks - 1 };
297 return retryLater(state);
298 }),
299 Effect.forkScoped,
300 );
301 return false;
302 case "download":
303 attempts = { ...attempts, downloads: attempts.downloads + 1 };
304 yield* updates.download.pipe(
305 Effect.flatMap((result) => {
306 if (result.accepted) return Effect.void;
307 attempts = { ...attempts, downloads: attempts.downloads - 1 };
308 return retryLater(state);
309 }),
310 Effect.forkScoped,
311 );
312 return false;
313 case "install": {
314 // The download event fires before its action releases the
315 // updater reservation. Wait until the prepared install can
316 // be committed by the client in a separate RPC.
317 if (yield* updates.isActionActive) {
318 yield* retryLater(state);
319 return false;
320 }
321 if (state.downloadedVersion === null) {
322 yield* publishReport(
323 state,
324 {
325 outcome: "failed",
326 reason: "The desktop app lost the downloaded update.",
327 },
328 request.requestId,
329 );
330 return true;
331 }
332 yield* Ref.set(
333 preparedUpdateRef,
334 Option.some({
335 requestId: request.requestId,
336 channel: request.channel,
337 targetVersion: request.targetVersion,
338 downloadedVersion: state.downloadedVersion,
339 status: "prepared",
340 expiresAt:
341 (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),
342 }),
343 );
344 yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);
345 yield* logInfo("remote update prepared", { requestId: request.requestId });
346 return true;
347 }
348 case "done": {
349 // A switch that leaves the host on its old track, or below its checked release, did
350 // not reach it; a track-only host already at the release is done.
351 const done =
352 request.targetVersion !== undefined &&
353 next.outcome === "up-to-date" &&
354 (crossing(state) ||
355 compareSemverVersions(state.currentVersion, request.targetVersion) < 0)
356 ? {
357 outcome: "failed" as const,
358 reason: `The desktop app found no build of ${request.targetVersion}.`,
359 }
360 : next;
361 yield* publishReport(
362 state,
363 {
364 outcome: done.outcome,
365 ...(done.reason === undefined ? {} : { reason: done.reason }),
366 },
367 request.requestId,
368 );
369 yield* logInfo("remote update finished", {
370 requestId: request.requestId,
371 outcome: done.outcome,
372 reason: done.reason ?? null,
373 });
374 return true;
375 }
376 }
377 });
378
379 yield* Effect.raceFirst(
380 Effect.gen(function* () {
381 if (yield* step(latest)) return;
382 yield* Stream.merge(changes, Stream.fromQueue(retries)).pipe(
383 Stream.mapEffect(step),
384 Stream.takeUntil((done) => done),
385 Stream.runDrain,
386 );
387 }),
388 Deferred.await(cancellation),
389 );
390 }),
391 ).pipe(
392 Effect.ensuring(
393 Effect.all(
394 [
395 clearActiveRequest(request.requestId),
396 Ref.update(requestControlRef, (control) => ({
397 ...control,
398 active:
399 Option.isSome(control.active) &&
400 control.active.value.requestId === request.requestId
401 ? Option.none()
402 : control.active,
403 })),
404 ],
405 { discard: true },
406 ),
407 ),
408 Effect.catchCause((cause) =>
409 logError("remote update request failed unexpectedly", {
410 requestId: request.requestId,
411 cause: String(cause),
412 }),
413 ),
414 );
415
416 yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
417
418 yield* Stream.runForEach(publisher.updateCancellations, (cancellation) =>
419 Effect.gen(function* () {
420 const activeSignal = yield* Ref.modify(requestControlRef, (control) => {
421 if (
422 Option.isSome(control.active) &&
423 control.active.value.requestId === cancellation.requestId
424 ) {
425 return [Option.some(control.active.value.signal), control] as const;
426 }
427 return [
428 Option.none<Deferred.Deferred<void>>(),
429 {
430 ...control,
431 cancelledBeforeStart: [
432 ...control.cancelledBeforeStart.filter(
433 (requestId) => requestId !== cancellation.requestId,
434 ),
435 cancellation.requestId,
436 ],
437 },
438 ] as const;
439 });
440 if (Option.isSome(activeSignal)) {
441 yield* Deferred.succeed(activeSignal.value, undefined);
442 }
443 const matchedPrepared = yield* Ref.modify(preparedUpdateRef, (prepared) => {
444 if (Option.isNone(prepared) || prepared.value.requestId !== cancellation.requestId) {
445 return [false, prepared] as const;
446 }
447 return [true, prepared.value.status === "prepared" ? Option.none() : prepared] as const;
448 });
449 if (matchedPrepared) {
450 yield* Ref.update(requestControlRef, (control) => {
451 return {
452 ...control,
453 cancelledBeforeStart: control.cancelledBeforeStart.filter(
454 (requestId) => requestId !== cancellation.requestId,
455 ),
456 };
457 });
458 }
459 }),
460 ).pipe(Effect.forkScoped);
461
462 yield* Stream.runForEach(publisher.updateCommits, (commit) =>
463 Effect.gen(function* () {
464 const current = yield* updates.getState;
465 const now = yield* Clock.currentTimeMillis;
466 const claim = yield* Ref.modify(
467 preparedUpdateRef,
468 (prepared): readonly [CommitClaim, Option.Option<PreparedUpdate>] => {
469 if (
470 Option.isNone(prepared) ||
471 prepared.value.requestId !== commit.requestId ||
472 (prepared.value.status === "prepared" && prepared.value.expiresAt <= now)
473 ) {
474 return [{ _tag: "invalid" as const }, prepared] as const;
475 }
476 if (prepared.value.status === "failed") {
477 return [{ _tag: "failed" as const, prepared: prepared.value }, prepared] as const;
478 }
479 if (prepared.value.status === "committing") {
480 return [{ _tag: "committing" as const }, prepared] as const;
481 }
482 return [
483 { _tag: "claimed" as const, prepared: prepared.value },
484 Option.some({ ...prepared.value, status: "committing" as const }),
485 ] as const;
486 },
487 );
488 if (claim._tag === "invalid") {
489 yield* publishReport(
490 yield* updates.getState,
491 {
492 outcome: "failed",
493 reason: "This desktop update is no longer prepared.",
494 },
495 commit.requestId,
496 );
497 return;
498 }
499 if (claim._tag === "failed") {
500 yield* publishReport(
501 current,
502 {
503 outcome: "failed",
504 reason: claim.prepared.failureReason ?? "The desktop app failed to install the update.",
505 },
506 commit.requestId,
507 );
508 return;
509 }
510 if (claim._tag === "committing") {
511 return;
512 }
513 yield* Ref.set(activeRequestIdRef, Option.some(commit.requestId));
514 if (current.downloadedVersion !== claim.prepared.downloadedVersion) {
515 const reason = "This desktop update is no longer prepared.";
516 if (yield* recordPreparedFailure(commit.requestId, reason)) {
517 yield* publishReport(current, { outcome: "failed", reason }, commit.requestId);
518 }
519 return;
520 }
521 const result = yield* updates.installPrepared(claim.prepared.downloadedVersion);
522 if (
523 !result.accepted &&
524 result.state.downloadedVersion === claim.prepared.downloadedVersion &&
525 (yield* updates.isInstallActive)
526 ) {
527 // Join the existing install; reconnect and target-version checks prove its handoff.
528 yield* logInfo("remote update commit joining an in-progress install", {
529 requestId: commit.requestId,
530 });
531 return;
532 }
533 if (!result.accepted || result.failed) {
534 const reason = result.state.message ?? "The desktop app could not start the install.";
535 if (yield* recordPreparedFailure(commit.requestId, reason)) {
536 yield* publishReport(result.state, { outcome: "failed", reason }, commit.requestId);
537 }
538 return;
539 }
540 // Installation kills this backend; only transport loss followed by the target version proves handoff.
541 }).pipe(
542 Effect.ensuring(clearActiveRequest(commit.requestId)),
543 Effect.catchCause((cause) =>
544 logError("remote update commit failed unexpectedly", {
545 requestId: commit.requestId,
546 cause: String(cause),
547 }),
548 ),
549 ),
550 ).pipe(Effect.forkScoped);
551});