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

serverRuntimeStartup.ts

676 lines24.4 KB

1import {
2 CommandId,
3 DEFAULT_MODEL,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 DEFAULT_SERVER_SETTINGS,
6 type ModelSelection,
7 type Project,
8 ProjectId,
9 ProviderInstanceId,
10 ThreadId,
11} from "@t3tools/contracts";
12import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
13import * as Cause from "effect/Cause";
14import * as Console from "effect/Console";
15import * as Context from "effect/Context";
16import * as Crypto from "effect/Crypto";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Exit from "effect/Exit";
21import * as Fiber from "effect/Fiber";
22import * as Layer from "effect/Layer";
23import * as Path from "effect/Path";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as Schema from "effect/Schema";
27​
28import * as ServerConfig from "./config.ts";
29import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
30import { flushCompileCache } from "./compileCache.ts";
31import * as Keybindings from "./keybindings.ts";
32import * as ExternalLauncher from "./process/externalLauncher.ts";
33import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
34import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
35import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
36import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
37import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
38import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
39import * as ProjectService from "./project/ProjectService.ts";
40import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
41import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
42import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
43import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
44import * as ServerSettings from "./serverSettings.ts";
45import { forkParked, forkParkedFiber } from "./serverActivation.ts";
46import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
47import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
48import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
49import {
50 formatHeadlessServeOutput,
51 formatHostForUrl,
52 isWildcardHost,
53 issueHeadlessServeAccessInfo,
54} from "./startupAccess.ts";
55​
56export class ServerRuntimeStartupError extends Schema.TaggedError<ServerRuntimeStartupError>()(
57 "ServerRuntimeStartupError",
58 {
59 mode: ServerConfig.RuntimeMode,
60 host: Schema.NullOr(Schema.String),
61 port: Schema.Number,
62 cause: Schema.Defect(),
63 },
64) {
65 override get message(): string {
66 return "Server runtime startup failed before command readiness.";
67 }
69​
70export class ServerRuntimeStartup extends Context.Service<
71 ServerRuntimeStartup,
72 {
73 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
74 readonly markHttpListening: Effect.Effect<void>;
75 readonly enqueueCommand: <A, E>(
76 effect: Effect.Effect<A, E>,
77 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
78 }
79>()("t3/serverRuntimeStartup") {}
80​
81interface QueuedCommand {
82 readonly run: Effect.Effect<void, never>;
84​
85type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
86​
87interface CommandGate {
88 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
89 readonly signalCommandReady: Effect.Effect<void>;
90 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
91 readonly enqueueCommand: <A, E>(
92 effect: Effect.Effect<A, E>,
93 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
95​
96const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
97 Exit.isSuccess(exit)
98 ? Deferred.succeed(deferred, exit.value)
99 : Deferred.failCause(deferred, exit.cause);
100​
101export const makeCommandGate = Effect.gen(function* () {
102 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
103 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
104 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
105​
106 const commandWorker = Effect.forever(
107 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
108 );
109 yield* Effect.forkScoped(commandWorker);
110​
111 return {
112 awaitCommandReady: Deferred.await(commandReady),
113 signalCommandReady: Effect.gen(function* () {
114 yield* Ref.set(commandReadinessState, "ready");
115 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
116 }),
117 failCommandReady: (error) =>
118 Effect.gen(function* () {
119 yield* Ref.set(commandReadinessState, error);
120 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
121 }),
122 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
123 Effect.gen(function* () {
124 const readinessState = yield* Ref.get(commandReadinessState);
125 if (readinessState === "ready") {
126 return yield* effect;
127 }
128 if (readinessState !== "pending") {
129 return yield* readinessState;
130 }
131​
132 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
133 yield* Queue.offer(commandQueue, {
134 run: Deferred.await(commandReady).pipe(
135 Effect.flatMap(() => effect),
136 Effect.exit,
137 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
138 ),
139 });
140 return yield* Deferred.await(result);
141 }),
142 } satisfies CommandGate;
143});
144​
145const recordStartupHeartbeat = Effect.gen(function* () {
146 const analytics = yield* AnalyticsService.AnalyticsService;
147 const projects = yield* ProjectService.ProjectService;
148 const threads = yield* ThreadManagement.ThreadManagementService;
149​
150 const { threadCount, projectCount } = yield* Effect.all({
151 projects: projects.snapshot,
152 threads: threads.getShellSnapshot(),
153 }).pipe(
154 Effect.map(({ projects: projectSnapshot, threads: shellSnapshot }) => ({
155 projectCount: projectSnapshot.projects.length,
156 threadCount: shellSnapshot.threads.length + shellSnapshot.archivedThreads.length,
157 })),
158 Effect.catch((cause) =>
159 Effect.logWarning("failed to gather V2 startup counts for telemetry", {
160 cause,
161 }).pipe(
162 Effect.as({
163 threadCount: 0,
164 projectCount: 0,
165 }),
166 ),
167 ),
168 );
169​
170 yield* analytics.record("server.boot.heartbeat", {
171 threadCount,
172 projectCount,
173 });
174});
175​
176export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
177 instanceId: ProviderInstanceId.make("codex"),
178 model: DEFAULT_MODEL,
179});
180​
181interface AutoBootstrapWelcomeTargets {
182 readonly bootstrapProjectId?: ProjectId;
183 readonly bootstrapThreadId?: ThreadId;
185​
186export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
187 projects: ReadonlyArray<Pick<Project, "id" | "workspaceRoot" | "autoPull">>,
188 settings = DEFAULT_SERVER_SETTINGS,
189) {
190 const git = yield* GitVcsDriver.GitVcsDriver;
191 const workspaceRoots = [
192 ...new Set(
193 projects
194 .filter((project) => resolveProjectSettings(settings, project.id).settings.defaultAutoPull)
195 .map((project) => project.workspaceRoot),
196 ),
197 ];
198​
199 yield* Effect.forEach(
200 workspaceRoots,
201 (cwd) =>
202 Effect.gen(function* () {
203 const status = yield* git.statusDetails(cwd);
204 if (
205 !status.isRepo ||
206 !status.isDefaultBranch ||
207 !status.hasUpstream ||
208 status.hasWorkingTreeChanges ||
209 status.aheadCount > 0
210 ) {
211 yield* Effect.logDebug("Skipped automatic project pull", {
212 cwd,
213 reason: !status.isRepo
214 ? "not-a-repository"
215 : !status.isDefaultBranch
216 ? "not-on-default-branch"
217 : !status.hasUpstream
218 ? "no-upstream"
219 : status.hasWorkingTreeChanges
220 ? "working-tree-changes"
221 : "local-commits",
222 });
223 return;
224 }
225​
226 if (status.behindCount <= 0) return;
227​
228 const result = yield* git.pullCurrentBranch(cwd);
229 yield* Effect.logDebug("Automatic project pull completed", {
230 cwd,
231 status: result.status,
232 refName: result.refName,
233 });
234 }).pipe(
235 Effect.catch((cause) =>
236 Effect.logWarning("Automatic project pull failed", {
237 cwd,
238 cause,
239 }),
240 ),
241 ),
242 { concurrency: 4, discard: true },
243 );
244});
245​
246export const resolveWelcomeBase = Effect.gen(function* () {
247 const serverConfig = yield* ServerConfig.ServerConfig;
248 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
249 const projectName = segments[segments.length - 1] ?? "project";
250​
251 return {
252 cwd: serverConfig.cwd,
253 projectName,
254 } as const;
255});
256​
257const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
258 const crypto = yield* Crypto.Crypto;
259 const randomUUID = crypto.randomUUIDv4;
260 const serverConfig = yield* ServerConfig.ServerConfig;
261 const projects = yield* ProjectService.ProjectService;
262 const threads = yield* ThreadManagement.ThreadManagementService;
263 const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
264 const path = yield* Path.Path;
265​
266 let bootstrapProjectId: ProjectId | undefined;
267 let bootstrapThreadId: ThreadId | undefined;
268​
269 if (serverConfig.autoBootstrapProjectFromCwd) {
270 // Project creation has no user model choice; only the bootstrap thread
271 // gets an automatic selection, and an explicit project default wins.
272 const threadModelSelection = getAutoBootstrapThreadModelSelection();
273 const { project } = yield* projects.bootstrap({
274 commandId: CommandId.make(yield* randomUUID),
275 projectId: ProjectId.make(yield* randomUUID),
276 title: path.basename(serverConfig.cwd) || "project",
277 workspaceRoot: serverConfig.cwd,
278 });
279 const shell = yield* threads.getShellSnapshot();
280 const existingThread = shell.threads.find(
281 (thread) =>
282 thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",
283 );
284 if (existingThread === undefined) {
285 const serverSettings = yield* ServerSettings.ServerSettingsService;
286 const settings = yield* serverSettings.getSettings;
287 const launched = yield* threadLaunch.launch({
288 commandId: CommandId.make(yield* randomUUID),
289 projectId: project.id,
290 title: "New thread",
291 modelSelection:
292 resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
293 threadModelSelection,
294 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
295 runtimeMode: resolveProjectSettings(settings, project.id, project).settings
296 .defaultRuntimeMode,
297 workspaceStrategy: { type: "root" },
298 createdBy: "system",
299 creationSource: "server",
300 });
301 bootstrapProjectId = project.id;
302 bootstrapThreadId = launched.threadId;
303 } else {
304 bootstrapProjectId = project.id;
305 bootstrapThreadId = existingThread.id;
306 }
307 }
308​
309 return {
310 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
311 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
312 } satisfies AutoBootstrapWelcomeTargets;
313});
314​
315const resolveStartupBrowserTarget = Effect.gen(function* () {
316 const serverConfig = yield* ServerConfig.ServerConfig;
317 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
318 const localUrl = `http://localhost:${serverConfig.port}`;
319 const bindUrl =
320 serverConfig.host && !isWildcardHost(serverConfig.host)
321 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
322 : localUrl;
323 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
324 return serverConfig.mode === "desktop"
325 ? baseTarget
326 : yield* serverAuth.issueStartupPairingUrl(baseTarget);
327});
328​
329const maybeOpenBrowser = (target: string) =>
330 Effect.gen(function* () {
331 const serverConfig = yield* ServerConfig.ServerConfig;
332 if (serverConfig.noBrowser) {
333 return;
334 }
335 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
336​
337 yield* externalLauncher.launchBrowser(target).pipe(
338 Effect.catch(() =>
339 Effect.logInfo("browser auto-open unavailable", {
340 hint: `Open ${target} in your browser.`,
341 }),
342 ),
343 );
344 });
345​
346const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
347 effect.pipe(
348 Effect.annotateSpans({ "startup.phase": phase }),
349 Effect.withSpan(`server.startup.${phase}`),
350 );
351​
352interface StartupOptions {
353 readonly activate?: Effect.Effect<void>;
354 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
355 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
357​
358export const startEffectWorkerWithRelay = Effect.fn(
359 "ServerRuntimeStartup.startEffectWorkerWithRelay",
360)(function* <WorkerContext, RelayContext>(input: {
361 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
362 readonly startRelay: Effect.Effect<void, never, RelayContext>;
363 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
364}) {
365 const workerFiber = yield* forkParkedFiber(input.runWorker);
366 yield* Ref.set(input.workerFiberRef, workerFiber);
367 yield* input.startRelay.pipe(
368 Effect.onExit((exit) => {
369 if (Exit.isSuccess(exit)) {
370 return Effect.void;
371 }
372 return Ref.getAndSet(input.workerFiberRef, null).pipe(
373 Effect.flatMap((ownedWorkerFiber) =>
374 ownedWorkerFiber === null
375 ? Effect.void
376 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
377 ),
378 );
379 }),
380 );
381});
382​
383export function runOrderedV2StartupPhases<
384 Import,
385 Recovery,
386 Bootstrap,
387 ImportError,
388 RecoveryError,
389 WorkerError,
390 BootstrapError,
391 ImportContext,
392 RecoveryContext,
393 WorkerContext,
394 BootstrapContext,
395>(input: {
396 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
397 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
398 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
399 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
400}) {
401 return Effect.gen(function* () {
402 yield* input.importLegacyShells;
403 const recovery = yield* input.recover;
404 yield* input.startEffectWorker;
405 const bootstrap = yield* input.autoBootstrap;
406 return { recovery, bootstrap } as const;
407 });
409​
410const make = (options?: StartupOptions) =>
411 Effect.gen(function* () {
412 const serverConfig = yield* ServerConfig.ServerConfig;
413 const keybindings = yield* Keybindings.Keybindings;
414 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
415 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
416 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
417 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
418 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
419 const serverSettings = yield* ServerSettings.ServerSettingsService;
420 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
421 const crypto = yield* Crypto.Crypto;
422 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
423​
424 const commandGate = yield* makeCommandGate;
425 const httpListening = yield* Deferred.make<void>();
426 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
427​
428 yield* Effect.addFinalizer(() =>
429 Effect.gen(function* () {
430 yield* commandGate.failCommandReady(
431 new ServerRuntimeStartupError({
432 mode: serverConfig.mode,
433 host: serverConfig.host ?? null,
434 port: serverConfig.port,
435 cause: "Server runtime is shutting down.",
436 }),
437 );
438 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
439 if (workerFiber !== null) {
440 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
441 }
442 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
443 Effect.ensuring(providerSessions.shutdown),
444 );
445 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
446 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
447 }).pipe(
448 Effect.catchCause((cause) =>
449 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
450 cause: Cause.pretty(cause),
451 }),
452 ),
453 ),
454 );
455​
456 const startup = Effect.gen(function* () {
457 yield* Effect.logDebug("startup phase: starting keybindings runtime");
458 yield* runStartupPhase(
459 "keybindings.start",
460 keybindings.start.pipe(
461 Effect.catch((error) =>
462 Effect.logWarning("failed to start keybindings runtime", {
463 path: error.configPath,
464 detail: error.detail,
465 cause: error.cause,
466 }),
467 ),
468 ),
469 );
470​
471 yield* Effect.logDebug("startup phase: starting server settings runtime");
472 yield* runStartupPhase(
473 "settings.start",
474 serverSettings.start.pipe(
475 Effect.catch((error) =>
476 Effect.logWarning("failed to start server settings runtime", {
477 path: error.settingsPath,
478 operation: error.operation,
479 providerInstanceId: error.providerInstanceId,
480 environmentVariable: error.environmentVariable,
481 cause: error.cause,
482 }),
483 ),
484 ),
485 );
486​
487 const welcomeBase = yield* resolveWelcomeBase;
488 const environment = yield* serverEnvironment.getDescriptor;
489 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
490 if (legacyMigrationThreadCount > 0) {
491 yield* lifecycleEvents.publish({
492 version: 1,
493 type: "legacyThreadMigration",
494 payload: {
495 status: "running",
496 totalThreadCount: legacyMigrationThreadCount,
497 },
498 });
499 }
500 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
501 importLegacyShells: runStartupPhase(
502 "orchestration-v2.legacy-v1.import-shells",
503 legacyV1ThreadImporter.reconcileShells.pipe(
504 Effect.tap((summary) =>
505 summary.importedThreadCount === 0
506 ? Effect.void
507 : Effect.logInfo("Imported legacy v1 thread shells", summary),
508 ),
509 ),
510 ),
511 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
512 startEffectWorker: runStartupPhase(
513 "orchestration-v2.effect-worker.start",
514 startEffectWorkerWithRelay({
515 runWorker: EffectWorker.runDaemon,
516 startRelay: agentAwarenessRelay.start(),
517 workerFiberRef: effectWorkerFiber,
518 }),
519 ),
520 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
521 ? runStartupPhase(
522 "welcome.autobootstrap",
523 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
524 )
525 : Effect.succeed({})
526 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
527 });
528 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
529 yield* runStartupPhase(
530 "projects.auto-pull",
531 Effect.gen(function* () {
532 const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
533 const settings = yield* serverSettings.getSettings;
534 yield* autoPullProjects(projects, settings);
535 }),
536 );
537​
538 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
539 Effect.tap((summary) =>
540 summary.importedThreadCount === 0
541 ? Effect.void
542 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
543 ),
544 );
545 yield* (
546 legacyMigrationThreadCount > 0
547 ? importPendingTranscripts.pipe(
548 Effect.tap(() =>
549 lifecycleEvents.publish({
550 version: 1,
551 type: "legacyThreadMigration",
552 payload: {
553 status: "complete",
554 totalThreadCount: legacyMigrationThreadCount,
555 },
556 }),
557 ),
558 )
559 : importPendingTranscripts
560 ).pipe(forkParked);
561​
562 yield* forkParked(
563 Effect.gen(function* () {
564 yield* Effect.logDebug("startup phase: recording startup heartbeat");
565 yield* recordStartupHeartbeat.pipe(
566 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
567 Effect.withSpan("server.startup.heartbeat.record"),
568 Effect.ignoreCause({ log: true }),
569 );
570 if (serverConfig.startupPresentation === "headless") {
571 yield* Effect.logDebug("startup phase: headless access info");
572 const accessInfo = yield* issueHeadlessServeAccessInfo();
573 yield* runStartupPhase(
574 "headless.output",
575 Console.log(formatHeadlessServeOutput(accessInfo)),
576 );
577 } else {
578 yield* Effect.logDebug("startup phase: browser open check");
579 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
580 if (serverConfig.mode !== "desktop") {
581 yield* Effect.logInfo(
582 "Authentication required. Open T3 Code using the pairing URL.",
583 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
584 }
585 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
586 }
587 }),
588 );
589​
590 yield* Effect.logDebug("startup phase: waiting for http listener");
591 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
592 yield* runStartupPhase(
593 "auxiliary-roots.parked",
594 options?.awaitAuxiliaryParked ?? Effect.void,
595 );
596​
597 const updateOutcome = yield* launcher.prepareTrial;
598​
599 yield* Effect.logDebug("startup phase: publishing welcome event", {
600 environmentId: environment.environmentId,
601 cwd: welcomeBase.cwd,
602 projectName: welcomeBase.projectName,
603 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
604 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
605 });
606 yield* runStartupPhase(
607 "welcome.publish",
608 lifecycleEvents.publish({
609 version: 1,
610 type: "welcome",
611 payload: {
612 environment,
613 ...welcomeBase,
614 ...bootstrapTargets,
615 },
616 }),
617 );
618​
619 yield* options?.activate ?? Effect.void;
620 yield* Effect.logDebug("Accepting commands");
621 yield* commandGate.signalCommandReady;
622 yield* Effect.logDebug("startup phase: publishing ready event");
623 yield* runStartupPhase(
624 "ready.publish",
625 lifecycleEvents.publish({
626 version: 1,
627 type: "ready",
628 payload: {
629 at: DateTime.formatIso(yield* DateTime.now),
630 environment,
631 ...(updateOutcome === undefined ? {} : { updateOutcome }),
632 },
633 }),
634 );
635 yield* Effect.logDebug("startup phase: complete");
636 yield* flushCompileCache;
637 }).pipe(
638 Effect.annotateSpans({
639 "server.mode": serverConfig.mode,
640 "server.port": serverConfig.port,
641 "server.host": serverConfig.host ?? "default",
642 }),
643 Effect.withSpan("server.startup", { kind: "server", root: true }),
644 );
645​
646 yield* Effect.forkScoped(
647 Effect.exit(startup).pipe(
648 Effect.flatMap((startupExit) => {
649 if (Exit.isSuccess(startupExit)) return Effect.void;
650 const error = new ServerRuntimeStartupError({
651 mode: serverConfig.mode,
652 host: serverConfig.host ?? null,
653 port: serverConfig.port,
654 cause: startupExit.cause,
655 });
656 return Effect.logError("server runtime startup failed", {
657 cause: Cause.pretty(startupExit.cause),
658 }).pipe(
659 Effect.andThen(commandGate.failCommandReady(error)),
660 Effect.andThen(options?.abort?.(error) ?? Effect.void),
661 );
662 }),
663 ),
664 );
665​
666 return {
667 awaitCommandReady: commandGate.awaitCommandReady,
668 markHttpListening: Deferred.succeed(httpListening, undefined),
669 enqueueCommand: commandGate.enqueueCommand,
670 } satisfies ServerRuntimeStartup["Service"];
671 });
672​
673export const layerWithOptions = (options?: StartupOptions) =>
674 Layer.effect(ServerRuntimeStartup, make(options));
675​
676const layer = layerWithOptions();