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

server.ts

666 lines28.4 KB

1import { EnvironmentHttpApi } from "@t3tools/contracts";
2import * as Duration from "effect/Duration";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schedule from "effect/Schedule";
7import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
8import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
9​
10import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
11import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
12import * as ServerConfig from "./config.ts";
13import {
14 otlpTracesProxyRouteLayer,
15 assetRouteLayer,
16 serverEnvironmentHttpApiLayer,
17 staticAndDevRouteLayer,
18 browserApiCorsLayer,
19 httpCompressionLayer,
20} from "./http.ts";
21import { fixPath } from "./os-jank.ts";
22import { websocketRpcRouteLayer } from "./ws.ts";
23import * as ExternalLauncher from "./process/externalLauncher.ts";
24import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
25import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
26import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
27import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
28import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts";
29import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
30import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
31import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
32import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
33import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
34import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
35import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
36import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
37import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
38import * as GitHubCli from "./sourceControl/GitHubCli.ts";
39import * as GitLabCli from "./sourceControl/GitLabCli.ts";
40import * as TextGeneration from "./textGeneration/TextGeneration.ts";
41import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
42import * as TerminalManager from "./terminal/Manager.ts";
43import * as McpHttpServer from "./mcp/McpHttpServer.ts";
44import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
45import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
46import * as PreviewManager from "./preview/Manager.ts";
47import * as PortScanner from "./preview/PortScanner.ts";
48import * as ProcessRunner from "./processRunner.ts";
49import * as GitManager from "./git/GitManager.ts";
50import * as Keybindings from "./keybindings.ts";
51import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
52import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";
53import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.ts";
54import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts";
55import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
56import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
57import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
58import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
59import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
60import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
61import * as ServerSettings from "./serverSettings.ts";
62import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
63import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
64import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
65import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
66import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
67import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
68import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
69import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
70import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
71import * as VcsProcess from "./vcs/VcsProcess.ts";
72import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
73import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
74import * as GitWorkflowService from "./git/GitWorkflowService.ts";
75import * as ReviewService from "./review/ReviewService.ts";
76import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
77import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
78import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
79import { ObservabilityLive } from "./observability/Layers/Observability.ts";
80import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
81import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
82import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
83import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
84import {
85 connectHttpApiLayer,
86 pendingServiceUpdateExists,
87 reconcileDesiredCloudLink,
88 releaseManagedTunnelOnShutdown,
89} from "./cloud/http.ts";
90import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
91import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
92import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
93import * as CloudCliState from "./cloud/CliState.ts";
94import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
95import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
96import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
97import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
98import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
99import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
100import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
101import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
102import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
103import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
104import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
105import {
106 clearPersistedServerRuntimeState,
107 makePersistedServerRuntimeState,
108 persistServerRuntimeState,
109} from "./serverRuntimeState.ts";
110import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
111import * as NetService from "@t3tools/shared/Net";
112import * as RelayClient from "@t3tools/shared/relayClient";
113import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
114import { forkParked, ServerActivation } from "./serverActivation.ts";
115​
116// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
117// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
118// already closes the websocket gracefully. Do not add an artificial drain before
119// those finalizers get a chance to run.
120const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
121const ResourceAttributionLayerLive = ResourceAttribution.layer;
122const ApplicationObservabilityLive = ObservabilityLive.pipe(
123 Layer.provideMerge(ResourceAttributionLayerLive),
124);
125​
126const PtyAdapterLive = Layer.unwrap(
127 Effect.gen(function* () {
128 if (typeof Bun !== "undefined") {
129 const BunPtyAdapter = yield* Effect.promise(() => import("./terminal/BunPtyAdapter.ts"));
130 return BunPtyAdapter.layer;
131 } else {
132 const NodePtyAdapter = yield* Effect.promise(() => import("./terminal/NodePtyAdapter.ts"));
133 return NodePtyAdapter.layer;
134 }
135 }),
136);
137​
138const ServerSettingsLayerLive = ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer));
139​
140const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
141 Layer.provide(ResourceMonitorBinary.layer),
142);
143const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(
144 Layer.provideMerge(ServerSettingsLayerLive),
145);
146​
147const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
148 Layer.provideMerge(NativeTelemetryLayerLive),
149 Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
150);
151​
152const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
153 Layer.provide(DesktopTelemetryReceiverLayerLive),
154);
155​
156const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
157 Layer.provide(HostPowerMonitorLayerLive),
158 Layer.provideMerge(ServerSettingsLayerLive),
159);
160​
161const ResourceDiagnosticsLayerLive = Layer.mergeAll(
162 ResourceTelemetryLayerLive,
163 ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
164 ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
165);
166​
167const RelayClientLive = Layer.unwrap(
168 Effect.gen(function* () {
169 const config = yield* ServerConfig.ServerConfig;
170 return RelayClient.layerCloudflared({ baseDir: config.baseDir });
171 }),
172);
173​
174const HttpServerLive = Layer.unwrap(
175 Effect.gen(function* () {
176 const config = yield* ServerConfig.ServerConfig;
177 if (typeof Bun !== "undefined") {
178 const BunHttpServer = yield* Effect.promise(
179 () => import("@effect/platform-bun/BunHttpServer"),
180 );
181 return BunHttpServer.layer({
182 port: config.port,
183 hostname: config.host ?? "127.0.0.1",
184 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
185 websocket: {
186 // Negotiate permessage-deflate with clients that offer it; clients
187 // that don't still get uncompressed frames on their connection. A
188 // dedicated compressor keeps a per-connection sliding window
189 // (context takeover) so the compression dictionary is shared across
190 // server-to-client frames. Decompression uses the shared
191 // decompressor: uWebSockets' dedicated decompressor path can abort
192 // connections (close 1006) on valid DEFLATE input — see
193 // https://github.com/uNetworking/uWebSockets.js/issues/633.
194 perMessageDeflate: {
195 compress: "dedicated",
196 decompress: "shared",
197 },
198 },
199 });
200 } else {
201 const [NodeHttpServer, NodeHttp] = yield* Effect.all([
202 Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
203 Effect.promise(() => import("node:http")),
204 ]);
205 return NodeHttpServer.layer(NodeHttp.createServer, {
206 host: config.host ?? "127.0.0.1",
207 port: config.port,
208 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
209 // Negotiate permessage-deflate with clients that offer it; clients
210 // that don't still get uncompressed frames on their connection.
211 // Context takeover stays enabled (ws default) so the compression
212 // window is shared across frames — that also makes small frames cheap
213 // to compress, so no size threshold is set (ws only honors
214 // `threshold` when context takeover is disabled).
215 websocket: { perMessageDeflate: true },
216 });
217 }
218 }),
219);
220​
221const PlatformServicesLive = Layer.unwrap(
222 Effect.gen(function* () {
223 if (typeof Bun !== "undefined") {
224 const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
225 return layer;
226 } else {
227 const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
228 return layer;
229 }
230 }),
231);
232​
233const ReactorLayerLive = Layer.empty.pipe(
234 Layer.provideMerge(OrchestrationReactorLive),
235 Layer.provideMerge(ProviderRuntimeIngestionLive),
236 Layer.provideMerge(ProviderCommandReactorLive),
237 Layer.provideMerge(CheckpointReactorLive),
238 Layer.provideMerge(ThreadDeletionReactorLive),
239 Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
240 Layer.provideMerge(RuntimeReceiptBusLive),
241);
242​
243const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
244 Layer.provide(ProviderSessionRuntime.layer),
245);
246​
247// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter
248// by looking up the default `ProviderInstance` per driver in the instance
249// registry. Adapter construction itself moved inside each driver's
250// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical
251// NDJSON writers and is provided at the outer runtime layer so both
252// `ProviderService` and the per-instance drivers read the same logger pair.
253const ProviderLayerLive = ProviderServiceLive.pipe(
254 Layer.provide(ProviderAdapterRegistryLive),
255 Layer.provideMerge(ProviderSessionDirectoryLayerLive),
256);
257​
258const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
259​
260const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
261 Layer.provide(VcsProjectConfig.layer),
262);
263​
264const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
265 Layer.provide(
266 Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
267 ),
268 Layer.provideMerge(GitVcsDriver.layer),
269 Layer.provideMerge(VcsDriverRegistryLayerLive),
270);
271​
272const GitManagerLayerLive = GitManager.layer.pipe(
273 Layer.provideMerge(ProjectSetupScriptRunner.layer),
274 Layer.provideMerge(GitVcsDriver.layer),
275 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
276 Layer.provideMerge(TextGeneration.layer),
277);
278​
279const GitLayerLive = Layer.empty.pipe(
280 Layer.provideMerge(GitManagerLayerLive),
281 Layer.provideMerge(GitVcsDriver.layer),
282);
283​
284const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
285 Layer.provideMerge(VcsDriverRegistryLayerLive),
286 Layer.provideMerge(GitLayerLive),
287);
288​
289const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
290 Layer.provideMerge(GitVcsDriver.layer),
291 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
292);
293​
294const ReviewLayerLive = ReviewService.layer.pipe(
295 Layer.provideMerge(GitVcsDriver.layer),
296 Layer.provideMerge(VcsDriverRegistryLayerLive),
297);
298​
299const VcsLayerLive = Layer.empty.pipe(
300 Layer.provideMerge(VcsProjectConfig.layer),
301 Layer.provideMerge(VcsDriverRegistryLayerLive),
302 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
303 Layer.provideMerge(GitWorkflowLayerLive),
304 Layer.provideMerge(ReviewLayerLive),
305 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
306 Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
307);
308​
309const CheckpointingLayerLive = Layer.empty.pipe(
310 Layer.provideMerge(CheckpointDiffQuery.layer),
311 Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
312);
313​
314const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
315​
316const TerminalLayerLive = TerminalManager.layer.pipe(
317 Layer.provide(PtyAdapterLive),
318 Layer.provide(PortScannerLayerLive),
319);
320​
321const PreviewLayerLive = Layer.empty.pipe(
322 Layer.provideMerge(PreviewManager.layer),
323 Layer.provideMerge(PortScannerLayerLive),
324);
325​
326const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
327​
328const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
329 Layer.provide(WorkspacePaths.layer),
330 Layer.provide(WorkspaceEntriesLayerLive),
331);
332​
333const WorkspaceLayerLive = Layer.mergeAll(
334 WorkspacePaths.layer,
335 WorkspaceEntriesLayerLive,
336 WorkspaceFileSystemLayerLive,
337);
338​
339const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
340 Layer.provide(WorkspacePaths.layer),
341 Layer.provide(T3ProjectFileLoader.layer),
342);
343​
344const AuthLayerLive = EnvironmentAuth.layer.pipe(
345 Layer.provideMerge(PersistenceLayerLive),
346 Layer.provide(ServerSecretStore.layer),
347);
348​
349const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
350 RelayClientLive,
351 CloudManagedEndpointRuntime.layer.pipe(
352 Layer.provide(ServerSecretStore.layer),
353 Layer.provide(RelayClientLive),
354 ),
355);
356​
357const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
358 Layer.provideMerge(ProviderLayerLive),
359 Layer.provideMerge(OrchestrationLayerLive),
360);
361​
362const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
363 // Core Services
364 Layer.provideMerge(ServerSettingsLayerLive),
365 Layer.provideMerge(CheckpointingLayerLive),
366 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
367 Layer.provideMerge(GitLayerLive),
368 Layer.provideMerge(VcsLayerLive),
369 Layer.provideMerge(ProviderRuntimeLayerLive),
370 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
371 Layer.provideMerge(PersistenceLayerLive),
372 Layer.provideMerge(Keybindings.layer),
373 Layer.provideMerge(ProviderRegistryLive),
374 // The instance registry is the new routing keystone — text generation,
375 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
376 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
377 // `providerInstances` hydration merges `settings.providers.<kind>`
378 // with explicit `providerInstances` entries on boot.
379 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
380 // Shared native/canonical NDJSON writers used by both the per-instance
381 // drivers (native stream, written from inside each `<X>Adapter`) and
382 // `ProviderService` (canonical stream, written after event normalization).
383 // Provided once at the runtime level so every consumer sees the same
384 // logger instances.
385 Layer.provideMerge(ProviderEventLoggers.layer),
386 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
387 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
388 // the rewritten registry reads snapshots off the instance registry and
389 // no longer transitively provides it. Exposing it at the runtime level
390 // keeps a single Live for all opencode consumers.
391 Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
392 Layer.provideMerge(WorkspaceLayerLive),
393 Layer.provideMerge(ProjectFaviconResolverLayerLive),
394 Layer.provideMerge(RepositoryIdentityResolver.layer),
395 Layer.provideMerge(ServerEnvironment.layer),
396 Layer.provideMerge(AuthLayerLive),
397 Layer.provideMerge(ServerSecretStore.layer),
398 Layer.provideMerge(
399 Layer.mergeAll(
400 CloudCliTokenManager.layer.pipe(
401 Layer.provide(ServerSecretStore.layer),
402 Layer.provide(ExternalLauncher.layer),
403 ),
404 CloudManagedEndpointRuntimeLive,
405 ),
406 ),
407);
408​
409const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
410 // Misc.
411 Layer.provideMerge(BackgroundLayerLive),
412 Layer.provideMerge(ResourceDiagnosticsLayerLive),
413 Layer.provideMerge(TraceDiagnostics.layer),
414 Layer.provideMerge(AnalyticsService.layer),
415 Layer.provideMerge(ExternalLauncher.layer),
416 Layer.provideMerge(ServerLifecycleEvents.layer),
417 Layer.provide(NetService.layer),
418);
419​
420const commandReadinessLayer = HttpRouter.middleware(
421 (httpEffect) =>
422 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
423 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
424 ),
425 { global: true },
426);
427​
428export const makeRoutesLayer = Layer.mergeAll(
429 Layer.mergeAll(
430 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
431 Layer.provide(authHttpApiLayer),
432 Layer.provide(connectHttpApiLayer),
433 Layer.provide(orchestrationHttpApiLayer),
434 Layer.provide(serverEnvironmentHttpApiLayer),
435 Layer.provide(environmentAuthenticatedAuthLayer),
436 ),
437 otlpTracesProxyRouteLayer,
438 assetRouteLayer,
439 staticAndDevRouteLayer,
440 websocketRpcRouteLayer,
441 ),
442 McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
443).pipe(
444 Layer.provide(PreviewAutomationBroker.layer),
445 Layer.provide(ServerSelfUpdate.layer),
446 Layer.provide(commandReadinessLayer),
447 Layer.provide(browserApiCorsLayer),
448 Layer.provide(httpCompressionLayer),
449);
450​
451export const makeServerLayer = Layer.unwrap(
452 Effect.gen(function* () {
453 const config = yield* ServerConfig.ServerConfig;
454 const activation = yield* Deferred.make<void>();
455 const awaitActivation = Deferred.await(activation);
456 const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
457 const runtimeStateParked = yield* Deferred.make<void>();
458 const tailscaleParked = yield* Deferred.make<void>();
459 const cloudLinkParked = yield* Deferred.make<void>();
460 const routesReady = yield* Deferred.make<void>();
461 const launcherLayer = ServiceLauncherClient.layer;
462​
463 yield* fixPath();
464​
465 const httpListeningLayer = Layer.effectDiscard(
466 Effect.gen(function* () {
467 yield* HttpServer.HttpServer;
468 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
469 yield* startup.markHttpListening;
470 }),
471 );
472 const runtimeStateLayer = Layer.effectDiscard(
473 Effect.acquireRelease(
474 Effect.gen(function* () {
475 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
476 yield* awaitActivation;
477 const server = yield* HttpServer.HttpServer;
478 const address = server.address;
479 if (typeof address === "string" || !("port" in address)) {
480 return;
481 }
482​
483 const state = yield* makePersistedServerRuntimeState({
484 config,
485 port: address.port,
486 });
487 yield* persistServerRuntimeState({
488 path: config.serverRuntimeStatePath,
489 state,
490 }).pipe(
491 Effect.catchCause((cause) =>
492 Effect.logWarning("Failed to persist server runtime state", { cause }),
493 ),
494 );
495 }),
496 () =>
497 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
498 Effect.catchCause((cause) =>
499 Effect.logWarning("Failed to clear server runtime state", { cause }),
500 ),
501 ),
502 ),
503 );
504 const tailscaleServeLayer = config.tailscaleServeEnabled
505 ? Layer.effectDiscard(
506 Effect.acquireRelease(
507 Effect.gen(function* () {
508 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
509 yield* awaitActivation;
510 const server = yield* HttpServer.HttpServer;
511 const address = server.address;
512 if (typeof address === "string" || !("port" in address)) {
513 return null;
514 }
515​
516 const localPort = address.port;
517 return yield* ensureTailscaleServe({
518 localPort,
519 servePort: config.tailscaleServePort,
520 localHost: "127.0.0.1",
521 }).pipe(
522 Effect.as({ localPort, servePort: config.tailscaleServePort }),
523 Effect.tap(() =>
524 Effect.logInfo("Tailscale Serve configured", {
525 localPort,
526 servePort: config.tailscaleServePort,
527 }),
528 ),
529 Effect.catch((cause) =>
530 Effect.logWarning("Failed to configure Tailscale Serve", {
531 cause,
532 localPort,
533 servePort: config.tailscaleServePort,
534 }).pipe(Effect.as(null)),
535 ),
536 );
537 }),
538 (configured) =>
539 configured
540 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
541 Effect.tap(() =>
542 Effect.logInfo("Tailscale Serve disabled", {
543 servePort: configured.servePort,
544 }),
545 ),
546 Effect.catch((cause) =>
547 Effect.logWarning("Failed to disable Tailscale Serve", {
548 cause,
549 servePort: configured.servePort,
550 }),
551 ),
552 )
553 : Effect.void,
554 ),
555 )
556 : Layer.empty;
557 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
558 Effect.gen(function* () {
559 if (!hasCloudPublicConfig) {
560 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
561 return;
562 }
563 const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
564 Effect.timeout("10 seconds"),
565 Effect.tap((released) =>
566 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
567 ),
568 Effect.catchCause((cause) =>
569 Effect.logWarning(
570 "Failed to release the managed tunnel on shutdown; the next link reuses it",
571 { cause },
572 ),
573 ),
574 Effect.asVoid,
575 );
576 // A launcher trial can be stopped before activation. The previous
577 // server is already gone, so the trial owns cleanup immediately; the
578 // pending-state check keeps the tunnel for normal commit or rollback,
579 // while the launcher's explicit-stop marker allows it to be released.
580 // Other runtimes wait for activation so a failed standby cannot tear
581 // down the active runtime's tunnel.
582 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
583 if (cleanupBeforeActivation) {
584 yield* Effect.addFinalizer(() => releaseManagedTunnel);
585 }
586 yield* forkParked(
587 Effect.gen(function* () {
588 if (!cleanupBeforeActivation) {
589 yield* Effect.addFinalizer(() => releaseManagedTunnel);
590 }
591 if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
592 const server = yield* HttpServer.HttpServer;
593 const address = server.address;
594 if (typeof address === "string" || !("port" in address)) return;
595 // No settling delay before the first attempt: routes are already
596 // serving by the time activation opens this gate (the startup
597 // sequence awaits routesReady), and the retry schedule below
598 // covers anything this sleep used to hedge against. Every
599 // millisecond here is dead time on the path to remote
600 // reachability after a restart.
601 yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
602 Effect.retry({
603 while: (error) =>
604 error._tag !== "EnvironmentHttpBadRequestError" &&
605 error._tag !== "EnvironmentHttpUnauthorizedError" &&
606 error._tag !== "EnvironmentHttpConflictError",
607 schedule: Schedule.exponential("1 second").pipe(
608 Schedule.modifyDelay(({ duration }) =>
609 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
610 ),
611 Schedule.upTo({ duration: "10 minutes" }),
612 ),
613 }),
614 Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
615 Effect.catch((cause) =>
616 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
617 cause,
618 }),
619 ),
620 );
621 }),
622 );
623 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
624 }),
625 );
626​
627 const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
628 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
629 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
630 awaitAuxiliaryParked: Effect.all(
631 [
632 Deferred.await(runtimeStateParked),
633 Deferred.await(cloudLinkParked),
634 Deferred.await(routesReady),
635 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
636 ],
637 { concurrency: "unbounded" },
638 ).pipe(Effect.asVoid),
639 }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
640​
641 const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
642 disableLogger: !config.logWebSocketEvents,
643 }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
644 const serverApplicationLayer = Layer.mergeAll(
645 routesLayer,
646 httpListeningLayer,
647 runtimeStateLayer,
648 tailscaleServeLayer,
649 cloudDesiredLinkReconcileLayer,
650 );
651​
652 return serverApplicationLayer.pipe(
653 Layer.provideMerge(runtimeServicesLive),
654 Layer.provide(activationLayer),
655 Layer.provideMerge(serverRelayBrokerTracingLayer),
656 Layer.provideMerge(HttpServerLive),
657 Layer.provide(ApplicationObservabilityLive),
658 Layer.provideMerge(FetchHttpClient.layer),
659 Layer.provideMerge(VcsProcess.layer),
660 Layer.provideMerge(PlatformServicesLive),
661 );
662 }),
663);
664​
665// The CLI supplies configuration.
666export const runServer = Layer.launch(makeServerLayer);