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

DesktopHomeOwner.ts

106 lines5.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - Probes the server's native SQLite ownership lock.
2import * as NodeSqlite from "node:sqlite";
3​
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10​
11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12import { BACKEND_QUIT_STOP_TIMEOUT } from "./DesktopBackendManager.ts";
13​
14// The fields of the server's `server-runtime.json` that identify the owner of a T3 home.
15const HomeOwnerRuntimeState = Schema.Struct({
16 pid: Schema.Int,
17 port: Schema.Int,
18 serviceManaged: Schema.optional(Schema.Boolean),
19 serverVersion: Schema.optional(Schema.String),
20});
21export type HomeOwner = typeof HomeOwnerRuntimeState.Type;
22​
23const decodeHomeOwner = Schema.decodeUnknownOption(Schema.fromJsonString(HomeOwnerRuntimeState));
24​
25/** Signal 0 only probes existence; EPERM still means alive. */
26const isProcessAlive = (pid: number): boolean => {
27 if (!Number.isInteger(pid) || pid <= 0) return false;
28 try {
29 process.kill(pid, 0);
30 return true;
31 } catch (error) {
32 return error instanceof Error && "code" in error && error.code === "EPERM";
33 }
34};
35​
36/**
37 * Whether a server holds the T3 home's ownership lock (an exclusive transaction on
38 * `server-owner.sqlite`). A read-only read is refused with SQLITE_BUSY only while it is held.
39 */
40const isHomeOwnershipLocked = Effect.fn("DesktopHomeOwner.isHomeOwnershipLocked")(function* () {
41 const path = yield* Path.Path;
42 const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment;
43 const lockPath = path.join(stateDir, "server-owner.sqlite");
44 return yield* Effect.sync(() => {
45 try {
46 const db = new NodeSqlite.DatabaseSync(lockPath, { readOnly: true });
47 try {
48 db.exec("PRAGMA busy_timeout = 0");
49 db.prepare("SELECT count(*) FROM sqlite_master").get();
50 return false;
51 } finally {
52 db.close();
53 }
54 } catch (cause) {
55 // Anything but SQLITE_BUSY (a missing file included) leaves the decision to the backend.
56 return cause instanceof Error && "errcode" in cause && cause.errcode === 5;
57 }
58 });
59});
60​
61// A quitting app's backend holds the lock until it exits, which can outlast the relaunch of an update.
62const HOME_OWNERSHIP_RELEASE_GRACE = Duration.sum(BACKEND_QUIT_STOP_TIMEOUT, Duration.seconds(3));
63const HOME_OWNERSHIP_RELEASE_POLL_INTERVAL = Duration.millis(250);
64​
65/** Whether the ownership lock is free, or frees within the grace a shutting-down server needs. */
66export const awaitHomeOwnershipRelease = Effect.fn("DesktopHomeOwner.awaitHomeOwnershipRelease")(
67 function* () {
68 while (yield* isHomeOwnershipLocked()) {
69 yield* Effect.sleep(HOME_OWNERSHIP_RELEASE_POLL_INTERVAL);
70 }
71 return true;
72 },
73 Effect.timeoutOrElse({
74 duration: HOME_OWNERSHIP_RELEASE_GRACE,
75 orElse: () => Effect.succeed(false),
76 }),
77);
78​
79/** 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. */
80export const readLiveHomeOwner = Effect.fn("DesktopHomeOwner.readLiveHomeOwner")(function* () {
81 const fs = yield* FileSystem.FileSystem;
82 const path = yield* Path.Path;
83 const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment;
84 const raw = yield* fs
85 .readFileString(path.join(stateDir, "server-runtime.json"))
86 .pipe(Effect.option);
87 return Option.flatMap(raw, decodeHomeOwner).pipe(
88 Option.filter((owner) => isProcessAlive(owner.pid)),
89 );
90});
91​
92export const homeOwnedMessage = (owner: Option.Option<HomeOwner>): string =>
93 Option.match(owner, {
94 onNone: () =>
95 "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.",
96 onSome: (owner) => {
97 const kind = owner.serviceManaged
98 ? "The T3 Code background service"
99 : "Another T3 Code server (for example `t3 serve`, or one started over SSH)";
100 const version = owner.serverVersion ? `, version ${owner.serverVersion}` : "";
101 const stop = owner.serviceManaged
102 ? "Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home"
103 : "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";
104 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.`;
105 },
106 });