Repository navigation
Expand file tree
/
Copy pathDesktopAppUpdate.ts
More file actions
232 lines (218 loc) · 8.32 KB
/
Copy pathDesktopAppUpdate.ts
File metadata and controls
232 lines (218 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import {
ServerSelfUpdateError,
type DesktopUpdateState,
type DesktopUpdateStatusReport,
type ServerSelfUpdateProgressStage,
type ServerSelfUpdateResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Stream from "effect/Stream";
import * as ServerConfig from "../config.ts";
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
const DESKTOP_UPDATE_TIMEOUT = Duration.minutes(20);
const DESKTOP_INSTALL_TIMEOUT = Duration.minutes(2);
function desktopUpdateProgressStage(
state: DesktopUpdateState,
): ServerSelfUpdateProgressStage | null {
switch (state.status) {
case "checking":
case "available":
case "downloading":
return "downloading";
case "downloaded":
return "installing";
default:
return null;
}
}
export class DesktopAppUpdate extends Context.Service<
DesktopAppUpdate,
{
readonly available: boolean;
readonly run: (
reportProgress: (
stage: ServerSelfUpdateProgressStage,
) => Effect.Effect<void, ServerSelfUpdateError>,
trackSwitch?: DesktopTelemetryReceiver.DesktopTrackSwitch,
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
/** Success stops the server; returns only on installation failure or timeout. */
readonly commit: (
requestId: string,
onHandoffAccepted?: () => Effect.Effect<void>,
) => Effect.Effect<never, ServerSelfUpdateError>;
}
>()("t3/desktopUpdate/DesktopAppUpdate") {}
export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* () {
const config = yield* ServerConfig.ServerConfig;
const random = yield* SecureRandom.SecureRandom;
const receiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
const inFlight = yield* Ref.make(false);
const available = config.mode === "desktop" && config.desktopTelemetryControlFd !== undefined;
const failWith = (reason: string, cause?: unknown) =>
cause === undefined
? new ServerSelfUpdateError({ reason })
: new ServerSelfUpdateError({ reason, cause });
const consumeReports = Effect.fn("DesktopAppUpdate.consumeReports")(function* (
requestId: string,
changes: Stream.Stream<DesktopUpdateStatusReport>,
reportProgress: (
stage: ServerSelfUpdateProgressStage,
) => Effect.Effect<void, ServerSelfUpdateError>,
trackSwitch: boolean,
) {
const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
const emitStage = (
stage: ServerSelfUpdateProgressStage | null,
): Effect.Effect<void, ServerSelfUpdateError> =>
stage === null
? Effect.void
: Ref.get(lastStage).pipe(
Effect.flatMap((previous) =>
previous === stage
? Effect.void
: Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),
),
);
const terminal = yield* changes.pipe(
Stream.filter((report) => report.requestId === requestId),
Stream.mapEffect(
(report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>
report.outcome === undefined
? emitStage(desktopUpdateProgressStage(report.state)).pipe(
Effect.as(Option.none<DesktopUpdateStatusReport>()),
)
: Effect.succeedSome(report),
),
Stream.filterMap(
Option.match({
onNone: () => Result.failVoid,
onSome: Result.succeed,
}),
),
Stream.runHead,
);
if (Option.isNone(terminal)) {
return yield* failWith("The desktop app stopped reporting its update.");
}
const report = terminal.value;
if (report.outcome === "ready-to-install") {
yield* emitStage("installing");
const targetVersion =
report.state.downloadedVersion ??
report.state.availableVersion ??
report.state.currentVersion;
yield* Effect.logInfo("Desktop app update prepared for install.", {
targetVersion,
});
yield* Ref.set(inFlight, false);
return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };
}
if (report.outcome === "up-to-date") {
// A switch's host already on the newest build of its track only saved the track.
if (trackSwitch) {
yield* Ref.set(inFlight, false);
return { targetVersion: report.state.currentVersion, method: "desktop-app" as const };
}
return yield* failWith(
`The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
);
}
return yield* failWith(
report.reason ?? report.state.message ?? "The desktop app update failed.",
);
});
const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
function* (reportProgress, trackSwitch) {
if (!available) {
return yield* failWith(
"This server was not started by the T3 Code desktop app, so it cannot drive a desktop update.",
);
}
if (yield* Ref.getAndSet(inFlight, true)) {
return yield* failWith("A desktop app update is already in progress.");
}
return yield* Effect.scoped(
Effect.gen(function* () {
const requestId = yield* random
.uuidV4()
.pipe(
Effect.mapError((error) =>
failWith("Could not generate a desktop update request id.", error),
),
);
// Subscribe before requesting to catch fast reports.
const { changes } = yield* receiver.desktopUpdates;
yield* receiver
.requestDesktopUpdate(requestId, trackSwitch)
.pipe(
Effect.mapError((error) =>
failWith("Could not reach the T3 Code desktop app on this machine.", error),
),
);
return yield* consumeReports(
requestId,
changes,
reportProgress,
trackSwitch !== undefined,
).pipe(
Effect.onInterrupt(() => receiver.cancelDesktopUpdate(requestId).pipe(Effect.ignore)),
);
}),
).pipe(
Effect.timeout(DESKTOP_UPDATE_TIMEOUT),
Effect.catchTags({
TimeoutError: () => failWith("The desktop app did not finish the update in time."),
}),
Effect.onError(() => Ref.set(inFlight, false)),
);
},
);
const commit: DesktopAppUpdate["Service"]["commit"] = Effect.fn(
"desktopUpdate.desktopAppUpdate.commit",
)(function* (requestId, onHandoffAccepted = () => Effect.void) {
if (!available) {
return yield* failWith("This server cannot commit a desktop app update.");
}
const terminal = yield* Effect.scoped(
Effect.gen(function* () {
const { latest, changes } = yield* receiver.desktopUpdates;
const reports = Option.match(latest, {
onNone: () => changes,
onSome: (report) => Stream.concat(Stream.make(report), changes),
});
yield* Effect.uninterruptible(
receiver.commitDesktopUpdate(requestId).pipe(
Effect.mapError((error) => failWith("Could not reach the T3 Code desktop app.", error)),
Effect.tap(() => onHandoffAccepted()),
),
);
return yield* reports.pipe(
Stream.filter((report) => report.requestId === requestId && report.outcome === "failed"),
Stream.runHead,
Effect.timeout(DESKTOP_INSTALL_TIMEOUT),
Effect.catchTags({
TimeoutError: () =>
failWith("The desktop app did not report an install result in time."),
}),
);
}),
);
if (Option.isNone(terminal)) {
return yield* failWith("The desktop app stopped reporting the install.");
}
return yield* failWith(
terminal.value.reason ??
terminal.value.state.message ??
"The desktop app failed to install the update.",
);
});
return DesktopAppUpdate.of({ available, run, commit });
});
export const layer = Layer.effect(DesktopAppUpdate, make());