Skip to content
TypeScript

fix(server): a slow server update download no longer fails at a 10-minute cap (#19649)

Ibrahim Elkamalia3635a14e8ea
diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts
index 9ee29f58868..0556425ef21 100644
--- a/apps/server/src/cloud/pinnedRuntime.test.ts
+++ b/apps/server/src/cloud/pinnedRuntime.test.ts
@@ -1,10 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";
+import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
@@ -215,6 +217,165 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
}),
);
+ it.effect.each([true, false])(
+ "installs a download receiving bytes for over ten minutes (progress: %s)",
+ (reportProgress) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-slow-" });
+ const checksums = yield* validChecksums;
+ const reads = yield* Effect.forEach(archiveBytes, () => Deferred.make<void>());
+ let controller: ReadableStreamDefaultController<Uint8Array>;
+ let offset = 0;
+ const body = new ReadableStream<Uint8Array>(
+ {
+ start(value) {
+ controller = value;
+ },
+ pull() {
+ Deferred.doneUnsafe(reads[offset++]!, Effect.void);
+ },
+ },
+ { highWaterMark: 0 },
+ );
+ const client = HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response(request.url.endsWith("/SHA256SUMS") ? checksums : body),
+ ),
+ ),
+ );
+ const progress: PinnedRuntimeProgress[] = [];
+ yield* Effect.gen(function* () {
+ // Each read is demanded by the consumer, with no prefetched chunks.
+ for (let index = 0; index < archiveBytes.length; index++) {
+ yield* Deferred.await(reads[index]!);
+ yield* TestClock.adjust(Duration.seconds(40));
+ controller.enqueue(archiveBytes.slice(index, index + 1));
+ }
+ controller.close();
+ }).pipe(Effect.forkScoped);
+ const installed = yield* ensurePinnedRuntimeInstalled({
+ baseDir,
+ version,
+ fs,
+ path,
+ platform: "linux",
+ arch: "x64",
+ httpClient: client,
+ runner: extractingRunner(fs, path),
+ validate: () => Effect.void,
+ ...(reportProgress
+ ? { onProgress: (event: PinnedRuntimeProgress) => progress.push(event) }
+ : {}),
+ });
+ assert.equal(yield* fs.readFileString(installed.sentinelPath), `${version}\n`);
+ if (reportProgress) {
+ assert.deepEqual(progress.slice(-4), [
+ { stage: "download", received: archiveBytes.length, total: archiveBytes.length },
+ { stage: "verify" },
+ { stage: "extract" },
+ { stage: "validate" },
+ ]);
+ }
+ }),
+ );
+
+ it.effect.each([
+ { stall: "response", reportProgress: false },
+ { stall: "body", reportProgress: false },
+ { stall: "body", reportProgress: true },
+ ])(
+ "fails a one-minute $stall stall, cleans up and releases the lock (progress: $reportProgress)",
+ ({ stall, reportProgress }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-stalled-" });
+ const checksums = yield* validChecksums;
+ const waiting = yield* Deferred.make<void>();
+ let cancelled = false;
+ let sentChunk = false;
+ const client = HttpClient.make((request) => {
+ if (request.url.endsWith("/SHA256SUMS")) {
+ return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(checksums)));
+ }
+ if (stall === "response") {
+ return Deferred.succeed(waiting, undefined).pipe(
+ Effect.andThen(Effect.never),
+ Effect.ensuring(
+ Effect.sync(() => {
+ cancelled = true;
+ }),
+ ),
+ );
+ }
+ return Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response(
+ new ReadableStream<Uint8Array>(
+ {
+ pull(controller) {
+ if (!sentChunk) {
+ sentChunk = true;
+ controller.enqueue(archiveBytes.slice(0, 4));
+ } else {
+ Deferred.doneUnsafe(waiting, Effect.void);
+ }
+ },
+ cancel() {
+ cancelled = true;
+ },
+ },
+ { highWaterMark: 0 },
+ ),
+ ),
+ ),
+ );
+ });
+ const progress: PinnedRuntimeProgress[] = [];
+ const commands: string[] = [];
+ const install = yield* ensurePinnedRuntimeInstalled({
+ baseDir,
+ version,
+ fs,
+ path,
+ platform: "linux",
+ arch: "x64",
+ httpClient: client,
+ runner: extractingRunner(fs, path, commands),
+ validate: () => Effect.die("must not validate a stalled archive"),
+ ...(reportProgress
+ ? { onProgress: (event: PinnedRuntimeProgress) => progress.push(event) }
+ : {}),
+ }).pipe(Effect.forkScoped);
+ yield* Deferred.await(waiting);
+ yield* TestClock.adjust(Duration.minutes(1));
+ assert.isTrue(cancelled, "the stalled transfer must be cancelled after one minute");
+ const error = yield* Fiber.join(install).pipe(Effect.flip);
+ assert.instanceOf(error, PinnedRuntimeInstallError);
+ assert.equal(error.step, "downloading the t3 release archive (timed out)");
+ assert.deepEqual(commands, []);
+ assert.isTrue(progress.every((event) => event.stage === "download"));
+ assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
+ const installed = yield* ensurePinnedRuntimeInstalled({
+ baseDir,
+ version,
+ fs,
+ path,
+ platform: "linux",
+ arch: "x64",
+ httpClient: releaseHttpClient(checksums),
+ runner: extractingRunner(fs, path),
+ validate: () => Effect.void,
+ });
+ assert.equal(yield* fs.readFileString(installed.sentinelPath), `${version}\n`);
+ }),
+ );
+
it.effect("refuses an archive whose checksum does not match the release", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts
index dfcd6041dfd..0b3592a2019 100644
--- a/apps/server/src/cloud/pinnedRuntime.ts
+++ b/apps/server/src/cloud/pinnedRuntime.ts
@@ -1,3 +1,4 @@
+import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
@@ -22,6 +23,7 @@ import * as ProcessRunner from "../processRunner.ts";
const PINNED_RUNTIME_DIR = "runtime";
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
+const PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT = Duration.minutes(1);
const PINNED_RUNTIME_ARCHIVE_FILE = "t3-runtime-archive";
// Boot-service setup and remote update can construct separate layers. Serialize
// the complete install transaction across every caller in this process.
@@ -119,28 +121,32 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(
step: string,
onProgress?: (progress: PinnedRuntimeProgress) => void,
) {
- // The install lock is held for the whole transaction, so a stalled download
- // must fail rather than block every other caller.
+ // Bound stalls while holding the install lock, but allow transfers that keep
+ // receiving bytes to finish regardless of their total duration.
return yield* httpClient.execute(HttpClientRequest.get(url)).pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk),
+ Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT),
Effect.flatMap(
Effect.fn(function* (response) {
- if (onProgress === undefined) return new Uint8Array(yield* response.arrayBuffer);
const length = Number(response.headers["content-length"]);
const total = Number.isFinite(length) && length > 0 ? length : undefined;
let received = 0;
- onProgress({ stage: "download", received, total });
+ onProgress?.({ stage: "download", received, total });
const chunks = yield* response.stream.pipe(
+ Stream.timeoutOrElse({
+ duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT,
+ orElse: () => Stream.fail(new Cause.TimeoutError()),
+ }),
Stream.tap((chunk) =>
Effect.sync(() => {
received += chunk.byteLength;
- onProgress({ stage: "download", received, total });
+ onProgress?.({ stage: "download", received, total });
}),
),
Stream.runCollect,
);
if (total === undefined && received > 0) {
- onProgress({ stage: "download", received, total: received });
+ onProgress?.({ stage: "download", received, total: received });
}
const bytes = new Uint8Array(received);
let offset = 0;
@@ -151,11 +157,13 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(
return bytes;
}),
),
- Effect.mapError((cause) => new PinnedRuntimeInstallError({ step, cause })),
- Effect.timeoutOrElse({
- duration: PINNED_RUNTIME_INSTALL_TIMEOUT,
- orElse: () => Effect.fail(new PinnedRuntimeInstallError({ step: `${step} (timed out)` })),
- }),
+ Effect.mapError(
+ (cause) =>
+ new PinnedRuntimeInstallError({
+ step: cause._tag === "TimeoutError" ? `${step} (timed out)` : step,
+ cause,
+ }),
+ ),
);
});