Skip to content

Commit 9561900

Browse files
fix(relay): make the client-config env write robust to duplicates and line breaks
- reconcileEnvFile drops every existing assignment for a name rather than the first; the file is read with parseEnv, where the last duplicate wins. - A provider value carrying a line break fails the Action instead of adding an assignment. - The test file suppresses anyUnknownInErrorContext for Alchemy's ScratchStack.deploy, whose error channel is any upstream. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 8ae0262 commit 9561900

2 files changed

Lines changed: 74 additions & 16 deletions

File tree

‎infra/relay/src/clientConfig.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// @effect-diagnostics anyUnknownInErrorContext:off - ScratchStack.deploy is typed with `any` in its error channel by Alchemy.
12
import { inMemoryState } from "alchemy/State";
23
import * as Test from "alchemy/Test/Vitest";
34
import * as ConfigProvider from "effect/ConfigProvider";
@@ -26,6 +27,14 @@ describe("reconcileEnvFile", () => {
2627
it("appends a newline before adding to a file without one", () => {
2728
expect(reconcileEnvFile("A=1", { B: "2" })).toBe("A=1\nB=2\n");
2829
});
30+
31+
it("collapses duplicate assignments to one, since parseEnv lets the last win", () => {
32+
expect(reconcileEnvFile("A=old\nKEEP=1\nA=older\n", { A: "new" })).toBe("A=new\nKEEP=1\n");
33+
});
34+
35+
it("leaves a commented-out assignment alone", () => {
36+
expect(reconcileEnvFile("#A=old\n", { A: "new" })).toBe("#A=old\nA=new\n");
37+
});
2938
});
3039

3140
const { test } = Test.make({
@@ -96,4 +105,32 @@ describe("PublishClientConfig", () => {
96105
expect(third).toContain("KEEP=yes\n");
97106
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
98107
);
108+
109+
test.provider("refuses a value with a line break rather than corrupting the file", (stack) =>
110+
Effect.gen(function* () {
111+
const fs = yield* FileSystem.FileSystem;
112+
const path = yield* Path.Path;
113+
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-relay-client-config-" });
114+
const target = path.join(dir, "client.env");
115+
const exit = yield* stack
116+
.deploy(
117+
Effect.gen(function* () {
118+
return yield* PublishClientConfig({
119+
...clientConfig("v1"),
120+
clientTracingDataset: "relay-traces\nINJECTED=1",
121+
});
122+
}),
123+
)
124+
.pipe(
125+
Effect.provide(
126+
ConfigProvider.layer(
127+
ConfigProvider.fromUnknown({ T3CODE_RELAY_CLIENT_CONFIG_ENV: target }),
128+
),
129+
),
130+
Effect.exit,
131+
);
132+
expect(exit._tag).toBe("Failure");
133+
expect(yield* fs.exists(target)).toBe(false);
134+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
135+
);
99136
});

‎infra/relay/src/clientConfig.ts‎

Lines changed: 37 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -50,26 +50,44 @@ export const relayClientConfigEnv = (config: RelayClientConfig & { readonly url:
5050
T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: Redacted.value(config.clientTracingToken),
5151
}) as const;
5252

53-
/** Replaces or appends each `NAME=value` line, leaving unrelated lines alone. */
53+
export class EnvValueNotSingleLineError extends Schema.TaggedError<EnvValueNotSingleLineError>()(
54+
"EnvValueNotSingleLineError",
55+
{ name: Schema.String },
56+
) {
57+
override get message(): string {
58+
return `${this.name} contains a line break and cannot be written as one .env assignment.`;
59+
}
60+
}
61+
62+
/**
63+
* Replaces or appends each `NAME=value` assignment, leaving unrelated lines
64+
* alone. Every existing line for a name is dropped, not just the first: the
65+
* file is read with `parseEnv`, where the last duplicate wins, so a stale
66+
* second copy would override the value just written.
67+
*/
5468
export function reconcileEnvFile(
5569
contents: string,
5670
entries: Readonly<Record<string, string>>,
5771
): string {
58-
let next = contents;
59-
for (const [name, value] of Object.entries(entries)) {
60-
const entry = `${name}=${value}`;
61-
const pattern = new RegExp(`^${name}=.*$`, "mu");
62-
if (pattern.test(next)) {
63-
next = next.replace(pattern, entry);
72+
const lines = contents === "" ? [] : contents.replace(/\n$/u, "").split("\n");
73+
const assignment = /^([A-Za-z_][A-Za-z0-9_]*)=/u;
74+
const pending = new Map(Object.entries(entries));
75+
const out: string[] = [];
76+
for (const line of lines) {
77+
const name = assignment.exec(line)?.[1];
78+
if (name === undefined || !(name in entries)) {
79+
out.push(line);
6480
continue;
6581
}
66-
if (!next) {
67-
next = `${entry}\n`;
68-
continue;
82+
// The first occurrence keeps its position; later duplicates are dropped.
83+
const value = pending.get(name);
84+
if (value !== undefined) {
85+
out.push(`${name}=${value}`);
86+
pending.delete(name);
6987
}
70-
next = `${next}${next.endsWith("\n") ? "" : "\n"}${entry}\n`;
7188
}
72-
return next;
89+
for (const [name, value] of pending) out.push(`${name}=${value}`);
90+
return out.length === 0 ? "" : `${out.join("\n")}\n`;
7391
}
7492

7593
/**
@@ -93,11 +111,14 @@ export const PublishClientConfig = Alchemy.Action(
93111
return Effect.fn(function* (input: RelayClientConfig) {
94112
const url = input.url;
95113
if (url === undefined) return yield* new RelayUrlUnavailableError();
114+
const entries = relayClientConfigEnv({ ...input, url });
115+
// Provider responses are copied in verbatim; a line break in one would
116+
// become an extra assignment.
117+
for (const [name, value] of Object.entries(entries)) {
118+
if (/[\r\n]/u.test(value)) return yield* new EnvValueNotSingleLineError({ name });
119+
}
96120
const existing = (yield* fs.exists(target)) ? yield* fs.readFileString(target) : "";
97-
yield* fs.writeFileString(
98-
target,
99-
reconcileEnvFile(existing, relayClientConfigEnv({ ...input, url })),
100-
);
121+
yield* fs.writeFileString(target, reconcileEnvFile(existing, entries));
101122
yield* Console.log(`Wrote relay client configuration to ${target}`);
102123
return { path: target };
103124
});

0 commit comments

Comments
 (0)