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

DesktopHomeOwner.ts

88 lines4.2 KB

1// @effect-diagnostics nodeBuiltinImport:off - Probes the server's native SQLite ownership lock.
2import * as NodeSqlite from "node:sqlite";
3​
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9​
10import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
11​
12// The fields of the server's `server-runtime.json` that identify the owner of a T3 home.
13const HomeOwnerRuntimeState = Schema.Struct({
14 pid: Schema.Int,
15 port: Schema.Int,
16 serviceManaged: Schema.optional(Schema.Boolean),
17 serverVersion: Schema.optional(Schema.String),
18});
19export type HomeOwner = typeof HomeOwnerRuntimeState.Type;
20​
21const decodeHomeOwner = Schema.decodeUnknownOption(Schema.fromJsonString(HomeOwnerRuntimeState));
22​
23/** Signal 0 only probes existence; EPERM still means alive. */
24const isProcessAlive = (pid: number): boolean => {
25 if (!Number.isInteger(pid) || pid <= 0) return false;
26 try {
27 process.kill(pid, 0);
28 return true;
29 } catch (error) {
30 return error instanceof Error && "code" in error && error.code === "EPERM";
31 }
32};
33​
34/**
35 * Whether a server holds the T3 home's ownership lock (an exclusive transaction on
36 * `server-owner.sqlite`). A read-only read is refused with SQLITE_BUSY only while it is held.
37 */
38export const isHomeOwnershipLocked = Effect.fn("DesktopHomeOwner.isHomeOwnershipLocked")(
39 function* () {
40 const path = yield* Path.Path;
41 const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment;
42 const lockPath = path.join(stateDir, "server-owner.sqlite");
43 return yield* Effect.sync(() => {
44 try {
45 const db = new NodeSqlite.DatabaseSync(lockPath, { readOnly: true });
46 try {
47 db.exec("PRAGMA busy_timeout = 0");
48 db.prepare("SELECT count(*) FROM sqlite_master").get();
49 return false;
50 } finally {
51 db.close();
52 }
53 } catch (cause) {
54 // Anything but SQLITE_BUSY (a missing file included) leaves the decision to the backend.
55 return cause instanceof Error && "errcode" in cause && cause.errcode === 5;
56 }
57 });
58 },
59);
60​
61/** The live server recorded as owning the desktop's T3 home. Only call once the ownership lock is known held: a live PID alone may be reused. */
62export const readLiveHomeOwner = Effect.fn("DesktopHomeOwner.readLiveHomeOwner")(function* () {
63 const fs = yield* FileSystem.FileSystem;
64 const path = yield* Path.Path;
65 const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment;
66 const raw = yield* fs
67 .readFileString(path.join(stateDir, "server-runtime.json"))
68 .pipe(Effect.option);
69 return Option.flatMap(raw, decodeHomeOwner).pipe(
70 Option.filter((owner) => isProcessAlive(owner.pid)),
71 );
72});
73​
74export const homeOwnedMessage = (owner: Option.Option<HomeOwner>): string =>
75 Option.match(owner, {
76 onNone: () =>
77 "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.",
78 onSome: (owner) => {
79 const kind = owner.serviceManaged
80 ? "The T3 Code background service"
81 : "Another T3 Code server (for example `t3 serve`, or one started over SSH)";
82 const version = owner.serverVersion ? `, version ${owner.serverVersion}` : "";
83 const stop = owner.serviceManaged
84 ? "Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home"
85 : "If a T3 Code app on another machine started it over SSH, that app restarts it: remove or disconnect that SSH environment there, or quit that app. Then stop the server";
86 return `${kind} is using this T3 home (PID ${owner.pid}, port ${owner.port}${version}). ${stop}, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.`;
87 },
88 });