-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathcodezip.ts
More file actions
165 lines (151 loc) · 6.06 KB
/
Copy pathcodezip.ts
File metadata and controls
165 lines (151 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import { existsSync } from "node:fs";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";
type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};
const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";
// Windows Python defaults piped stdout to the ANSI code page and block buffering.
const PYTHON_ENV = { PYTHONUTF8: "1", PYTHONUNBUFFERED: "1" } as const;
export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;
constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}
public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
const directory = resolve(input.projectRoot, input.runtime.codeLocation);
if (!isDirectory(directory)) {
throw new InputValidationError(`runtime code directory not found: ${directory}`);
}
resolvePathWithinProject(input.projectRoot, directory, "runtime code directory");
const [entrypoint] = input.runtime.entrypoint.split(":");
// the spec stores `.js` to be compatible with deploy, but dev uses `tsx watch` on the source code.
// therefore we take the `.ts` version of the entrypoint if it exists for dev, and fallback to the
// `.js` in case a project has a pure js entrypoint.
const devEntrypoint =
entrypoint!.endsWith(".js") && isFile(resolve(directory, entrypoint!.replace(/\.js$/, ".ts")))
? entrypoint!.replace(/\.js$/, ".ts")
: entrypoint!;
const entrypointPath = resolve(directory, devEntrypoint);
if (!isFile(entrypointPath)) {
throw new InputValidationError(`runtime entrypoint not found: ${entrypointPath}`);
}
resolvePathWithinProject(input.projectRoot, entrypointPath, "runtime entrypoint");
if (!devEntrypoint.endsWith(".py") && !existsSync(join(directory, "node_modules"))) {
yield { type: "status", message: "Installing Node dependencies with npm" };
yield* this.streamProcess(["npm", "install"], {
cwd: directory,
signal: input.signal,
});
}
yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(devEntrypoint, directory, input);
if (devEntrypoint.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}
/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(
directory: string,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
env: { ...process.env, ...PYTHON_ENV },
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}
function commandForRuntime(
entrypoint: string,
directory: string,
input: DevServerInput,
): { command: string[]; options: StreamProcessOptions } {
const env: NodeJS.ProcessEnv = {
...process.env,
...(entrypoint.endsWith(".py") ? PYTHON_ENV : {}),
...input.env,
PORT: String(input.port),
LOCAL_DEV: "1",
};
if (input.runtime.protocol === "MCP") {
env.FASTMCP_PORT = String(input.port);
}
if (!entrypoint.endsWith(".py")) {
return {
command: ["npm", "exec", "--", "tsx", "watch", entrypoint],
options: { cwd: directory, env, signal: input.signal },
};
}
if ((input.runtime.protocol ?? "HTTP") !== "HTTP") {
return {
command: ["uv", "run", "python", entrypoint],
options: { cwd: directory, env, signal: input.signal },
};
}
const [, handler = "app"] = input.runtime.entrypoint.split(":");
const module = entrypoint.replace(/\.py$/, "").replaceAll("/", ".");
return {
command: [
"uv",
"run",
"uvicorn",
`${module}:${handler}`,
"--reload",
"--host",
"127.0.0.1",
"--port",
String(input.port),
],
options: { cwd: directory, env, signal: input.signal },
};
}