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

serverRuntimeStartup.ts

379 lines12.7 KB

1import {
2 CommandId,
3 DEFAULT_PROVIDER_INTERACTION_MODE,
4 type ModelSelection,
5 ProjectId,
6 ThreadId,
7} from "@t3tools/contracts";
8import {
9 Data,
10 Deferred,
11 Effect,
12 Exit,
13 Layer,
14 Option,
15 Path,
16 Queue,
17 Ref,
18 Scope,
19 ServiceMap,
20} from "effect";
21​
22import { ServerConfig } from "./config";
23import { Keybindings } from "./keybindings";
24import { Open } from "./open";
25import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
26import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
27import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
28import { ServerLifecycleEvents } from "./serverLifecycleEvents";
29import { ServerSettingsService } from "./serverSettings";
30import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
31​
32const isWildcardHost = (host: string | undefined): boolean =>
33 host === "0.0.0.0" || host === "::" || host === "[::]";
34​
35const formatHostForUrl = (host: string): string =>
36 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
37​
38export class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{
39 readonly message: string;
40 readonly cause?: unknown;
41}> {}
42​
43export interface ServerRuntimeStartupShape {
44 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
45 readonly markHttpListening: Effect.Effect<void>;
46 readonly enqueueCommand: <A, E>(
47 effect: Effect.Effect<A, E>,
48 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
50​
51export class ServerRuntimeStartup extends ServiceMap.Service<
52 ServerRuntimeStartup,
53 ServerRuntimeStartupShape
54>()("t3/serverRuntimeStartup") {}
55​
56interface QueuedCommand {
57 readonly run: Effect.Effect<void, never>;
59​
60type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
61​
62interface CommandGate {
63 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
64 readonly signalCommandReady: Effect.Effect<void>;
65 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
66 readonly enqueueCommand: <A, E>(
67 effect: Effect.Effect<A, E>,
68 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
70​
71const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
72 Exit.isSuccess(exit)
73 ? Deferred.succeed(deferred, exit.value)
74 : Deferred.failCause(deferred, exit.cause);
75​
76export const makeCommandGate = Effect.gen(function* () {
77 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
78 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
79 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
80​
81 const commandWorker = Effect.forever(
82 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
83 );
84 yield* Effect.forkScoped(commandWorker);
85​
86 return {
87 awaitCommandReady: Deferred.await(commandReady),
88 signalCommandReady: Effect.gen(function* () {
89 yield* Ref.set(commandReadinessState, "ready");
90 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
91 }),
92 failCommandReady: (error) =>
93 Effect.gen(function* () {
94 yield* Ref.set(commandReadinessState, error);
95 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
96 }),
97 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
98 Effect.gen(function* () {
99 const readinessState = yield* Ref.get(commandReadinessState);
100 if (readinessState === "ready") {
101 return yield* effect;
102 }
103 if (readinessState !== "pending") {
104 return yield* readinessState;
105 }
106​
107 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
108 yield* Queue.offer(commandQueue, {
109 run: Deferred.await(commandReady).pipe(
110 Effect.flatMap(() => effect),
111 Effect.exit,
112 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
113 ),
114 });
115 return yield* Deferred.await(result);
116 }),
117 } satisfies CommandGate;
118});
119​
120export const recordStartupHeartbeat = Effect.gen(function* () {
121 const analytics = yield* AnalyticsService;
122 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
123​
124 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
125 Effect.catch((cause) =>
126 Effect.logWarning("failed to gather startup projection counts for telemetry", {
127 cause,
128 }).pipe(
129 Effect.as({
130 threadCount: 0,
131 projectCount: 0,
132 }),
133 ),
134 ),
135 );
136​
137 yield* analytics.record("server.boot.heartbeat", {
138 threadCount,
139 projectCount,
140 });
141});
142​
143export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
144 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
145 Effect.withSpan("server.startup.heartbeat.record"),
146 Effect.ignoreCause({ log: true }),
147 Effect.forkScoped,
148 Effect.asVoid,
149);
150​
151const autoBootstrapWelcome = Effect.gen(function* () {
152 const serverConfig = yield* ServerConfig;
153 const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
154 const orchestrationEngine = yield* OrchestrationEngineService;
155 const path = yield* Path.Path;
156​
157 let bootstrapProjectId: ProjectId | undefined;
158 let bootstrapThreadId: ThreadId | undefined;
159​
160 if (serverConfig.autoBootstrapProjectFromCwd) {
161 yield* Effect.gen(function* () {
162 const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
163 serverConfig.cwd,
164 );
165 let nextProjectId: ProjectId;
166 let nextProjectDefaultModelSelection: ModelSelection;
167​
168 if (Option.isNone(existingProject)) {
169 const createdAt = new Date().toISOString();
170 nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
171 const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
172 nextProjectDefaultModelSelection = {
173 provider: "codex",
174 model: "gpt-5-codex",
175 };
176 yield* orchestrationEngine.dispatch({
177 type: "project.create",
178 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
179 projectId: nextProjectId,
180 title: bootstrapProjectTitle,
181 workspaceRoot: serverConfig.cwd,
182 defaultModelSelection: nextProjectDefaultModelSelection,
183 createdAt,
184 });
185 } else {
186 nextProjectId = existingProject.value.id;
187 nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? {
188 provider: "codex",
189 model: "gpt-5-codex",
190 };
191 }
192​
193 const existingThreadId =
194 yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
195 if (Option.isNone(existingThreadId)) {
196 const createdAt = new Date().toISOString();
197 const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID());
198 yield* orchestrationEngine.dispatch({
199 type: "thread.create",
200 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
201 threadId: createdThreadId,
202 projectId: nextProjectId,
203 title: "New thread",
204 modelSelection: nextProjectDefaultModelSelection,
205 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
206 runtimeMode: "full-access",
207 branch: null,
208 worktreePath: null,
209 createdAt,
210 });
211 bootstrapProjectId = nextProjectId;
212 bootstrapThreadId = createdThreadId;
213 } else {
214 bootstrapProjectId = nextProjectId;
215 bootstrapThreadId = existingThreadId.value;
216 }
217 });
218 }
219​
220 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
221 const projectName = segments[segments.length - 1] ?? "project";
222​
223 return {
224 cwd: serverConfig.cwd,
225 projectName,
226 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
227 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
228 } as const;
229});
230​
231const maybeOpenBrowser = Effect.gen(function* () {
232 const serverConfig = yield* ServerConfig;
233 if (serverConfig.noBrowser) {
234 return;
235 }
236 const { openBrowser } = yield* Open;
237 const localUrl = `http://localhost:${serverConfig.port}`;
238 const bindUrl =
239 serverConfig.host && !isWildcardHost(serverConfig.host)
240 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
241 : localUrl;
242 const target = serverConfig.devUrl?.toString() ?? bindUrl;
243​
244 yield* openBrowser(target).pipe(
245 Effect.catch(() =>
246 Effect.logInfo("browser auto-open unavailable", {
247 hint: `Open ${target} in your browser.`,
248 }),
249 ),
250 );
251});
252​
253const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
254 effect.pipe(
255 Effect.annotateSpans({ "startup.phase": phase }),
256 Effect.withSpan(`server.startup.${phase}`),
257 );
258​
259const makeServerRuntimeStartup = Effect.gen(function* () {
260 const serverConfig = yield* ServerConfig;
261 const keybindings = yield* Keybindings;
262 const orchestrationReactor = yield* OrchestrationReactor;
263 const lifecycleEvents = yield* ServerLifecycleEvents;
264 const serverSettings = yield* ServerSettingsService;
265​
266 const commandGate = yield* makeCommandGate;
267 const httpListening = yield* Deferred.make<void>();
268 const reactorScope = yield* Scope.make("sequential");
269​
270 yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
271​
272 const startup = Effect.gen(function* () {
273 yield* Effect.logDebug("startup phase: starting keybindings runtime");
274 yield* runStartupPhase(
275 "keybindings.start",
276 keybindings.start.pipe(
277 Effect.catch((error) =>
278 Effect.logWarning("failed to start keybindings runtime", {
279 path: error.configPath,
280 detail: error.detail,
281 cause: error.cause,
282 }),
283 ),
284 Effect.forkScoped,
285 ),
286 );
287​
288 yield* Effect.logDebug("startup phase: starting server settings runtime");
289 yield* runStartupPhase(
290 "settings.start",
291 serverSettings.start.pipe(
292 Effect.catch((error) =>
293 Effect.logWarning("failed to start server settings runtime", {
294 path: error.settingsPath,
295 detail: error.detail,
296 cause: error.cause,
297 }),
298 ),
299 Effect.forkScoped,
300 ),
301 );
302​
303 yield* Effect.logDebug("startup phase: starting orchestration reactors");
304 yield* runStartupPhase(
305 "reactors.start",
306 orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
307 );
308​
309 yield* Effect.logDebug("startup phase: preparing welcome payload");
310 const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome);
311 yield* Effect.logDebug("startup phase: publishing welcome event", {
312 cwd: welcome.cwd,
313 projectName: welcome.projectName,
314 bootstrapProjectId: welcome.bootstrapProjectId,
315 bootstrapThreadId: welcome.bootstrapThreadId,
316 });
317 yield* runStartupPhase(
318 "welcome.publish",
319 lifecycleEvents.publish({
320 version: 1,
321 type: "welcome",
322 payload: welcome,
323 }),
324 );
325 }).pipe(
326 Effect.annotateSpans({
327 "server.mode": serverConfig.mode,
328 "server.port": serverConfig.port,
329 "server.host": serverConfig.host ?? "default",
330 }),
331 Effect.withSpan("server.startup", { kind: "server", root: true }),
332 );
333​
334 yield* Effect.forkScoped(
335 Effect.gen(function* () {
336 const startupExit = yield* Effect.exit(startup);
337 if (Exit.isFailure(startupExit)) {
338 const error = new ServerRuntimeStartupError({
339 message: "Server runtime startup failed before command readiness.",
340 cause: startupExit.cause,
341 });
342 yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause });
343 yield* commandGate.failCommandReady(error);
344 return;
345 }
346​
347 yield* Effect.logDebug("Accepting commands");
348 yield* commandGate.signalCommandReady;
349 yield* Effect.logDebug("startup phase: waiting for http listener");
350 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
351 yield* Effect.logDebug("startup phase: publishing ready event");
352 yield* runStartupPhase(
353 "ready.publish",
354 lifecycleEvents.publish({
355 version: 1,
356 type: "ready",
357 payload: { at: new Date().toISOString() },
358 }),
359 );
360​
361 yield* Effect.logDebug("startup phase: recording startup heartbeat");
362 yield* launchStartupHeartbeat;
363 yield* Effect.logDebug("startup phase: browser open check");
364 yield* runStartupPhase("browser.open", maybeOpenBrowser);
365 yield* Effect.logDebug("startup phase: complete");
366 }),
367 );
368​
369 return {
370 awaitCommandReady: commandGate.awaitCommandReady,
371 markHttpListening: Deferred.succeed(httpListening, undefined),
372 enqueueCommand: commandGate.enqueueCommand,
373 } satisfies ServerRuntimeStartupShape;
374});
375​
376export const ServerRuntimeStartupLive = Layer.effect(
377 ServerRuntimeStartup,
378 makeServerRuntimeStartup,
379);