Skip to content
TypeScript

fix(server): preserve service environment across updates (#19486)

James C29a7d80469e7
diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts
index bbaf441383f..a838b710c84 100644
--- a/apps/server/src/cloud/bootService.test.ts
+++ b/apps/server/src/cloud/bootService.test.ts
@@ -15,6 +15,7 @@ import * as BootService from "./bootService.ts";
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
import {
parseServiceState,
+ SERVICE_ENV_FILE,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_RESTART_PENDING_FILE,
serviceStateHasPendingUpdate,
@@ -246,7 +247,18 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
),
);
const service = yield* makeService();
- return { service, makeService, fs, statePath, commands, invocations, timeouts, control, runtime };
+ return {
+ service,
+ makeService,
+ fs,
+ baseDir,
+ statePath,
+ commands,
+ invocations,
+ timeouts,
+ control,
+ runtime,
+ };
});
it.layer(NodeServices.layer)("boot service install", (it) => {
@@ -487,34 +499,48 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
- it.effect("install with start=false rewrites the files and marks a restart pending", () =>
- Effect.gen(function* () {
- const { service, fs, statePath, commands, makeService } = yield* makeHarness();
- yield* service.install();
- commands.length = 0;
+ it.effect.each(["linux", "darwin"] as const)(
+ "install with start=false rewrites files, preserves service.env, and marks a restart pending on %s",
+ (platform) =>
+ Effect.gen(function* () {
+ const { service, fs, baseDir, statePath, commands, makeService } =
+ yield* makeHarness(platform);
+ const path = yield* Path.Path;
+ const envPath = path.join(baseDir, SERVICE_ENV_FILE);
+ const envBytes = new TextEncoder().encode(
+ '# user configuration\r\nT3CODE_TOKEN="literal $HOME # token"',
+ );
+ yield* fs.writeFile(envPath, envBytes);
+ yield* service.install();
+ expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
+ yield* service.install();
+ expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
+ commands.length = 0;
- const newer = yield* makeService(undefined, "1.2.4");
- const plan = yield* newer.install({ start: false });
+ const newer = yield* makeService(undefined, "1.2.4");
+ const plan = yield* newer.install({ start: false });
+ expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
- expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
- protocol: SERVICE_LAUNCHER_PROTOCOL,
- activeVersion: "1.2.4",
- });
- expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
- expect(
- commands.filter(
- (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
- ),
- ).toEqual([]);
- const status = yield* newer.status;
- expect(status.current).toBe(false);
- expect(status.problems).toContain("restart-pending");
+ expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
+ protocol: SERVICE_LAUNCHER_PROTOCOL,
+ activeVersion: "1.2.4",
+ });
+ expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
+ expect(
+ commands.filter(
+ (command) =>
+ /^(systemctl|launchctl) /.test(command) && !command.includes("show-environment"),
+ ),
+ ).toEqual([]);
+ const status = yield* newer.status;
+ expect(status.current).toBe(false);
+ expect(status.problems).toContain("restart-pending");
- commands.length = 0;
- expect(yield* newer.restart).toBe("restarted");
- expect((yield* newer.status).problems).not.toContain("restart-pending");
- expect((yield* newer.status).current).toBe(true);
- }),
+ commands.length = 0;
+ expect(yield* newer.restart).toBe("restarted");
+ expect((yield* newer.status).problems).not.toContain("restart-pending");
+ expect((yield* newer.status).current).toBe(true);
+ }),
);
it.effect("install with start=false keeps the marker when a later write fails", () =>
diff --git a/apps/server/src/cloud/serviceProtocol.ts b/apps/server/src/cloud/serviceProtocol.ts
index 004cc7de504..5704c38b8af 100644
--- a/apps/server/src/cloud/serviceProtocol.ts
+++ b/apps/server/src/cloud/serviceProtocol.ts
@@ -4,6 +4,7 @@ import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
// or the installed runtime tree changes incompatibly; launchers survive self-updates.
export const SERVICE_LAUNCHER_PROTOCOL = 3 as const;
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
+export const SERVICE_ENV_FILE = "service.env";
export const SERVICE_STATE_FILE = "service-state.json";
/** Written by the launcher just before an explicit stop kills its child, so
the child can tell "the service is going away" from "the launcher is about
diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts
index 3381b763053..faba5b27071 100644
--- a/apps/server/src/serviceLauncher.test.ts
+++ b/apps/server/src/serviceLauncher.test.ts
@@ -12,6 +12,8 @@ import { vi } from "vite-plus/test";
import {
databaseBackupBlocker,
Launcher,
+ main,
+ readServiceEnvironment,
PREPARED_TIMEOUT_MS,
type BackupSpaceProbe,
readServiceState,
@@ -21,6 +23,7 @@ import {
compareExactServiceVersions,
decodeServiceState,
isExactServiceVersion,
+ SERVICE_ENV_FILE,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_RESTART_PENDING_FILE,
SERVICE_STOP_MARKER_FILE,
@@ -126,6 +129,52 @@ const writeFakeRuntime = (
});
it.layer(NodeServices.layer)("service state persistence", (it) => {
+ it.effect(
+ "loads optional service.env literally without changing inherited or managed variables",
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-env-" });
+ const inherited = Object.freeze({
+ PATH: "inherited-path",
+ T3CODE_HOME: root,
+ T3_BOOT_SERVICE_UNIT: "managed-unit",
+ T3_SERVICE_LAUNCHER_CONTEXT: "managed-context",
+ T3CODE_PORT: "ambient",
+ });
+ assert.deepEqual(
+ yield* Effect.promise(() => readServiceEnvironment(root, inherited)),
+ inherited,
+ );
+ yield* fs.writeFileString(
+ path.join(root, SERVICE_ENV_FILE),
+ [
+ "# service configuration",
+ "export T3CODE_PORT=1234 # inline comment",
+ 'T3CODE_TOKEN="literal $HOME ${USER} $(whoami) # token"',
+ 'MULTILINE="first\nsecond"',
+ "EMPTY=",
+ "PATH=/bad",
+ "Path=/bad",
+ "T3CODE_HOME=/bad",
+ "t3code_home=/bad",
+ "T3_BOOT_SERVICE_UNIT=bad",
+ "t3_boot_service_unit=bad",
+ "T3_SERVICE_LAUNCHER_CONTEXT=bad",
+ "t3_service_launcher_context=bad",
+ ].join("\n"),
+ );
+ assert.deepEqual(yield* Effect.promise(() => readServiceEnvironment(root, inherited)), {
+ ...inherited,
+ T3CODE_PORT: "1234",
+ T3CODE_TOKEN: "literal $HOME ${USER} $(whoami) # token",
+ MULTILINE: "first\nsecond",
+ EMPTY: "",
+ });
+ }),
+ );
+
it.effect("durably replaces and strictly reads one state document", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -303,21 +352,33 @@ if (context.update?.status === "pending") {
}),
);
- it.effect("rolls back a trial that reports the wrong update ID", () =>
+ it.effect("rolls back invalid trials with the startup environment", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
+ const observationsPath = path.join(root, "environment-observations.jsonl");
+ const envPath = path.join(root, SERVICE_ENV_FILE);
+ yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n");
+ vi.stubEnv("T3CODE_HOME", root);
+ vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited");
+ yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs()));
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, "before trial");
const encodedDatabasePath = JSON.stringify(databasePath);
const childSource = `
+import { appendFileSync, writeFileSync } from "node:fs";
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
+appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({
+ token: process.env.T3CODE_TEST_SERVICE_TOKEN,
+ update: context.update?.status ?? "active",
+}) + "\\n");
if (context.update?.status === "pending") {
process.send({ type: "prepared", updateId: "wrong-update" });
} else if (context.update === undefined) {
+ writeFileSync(${JSON.stringify(envPath)}, "T3CODE_TEST_SERVICE_TOKEN=changed\\n");
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
setInterval(() => {}, 1_000);
} else {
@@ -339,9 +400,8 @@ if (context.update?.status === "pending") {
}),
);
- const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
yield* Effect.promise(() =>
- launcher.run().then(
+ main().then(
() => Promise.reject(new Error("launcher unexpectedly completed")),
() => Promise.resolve(),
),
@@ -354,6 +414,17 @@ if (context.update?.status === "pending") {
state.update?.status === "rolled-back" ? state.update.reason : undefined,
"invalid-prepared",
);
+ const observations = (yield* fs.readFileString(observationsPath))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ assert.deepEqual(observations, [
+ { token: "initial", update: "active" },
+ { token: "initial", update: "pending" },
+ { token: "initial", update: "rolled-back" },
+ ]);
+ assert.equal(process.env.T3CODE_TEST_SERVICE_TOKEN, "inherited");
+ assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n");
}),
);
diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts
index 86470023dcb..e57c4b14905 100644
--- a/apps/server/src/serviceLauncher.ts
+++ b/apps/server/src/serviceLauncher.ts
@@ -9,6 +9,7 @@ import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
+import * as NodeUtil from "node:util";
import type {
PendingServiceUpdate,
@@ -23,6 +24,7 @@ import {
decodeServiceLauncherChildMessage,
isExactServiceVersion,
parseServiceState,
+ SERVICE_ENV_FILE,
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
@@ -85,6 +87,36 @@ async function pathExists(target: string): Promise<boolean> {
}
}
+const MANAGED_SERVICE_ENV_NAMES = new Set([
+ "PATH",
+ "T3CODE_HOME",
+ "T3_BOOT_SERVICE_UNIT",
+ SERVICE_LAUNCHER_CONTEXT_ENV,
+]);
+
+export async function readServiceEnvironment(
+ baseDir: string,
+ inherited: NodeJS.ProcessEnv = process.env,
+): Promise<NodeJS.ProcessEnv> {
+ const environment = { ...inherited };
+ let contents: string;
+ try {
+ contents = await NodeFSP.readFile(NodePath.join(baseDir, SERVICE_ENV_FILE), "utf8");
+ } catch (cause) {
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return environment;
+ throw cause;
+ }
+ for (const [name, value] of Object.entries(NodeUtil.parseEnv(contents))) {
+ if (
+ /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) &&
+ !MANAGED_SERVICE_ENV_NAMES.has(name.toUpperCase())
+ ) {
+ environment[name] = value;
+ }
+ }
+ return environment;
+}
+
// Opened read-write: Windows refuses to flush a handle without write access.
async function syncFile(filePath: string): Promise<void> {
const handle = await NodeFSP.open(filePath, "r+");
@@ -443,14 +475,19 @@ export class Launcher {
#done = false;
readonly #completion = Promise.withResolvers<void>();
readonly #backupSpaceProbe: Partial<BackupSpaceProbe> | undefined;
+ readonly #environment: Readonly<NodeJS.ProcessEnv>;
constructor(
baseDir: string,
state: ServiceState,
- options: { readonly backupSpaceProbe?: Partial<BackupSpaceProbe> } = {},
+ options: {
+ readonly backupSpaceProbe?: Partial<BackupSpaceProbe>;
+ readonly environment?: Readonly<NodeJS.ProcessEnv>;
+ } = {},
) {
this.#baseDir = baseDir;
this.#backupSpaceProbe = options.backupSpaceProbe;
+ this.#environment = { ...(options.environment ?? process.env) };
this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
this.#state = state;
}
@@ -581,7 +618,7 @@ export class Launcher {
};
const spawnArguments = runtimeSpawnArguments(paths);
const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
- env: { ...process.env, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
+ env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
stdio: ["inherit", "inherit", "inherit", "ipc"],
});
await new Promise<void>((resolve, reject) => {
@@ -829,7 +866,8 @@ export async function main(): Promise<void> {
if (baseDir === undefined || baseDir === "") {
throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
}
+ const environment = await readServiceEnvironment(baseDir);
const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
const state = await readServiceState(statePath);
- await new Launcher(baseDir, state).run();
+ await new Launcher(baseDir, state, { environment }).run();
}
diff --git a/docs/user/background-service.md b/docs/user/background-service.md
index 83693a106c9..6f3c56d53a5 100644
--- a/docs/user/background-service.md
+++ b/docs/user/background-service.md
@@ -37,8 +37,32 @@ installing one.
`t3 uninstall` removes the background service, the `t3` launcher, and the
downloaded versions after showing you the list and asking once. Your projects,
-threads, and settings under `~/.t3/userdata` are kept. Pass `--yes` from a
-script.
+threads, and settings under `~/.t3/userdata` are kept, along with `service.env`
+under T3 home. Pass `--yes` from a script.
+
+## Configure the service environment
+
+Put custom environment variables in `service.env` under the service's T3 home
+directory, normally `~/.t3/service.env`. This file survives service installation
+and updates. For example:
+
+```dotenv
+T3CODE_PORT=3773
+T3CODE_HOST=127.0.0.1
+```
+
+Use `KEY=VALUE` entries, quoting values that contain spaces or `#`. Values are
+literal: shell commands and variable expansion are not evaluated. Entries
+override the inherited service environment, except for `PATH`, `T3CODE_HOME`,
+`T3_BOOT_SERVICE_UNIT`, and `T3_SERVICE_LAUNCHER_CONTEXT` (including case variants).
+
+Run `t3 service restart` after changing the file. Changes apply when the service
+starts again; switching the server version alone keeps the current values.
+For a service installed before env-file support, run `t3 service install` once
+with an up-to-date CLI.
+A missing file is ignored; other read failures stop service startup.
+If the file contains credentials, restrict access to that file with `chmod 600`
+(for the default T3 home, `chmod 600 ~/.t3/service.env`).
## Platform support
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index 5fc4bfd81de..a065639aba2 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -87,6 +87,11 @@ export T3CODE_BITBUCKET_EMAIL="[email protected]"
export T3CODE_BITBUCKET_API_TOKEN="your-token"
```
+For a background service, put these `KEY=VALUE` entries in
+[`service.env`](./background-service.md#configure-the-service-environment)
+under T3 home, then run `t3 service restart`. Service installation and updates
+preserve that file.
+
### Azure DevOps
Install [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/), add the DevOps extension, and sign in: