Skip to content

Commit dced141

Browse files
committed
refactor(box): Address Tejas's review of #2886
- withEvents in events.ts replaces eventsWhile: withOutputEvents is now the case of an operation that emits lines. - stageBoxImage, stageBoxContainers and the container dev runner read BOX_RELEASE in place, as no caller passes another release. - The deployed egress test retries only its invoke, so a failed call does not deploy and remove the stack again. - e2eTest/README.md says CI runs only the dev egress test, and the testing guide says the CLI does not check the local box version. - Two loops in boxProfileCredentials.test.ts are test.each.
1 parent 4693235 commit dced141

11 files changed

Lines changed: 117 additions & 145 deletions

File tree

‎docs/box-local-testing.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,8 @@ box --version
334334
aws sts get-caller-identity
335335
```
336336

337-
- `box --version` must print the pinned version. Dev and build read the profile with
337+
- `box --version` should print the pinned version. The CLI does not check it, and an older box can
338+
refuse the profiles that the CLI writes. Dev and build read the profile with
338339
`box profile show --format json --full`. The AgentCore Runtime profile signs each Box gateway
339340
backend for `${{ inputs.aws.region }}`, and its default telemetry target reads one key of
340341
`OTEL_EXPORTER_OTLP_LOGS_HEADERS`. An older box release cannot do all of these.

‎e2eTest/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,9 @@ The `box-egress` tests check that box lets the agent reach the host its profile
5757
(`checkip.amazonaws.com`) and blocks any other (`example.com`): one under `agentcore dev`, and one
5858
on AgentCore Runtime, where the allowed host's calls go through the runtime's Box gateway. The
5959
second deploys, so it also needs `AGENTCORE_E2E_BOX_CDK`. They reach public hosts, so the network
60-
can make them fail. They retry twice, and `--tagsFilter='box'` leaves them out. A full run includes
61-
them, so in CI they run on the macOS and Linux arm64 runners:
60+
can make them fail: the dev test retries twice, and the deployed one retries only its invoke.
61+
`--tagsFilter='box'` leaves them out. A full run includes them, but in CI only the dev test runs, on
62+
the macOS and Linux arm64 runners, as CI does not set `AGENTCORE_E2E_BOX_CDK`:
6263

6364
```sh
6465
bun run test:e2e -- --tagsFilter='box-egress'

‎e2eTest/project/templates.test.ts‎

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -524,13 +524,14 @@ describe.skipIf(!BOX_DEPLOYS)(
524524
const runtime = BOX_TEMPLATES.find((t) => t.template === "agent-python-minimal-box");
525525
if (!runtime) throw new Error("BOX_TEMPLATES has no agent-python-minimal-box case");
526526

527+
// The public hosts can fail a call, so only the invoke retries: a retry of the whole test would
528+
// deploy and remove the stack again.
527529
test(
528530
"allows the profile's host through the Box gateway and blocks any other",
529531
{
530-
retry: 2,
531532
timeout:
532533
TIMEOUT_MS.PROJECT_CREATE +
533-
TIMEOUT_MS.PROJECT_INVOKE +
534+
3 * TIMEOUT_MS.PROJECT_INVOKE +
534535
2 * TIMEOUT_MS.PROJECT_DEPLOY +
535536
TIMEOUT_MS.PROJECT_REMOVE,
536537
},
@@ -545,25 +546,31 @@ describe.skipIf(!BOX_DEPLOYS)(
545546
);
546547
expect(deployment.message).toContain("deployed project");
547548

548-
const response = parseResult(
549-
RuntimeInvokeResponseSchema,
550-
await cli.run(
551-
[
552-
"invoke",
553-
"--runtime",
554-
CREATED_RUNTIME_NAME,
555-
"--session-id",
556-
getSessionId(`${runtime.name}-egress`),
557-
"--payload",
558-
JSON.stringify(runtime.payload),
559-
"--json",
560-
],
561-
projectDir,
562-
),
549+
await retry(
550+
async () => {
551+
const response = parseResult(
552+
RuntimeInvokeResponseSchema,
553+
await cli.run(
554+
[
555+
"invoke",
556+
"--runtime",
557+
CREATED_RUNTIME_NAME,
558+
"--session-id",
559+
getSessionId(`${runtime.name}-egress`),
560+
"--payload",
561+
JSON.stringify(runtime.payload),
562+
"--json",
563+
],
564+
projectDir,
565+
),
566+
);
567+
expect(response.statusCode).toBeGreaterThanOrEqual(200);
568+
expect(response.statusCode).toBeLessThan(300);
569+
assertEgressReply(response.body);
570+
},
571+
3 * TIMEOUT_MS.PROJECT_INVOKE,
572+
15 * 1000,
563573
);
564-
expect(response.statusCode).toBeGreaterThanOrEqual(200);
565-
expect(response.statusCode).toBeLessThan(300);
566-
assertEgressReply(response.body);
567574
scenarioCompleted = true;
568575
} finally {
569576
// Tear the stack down even when a step above failed.

‎src/core/dev/container.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import {
2626
imageTakesBoxDistArg,
2727
stageBoxImage,
2828
} from "../project/backends/boxContainer";
29-
import { BOX_RELEASE, type BoxRelease } from "../project/backends/boxRelease";
3029
import { boxPolicyFileCopies } from "../project/boxNetworkSource";
3130
import {
3231
boxLocalProfileFile,
@@ -115,8 +114,6 @@ type ContainerDevRunnerConfig = {
115114
toolAvailable?: ToolAvailable;
116115
awsDirectory?: string;
117116
processEnv?: NodeJS.ProcessEnv;
118-
/** The box release the image downloads: the pinned one. Tests inject another. */
119-
release?: BoxRelease;
120117
/** Resolves the credentials a boxed container signs with; the default AWS SDK chain by default. */
121118
resolveAwsCredentials?: ResolveAwsCredentials;
122119
/** The platform, whose rules for variable names apply to `processEnv`; tests inject one. */
@@ -128,7 +125,6 @@ export class ContainerDevRunner implements DevRunner {
128125
private readonly toolAvailable: ToolAvailable;
129126
private readonly awsDirectory: string;
130127
private readonly processEnv: NodeJS.ProcessEnv;
131-
private readonly release: BoxRelease;
132128
private readonly resolveAwsCredentials: ResolveAwsCredentials;
133129
private readonly platform: NodeJS.Platform;
134130

@@ -137,7 +133,6 @@ export class ContainerDevRunner implements DevRunner {
137133
this.toolAvailable = config.toolAvailable ?? toolAvailable;
138134
this.awsDirectory = config.awsDirectory ?? join(homedir(), ".aws");
139135
this.processEnv = config.processEnv ?? process.env;
140-
this.release = config.release ?? BOX_RELEASE;
141136
this.resolveAwsCredentials = config.resolveAwsCredentials ?? resolveDefaultAwsCredentials;
142137
this.platform = config.platform ?? process.platform;
143138
}
@@ -395,7 +390,6 @@ export class ContainerDevRunner implements DevRunner {
395390
context,
396391
profileText,
397392
boxPolicyFileCopies(input.projectRoot, input.runtime.name),
398-
this.release,
399393
folder,
400394
);
401395
return { folder, profileText };

‎src/core/project/backends/boxContainer.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ describe("stageBoxContainers", () => {
6565
const demo = await project(BOX_DOCKERFILE);
6666
demo.spec.runtimes[0]!.box = { version: "2.0.0" };
6767

68-
expect(await stageBoxContainers(demo, [model([])], BOX_RELEASE)).toEqual(["agent"]);
68+
expect(await stageBoxContainers(demo, [model([])])).toEqual(["agent"]);
6969

7070
const dist = join(demo.rootPath, "app", "agent", ".box-dist");
7171
// The Runtime profile is the one build derived from the local profile.
@@ -99,7 +99,7 @@ describe("stageBoxContainers", () => {
9999
await writeFile(join(dist, "box"), "old");
100100
await writeFile(join(dist, "stale.dw"), "old");
101101

102-
await stageBoxContainers(demo, [model([])], BOX_RELEASE);
102+
await stageBoxContainers(demo, [model([])]);
103103

104104
expect((await readdir(dist)).sort()).toEqual([...STAGED, "resources"].sort());
105105
});
@@ -108,13 +108,13 @@ describe("stageBoxContainers", () => {
108108
const demo = await project(BOX_DOCKERFILE);
109109
delete demo.spec.runtimes[0]!.box;
110110

111-
expect(await stageBoxContainers(demo, [model([])], BOX_RELEASE)).toEqual([]);
111+
expect(await stageBoxContainers(demo, [model([])])).toEqual([]);
112112
});
113113

114114
test("stages nothing for a runtime with no box.version", async () => {
115115
const demo = await project("FROM scratch\n");
116116

117-
expect(await stageBoxContainers(demo, [model([])], BOX_RELEASE)).toEqual([]);
117+
expect(await stageBoxContainers(demo, [model([])])).toEqual([]);
118118
expect(existsSync(join(demo.rootPath, "app", "agent", ".box-dist"))).toBe(false);
119119
});
120120

@@ -123,7 +123,7 @@ describe("stageBoxContainers", () => {
123123
await mkdir(join(demo.rootPath, ".box", "agent", "local"), { recursive: true });
124124
await writeFile(join(demo.rootPath, ".box", "agent", "local", "policy.dw"), "// rules\n");
125125

126-
await stageBoxContainers(demo, [model(["policy.dw"])], BOX_RELEASE);
126+
await stageBoxContainers(demo, [model(["policy.dw"])]);
127127

128128
const dist = join(demo.rootPath, "app", "agent", ".box-dist");
129129
expect((await readdir(dist)).sort()).toEqual(["policy.dw", ...STAGED, "resources"].sort());
@@ -135,7 +135,7 @@ describe("stageBoxContainers", () => {
135135
await mkdir(join(demo.rootPath, ".box", "agent", "local"), { recursive: true });
136136
await writeFile(join(demo.rootPath, ".box", "agent", "local", "policy.dw"), "// rules\n");
137137

138-
await expect(stageBoxContainers(demo, [model(["policy.dw"])], BOX_RELEASE)).rejects.toThrow(
138+
await expect(stageBoxContainers(demo, [model(["policy.dw"])])).rejects.toThrow(
139139
"does not copy .box-dist/ whole into the image",
140140
);
141141
expect(existsSync(join(demo.rootPath, "app", "agent", ".box-dist"))).toBe(false);

‎src/core/project/backends/boxContainer.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
} from "../boxNetworkWriters";
1313
import { isFile } from "../runtimeBuild";
1414
import { runtimeRunsInBox } from "../templates/boxProfile";
15-
import type { BoxRelease } from "./boxRelease";
15+
import { BOX_RELEASE, type BoxRelease } from "./boxRelease";
1616
import { assertImageCopiesPolicyFiles } from "./boxStaging";
1717

1818
/** The folder a box image's Dockerfile copies its box profile and policy files from. */
@@ -93,14 +93,13 @@ export async function stageBoxImage(
9393
context: string,
9494
profileText: string,
9595
policies: readonly PolicyFileCopy[],
96-
release: BoxRelease,
9796
folder: string = BOX_IMAGE_DIST,
9897
): Promise<void> {
9998
const dist = join(context, folder);
10099
await rm(dist, { recursive: true, force: true });
101100
await mkdir(dist, { recursive: true });
102101
await writeFile(join(dist, "profile.toml"), profileText);
103-
await writeFile(join(dist, BOX_RELEASE_ENV), boxReleaseEnv(release));
102+
await writeFile(join(dist, BOX_RELEASE_ENV), boxReleaseEnv(BOX_RELEASE));
104103
for (const { from, relative } of policies) {
105104
const to = join(dist, ...relative.split("/"));
106105
await mkdir(dirname(to), { recursive: true });
@@ -110,7 +109,7 @@ export async function stageBoxImage(
110109

111110
/**
112111
* Stages box for build and deploy into each container runtime that runs in a box
113-
* ({@link runtimeRunsInBox}): the build context's `.box-dist/` gets `release`, the pinned box, and
112+
* ({@link runtimeRunsInBox}): the build context's `.box-dist/` gets the pinned box, and
114113
* what the runtime profile writer writes from the runtime's Box network
115114
* model (the Runtime profile and a byte copy of each policy file it names). `.box/<name>/aws/`
116115
* gets only what the writer writes, for people to read. Returns the names of the runtimes it
@@ -119,7 +118,6 @@ export async function stageBoxImage(
119118
export async function stageBoxContainers(
120119
project: Project,
121120
networks: readonly BoxNetwork[],
122-
release: BoxRelease,
123121
): Promise<string[]> {
124122
const runtimes = project.spec.runtimes.filter(
125123
(runtime) => runtime.build === "Container" && runtimeRunsInBox(project.spec, runtime),
@@ -150,7 +148,7 @@ export async function stageBoxContainers(
150148
const folder = join(project.rootPath, ...dist.split("/"));
151149
await rm(folder, { recursive: true, force: true });
152150
await mkdir(folder, { recursive: true });
153-
await writeFile(join(folder, BOX_RELEASE_ENV), boxReleaseEnv(release));
151+
await writeFile(join(folder, BOX_RELEASE_ENV), boxReleaseEnv(BOX_RELEASE));
154152
writeBoxNetworkFiles(project.rootPath, filesOf(dist));
155153
writeRenderedBoxFiles(project.rootPath, runtime.name, dist, filesOf(dist));
156154
}

‎src/core/project/backends/cdk.test.ts‎

Lines changed: 1 addition & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { BOX_RELEASE } from "./boxRelease";
1010
import { ProjectRuntimeSchema } from "../../../projectSchemas/runtime";
1111
import { createSilentLogger } from "../../../testing";
1212
import { TransactionSearchSetupError } from "../../../errors";
13-
import { boxOtelWarnings, CdkBackend, eventsWhile } from "./cdk";
13+
import { boxOtelWarnings, CdkBackend } from "./cdk";
1414
import type {
1515
CredentialProviderCalls,
1616
CredentialProvisionInput,
@@ -1875,38 +1875,3 @@ describe("CdkBackend.resolveProjectResources", () => {
18751875
).toEqual([["gateway", "gw", ["owned", "second"]]]);
18761876
});
18771877
});
1878-
1879-
describe("eventsWhile", () => {
1880-
test("yields an event as soon as the work emits it, before the work ends", async () => {
1881-
let finish!: () => void;
1882-
const events = eventsWhile(async (emit) => {
1883-
emit({ type: "step", message: "downloading box" });
1884-
await new Promise<void>((resolve) => (finish = resolve));
1885-
});
1886-
1887-
// The work is still waiting, so the first event arrives without it.
1888-
expect(await events.next()).toEqual({
1889-
done: false,
1890-
value: { type: "step", message: "downloading box" },
1891-
});
1892-
finish();
1893-
expect(await events.next()).toEqual({ done: true, value: undefined });
1894-
});
1895-
1896-
test("throws the work's error after the events it emitted first", async () => {
1897-
const seen: ProjectEvent[] = [];
1898-
const failure = new Error("download failed");
1899-
1900-
const run = async () => {
1901-
for await (const event of eventsWhile(async (emit) => {
1902-
emit({ type: "step", message: "downloading box" });
1903-
throw failure;
1904-
})) {
1905-
seen.push(event);
1906-
}
1907-
};
1908-
1909-
await expect(run()).rejects.toBe(failure);
1910-
expect(seen).toEqual([{ type: "step", message: "downloading box" }]);
1911-
});
1912-
});

‎src/core/project/backends/cdk.ts‎

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
type ProcessRunner,
2626
type ReadWriteJson,
2727
} from "../../../io";
28-
import { withOutputEvents } from "../events";
28+
import { withEvents, withOutputEvents } from "../events";
2929
import type { Logger } from "../../../logging";
3030
import type { AwsDeploymentTarget } from "../../../projectSchemas/aws-targets";
3131
import type {
@@ -254,7 +254,7 @@ export class CdkBackend implements ProjectBackend {
254254
// The zip carries box and the image its box profile, so both are staged before synth packages
255255
// the code. The box release downloads only when a CodeZip runtime runs in a box, and its notice
256256
// goes out when the download starts, not once staging ends.
257-
yield* eventsWhile(async (emit) => {
257+
yield* withEvents(async (emit) => {
258258
// Every box runtime ships the pinned box: build set each box.version to it.
259259
const box = () =>
260260
resolveBoxLinuxBuild(this.processEnv, {
@@ -264,7 +264,7 @@ export class CdkBackend implements ProjectBackend {
264264
emit({ type: "step", message: boxDownloadMessage(download, "AgentCore Runtime") }),
265265
});
266266
await stageBoxCodeZip(project, boxNetworks, box);
267-
await stageBoxContainers(project, boxNetworks, BOX_RELEASE);
267+
await stageBoxContainers(project, boxNetworks);
268268
});
269269
}
270270

@@ -817,37 +817,3 @@ export class CdkBackend implements ProjectBackend {
817817
return join(this.cdkDirectory(project), "cdk.out");
818818
}
819819
}
820-
821-
/**
822-
* Runs `work`, yielding each event it emits as soon as it emits it, then ends when `work` does.
823-
* An error of `work` is thrown after the events it emitted first.
824-
*/
825-
export async function* eventsWhile(
826-
work: (emit: (event: ProjectEvent) => void) => Promise<void>,
827-
): AsyncGenerator<ProjectEvent, void> {
828-
const queue: ProjectEvent[] = [];
829-
let wake: (() => void) | undefined;
830-
let done = false;
831-
const notify = () => {
832-
wake?.();
833-
wake = undefined;
834-
};
835-
const running = work((event) => {
836-
queue.push(event);
837-
notify();
838-
});
839-
const finish = () => {
840-
done = true;
841-
notify();
842-
};
843-
running.then(finish, finish);
844-
for (;;) {
845-
while (queue.length > 0) yield queue.shift()!;
846-
if (done) break;
847-
await new Promise<void>((resolve) => {
848-
wake = resolve;
849-
if (queue.length > 0 || done) notify();
850-
});
851-
}
852-
await running;
853-
}

‎src/core/project/boxProfileCredentials.test.ts‎

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,14 @@ describe("planBoxProfileCredentials", () => {
8787
expect(plan.entries[0]?.value).toBe("ghp_shell");
8888
});
8989

90-
test("adds the credential with no entry when its reserved variable is already set", () => {
91-
for (const sources of [
92-
{ env: { [RESERVED]: "k" }, envLocal: {} },
93-
{ env: {}, envLocal: { [RESERVED]: "k" } },
94-
]) {
95-
const plan = planBoxProfileCredentials(spec(), [GITHUB], sources);
96-
97-
expect(plan.added).toEqual([API_KEY]);
98-
expect(plan.entries).toEqual([]);
99-
}
90+
test.each([
91+
["the shell", { env: { [RESERVED]: "k" }, envLocal: {} }],
92+
[".env.local", { env: {}, envLocal: { [RESERVED]: "k" } }],
93+
])("adds the credential with no entry when %s sets its reserved variable", (_where, sources) => {
94+
const plan = planBoxProfileCredentials(spec(), [GITHUB], sources);
95+
96+
expect(plan.added).toEqual([API_KEY]);
97+
expect(plan.entries).toEqual([]);
10098
});
10199

102100
test("is idempotent: a later build adds nothing, but still stores a key it can find", () => {
@@ -137,16 +135,17 @@ describe("planBoxProfileCredentials", () => {
137135
]);
138136
});
139137

140-
test("leaves a stored key alone when the variable holds it, or when nothing sets the variable", () => {
141-
for (const env of [{ GITHUB_TOKEN: "ghp_same" }, {}]) {
142-
const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], {
143-
env,
144-
envLocal: { [RESERVED]: "ghp_same" },
145-
});
138+
test.each([
139+
["the variable holds it", { GITHUB_TOKEN: "ghp_same" }],
140+
["nothing sets the variable", {}],
141+
])("leaves a stored key alone when %s", (_when, env) => {
142+
const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], {
143+
env,
144+
envLocal: { [RESERVED]: "ghp_same" },
145+
});
146146

147-
expect(plan.entries).toEqual([]);
148-
expect(plan.messages).toEqual([]);
149-
}
147+
expect(plan.entries).toEqual([]);
148+
expect(plan.messages).toEqual([]);
150149
});
151150

152151
test("leaves the stored key alone when the shell sets the credential's own variable", () => {

0 commit comments

Comments
 (0)