TypeScript
fix(desktop): desktop updates reconnect in seconds, not minutes (#12006)
Theo Browned4a33457cb0d
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.tsindex 50977852151..c9ed4c66bce 100644--- a/apps/desktop/src/updates/DesktopUpdates.test.ts+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts@@ -1,4 +1,5 @@import { assert, describe, it } from "@effect/vitest";+import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Deferred from "effect/Deferred";import * as Duration from "effect/Duration";@@ -14,6 +15,7 @@ import * as TestClock from "effect/testing/TestClock";import * as ElectronUpdater from "../electron/ElectronUpdater.ts";import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";+import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";import * as DesktopState from "../app/DesktopState.ts";import * as DesktopUpdates from "./DesktopUpdates.ts";import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";@@ -559,6 +561,55 @@ describe("DesktopUpdates", () => {).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));});+ it.effect("marks the backend stop for an install as an update restart", () => {+ let markersAtStop: ReadonlyArray<string> = [];+ const harness = makeHarness({+ stopBackend: Effect.sync(() => {+ markersAtStop = [...harness.updateRestartMarkers];+ }),+ });++ return Effect.scoped(+ Effect.gen(function* () {+ const environment = yield* DesktopEnvironment.DesktopEnvironment;+ const updates = yield* DesktopUpdates.DesktopUpdates;+ yield* updates.configure;+ harness.emit("update-downloaded", { version: "1.2.4" });+ yield* flushCallbacks;++ assert.isTrue((yield* updates.install).accepted);+ assert.deepEqual(markersAtStop, [+ environment.path.join(environment.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE),+ ]);+ }),+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));+ });++ it.effect("drops the update restart marker when an install is interrupted", () =>+ Effect.gen(function* () {+ const stopping = yield* Deferred.make<void>();+ const harness = makeHarness({+ stopBackend: Deferred.succeed(stopping, undefined).pipe(Effect.andThen(Effect.never)),+ });++ yield* Effect.scoped(+ Effect.gen(function* () {+ const updates = yield* DesktopUpdates.DesktopUpdates;+ yield* updates.configure;+ harness.emit("update-downloaded", { version: "1.2.4" });+ yield* flushCallbacks;++ const installFiber = yield* updates.install.pipe(Effect.forkScoped);+ yield* Deferred.await(stopping);+ assert.equal(harness.updateRestartMarkers.size, 1);++ yield* Fiber.interrupt(installFiber);+ assert.equal(harness.updateRestartMarkers.size, 0);+ }),+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));+ }),+ );+it.effect("keeps windows and restarts backends when quitAndInstall fails", () => {const harness = makeHarness({quitAndInstall: Effect.fail(@@ -583,6 +634,8 @@ describe("DesktopUpdates", () => {assert.isTrue(result.accepted);assert.isFalse(yield* Ref.get(desktopState.quitting));assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);+ // The restarted old backend must release its tunnel on a later quit.+ assert.equal(harness.updateRestartMarkers.size, 0);}),).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));});diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.tsindex c35b52e8343..5336c8ac1d2 100644--- a/apps/desktop/src/updates/DesktopUpdates.ts+++ b/apps/desktop/src/updates/DesktopUpdates.ts@@ -1,4 +1,5 @@import {+ DESKTOP_UPDATE_RESTART_MARKER_FILE,DesktopUpdateChannelSchema,type DesktopRuntimeInfo,type DesktopUpdateActionResult,@@ -501,8 +502,35 @@ export const make = Effect.gen(function* () {);}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));+ // Tells the primary backend that the coming stop is an update restart, so it+ // keeps its managed tunnel for the backend the updated app starts. Best+ // effort: without the marker the backend only re-provisions its tunnel.+ const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");+ const updateRestartMarkerPath = environment.path.join(+ updateRestartMarkerDir,+ DESKTOP_UPDATE_RESTART_MARKER_FILE,+ );+ const writeUpdateRestartMarker = fileSystem+ .makeDirectory(updateRestartMarkerDir, { recursive: true })+ .pipe(+ Effect.andThen(fileSystem.writeFileString(updateRestartMarkerPath, "")),+ Effect.catch((error) =>+ logUpdaterWarning("Could not write the update restart marker.", { errorTag: error._tag }),+ ),+ );++ // A failed or interrupted install brings no updated backend, so a later+ // quit must release the tunnel.+ const removeUpdateRestartMarker = fileSystem+ .remove(updateRestartMarkerPath, { force: true })+ .pipe(Effect.ignore);+const resetInstallAction = Effect.all(- [finishUpdateAction("install"), Ref.set(desktopState.quitting, false)],+ [+ finishUpdateAction("install"),+ Ref.set(desktopState.quitting, false),+ removeUpdateRestartMarker,+ ],{ discard: true },);@@ -517,6 +545,7 @@ export const make = Effect.gen(function* () {if (!ownsRecovery) return;yield* Ref.set(desktopState.quitting, false);+ yield* removeUpdateRestartMarker;yield* Effect.gen(function* () {const instances = yield* pool.list;const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {@@ -586,6 +615,7 @@ export const make = Effect.gen(function* () {yield* Ref.set(desktopState.quitting, true);return yield* Effect.gen(function* () {+ yield* writeUpdateRestartMarker;// Stop every backend in the pool, not just the primary. With// parallel WSL + Windows backends, leaving the WSL instance up// means quitAndInstall's app.quit() exits before the pool'sdiff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.tsindex fbcbb349f9e..cc50349e1fe 100644--- a/apps/desktop/src/updates/updatesTestHarness.ts+++ b/apps/desktop/src/updates/updatesTestHarness.ts@@ -1,6 +1,7 @@import * as NodeServices from "@effect/platform-node/NodeServices";import type { DesktopUpdateState } from "@t3tools/contracts";import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -203,7 +204,23 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {} satisfies DesktopAppSettings.DesktopAppSettings["Service"]): DesktopAppSettings.layer;+ // Tracks the restart markers installs leave, so installs stay free of real+ // disk I/O that would outrun the tests' settle loops.+ const updateRestartMarkers = new Set<string>();+ const fileSystemLayer = FileSystem.layerNoop({+ makeDirectory: () => Effect.void,+ writeFileString: (path) =>+ Effect.sync(() => {+ updateRestartMarkers.add(path);+ }),+ remove: (path) =>+ Effect.sync(() => {+ updateRestartMarkers.delete(path);+ }),+ });+const layer = DesktopUpdates.layer.pipe(+ Layer.provide(fileSystemLayer),Layer.provideMerge(updaterLayer),Layer.provideMerge(windowLayer),Layer.provideMerge(backendLayer),@@ -226,6 +243,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {checkCount: () => checkCount,quitAndInstalls: () => quitAndInstallCount,installSteps,+ updateRestartMarkers,downloadCount: () => downloadCount,feedUrls: () => feedUrls,fullChangelog: () => fullChangelog,diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.tsindex 0f24e6f3417..cf3abdab3f2 100644--- a/apps/server/src/cloud/http.test.ts+++ b/apps/server/src/cloud/http.test.ts@@ -1,11 +1,13 @@import * as NodeServices from "@effect/platform-node/NodeServices";import { describe, expect, it } from "@effect/vitest";+import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Path from "effect/Path";import * as PlatformError from "effect/PlatformError";+import * as TestClock from "effect/testing/TestClock";import * as Tracer from "effect/Tracer";import {HttpClient,@@ -14,7 +16,7 @@ import {type HttpClientRequest,} from "effect/unstable/http";-import { EnvironmentId } from "@t3tools/contracts";+import { DESKTOP_UPDATE_RESTART_MARKER_FILE, EnvironmentId } from "@t3tools/contracts";import { RelayClientTracer } from "@t3tools/shared/relayTracing";import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";@@ -285,6 +287,20 @@ describe("releaseManagedTunnelOnShutdown", () => {);});+ // Writes the marker the desktop app leaves just before it stops its backend+ // to install an update, and returns when it was written.+ const writeDesktopUpdateRestartMarker = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const config = yield* ServerConfigModule.ServerConfig;+ const runtimeDir = path.join(config.baseDir, "runtime");+ const markerPath = path.join(runtimeDir, DESKTOP_UPDATE_RESTART_MARKER_FILE);+ yield* fs.makeDirectory(runtimeDir, { recursive: true });+ yield* fs.writeFileString(markerPath, "");+ const { mtime } = yield* fs.stat(markerPath);+ return Option.getOrThrow(mtime).getTime();+ });+const provideReleaseHarness =(harness: ReleaseHarness) =><A, E, R>(effect: Effect.Effect<A, E, R>) =>@@ -454,6 +470,38 @@ describe("releaseManagedTunnelOnShutdown", () => {}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));});+ it.effect("keeps the tunnel once when the desktop app restarts it for an update", () => {+ const { store, values } = makeMemorySecretStore(managedLinkSecrets);+ const applyConfigCalls: Array<unknown> = [];+ const requests: Array<HttpClientRequest.HttpClientRequest> = [];++ return Effect.gen(function* () {+ yield* TestClock.setTime(yield* writeDesktopUpdateRestartMarker);++ expect(yield* releaseManagedTunnelOnShutdown()).toBe(false);+ expect(requests).toEqual([]);+ expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);++ // The shutdown consumed the marker, so a later quit releases the tunnel.+ expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);+ expect(requests).toHaveLength(1);+ }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));+ });++ it.effect("releases the tunnel when the desktop update marker is stale", () => {+ const { store } = makeMemorySecretStore(managedLinkSecrets);+ const applyConfigCalls: Array<unknown> = [];+ const requests: Array<HttpClientRequest.HttpClientRequest> = [];++ return Effect.gen(function* () {+ const writtenAt = yield* writeDesktopUpdateRestartMarker;+ yield* TestClock.setTime(writtenAt + Duration.toMillis(Duration.minutes(2)));++ expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);+ expect(requests).toHaveLength(1);+ }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));+ });+it.effect("still releases a pending update when the launcher is stopping", () => {// `t3 service uninstall` or `systemctl stop` during the pending window:// the launcher writes its stop marker before signalling the child, so nodiff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.tsindex e0d458b4b97..4a31f10605b 100644--- a/apps/server/src/cloud/http.ts+++ b/apps/server/src/cloud/http.ts@@ -11,6 +11,7 @@ import {EnvironmentHttpConflictError,EnvironmentHttpInternalServerError,EnvironmentHttpUnauthorizedError,+ DESKTOP_UPDATE_RESTART_MARKER_FILE,} from "@t3tools/contracts";import {RelayCloudEnvironmentHealthProofPayload,@@ -42,6 +43,7 @@ import {verifyRelayJwt,} from "@t3tools/shared/relayJwt";import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";+import * as Clock from "effect/Clock";import * as DateTime from "effect/DateTime";import * as Crypto from "effect/Crypto";import * as Duration from "effect/Duration";@@ -93,6 +95,8 @@ const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-";const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-";const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;+// The desktop app stops its backends within seconds of writing the marker.+const DESKTOP_UPDATE_RESTART_MARKER_TTL = Duration.minutes(1);const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {"cache-control": "no-store",@@ -663,6 +667,29 @@ const pendingUpdateHandoffExists = Effect.gen(function* () {return !stopping;});+// The desktop app writes its marker right before it stops this server to+// install an update, whether a remote client or the local app started it.+// Reading consumes it, so shutdown checks it first. Only a fresh marker counts,+// so a marker the server never read (a hard kill) cannot keep the tunnel on a+// later quit.+const desktopUpdateRestartPending = Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const markerPath = path.join(config.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE);+ const marker = yield* fs.stat(markerPath).pipe(Effect.option);+ if (Option.isNone(marker)) {+ return false;+ }+ yield* fs.remove(markerPath).pipe(Effect.ignore);+ const now = yield* Clock.currentTimeMillis;+ return Option.match(marker.value.mtime, {+ onNone: () => false,+ onSome: (writtenAt) =>+ now - writtenAt.getTime() < Duration.toMillis(DESKTOP_UPDATE_RESTART_MARKER_TTL),+ });+});+// Cloudflare bills per provisioned tunnel, so an environment that goes offline// must not leave its tunnel behind. Releasing deletes only the tunnel — the// relay keeps the link and its hostname reservation, and the next startup's@@ -685,16 +712,16 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {return false;}- // A shutdown that hands off to a pending remote update is not the- // environment going offline: the launcher immediately brings a server back- // (the new version, or the old one after a rollback). Deleting the tunnel- // here forces that server to provision a replacement UUID, and the public- // hostname's route to the new tunnel takes 1-2 minutes to propagate — the- // dominant cost of an update restart. Keep the tunnel instead: the next+ // A shutdown that hands off to a pending update is not the environment+ // going offline: the service launcher or the desktop app immediately brings+ // a server back (the new version, or the old one after a rollback). Deleting+ // the tunnel here forces that server to provision a replacement UUID, and the+ // public hostname's route to the new tunnel takes 1-2 minutes to propagate —+ // the dominant cost of an update restart. Keep the tunnel instead: the next// boot respawns the connector from the stored config and is reachable as// soon as it connects, and the reconcile confirms the still-live tunnel// without replacing it.- if (yield* pendingUpdateHandoffExists) {+ if ((yield* desktopUpdateRestartPending) || (yield* pendingUpdateHandoffExists)) {yield* Effect.logInfo("Keeping the managed tunnel across the update restart");return false;}diff --git a/packages/contracts/src/desktopBootstrap.ts b/packages/contracts/src/desktopBootstrap.tsindex bc3558aa296..31c604ffd7f 100644--- a/packages/contracts/src/desktopBootstrap.ts+++ b/packages/contracts/src/desktopBootstrap.ts@@ -23,3 +23,9 @@ export const DesktopBackendBootstrap = Schema.Struct({});export type DesktopBackendBootstrap = typeof DesktopBackendBootstrap.Type;++/** Written to `<t3Home>/runtime` just before the desktop app stops its+ backend to install an update. The updated app starts a new backend right+ away, so a backend that sees a fresh marker at shutdown keeps its managed+ tunnel. */+export const DESKTOP_UPDATE_RESTART_MARKER_FILE = "desktop-update-restart";