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

DesktopRemoteUpdates.ts

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