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

DesktopRemoteUpdates.ts

449 lines16.8 KB

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;
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 // A state event can land while the action that produced it still holds
179 // the reservation (e.g. "available" before the check releases), so a
180 // forked action can be refused with no later state event to retry on.
181 // Rejected actions re-enqueue their state here after a short pause so
182 // the step runs again once the reservation is free.
183 const retries = yield* Queue.unbounded<DesktopUpdateState>();
184 const retryLater = (state: DesktopUpdateState) =>
185 Effect.sleep(ACTION_RETRY_DELAY).pipe(
186 Effect.andThen(Queue.offer(retries, state)),
187 Effect.asVoid,
188 Effect.forkScoped,
189 );
190​
191 const step = Effect.fn("DesktopRemoteUpdates.step")(function* (
192 state: DesktopUpdateState,
193 ): Effect.fn.Return<boolean, never, Scope.Scope> {
194 const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
195 switch (next.action) {
196 case "wait":
197 return false;
198 case "check":
199 attempts = { ...attempts, checks: attempts.checks + 1 };
200 yield* updates.check("remote-update").pipe(
201 Effect.flatMap((result) => {
202 if (result.checked) return Effect.void;
203 attempts = { ...attempts, checks: attempts.checks - 1 };
204 return retryLater(state);
205 }),
206 Effect.forkScoped,
207 );
208 return false;
209 case "download":
210 attempts = { ...attempts, downloads: attempts.downloads + 1 };
211 yield* updates.download.pipe(
212 Effect.flatMap((result) => {
213 if (result.accepted) return Effect.void;
214 attempts = { ...attempts, downloads: attempts.downloads - 1 };
215 return retryLater(state);
216 }),
217 Effect.forkScoped,
218 );
219 return false;
220 case "install": {
221 // The download event fires before its action releases the
222 // updater reservation. Wait until the prepared install can
223 // be committed by the client in a separate RPC.
224 if (yield* updates.isActionActive) {
225 yield* retryLater(state);
226 return false;
227 }
228 if (state.downloadedVersion === null) {
229 yield* publishReport(
230 state,
231 {
232 outcome: "failed",
233 reason: "The desktop app lost the downloaded update.",
234 },
235 request.requestId,
236 );
237 return true;
238 }
239 yield* Ref.set(
240 preparedUpdateRef,
241 Option.some({
242 requestId: request.requestId,
243 downloadedVersion: state.downloadedVersion,
244 status: "prepared",
245 expiresAt:
246 (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),
247 }),
248 );
249 yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);
250 yield* logInfo("remote update prepared", { requestId: request.requestId });
251 return true;
252 }
253 case "done":
254 yield* publishReport(
255 state,
256 {
257 outcome: next.outcome,
258 ...(next.reason === undefined ? {} : { reason: next.reason }),
259 },
260 request.requestId,
261 );
262 yield* logInfo("remote update finished", {
263 requestId: request.requestId,
264 outcome: next.outcome,
265 reason: next.reason ?? null,
266 });
267 return true;
268 }
269 });
270​
271 yield* Effect.raceFirst(
272 Effect.gen(function* () {
273 if (yield* step(latest)) return;
274 yield* Stream.merge(changes, Stream.fromQueue(retries)).pipe(
275 Stream.mapEffect(step),
276 Stream.takeUntil((done) => done),
277 Stream.runDrain,
278 );
279 }),
280 Deferred.await(cancellation),
281 );
282 }),
283 ).pipe(
284 Effect.ensuring(
285 Effect.all(
286 [
287 clearActiveRequest(request.requestId),
288 Ref.update(requestControlRef, (control) => ({
289 ...control,
290 active:
291 Option.isSome(control.active) &&
292 control.active.value.requestId === request.requestId
293 ? Option.none()
294 : control.active,
295 })),
296 ],
297 { discard: true },
298 ),
299 ),
300 Effect.catchCause((cause) =>
301 logError("remote update request failed unexpectedly", {
302 requestId: request.requestId,
303 cause: String(cause),
304 }),
305 ),
306 );
307​
308 yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
309​
310 yield* Stream.runForEach(publisher.updateCancellations, (cancellation) =>
311 Effect.gen(function* () {
312 const activeSignal = yield* Ref.modify(requestControlRef, (control) => {
313 if (
314 Option.isSome(control.active) &&
315 control.active.value.requestId === cancellation.requestId
316 ) {
317 return [Option.some(control.active.value.signal), control] as const;
318 }
319 return [
320 Option.none<Deferred.Deferred<void>>(),
321 {
322 ...control,
323 cancelledBeforeStart: [
324 ...control.cancelledBeforeStart.filter(
325 (requestId) => requestId !== cancellation.requestId,
326 ),
327 cancellation.requestId,
328 ],
329 },
330 ] as const;
331 });
332 if (Option.isSome(activeSignal)) {
333 yield* Deferred.succeed(activeSignal.value, undefined);
334 }
335 const matchedPrepared = yield* Ref.modify(preparedUpdateRef, (prepared) => {
336 if (Option.isNone(prepared) || prepared.value.requestId !== cancellation.requestId) {
337 return [false, prepared] as const;
338 }
339 return [true, prepared.value.status === "prepared" ? Option.none() : prepared] as const;
340 });
341 if (matchedPrepared) {
342 yield* Ref.update(requestControlRef, (control) => {
343 return {
344 ...control,
345 cancelledBeforeStart: control.cancelledBeforeStart.filter(
346 (requestId) => requestId !== cancellation.requestId,
347 ),
348 };
349 });
350 }
351 }),
352 ).pipe(Effect.forkScoped);
353​
354 yield* Stream.runForEach(publisher.updateCommits, (commit) =>
355 Effect.gen(function* () {
356 const current = yield* updates.getState;
357 const now = yield* Clock.currentTimeMillis;
358 const claim = yield* Ref.modify(
359 preparedUpdateRef,
360 (prepared): readonly [CommitClaim, Option.Option<PreparedUpdate>] => {
361 if (
362 Option.isNone(prepared) ||
363 prepared.value.requestId !== commit.requestId ||
364 (prepared.value.status === "prepared" && prepared.value.expiresAt <= now)
365 ) {
366 return [{ _tag: "invalid" as const }, prepared] as const;
367 }
368 if (prepared.value.status === "failed") {
369 return [{ _tag: "failed" as const, prepared: prepared.value }, prepared] as const;
370 }
371 if (prepared.value.status === "committing") {
372 return [{ _tag: "committing" as const }, prepared] as const;
373 }
374 return [
375 { _tag: "claimed" as const, prepared: prepared.value },
376 Option.some({ ...prepared.value, status: "committing" as const }),
377 ] as const;
378 },
379 );
380 if (claim._tag === "invalid") {
381 yield* publishReport(
382 yield* updates.getState,
383 {
384 outcome: "failed",
385 reason: "This desktop update is no longer prepared.",
386 },
387 commit.requestId,
388 );
389 return;
390 }
391 if (claim._tag === "failed") {
392 yield* publishReport(
393 current,
394 {
395 outcome: "failed",
396 reason: claim.prepared.failureReason ?? "The desktop app failed to install the update.",
397 },
398 commit.requestId,
399 );
400 return;
401 }
402 if (claim._tag === "committing") {
403 return;
404 }
405 yield* Ref.set(activeRequestIdRef, Option.some(commit.requestId));
406 if (current.downloadedVersion !== claim.prepared.downloadedVersion) {
407 const reason = "This desktop update is no longer prepared.";
408 if (yield* recordPreparedFailure(commit.requestId, reason)) {
409 yield* publishReport(current, { outcome: "failed", reason }, commit.requestId);
410 }
411 return;
412 }
413 const result = yield* updates.installPrepared(claim.prepared.downloadedVersion);
414 if (
415 !result.accepted &&
416 result.state.downloadedVersion === claim.prepared.downloadedVersion &&
417 (yield* updates.isInstallActive)
418 ) {
419 // Another install (local, or an earlier remote request) already owns
420 // the shutdown and will relaunch the app on the same downloaded
421 // version. This commit joins it: no failure marker, and the client
422 // proves the handoff the same way, by transport loss then the
423 // target version on reconnect.
424 yield* logInfo("remote update commit joining an in-progress install", {
425 requestId: commit.requestId,
426 });
427 return;
428 }
429 if (!result.accepted || result.failed) {
430 const reason = result.state.message ?? "The desktop app could not start the install.";
431 if (yield* recordPreparedFailure(commit.requestId, reason)) {
432 yield* publishReport(result.state, { outcome: "failed", reason }, commit.requestId);
433 }
434 return;
435 }
436 // A successful install tears down this backend. Do not send a success
437 // marker from the old process: transport loss followed by the target
438 // version is the only proof that the handoff succeeded.
439 }).pipe(
440 Effect.ensuring(clearActiveRequest(commit.requestId)),
441 Effect.catchCause((cause) =>
442 logError("remote update commit failed unexpectedly", {
443 requestId: commit.requestId,
444 cause: String(cause),
445 }),
446 ),
447 ),
448 ).pipe(Effect.forkScoped);
449});