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

main.ts

347 lines11.3 KB

1/**
2 * CliConfig - CLI/runtime bootstrap service definitions.
3 *
4 * Defines startup-only service contracts used while resolving process config
5 * and constructing server runtime layers.
6 *
7 * @module CliConfig
8 */
9import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
10import { Command, Flag } from "effect/unstable/cli";
11import { NetService } from "@t3tools/shared/Net";
12import {
13 DEFAULT_PORT,
14 resolveStaticDir,
15 ServerConfig,
16 type RuntimeMode,
17 type ServerConfigShape,
18} from "./config";
19import { fixPath, resolveStateDir } from "./os-jank";
20import { Open } from "./open";
21import * as SqlitePersistence from "./persistence/Layers/Sqlite";
22import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
23import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
24import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
25import { Server } from "./wsServer";
26import { ServerLoggerLive } from "./serverLogger";
27import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
28import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
29​
30export class StartupError extends Data.TaggedError("StartupError")<{
31 readonly message: string;
32 readonly cause?: unknown;
33}> {}
34​
35interface CliInput {
36 readonly mode: Option.Option<RuntimeMode>;
37 readonly port: Option.Option<number>;
38 readonly host: Option.Option<string>;
39 readonly stateDir: Option.Option<string>;
40 readonly devUrl: Option.Option<URL>;
41 readonly noBrowser: Option.Option<boolean>;
42 readonly authToken: Option.Option<string>;
43 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
44 readonly logWebSocketEvents: Option.Option<boolean>;
46​
47/**
48 * CliConfigShape - Startup helpers required while building server layers.
49 */
50export interface CliConfigShape {
51 /**
52 * Current process working directory.
53 */
54 readonly cwd: string;
55​
56 /**
57 * Apply OS-specific PATH normalization.
58 */
59 readonly fixPath: Effect.Effect<void>;
60​
61 /**
62 * Resolve static web asset directory for server mode.
63 */
64 readonly resolveStaticDir: Effect.Effect<string | undefined>;
66​
67/**
68 * CliConfig - Service tag for startup CLI/runtime helpers.
69 */
70export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
71 "t3/main/CliConfig",
72) {
73 static readonly layer = Layer.effect(
74 CliConfig,
75 Effect.gen(function* () {
76 const fileSystem = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 return {
79 cwd: process.cwd(),
80 fixPath: Effect.sync(fixPath),
81 resolveStaticDir: resolveStaticDir().pipe(
82 Effect.provideService(FileSystem.FileSystem, fileSystem),
83 Effect.provideService(Path.Path, path),
84 ),
85 } satisfies CliConfigShape;
86 }),
87 );
89​
90const CliEnvConfig = Config.all({
91 mode: Config.string("T3CODE_MODE").pipe(
92 Config.option,
93 Config.map(
94 Option.match<RuntimeMode, string>({
95 onNone: () => "web",
96 onSome: (value) => (value === "desktop" ? "desktop" : "web"),
97 }),
98 ),
99 ),
100 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
101 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
102 stateDir: Config.string("T3CODE_STATE_DIR").pipe(
103 Config.option,
104 Config.map(Option.getOrUndefined),
105 ),
106 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
107 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
108 Config.option,
109 Config.map(Option.getOrUndefined),
110 ),
111 authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
112 Config.option,
113 Config.map(Option.getOrUndefined),
114 ),
115 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
116 Config.option,
117 Config.map(Option.getOrUndefined),
118 ),
119 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
120 Config.option,
121 Config.map(Option.getOrUndefined),
122 ),
123});
124​
125const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
126 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
127​
128const ServerConfigLive = (input: CliInput) =>
129 Layer.effect(
130 ServerConfig,
131 Effect.gen(function* () {
132 const cliConfig = yield* CliConfig;
133 const { findAvailablePort } = yield* NetService;
134 const env = yield* CliEnvConfig.asEffect().pipe(
135 Effect.mapError(
136 (cause) =>
137 new StartupError({ message: "Failed to read environment configuration", cause }),
138 ),
139 );
140​
141 const mode = Option.getOrElse(input.mode, () => env.mode);
142​
143 const port = yield* Option.match(input.port, {
144 onSome: (value) => Effect.succeed(value),
145 onNone: () => {
146 if (env.port) {
147 return Effect.succeed(env.port);
148 }
149 if (mode === "desktop") {
150 return Effect.succeed(DEFAULT_PORT);
151 }
152 return findAvailablePort(DEFAULT_PORT);
153 },
154 });
155 const stateDir = yield* resolveStateDir(
156 Option.getOrUndefined(input.stateDir) ?? env.stateDir,
157 );
158 const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
159 const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
160 const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
161 const autoBootstrapProjectFromCwd = resolveBooleanFlag(
162 input.autoBootstrapProjectFromCwd,
163 env.autoBootstrapProjectFromCwd ?? mode === "web",
164 );
165 const logWebSocketEvents = resolveBooleanFlag(
166 input.logWebSocketEvents,
167 env.logWebSocketEvents ?? Boolean(devUrl),
168 );
169 const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
170 const { join } = yield* Path.Path;
171 const keybindingsConfigPath = join(stateDir, "keybindings.json");
172 const host =
173 Option.getOrUndefined(input.host) ??
174 env.host ??
175 (mode === "desktop" ? "127.0.0.1" : undefined);
176​
177 const config: ServerConfigShape = {
178 mode,
179 port,
180 cwd: cliConfig.cwd,
181 keybindingsConfigPath,
182 host,
183 stateDir,
184 staticDir,
185 devUrl,
186 noBrowser,
187 authToken,
188 autoBootstrapProjectFromCwd,
189 logWebSocketEvents,
190 } satisfies ServerConfigShape;
191​
192 return config;
193 }),
194 );
195​
196const LayerLive = (input: CliInput) =>
197 Layer.empty.pipe(
198 Layer.provideMerge(makeServerRuntimeServicesLayer()),
199 Layer.provideMerge(makeServerProviderLayer()),
200 Layer.provideMerge(ProviderHealthLive),
201 Layer.provideMerge(SqlitePersistence.layerConfig),
202 Layer.provideMerge(ServerLoggerLive),
203 Layer.provideMerge(AnalyticsServiceLayerLive),
204 Layer.provideMerge(ServerConfigLive(input)),
205 );
206​
207const isWildcardHost = (host: string | undefined): boolean =>
208 host === "0.0.0.0" || host === "::" || host === "[::]";
209​
210const formatHostForUrl = (host: string): string =>
211 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
212​
213export const recordStartupHeartbeat = Effect.gen(function* () {
214 const analytics = yield* AnalyticsService;
215 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
216​
217 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
218 Effect.map((snapshot) => ({
219 threadCount: snapshot.threads.length,
220 projectCount: snapshot.projects.length,
221 })),
222 Effect.catch((cause) =>
223 Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
224 Effect.as({
225 threadCount: 0,
226 projectCount: 0,
227 }),
228 ),
229 ),
230 );
231​
232 yield* analytics.record("server.boot.heartbeat", {
233 threadCount,
234 projectCount,
235 });
236});
237​
238const makeServerProgram = (input: CliInput) =>
239 Effect.gen(function* () {
240 const cliConfig = yield* CliConfig;
241 const { start, stopSignal } = yield* Server;
242 const openDeps = yield* Open;
243 yield* cliConfig.fixPath;
244​
245 const config = yield* ServerConfig;
246​
247 if (!config.devUrl && !config.staticDir) {
248 yield* Effect.logWarning(
249 "web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
250 {
251 hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
252 },
253 );
254 }
255​
256 yield* start;
257 yield* Effect.forkChild(recordStartupHeartbeat);
258​
259 const localUrl = `http://localhost:${config.port}`;
260 const bindUrl =
261 config.host && !isWildcardHost(config.host)
262 ? `http://${formatHostForUrl(config.host)}:${config.port}`
263 : localUrl;
264 const { authToken, devUrl, ...safeConfig } = config;
265 yield* Effect.logInfo("T3 Code running", {
266 ...safeConfig,
267 devUrl: devUrl?.toString(),
268 authEnabled: Boolean(authToken),
269 });
270​
271 if (!config.noBrowser) {
272 const target = config.devUrl?.toString() ?? bindUrl;
273 yield* openDeps.openBrowser(target).pipe(
274 Effect.catch(() =>
275 Effect.logInfo("browser auto-open unavailable", {
276 hint: `Open ${target} in your browser.`,
277 }),
278 ),
279 );
280 }
281​
282 return yield* stopSignal;
283 }).pipe(Effect.provide(LayerLive(input)));
284​
285/**
286 * These flags mirrors the environment variables and the config shape.
287 */
288​
289const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
290 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
291 Flag.optional,
292);
293const portFlag = Flag.integer("port").pipe(
294 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
295 Flag.withDescription("Port for the HTTP/WebSocket server."),
296 Flag.optional,
297);
298const hostFlag = Flag.string("host").pipe(
299 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
300 Flag.optional,
301);
302const stateDirFlag = Flag.string("state-dir").pipe(
303 Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
304 Flag.optional,
305);
306const devUrlFlag = Flag.string("dev-url").pipe(
307 Flag.withSchema(Schema.URLFromString),
308 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
309 Flag.optional,
310);
311const noBrowserFlag = Flag.boolean("no-browser").pipe(
312 Flag.withDescription("Disable automatic browser opening."),
313 Flag.optional,
314);
315const authTokenFlag = Flag.string("auth-token").pipe(
316 Flag.withDescription("Auth token required for WebSocket connections."),
317 Flag.withAlias("token"),
318 Flag.optional,
319);
320const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
321 Flag.withDescription(
322 "Create a project for the current working directory on startup when missing.",
323 ),
324 Flag.optional,
325);
326const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
327 Flag.withDescription(
328 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
329 ),
330 Flag.withAlias("log-ws-events"),
331 Flag.optional,
332);
333​
334export const t3Cli = Command.make("t3", {
335 mode: modeFlag,
336 port: portFlag,
337 host: hostFlag,
338 stateDir: stateDirFlag,
339 devUrl: devUrlFlag,
340 noBrowser: noBrowserFlag,
341 authToken: authTokenFlag,
342 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
343 logWebSocketEvents: logWebSocketEventsFlag,
344}).pipe(
345 Command.withDescription("Run the T3 Code server."),
346 Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
347);