Skip to content
TypeScript

fix(server): t3 project commands wait for a busy server's reply (#24090)

Victor Vogelb7c7a7819a9b
diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts
index 40a7ab71138..723f5254e7a 100644
--- a/apps/server/src/cli/project.test.ts
+++ b/apps/server/src/cli/project.test.ts
@@ -18,11 +18,14 @@ import {
import * as NetService from "@t3tools/shared/Net";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as References from "effect/References";
import * as Stream from "effect/Stream";
import { Command } from "effect/cli";
+import { FetchHttpClient } from "effect/http";
+import * as TestClock from "effect/testing/TestClock";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { cli } from "../binCli.ts";
@@ -37,6 +40,10 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
+import {
+ makePersistedServerRuntimeState,
+ persistServerRuntimeState,
+} from "../serverRuntimeState.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -121,6 +128,66 @@ it.effect("adds, renames, and removes projects through the V2 project CLI domain
}).pipe(Effect.provide(NodeServices.layer)),
);
+it.effect.each(["snapshot", "mutation"] as const)(
+ "waits for a busy live server's %s response",
+ (slowRequest) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-live-project-cli-" });
+ const baseDir = NodePath.join(root, "state");
+ const workspaceRoot = NodePath.join(root, "workspace");
+ yield* fs.makeDirectory(workspaceRoot);
+ yield* persistServerRuntimeState({
+ path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
+ state: yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: 3_773,
+ }),
+ });
+ const now = "2026-01-01T00:00:00.000Z";
+ const requestReceived = Promise.withResolvers<void>();
+ const releaseResponse = Promise.withResolvers<void>();
+ let snapshotRequests = 0;
+ let mutations = 0;
+ const fetch: typeof globalThis.fetch = async (_input, init) => {
+ const isMutation = init?.method === "POST";
+ if (isMutation) mutations++;
+ else snapshotRequests++;
+ if (slowRequest === "mutation" ? isMutation : !isMutation && snapshotRequests === 2) {
+ requestReceived.resolve();
+ await releaseResponse.promise;
+ }
+ return Response.json(
+ isMutation
+ ? {
+ id: "live-project",
+ title: NodePath.basename(workspaceRoot),
+ workspaceRoot,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: now,
+ updatedAt: now,
+ deletedAt: null,
+ }
+ : { projects: [], updatedAt: now },
+ );
+ };
+
+ const add = yield* runCli(["project", "add", workspaceRoot, "--base-dir", baseDir]).pipe(
+ Effect.provideService(FetchHttpClient.Fetch, fetch),
+ Effect.forkChild,
+ );
+ yield* Effect.promise(() => requestReceived.promise);
+ yield* TestClock.adjust("2 seconds");
+ releaseResponse.resolve();
+ yield* Fiber.join(add);
+
+ assert.equal(snapshotRequests, 2);
+ assert.equal(mutations, 1);
+ assert.deepEqual((yield* readProjects(baseDir)).projects, []);
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+);
+
const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () {
const fs = yield* FileSystem.FileSystem;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" });
diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts
index a5c8aa532ff..3d02f9c921f 100644
--- a/apps/server/src/cli/project.ts
+++ b/apps/server/src/cli/project.ts
@@ -214,7 +214,8 @@ const layerProjectCliRuntime = RuntimeLayer.layerProjectService.pipe(
Layer.provideMerge(SqlitePersistence.layerConfig),
);
-const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
+const PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT = Duration.seconds(1);
+const PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT = Duration.seconds(10);
const withProjectCliSessionToken = <A, E, R>(
environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
run: (token: string) => Effect.Effect<A, E, R>,
@@ -228,9 +229,6 @@ const withProjectCliSessionToken = <A, E, R>(
(issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
);
-const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
- effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
-
const makeLiveServerClient = (origin: string) =>
HttpApiClient.make(EnvironmentHttpApi, {
baseUrl: origin,
@@ -317,17 +315,14 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
});
const fetchLiveOrchestrationSnapshot = Effect.fn("project.fetchLiveOrchestrationSnapshot")(
- function* (origin: string, bearerToken: string) {
+ function* (origin: string, bearerToken: string, _timeout?: Duration.Duration) {
const client = yield* makeLiveServerClient(origin);
return yield* client.projects.snapshot({
headers: { authorization: `Bearer ${bearerToken}` },
});
},
- (effect, _origin, _bearerToken) =>
- effect.pipe(
- withProjectCliLiveServerTimeout,
- Effect.mapError(projectCommandErrorFromLiveServerRequest),
- ),
+ (effect, _origin, _bearerToken, timeout = PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT) =>
+ effect.pipe(Effect.timeout(timeout), Effect.mapError(projectCommandErrorFromLiveServerRequest)),
);
const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestrationCommand")(
@@ -340,7 +335,7 @@ const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestr
},
(effect, _origin, _bearerToken, _command) =>
effect.pipe(
- withProjectCliLiveServerTimeout,
+ Effect.timeout(PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT),
Effect.mapError(projectCommandErrorFromLiveServerRequest),
),
);
@@ -361,7 +356,11 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu
}
const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
- fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
+ fetchLiveOrchestrationSnapshot(
+ runtimeState.value.origin,
+ token,
+ PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT,
+ ).pipe(
Effect.as({
origin: runtimeState.value.origin,
}),