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

main.ts

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