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

server.ts

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