import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification"; import packageJson from "../package.json" with { type: "json" }; import type * as ServerConfig from "./config.ts"; export const PersistedServerRuntimeState = Schema.Struct({ version: Schema.Literal(1), pid: Schema.Int, // The machine `pid` belongs to; a T3 home on a shared filesystem is read by others. Absent from older servers. hostname: Schema.optional(Schema.String), ownerId: Schema.optional(Schema.String), host: Schema.optional(Schema.String), privateNetworkOnly: Schema.optional(Schema.Boolean), port: Schema.Int, origin: Schema.String, // Dev is single-origin: browsers must pair through this URL, not `origin`. devUrl: Schema.optional(Schema.String), startedAt: Schema.String, serviceManaged: Schema.optional(Schema.Boolean), serverVersion: Schema.optional(Schema.String), // The managed policy this server loaded at startup, null for none; absent from older servers. managedPolicy: Schema.optional( Schema.NullOr( Schema.Struct({ source: Schema.String, organization: Schema.String, fingerprint: Schema.String, }), ), ), }); export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type; export class ServerRuntimeStateError extends Schema.TaggedError()( "ServerRuntimeStateError", { operation: Schema.Literals(["persist", "read", "decode", "clear"]), statePath: Schema.String, cause: Schema.Defect(), }, ) { override get message(): string { return `Failed to ${this.operation} server runtime state at ${this.statePath}.`; } } const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect( Schema.fromJsonString(PersistedServerRuntimeState), ); const runtimeOriginForConfig = ( config: Pick, port: number, ): PersistedServerRuntimeState["origin"] => { const hostname = config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1"; return `http://${hostname}:${port}`; }; export const makePersistedServerRuntimeState = Effect.fn( "serverRuntimeState.makePersistedServerRuntimeState", )(function* (input: { readonly config: Pick< ServerConfig.ServerConfig["Service"], "host" | "privateNetworkOnly" | "devUrl" >; readonly port: number; readonly serviceManaged?: boolean; readonly managedPolicy?: PersistedServerRuntimeState["managedPolicy"]; }) { const now = yield* DateTime.now; return { version: 1 as const, pid: process.pid, hostname: yield* HostProcess.Hostname, ...(input.config.host ? { host: input.config.host } : {}), ...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}), port: input.port, origin: runtimeOriginForConfig(input.config, input.port), ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}), startedAt: DateTime.formatIso(now), ...(input.serviceManaged ? { serviceManaged: true } : {}), serverVersion: packageJson.version, ...(input.managedPolicy === undefined ? {} : { managedPolicy: input.managedPolicy }), } satisfies PersistedServerRuntimeState; }); export const persistServerRuntimeState = (input: { readonly path: string; readonly state: PersistedServerRuntimeState; }) => writeFileStringAtomically({ filePath: input.path, contents: `${JSON.stringify(input.state)}\n`, }).pipe( Effect.mapError( (cause) => new ServerRuntimeStateError({ operation: "persist", statePath: input.path, cause, }), ), ); export const clearPersistedServerRuntimeState = Effect.fn( "serverRuntimeState.clearPersistedServerRuntimeState", )(function* (path: string) { const fs = yield* FileSystem.FileSystem; yield* fs.remove(path, { force: true }).pipe( Effect.mapError( (cause) => new ServerRuntimeStateError({ operation: "clear", statePath: path, cause, }), ), Effect.catchTags({ ServerRuntimeStateError: (error) => Effect.logWarning(error.message).pipe( Effect.annotateLogs({ operation: error.operation, statePath: error.statePath, cause: error, }), ), }), ); }); /** Signal 0 only probes existence; EPERM still means alive. */ export const isProcessAlive = (pid: number): boolean => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (error) { return error instanceof Error && "code" in error && error.code === "EPERM"; } }; /** * The recorded machine when it is not this one. Its PID and loopback origin mean nothing * here. A hostname can also change under a running server, so this alone does not prove * the server is elsewhere. */ export const runtimeStateOtherMachine = Effect.fn("serverRuntimeState.runtimeStateOtherMachine")( function* (state: Pick) { const hostname = yield* HostProcess.Hostname; return state.hostname !== undefined && state.hostname !== hostname ? state.hostname : undefined; }, ); export const readPersistedServerRuntimeState = Effect.fn( "serverRuntimeState.readPersistedServerRuntimeState", )( function* (path: string) { const fs = yield* FileSystem.FileSystem; const raw = yield* fs.readFileString(path).pipe( Effect.matchEffect({ onFailure: (cause) => cause.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail( new ServerRuntimeStateError({ operation: "read", statePath: path, cause, }), ), onSuccess: (contents) => Effect.succeedSome(contents), }), ); if (Option.isNone(raw)) { return Option.none(); } const trimmed = raw.value.trim(); if (trimmed.length === 0) { return Option.none(); } return yield* decodePersistedServerRuntimeState(trimmed).pipe( Effect.asSome, Effect.mapError( (cause) => new ServerRuntimeStateError({ operation: "decode", statePath: path, cause, }), ), ); }, Effect.catchTags({ ServerRuntimeStateError: (error) => Effect.logWarning(error.message).pipe( Effect.annotateLogs({ operation: error.operation, statePath: error.statePath, cause: error, }), Effect.as(Option.none()), ), }), ); /** * The runtime record, only while its server process is alive. Read this before sending * credentials to the recorded origin: a killed server leaves its record behind, and * another process may own its port by now. */ export const readLiveServerRuntimeState = Effect.fn( "serverRuntimeState.readLiveServerRuntimeState", )((path: string) => readPersistedServerRuntimeState(path).pipe( Effect.map(Option.filter((state) => isProcessAlive(state.pid))), ), );