Base: codex-main originale (prima del fork aKode)
This commit is contained in:
12
bazel/build-info/BUILD.bazel
Normal file
12
bazel/build-info/BUILD.bazel
Normal file
@@ -0,0 +1,12 @@
|
||||
load("@bazel_lib//lib:expand_template.bzl", "expand_template")
|
||||
|
||||
# Isolate workspace status in a cheap action whose output changes only when
|
||||
# the embedded commit changes. Rust compiler actions consume only this file.
|
||||
expand_template(
|
||||
name = "build-commit-env",
|
||||
out = "build-commit.env",
|
||||
stamp = 1,
|
||||
stamp_substitutions = {"{BUILD_COMMIT}": "{{STABLE_GIT_COMMIT}}"},
|
||||
template = ["STABLE_GIT_COMMIT={BUILD_COMMIT}"],
|
||||
visibility = ["//codex-rs:__subpackages__"],
|
||||
)
|
||||
3
bazel/extensions/BUILD.bazel
Normal file
3
bazel/extensions/BUILD.bazel
Normal file
@@ -0,0 +1,3 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files(["codex_release_archive.bzl"])
|
||||
56
bazel/extensions/codex_release_archive.bzl
Normal file
56
bazel/extensions/codex_release_archive.bzl
Normal file
@@ -0,0 +1,56 @@
|
||||
"""Materialize the stable release packages selected before running Bazel."""
|
||||
|
||||
_CODEX_RELEASE_BUILD_FILE = """\
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
filegroup(
|
||||
name = "codex",
|
||||
srcs = [{entrypoint}],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package",
|
||||
srcs = glob([
|
||||
"codex-package.json",
|
||||
{binaries},
|
||||
{resources},
|
||||
{path},
|
||||
]),
|
||||
)
|
||||
"""
|
||||
|
||||
def _codex_release_repository_impl(repository_ctx):
|
||||
releases = repository_ctx.getenv("CODEX_COMPAT_RELEASES")
|
||||
if not releases:
|
||||
fail("Set CODEX_COMPAT_RELEASES to the JSON from resolve_exec_server_releases.py before building release compatibility targets.")
|
||||
release = json.decode(releases)[repository_ctx.attr.release]
|
||||
asset = "codex-package-x86_64-unknown-linux-musl.tar.gz"
|
||||
version = release["version"]
|
||||
repository_ctx.download_and_extract(
|
||||
url = [
|
||||
"https://releases.openai.com/codex/releases/{}/{}".format(version, asset),
|
||||
"https://github.com/openai/codex/releases/download/rust-v{}/{}".format(version, asset),
|
||||
],
|
||||
sha256 = release["sha256"],
|
||||
)
|
||||
manifest = json.decode(repository_ctx.read("codex-package.json"))
|
||||
entrypoint = manifest["entrypoint"]
|
||||
binaries = entrypoint.rpartition("/")[0] + "/**"
|
||||
repository_ctx.file(
|
||||
"BUILD.bazel",
|
||||
_CODEX_RELEASE_BUILD_FILE.format(
|
||||
binaries = json.encode(binaries),
|
||||
entrypoint = json.encode(entrypoint),
|
||||
path = json.encode(manifest["pathDir"] + "/**"),
|
||||
resources = json.encode(manifest["resourcesDir"] + "/**"),
|
||||
),
|
||||
executable = False,
|
||||
)
|
||||
return repository_ctx.repo_metadata(reproducible = True)
|
||||
|
||||
codex_release_archive = repository_rule(
|
||||
implementation = _codex_release_repository_impl,
|
||||
attrs = {
|
||||
"release": attr.string(mandatory = True, values = ["latest", "historical"]),
|
||||
},
|
||||
)
|
||||
1
bazel/modules/BUILD.bazel
Normal file
1
bazel/modules/BUILD.bazel
Normal file
@@ -0,0 +1 @@
|
||||
exports_files(["wine.MODULE.bazel"])
|
||||
26
bazel/modules/wine.MODULE.bazel
Normal file
26
bazel/modules/wine.MODULE.bazel
Normal file
@@ -0,0 +1,26 @@
|
||||
http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
|
||||
|
||||
# Pin a new-WoW64 build so tests need neither system Wine nor 32-bit host
|
||||
# libraries.
|
||||
http_archive(
|
||||
name = "wine_linux_x86_64",
|
||||
build_file = "//third_party/wine:BUILD.bazel",
|
||||
sha256 = "39574efa1132c3ca0d5c77dd2eddbe4a49cca0d6cc2c290ff4924493a1c40314",
|
||||
strip_prefix = "wine-11.0-amd64-wow64",
|
||||
urls = [
|
||||
"https://github.com/Kron4ek/Wine-Builds/releases/download/11.0/wine-11.0-amd64-wow64.tar.xz",
|
||||
],
|
||||
)
|
||||
|
||||
# Pin the self-contained Windows distribution so Wine tests need neither a
|
||||
# system PowerShell installation nor a separate .NET runtime. This intentionally
|
||||
# stays on 7.2.24 for the test fixture: 7.4.16 and 7.6.2 currently fail during
|
||||
# CLR startup under the pinned Wine 11 runtime, while 7.2.24 runs successfully.
|
||||
http_archive(
|
||||
name = "powershell_windows_x86_64",
|
||||
build_file = "//third_party/powershell:BUILD.bazel",
|
||||
sha256 = "a1ccb6d8ad52f917470a136c3752af4465f261bcbe570cf44f52aa69ae6e867e",
|
||||
urls = [
|
||||
"https://github.com/PowerShell/PowerShell/releases/download/v7.2.24/PowerShell-7.2.24-win-x64.zip",
|
||||
],
|
||||
)
|
||||
1
bazel/platforms/BUILD.bazel
Normal file
1
bazel/platforms/BUILD.bazel
Normal file
@@ -0,0 +1 @@
|
||||
# Release platform rules live in this package.
|
||||
30
bazel/platforms/release_binaries.bzl
Normal file
30
bazel/platforms/release_binaries.bzl
Normal file
@@ -0,0 +1,30 @@
|
||||
"""Rules for building release binaries across supported target platforms."""
|
||||
|
||||
load("@rules_platform//platform_data:defs.bzl", "platform_data")
|
||||
|
||||
_PLATFORM_TRIPLES = {
|
||||
"linux_arm64_musl": "aarch64-unknown-linux-musl",
|
||||
"linux_amd64_musl": "x86_64-unknown-linux-musl",
|
||||
"macos_amd64": "x86_64-apple-darwin",
|
||||
"macos_arm64": "aarch64-apple-darwin",
|
||||
"windows_amd64": "x86_64-pc-windows-msvc",
|
||||
"windows_arm64": "aarch64-pc-windows-msvc",
|
||||
}
|
||||
|
||||
PLATFORMS = _PLATFORM_TRIPLES.keys()
|
||||
|
||||
def multiplatform_binaries(name, platforms = PLATFORMS):
|
||||
"""Build a binary for a subset of the declared release platforms."""
|
||||
for platform in platforms:
|
||||
platform_data(
|
||||
name = name + "_" + platform,
|
||||
platform = "@rules_rs//rs/platforms:" + _PLATFORM_TRIPLES[platform],
|
||||
target = name,
|
||||
tags = ["manual"],
|
||||
)
|
||||
|
||||
native.filegroup(
|
||||
name = "release_binaries",
|
||||
srcs = [name + "_" + platform for platform in platforms],
|
||||
tags = ["manual"],
|
||||
)
|
||||
7
bazel/rules/BUILD.bazel
Normal file
7
bazel/rules/BUILD.bazel
Normal file
@@ -0,0 +1,7 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files([
|
||||
"e2e_benchmark.bzl",
|
||||
"runtime_package.bzl",
|
||||
"schema_bundle.bzl",
|
||||
])
|
||||
56
bazel/rules/e2e_benchmark.bzl
Normal file
56
bazel/rules/e2e_benchmark.bzl
Normal file
@@ -0,0 +1,56 @@
|
||||
load("@crates//:defs.bzl", "all_crate_deps")
|
||||
load("@rules_rust//rust:defs.bzl", "rust_binary")
|
||||
load("//:defs.bzl", "workspace_root_test")
|
||||
|
||||
_WORKSPACE_ROOT_MARKER = "//codex-rs/utils/cargo-bin:repo_root.marker"
|
||||
|
||||
def codex_e2e_benchmark(name, binaries = [], data = [], deps = []):
|
||||
"""Defines a Bazel-only Divan end-to-end benchmark.
|
||||
|
||||
The benchmark source lives at `e2e_benches/<name>.rs`, with hyphens in
|
||||
`name` replaced by underscores. `binaries` are runtime executables made
|
||||
available through the same `CARGO_BIN_EXE_*` bridge used by Rust tests.
|
||||
|
||||
Args:
|
||||
name: Stem for the generated `<name>-bench` target and benchmark.
|
||||
binaries: Runtime executable labels that the benchmark spawns.
|
||||
data: Additional runtime files needed by the benchmark.
|
||||
deps: Additional Rust dependencies beyond the crate's Cargo deps.
|
||||
"""
|
||||
benchmark_name = name.replace("-", "_")
|
||||
source = "e2e_benches/{}.rs".format(benchmark_name)
|
||||
binary_name = name + "-bench-bin"
|
||||
runfile_env = {
|
||||
binary: "CARGO_BIN_EXE_" + native.package_relative_label(binary).name
|
||||
for binary in binaries
|
||||
}
|
||||
|
||||
rust_binary(
|
||||
name = binary_name,
|
||||
testonly = True,
|
||||
srcs = [source],
|
||||
crate_name = benchmark_name + "_bench",
|
||||
crate_root = source,
|
||||
deps = all_crate_deps(
|
||||
normal = True,
|
||||
normal_dev = True,
|
||||
) + [
|
||||
"@crates//:divan",
|
||||
] + deps,
|
||||
)
|
||||
|
||||
workspace_root_test(
|
||||
name = name + "-bench",
|
||||
args = [
|
||||
"--bench",
|
||||
benchmark_name,
|
||||
],
|
||||
data = data,
|
||||
# Keep path resolution inside the wrapper so manifest-only runfiles
|
||||
# work on every supported host platform.
|
||||
runfile_env = runfile_env,
|
||||
tags = ["manual"],
|
||||
test_bin = ":" + binary_name,
|
||||
visibility = ["//codex-rs:__pkg__"],
|
||||
workspace_root_marker = _WORKSPACE_ROOT_MARKER,
|
||||
)
|
||||
189
bazel/rules/runtime_package.bzl
Normal file
189
bazel/rules/runtime_package.bzl
Normal file
@@ -0,0 +1,189 @@
|
||||
"""Archive unstripped release binaries and debug symbols for signing and packaging."""
|
||||
|
||||
load("@platforms//host:constraints.bzl", "HOST_CONSTRAINTS")
|
||||
load("@rules_pkg//pkg:providers.bzl", "PackageFilegroupInfo", "PackageFilesInfo")
|
||||
load("@rules_pkg//pkg:tar.bzl", "pkg_tar")
|
||||
|
||||
# Keep the profile in sync with --config=release in .bazelrc and Cargo.toml.
|
||||
# Archive targets apply it themselves, including when built without CI flags.
|
||||
_RUSTC_FLAGS = "@rules_rust//rust/settings:extra_rustc_flag"
|
||||
_EXEC_RUSTC_FLAGS = "@rules_rust//rust/settings:extra_exec_rustc_flag"
|
||||
_PROFILE_INPUTS = [
|
||||
"//command_line_option:features",
|
||||
"//command_line_option:host_features",
|
||||
"//command_line_option:copt",
|
||||
"//command_line_option:action_env",
|
||||
"//command_line_option:host_action_env",
|
||||
"//command_line_option:macos_minimum_os",
|
||||
"//command_line_option:host_platform",
|
||||
"//command_line_option:extra_toolchains",
|
||||
_RUSTC_FLAGS,
|
||||
_EXEC_RUSTC_FLAGS,
|
||||
]
|
||||
_PROFILE_OUTPUTS = _PROFILE_INPUTS + [
|
||||
"//command_line_option:compilation_mode",
|
||||
"@rules_rust//rust/settings:lto",
|
||||
"@rules_rust//rust/settings:codegen_units",
|
||||
]
|
||||
|
||||
def _release_profile_impl(settings, attr):
|
||||
profile = {key: settings[key] for key in _PROFILE_INPUTS}
|
||||
smoke = settings["//codex-rs:runtime_package_build_mode"] == "debug"
|
||||
profile.update({
|
||||
"//command_line_option:compilation_mode": "opt",
|
||||
"@rules_rust//rust/settings:lto": "off" if smoke else "thin",
|
||||
"@rules_rust//rust/settings:codegen_units": 256 if smoke else 4,
|
||||
# opt mode selects opt-level=3, which disables assertions and overflow
|
||||
# checks by default. Unoptimized release smokes need the explicit opt-out.
|
||||
_RUSTC_FLAGS: settings[_RUSTC_FLAGS] + ([
|
||||
"-Copt-level=0",
|
||||
"-Cdebug-assertions=no",
|
||||
] if smoke else []),
|
||||
# Cargo release build tools use opt-level=0, assertions/checks off,
|
||||
# and rustc's default 16 CGUs. Overflow checks follow debug assertions.
|
||||
_EXEC_RUSTC_FLAGS: settings[_EXEC_RUSTC_FLAGS] + [
|
||||
"-Copt-level=0",
|
||||
"-Ccodegen-units=16",
|
||||
"-Cdebug-assertions=no",
|
||||
],
|
||||
})
|
||||
for key in ["//command_line_option:features", "//command_line_option:host_features"]:
|
||||
profile[key] = settings[key] + ["cargo-release-profile"]
|
||||
if attr.platform_os == "macos":
|
||||
profile[_RUSTC_FLAGS] += ["-Csplit-debuginfo=packed"]
|
||||
profile["//command_line_option:macos_minimum_os"] = attr.macos_minimum_os
|
||||
profile["//command_line_option:action_env"] += ["MACOSX_DEPLOYMENT_TARGET=" + attr.macos_minimum_os]
|
||||
|
||||
# Host tools must run on the build host, including x86_64 cross builds.
|
||||
host_minimum_os = "11.0" if "@platforms//cpu:aarch64" in HOST_CONSTRAINTS else "10.12"
|
||||
profile["//command_line_option:host_action_env"] += ["MACOSX_DEPLOYMENT_TARGET=" + host_minimum_os]
|
||||
elif attr.platform_os == "linux":
|
||||
# Compatibility with the Cargo musl release: aws-lc jitter can hang.
|
||||
profile["//command_line_option:copt"] += ["-DDISABLE_CPU_JITTER_ENTROPY"]
|
||||
elif attr.platform_os == "windows" and "@platforms//os:windows" in HOST_CONSTRAINTS:
|
||||
# Native MSVC supplies the SDK and host tools for both architectures.
|
||||
profile["//command_line_option:host_platform"] = "//:local_windows_msvc"
|
||||
profile["//command_line_option:extra_toolchains"] += [
|
||||
"@local_config_cc//:cc-toolchain-x64_windows",
|
||||
"@local_config_cc//:cc-toolchain-arm64_windows",
|
||||
]
|
||||
if attr.linux_x86_64_musl:
|
||||
# Match the Cargo release linker for x86-64 static PIEs.
|
||||
profile[_RUSTC_FLAGS] += [
|
||||
"-Cllvm-args=--addrsig",
|
||||
"-Clink-arg=-Wl,--icf=safe,-z,pack-relative-relocs",
|
||||
]
|
||||
return profile
|
||||
|
||||
_release_profile = transition(
|
||||
implementation = _release_profile_impl,
|
||||
inputs = _PROFILE_INPUTS + ["//codex-rs:runtime_package_build_mode"],
|
||||
outputs = _PROFILE_OUTPUTS,
|
||||
)
|
||||
|
||||
def _runtime_binary_files_impl(ctx):
|
||||
binary = ctx.attr.binary[0]
|
||||
executable = binary[DefaultInfo].files_to_run.executable
|
||||
outputs = [executable]
|
||||
validations = []
|
||||
files = [PackageFilesInfo(
|
||||
attributes = {"mode": "0755"},
|
||||
dest_src_map = {executable.basename: executable},
|
||||
)]
|
||||
|
||||
# Use the binary's target configuration, including cross builds. Linux keeps
|
||||
# DWARF inside the executable until the existing packaging strip pass.
|
||||
for group, suffix in [("pdb_file", ".pdb"), ("dsym_folder", ".dSYM")]:
|
||||
symbols = getattr(binary[OutputGroupInfo], group, depset()).to_list()
|
||||
if not symbols and group == ctx.attr.symbol_group:
|
||||
fail("Missing %s for %s" % (group, binary.label))
|
||||
if not symbols:
|
||||
continue
|
||||
if len(symbols) != 1:
|
||||
fail("Expected one %s for %s, got %s" % (group, binary.label, symbols))
|
||||
if group == "dsym_folder":
|
||||
validation = ctx.actions.declare_file(ctx.label.name + ".dsym-checked")
|
||||
ctx.actions.run_shell(
|
||||
inputs = symbols,
|
||||
outputs = [validation],
|
||||
arguments = [symbols[0].path, executable.basename, validation.path],
|
||||
command = '''
|
||||
test -s "$1/Contents/Resources/DWARF/$2" || {
|
||||
echo "Missing or empty DWARF for $2 in $1" >&2
|
||||
exit 1
|
||||
}
|
||||
touch "$3"
|
||||
''',
|
||||
mnemonic = "ValidateRuntimeSymbols",
|
||||
)
|
||||
validations.append(validation)
|
||||
outputs.extend(symbols)
|
||||
files.append(PackageFilesInfo(
|
||||
attributes = {"mode": "0644"},
|
||||
dest_src_map = {binary.label.name + suffix: symbols[0]},
|
||||
))
|
||||
|
||||
return [
|
||||
DefaultInfo(files = depset(outputs)),
|
||||
OutputGroupInfo(_validation = depset(validations)),
|
||||
PackageFilegroupInfo(
|
||||
pkg_files = [(info, ctx.label) for info in files],
|
||||
pkg_dirs = [],
|
||||
pkg_symlinks = [],
|
||||
),
|
||||
]
|
||||
|
||||
_runtime_binary_files = rule(
|
||||
implementation = _runtime_binary_files_impl,
|
||||
attrs = {
|
||||
"binary": attr.label(mandatory = True, executable = True, cfg = _release_profile),
|
||||
"platform_os": attr.string(),
|
||||
"linux_x86_64_musl": attr.bool(),
|
||||
"macos_minimum_os": attr.string(),
|
||||
"_allowlist_function_transition": attr.label(
|
||||
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
|
||||
),
|
||||
"symbol_group": attr.string(),
|
||||
},
|
||||
)
|
||||
|
||||
def runtime_archive(name, srcs, **kwargs):
|
||||
"""Produce a flat archive of writable files, without stripping or signing."""
|
||||
pkg_tar(
|
||||
name = name,
|
||||
srcs = srcs,
|
||||
extension = "tar.gz",
|
||||
mode = "0755",
|
||||
stamp = 0,
|
||||
allow_duplicates_with_different_content = False,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
def release_binary(binary, name = "release", macos_x86_64_minimum_os = "10.12", **kwargs):
|
||||
"""Expose release_files and release.tar.gz; override name for sibling binaries."""
|
||||
kwargs.setdefault("tags", ["manual"])
|
||||
kwargs.setdefault("visibility", ["//visibility:public"])
|
||||
_runtime_binary_files(
|
||||
name = name + "_files",
|
||||
binary = binary,
|
||||
linux_x86_64_musl = select({
|
||||
"@llvm//platforms/config:linux_x86_64_musl": True,
|
||||
"//conditions:default": False,
|
||||
}),
|
||||
platform_os = select({
|
||||
"@platforms//os:macos": "macos",
|
||||
"@platforms//os:linux": "linux",
|
||||
"@platforms//os:windows": "windows",
|
||||
}),
|
||||
macos_minimum_os = select({
|
||||
"@platforms//cpu:aarch64": "11.0",
|
||||
"//conditions:default": macos_x86_64_minimum_os,
|
||||
}),
|
||||
symbol_group = select({
|
||||
"@platforms//os:macos": "dsym_folder",
|
||||
"@platforms//os:windows": "pdb_file",
|
||||
"//conditions:default": "",
|
||||
}),
|
||||
**kwargs
|
||||
)
|
||||
runtime_archive(name = name, srcs = [":" + name + "_files"], **kwargs)
|
||||
115
bazel/rules/schema_bundle.bzl
Normal file
115
bazel/rules/schema_bundle.bzl
Normal file
@@ -0,0 +1,115 @@
|
||||
"""Generate API artifacts with the existing Rust and Python exporters."""
|
||||
|
||||
load("@bazel_lib//lib:copy_file.bzl", "COPY_FILE_TOOLCHAINS", "copy_file_action")
|
||||
|
||||
def _schema_bundle_impl(ctx):
|
||||
outputs = []
|
||||
for mode in ["stable", "experimental"]:
|
||||
schema = ctx.actions.declare_directory(ctx.label.name + "." + mode)
|
||||
ctx.actions.run(
|
||||
executable = ctx.executable.generator,
|
||||
tools = [ctx.attr.generator[DefaultInfo].files_to_run],
|
||||
env = {
|
||||
"CODEX_APP_SERVER_SCHEMA_ROOT": schema.path,
|
||||
"CODEX_APP_SERVER_SCHEMA_EXPERIMENTAL": "1" if mode == "experimental" else "0",
|
||||
},
|
||||
outputs = [schema],
|
||||
mnemonic = "PublicSchema",
|
||||
progress_message = "Generating %s public app-server schemas" % mode,
|
||||
)
|
||||
outputs.append(schema)
|
||||
|
||||
# Expose the pinned compressor alongside the cached directories so callers
|
||||
# can normalize the JSON without a separate `bazel run` invocation.
|
||||
zstd = ctx.actions.declare_file(ctx.label.name + ".zstd")
|
||||
ctx.actions.symlink(output = zstd, target_file = ctx.executable.zstd, is_executable = True)
|
||||
return [
|
||||
DefaultInfo(files = depset(outputs + [zstd])),
|
||||
OutputGroupInfo(stable = depset([outputs[0]]), experimental = depset([outputs[1]])),
|
||||
]
|
||||
|
||||
schema_bundle = rule(
|
||||
implementation = _schema_bundle_impl,
|
||||
attrs = {
|
||||
"generator": attr.label(mandatory = True, executable = True, cfg = "exec"),
|
||||
"zstd": attr.label(default = "@zstd//:zstd_cli", executable = True, cfg = "exec"),
|
||||
},
|
||||
doc = "Generates both schema modes as cacheable actions with explicit tool dependencies.",
|
||||
)
|
||||
|
||||
def _schema_sources_impl(ctx):
|
||||
sources = []
|
||||
crate_root = None
|
||||
prefix = ctx.label.package + "/"
|
||||
for source in ctx.files.srcs:
|
||||
if not source.short_path.startswith(prefix):
|
||||
fail("Schema generator sources must belong to " + ctx.label.package)
|
||||
relative = source.short_path[len(prefix):]
|
||||
output = ctx.actions.declare_file(ctx.label.name + "/" + relative)
|
||||
ctx.actions.symlink(output = output, target_file = source)
|
||||
sources.append(output)
|
||||
if relative == ctx.attr.crate_root:
|
||||
crate_root = output
|
||||
if crate_root == None:
|
||||
fail("Schema generator sources must include " + ctx.attr.crate_root)
|
||||
|
||||
# Runtime builds embed generated bundles. The generator needs only empty
|
||||
# placeholders because it derives the bundles from Rust.
|
||||
precomputed = [
|
||||
ctx.actions.declare_file(ctx.label.name + "/schema/precomputed/app-server-exports-" + mode + ".json.zst")
|
||||
for mode in ["stable", "experimental"]
|
||||
]
|
||||
for mode, output in zip(["stable", "experimental"], precomputed):
|
||||
if ctx.attr.schema:
|
||||
directory = getattr(ctx.attr.schema[OutputGroupInfo], mode).to_list()[0]
|
||||
copy_file_action(ctx, directory, output, dir_path = "precomputed/" + output.basename)
|
||||
else:
|
||||
ctx.actions.write(output, "")
|
||||
return [
|
||||
DefaultInfo(files = depset(sources)),
|
||||
OutputGroupInfo(crate_root = depset([crate_root]), precomputed = depset(precomputed)),
|
||||
]
|
||||
|
||||
schema_sources = rule(
|
||||
implementation = _schema_sources_impl,
|
||||
attrs = {
|
||||
"srcs": attr.label_list(allow_files = [".rs"]),
|
||||
"crate_root": attr.string(default = "src/lib.rs"),
|
||||
"schema": attr.label(providers = [OutputGroupInfo]),
|
||||
},
|
||||
toolchains = COPY_FILE_TOOLCHAINS,
|
||||
)
|
||||
|
||||
def _python_sdk_exports_impl(ctx):
|
||||
output = ctx.actions.declare_directory(ctx.label.name)
|
||||
manifest = ctx.actions.declare_file(ctx.label.name + ".json")
|
||||
prefix = ctx.label.package + "/"
|
||||
files = []
|
||||
for source in ctx.files.srcs:
|
||||
if not source.short_path.startswith(prefix):
|
||||
fail("Python SDK generator inputs must belong to " + ctx.label.package)
|
||||
files.append([source.path, source.short_path[len(prefix):]])
|
||||
ctx.actions.write(manifest, json.encode(files))
|
||||
ctx.actions.run(
|
||||
executable = ctx.executable._generator,
|
||||
arguments = [manifest.path, ctx.file.schema.path + "/json", output.path],
|
||||
inputs = ctx.files.srcs + [ctx.file.schema, manifest],
|
||||
tools = [ctx.attr._generator[DefaultInfo].files_to_run],
|
||||
outputs = [output],
|
||||
env = {"PYTHONDONTWRITEBYTECODE": "1", "PYTHONUTF8": "1"},
|
||||
mnemonic = "PythonSdkExports",
|
||||
)
|
||||
return [DefaultInfo(files = depset([output]))]
|
||||
|
||||
python_sdk_exports = rule(
|
||||
implementation = _python_sdk_exports_impl,
|
||||
attrs = {
|
||||
"srcs": attr.label_list(allow_files = True),
|
||||
"schema": attr.label(mandatory = True, allow_single_file = True),
|
||||
"_generator": attr.label(
|
||||
default = "//bazel/schema/tools:python-codegen",
|
||||
executable = True,
|
||||
cfg = "exec",
|
||||
),
|
||||
},
|
||||
)
|
||||
5
bazel/rules/testing/BUILD.bazel
Normal file
5
bazel/rules/testing/BUILD.bazel
Normal file
@@ -0,0 +1,5 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files([
|
||||
"foreign_platform_binary.bzl",
|
||||
])
|
||||
31
bazel/rules/testing/compat/BUILD.bazel
Normal file
31
bazel/rules/testing/compat/BUILD.bazel
Normal file
@@ -0,0 +1,31 @@
|
||||
load("@rules_rust//rust:defs.bzl", "rust_test")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files(["exec_server_compat_test.bzl"])
|
||||
|
||||
# exec_server_compat_test wraps this shared binary with current or released builds.
|
||||
# Keep it manual so only wrapped compatibility tests enter the normal test graph.
|
||||
rust_test(
|
||||
name = "exec-server-compat-test-bin",
|
||||
srcs = ["exec_server_compat_test.rs"],
|
||||
crate_name = "exec_server_compat_test",
|
||||
crate_root = "exec_server_compat_test.rs",
|
||||
edition = "2024",
|
||||
tags = ["manual"],
|
||||
target_compatible_with = [
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
],
|
||||
visibility = ["//codex-rs/exec-server:__pkg__"],
|
||||
deps = [
|
||||
"//codex-rs/exec-server",
|
||||
"//codex-rs/exec-server/tests/support",
|
||||
"@crates//:anyhow",
|
||||
"@crates//:pretty_assertions",
|
||||
"@crates//:serde_json",
|
||||
"@crates//:tempfile",
|
||||
"@crates//:tokio",
|
||||
"@crates//:wiremock",
|
||||
],
|
||||
)
|
||||
47
bazel/rules/testing/compat/exec_server_compat_test.bzl
Normal file
47
bazel/rules/testing/compat/exec_server_compat_test.bzl
Normal file
@@ -0,0 +1,47 @@
|
||||
"""Bazel coverage for app-server and exec-server release compatibility."""
|
||||
|
||||
load("//:defs.bzl", "workspace_root_test")
|
||||
|
||||
def exec_server_compat_test(
|
||||
name,
|
||||
comparison_binary = None,
|
||||
current_binary = "//codex-rs/cli:codex",
|
||||
release = None):
|
||||
"""Tests both executor directions against another Codex build or release.
|
||||
|
||||
Args:
|
||||
name: Name of the generated compatibility test target.
|
||||
comparison_binary: Built Codex executable to compare with the current build.
|
||||
current_binary: Built Codex executable representing the current version.
|
||||
release: External release repository exposing `:codex` and `:package`.
|
||||
"""
|
||||
if (comparison_binary == None) == (release == None):
|
||||
fail("exactly one of comparison_binary and release must be set")
|
||||
|
||||
comparison = comparison_binary if release == None else release + "//:codex"
|
||||
data = [] if release == None else [release + "//:package"]
|
||||
comparison_alias = name + "-comparison-binary"
|
||||
native.alias(
|
||||
name = comparison_alias,
|
||||
actual = comparison,
|
||||
tags = ["manual"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
workspace_root_test(
|
||||
name = name,
|
||||
args = ["--test-threads=1"],
|
||||
data = data,
|
||||
runfile_env = {
|
||||
"//codex-rs/bwrap:bwrap": "CARGO_BIN_EXE_bwrap",
|
||||
current_binary: "CODEX_TEST_CURRENT_CODEX",
|
||||
":" + comparison_alias: "CODEX_TEST_RELEASED_CODEX",
|
||||
},
|
||||
tags = ["no-sandbox"],
|
||||
target_compatible_with = [
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
],
|
||||
test_bin = "//bazel/rules/testing/compat:exec-server-compat-test-bin",
|
||||
workspace_root_marker = "//codex-rs/utils/cargo-bin:repo_root.marker",
|
||||
)
|
||||
439
bazel/rules/testing/compat/exec_server_compat_test.rs
Normal file
439
bazel/rules/testing/compat/exec_server_compat_test.rs
Normal file
@@ -0,0 +1,439 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID_ENV_VAR;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_NOISE_REGISTRY_URL_ENV_VAR;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR;
|
||||
use codex_exec_server::REMOTE_ENVIRONMENT_ID;
|
||||
use codex_exec_server_test_support::relay::TEST_TIMEOUT as VERSION_SKEW_TIMEOUT;
|
||||
use codex_exec_server_test_support::relay::accept_websocket;
|
||||
use codex_exec_server_test_support::relay::assert_relay_data_is_encrypted;
|
||||
use codex_exec_server_test_support::relay::proxy_relay_frames;
|
||||
use codex_exec_server_test_support::relay::registered_executor_public_key;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::io::Lines;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::process::ChildStdin;
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const ENVIRONMENT_ID: &str = "env-noise-relay-test";
|
||||
const EXECUTOR_REGISTRATION_ID: &str = "registration-1";
|
||||
const HARNESS_KEY_AUTHORIZATION: &str = "harness-key-authorization";
|
||||
const REGISTRY_TOKEN: &str = "registry-token";
|
||||
const RELEASED_CODEX_ENV_VAR: &str = "CODEX_TEST_RELEASED_CODEX";
|
||||
const CURRENT_CODEX_ENV_VAR: &str = "CODEX_TEST_CURRENT_CODEX";
|
||||
const EXECUTOR_MARKER_ENV_VAR: &str = "CODEX_EXECUTOR_VERSION_SKEW_MARKER";
|
||||
const EXPECTED_OUTPUT: &str = "executor-version-skew-ok";
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn current_app_server_runs_commands_on_released_exec_server_over_noise() -> Result<()> {
|
||||
let Some((current, released)) = version_skew_binaries()? else {
|
||||
return Ok(());
|
||||
};
|
||||
assert_noise_version_skew(¤t, &released).await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn released_app_server_runs_commands_on_current_exec_server_over_noise() -> Result<()> {
|
||||
let Some((current, released)) = version_skew_binaries()? else {
|
||||
return Ok(());
|
||||
};
|
||||
assert_noise_version_skew(&released, ¤t).await
|
||||
}
|
||||
|
||||
fn version_skew_binaries() -> Result<Option<(PathBuf, PathBuf)>> {
|
||||
let Some(released) = std::env::var_os(RELEASED_CODEX_ENV_VAR) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let current = std::env::var_os(CURRENT_CODEX_ENV_VAR)
|
||||
.with_context(|| format!("{CURRENT_CODEX_ENV_VAR} must name the current Codex binary"))?;
|
||||
let current = PathBuf::from(current);
|
||||
let released = PathBuf::from(released);
|
||||
anyhow::ensure!(
|
||||
current.is_file(),
|
||||
"current Codex does not exist: {}",
|
||||
current.display()
|
||||
);
|
||||
anyhow::ensure!(
|
||||
released.is_file(),
|
||||
"released Codex does not exist: {}",
|
||||
released.display()
|
||||
);
|
||||
Ok(Some((current, released)))
|
||||
}
|
||||
|
||||
async fn assert_noise_version_skew(app_binary: &Path, executor_binary: &Path) -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let workspace = TempDir::new()?;
|
||||
let skill_dir = workspace.path().join(".agents/skills/version-skew");
|
||||
std::fs::create_dir_all(&skill_dir)?;
|
||||
let skill_path = skill_dir.join("SKILL.md");
|
||||
let skill_body = "Repository instructions loaded across executor versions.";
|
||||
std::fs::write(
|
||||
&skill_path,
|
||||
format!(
|
||||
"---\nname: version-skew\ndescription: Check executor compatibility.\n---\n{skill_body}\n"
|
||||
),
|
||||
)?;
|
||||
let selected_root = workspace.path().join("selected-skills");
|
||||
let selected_skill_dir = selected_root.join("selected-version-skew");
|
||||
std::fs::create_dir_all(&selected_skill_dir)?;
|
||||
let selected_skill_body = "Selected instructions loaded across executor versions.";
|
||||
std::fs::write(
|
||||
selected_skill_dir.join("SKILL.md"),
|
||||
format!(
|
||||
"---\nname: selected-version-skew\ndescription: Check selected skill compatibility.\n---\n{selected_skill_body}\n"
|
||||
),
|
||||
)?;
|
||||
let model = mock_model(workspace.path()).await?;
|
||||
let model_url = model.uri();
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
model = "mock-model"
|
||||
approval_policy = "never"
|
||||
sandbox_mode = "workspace-write"
|
||||
model_provider = "mock_provider"
|
||||
|
||||
[features]
|
||||
executor_capability_discovery = false
|
||||
executor_capability_discovery_v2 = false
|
||||
|
||||
[model_providers.mock_provider]
|
||||
name = "Mock provider"
|
||||
base_url = "{model_url}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let rendezvous_url = format!("ws://{}", listener.local_addr()?);
|
||||
let registry = MockServer::start().await;
|
||||
let registry_url = registry.uri();
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/cloud/environment/{ENVIRONMENT_ID}/register"
|
||||
)))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"environment_id": ENVIRONMENT_ID,
|
||||
"url": format!("{rendezvous_url}/relay?role=environment"),
|
||||
"security_profile": "noise_hybrid_ik_v1",
|
||||
"executor_registration_id": EXECUTOR_REGISTRATION_ID,
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/cloud/environment/{ENVIRONMENT_ID}/validate"
|
||||
)))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"valid": true})))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.await;
|
||||
|
||||
let mut executor = Command::new(executor_binary)
|
||||
.args([
|
||||
"exec-server",
|
||||
"--remote",
|
||||
registry_url.as_str(),
|
||||
"--environment-id",
|
||||
ENVIRONMENT_ID,
|
||||
])
|
||||
.current_dir(codex_home.path())
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env("CODEX_API_KEY", REGISTRY_TOKEN)
|
||||
.env(EXECUTOR_MARKER_ENV_VAR, EXPECTED_OUTPUT)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.with_context(|| format!("start remote executor from {}", executor_binary.display()))?;
|
||||
|
||||
let environment_websocket = accept_websocket(&listener, "environment").await?;
|
||||
let executor_public_key = registered_executor_public_key(®istry).await?;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!("/cloud/environment/{ENVIRONMENT_ID}/connect")))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"environment_id": ENVIRONMENT_ID,
|
||||
"url": format!("{rendezvous_url}/relay?role=harness"),
|
||||
"security_profile": "noise_hybrid_ik_v1",
|
||||
"executor_registration_id": EXECUTOR_REGISTRATION_ID,
|
||||
"executor_public_key": executor_public_key,
|
||||
"harness_key_authorization": HARNESS_KEY_AUTHORIZATION,
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.await;
|
||||
|
||||
let captured_frames = Arc::new(Mutex::new(Vec::new()));
|
||||
let captured_relay_frames = Arc::clone(&captured_frames);
|
||||
let relay = tokio::spawn(async move {
|
||||
let harness_websocket = accept_websocket(&listener, "harness").await?;
|
||||
proxy_relay_frames(
|
||||
environment_websocket,
|
||||
harness_websocket,
|
||||
captured_relay_frames,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
let mut app_server = Command::new(app_binary)
|
||||
.arg("app-server")
|
||||
.current_dir(codex_home.path())
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env("CODEX_API_KEY", REGISTRY_TOKEN)
|
||||
.env(
|
||||
"CODEX_APP_SERVER_MANAGED_CONFIG_PATH",
|
||||
codex_home.path().join("managed_config.toml"),
|
||||
)
|
||||
.env(CODEX_EXEC_SERVER_NOISE_REGISTRY_URL_ENV_VAR, ®istry_url)
|
||||
.env(
|
||||
CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID_ENV_VAR,
|
||||
ENVIRONMENT_ID,
|
||||
)
|
||||
.env(CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR, REGISTRY_TOKEN)
|
||||
.env_remove(CODEX_EXEC_SERVER_URL_ENV_VAR)
|
||||
.env_remove(EXECUTOR_MARKER_ENV_VAR)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.with_context(|| format!("start app-server from {}", app_binary.display()))?;
|
||||
let mut stdin = app_server.stdin.take().context("app-server stdin")?;
|
||||
let stdout = app_server.stdout.take().context("app-server stdout")?;
|
||||
let mut stdout = BufReader::new(stdout).lines();
|
||||
let mut notifications = Vec::new();
|
||||
|
||||
app_server_request(
|
||||
&mut stdin,
|
||||
&mut stdout,
|
||||
&mut notifications,
|
||||
/*id*/ 1,
|
||||
"initialize",
|
||||
json!({
|
||||
"clientInfo": {"name": "noise-version-skew", "version": "0.1.0"},
|
||||
"capabilities": {"experimentalApi": true},
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
stdin.write_all(b"{\"method\":\"initialized\"}\n").await?;
|
||||
|
||||
let thread = app_server_request(
|
||||
&mut stdin,
|
||||
&mut stdout,
|
||||
&mut notifications,
|
||||
/*id*/ 2,
|
||||
"thread/start",
|
||||
json!({
|
||||
"cwd": workspace.path(),
|
||||
"selectedCapabilityRoots": [{
|
||||
"id": "version-skew-selected",
|
||||
"location": {
|
||||
"type": "environment",
|
||||
"environmentId": REMOTE_ENVIRONMENT_ID,
|
||||
"path": selected_root,
|
||||
},
|
||||
}],
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let thread_id = thread["thread"]["id"]
|
||||
.as_str()
|
||||
.context("thread/start should return a thread id")?;
|
||||
app_server_request(
|
||||
&mut stdin,
|
||||
&mut stdout,
|
||||
&mut notifications,
|
||||
/*id*/ 3,
|
||||
"turn/start",
|
||||
json!({
|
||||
"threadId": thread_id,
|
||||
"input": [{
|
||||
"type": "text",
|
||||
"text": "Use $selected-version-skew and run the Noise compatibility command.",
|
||||
"textElements": [],
|
||||
}, {
|
||||
"type": "skill",
|
||||
"name": "version-skew",
|
||||
"path": skill_path,
|
||||
}],
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
while !notifications
|
||||
.iter()
|
||||
.any(|notification: &Value| notification["method"] == "turn/completed")
|
||||
{
|
||||
let line = timeout(VERSION_SKEW_TIMEOUT, stdout.next_line())
|
||||
.await
|
||||
.context("waiting for turn/completed")??
|
||||
.context("app-server exited before turn/completed")?;
|
||||
notifications.push(serde_json::from_str(&line)?);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(workspace.path().join("version-skew-output.txt"))?,
|
||||
EXPECTED_OUTPUT
|
||||
);
|
||||
let requests = model.received_requests().await.context("model requests")?;
|
||||
let first_request = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path() == "/v1/responses")
|
||||
.context("model response request")?;
|
||||
let first_request: Value = serde_json::from_slice(&first_request.body)?;
|
||||
let input = first_request["input"].as_array().context("model input")?;
|
||||
assert!(input.iter().any(|item| {
|
||||
item["role"] == "developer"
|
||||
&& item["content"]
|
||||
.to_string()
|
||||
.contains("selected-version-skew")
|
||||
}));
|
||||
for body in [skill_body, selected_skill_body] {
|
||||
assert!(
|
||||
input
|
||||
.iter()
|
||||
.any(|item| item["role"] == "user" && item["content"].to_string().contains(body))
|
||||
);
|
||||
}
|
||||
assert_relay_data_is_encrypted(&captured_frames)?;
|
||||
registry.verify().await;
|
||||
model.verify().await;
|
||||
|
||||
let _ = app_server.start_kill();
|
||||
let _ = executor.start_kill();
|
||||
relay.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn app_server_request(
|
||||
stdin: &mut ChildStdin,
|
||||
stdout: &mut Lines<BufReader<ChildStdout>>,
|
||||
notifications: &mut Vec<Value>,
|
||||
id: u64,
|
||||
method: &str,
|
||||
params: Value,
|
||||
) -> Result<Value> {
|
||||
let request = json!({"id": id, "method": method, "params": params});
|
||||
stdin.write_all(request.to_string().as_bytes()).await?;
|
||||
stdin.write_all(b"\n").await?;
|
||||
|
||||
loop {
|
||||
let line = timeout(VERSION_SKEW_TIMEOUT, stdout.next_line())
|
||||
.await
|
||||
.with_context(|| format!("waiting for {method} response"))??
|
||||
.with_context(|| format!("app-server exited before {method} response"))?;
|
||||
let response: Value = serde_json::from_str(&line)?;
|
||||
if response["id"] == id {
|
||||
anyhow::ensure!(
|
||||
response.get("error").is_none(),
|
||||
"{method} failed: {}",
|
||||
response["error"]
|
||||
);
|
||||
return response.get("result").cloned().context("missing result");
|
||||
}
|
||||
notifications.push(response);
|
||||
}
|
||||
}
|
||||
|
||||
async fn mock_model(codex_home: &Path) -> Result<MockServer> {
|
||||
let server = MockServer::start().await;
|
||||
let arguments = serde_json::to_string(&json!({
|
||||
"cmd": format!("printf '%s' \"${EXECUTOR_MARKER_ENV_VAR}\" > version-skew-output.txt"),
|
||||
"workdir": codex_home,
|
||||
"yield_time_ms": 5_000,
|
||||
}))?;
|
||||
let completed = |id| {
|
||||
json!({
|
||||
"type": "response.completed",
|
||||
"response": {
|
||||
"id": id,
|
||||
"usage": {
|
||||
"input_tokens": 0,
|
||||
"input_tokens_details": null,
|
||||
"output_tokens": 0,
|
||||
"output_tokens_details": null,
|
||||
"total_tokens": 0,
|
||||
},
|
||||
},
|
||||
})
|
||||
};
|
||||
let responses = vec![
|
||||
event_stream(vec![
|
||||
json!({"type": "response.created", "response": {"id": "response-1"}}),
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"item": {
|
||||
"type": "function_call",
|
||||
"call_id": "noise-version-skew-command",
|
||||
"name": "exec_command",
|
||||
"arguments": arguments,
|
||||
},
|
||||
}),
|
||||
completed("response-1"),
|
||||
])?,
|
||||
event_stream(vec![
|
||||
json!({"type": "response.created", "response": {"id": "response-2"}}),
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"item": {
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"id": "message-1",
|
||||
"content": [{"type": "output_text", "text": "done"}],
|
||||
},
|
||||
}),
|
||||
completed("response-2"),
|
||||
])?,
|
||||
];
|
||||
for response in responses {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/responses"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(response, "text/event-stream"))
|
||||
.up_to_n_times(1)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
fn event_stream(events: Vec<Value>) -> Result<String> {
|
||||
events
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
let event_type = event["type"].as_str().context("SSE event type")?;
|
||||
Ok(format!("event: {event_type}\ndata: {event}\n\n"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
53
bazel/rules/testing/foreign_platform_binary.bzl
Normal file
53
bazel/rules/testing/foreign_platform_binary.bzl
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Makes a binary built for a foreign platform available as test data."""
|
||||
|
||||
_EXTRA_RUSTC_FLAGS = "@rules_rust//rust/settings:extra_rustc_flags"
|
||||
|
||||
def _foreign_platform_transition_impl(settings, attr):
|
||||
# A transition cannot rewrite a dependency's rule attributes. Use the
|
||||
# rules_rust build setting when every Rust target in the foreign
|
||||
# configuration needs additional compiler or linker flags.
|
||||
return {
|
||||
"//command_line_option:platforms": [attr.platform],
|
||||
_EXTRA_RUSTC_FLAGS: settings[_EXTRA_RUSTC_FLAGS] + attr.extra_rustc_flags,
|
||||
}
|
||||
|
||||
_foreign_platform_transition = transition(
|
||||
implementation = _foreign_platform_transition_impl,
|
||||
inputs = [_EXTRA_RUSTC_FLAGS],
|
||||
outputs = [
|
||||
"//command_line_option:platforms",
|
||||
_EXTRA_RUSTC_FLAGS,
|
||||
],
|
||||
)
|
||||
|
||||
def _foreign_platform_binary_impl(ctx):
|
||||
if len(ctx.attr.binary) != 1:
|
||||
fail("expected exactly one transitioned binary")
|
||||
binary = ctx.attr.binary[0][DefaultInfo]
|
||||
runfiles = ctx.runfiles(transitive_files = binary.files)
|
||||
runfiles = runfiles.merge(binary.default_runfiles)
|
||||
return [
|
||||
DefaultInfo(
|
||||
files = binary.files,
|
||||
runfiles = runfiles,
|
||||
),
|
||||
]
|
||||
|
||||
foreign_platform_binary = rule(
|
||||
implementation = _foreign_platform_binary_impl,
|
||||
attrs = {
|
||||
"binary": attr.label(
|
||||
cfg = _foreign_platform_transition,
|
||||
executable = True,
|
||||
mandatory = True,
|
||||
),
|
||||
"extra_rustc_flags": attr.string_list(
|
||||
doc = "Additional flags applied to every Rust target in the foreign configuration.",
|
||||
),
|
||||
"platform": attr.string(mandatory = True),
|
||||
"_allowlist_function_transition": attr.label(
|
||||
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
|
||||
),
|
||||
},
|
||||
doc = "Builds `binary` for `platform` and exposes its files and runfiles.",
|
||||
)
|
||||
54
bazel/rules/testing/wine/BUILD.bazel
Normal file
54
bazel/rules/testing/wine/BUILD.bazel
Normal file
@@ -0,0 +1,54 @@
|
||||
load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library")
|
||||
load(":wine.bzl", "wine_rust_test")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files([
|
||||
"wine.bzl",
|
||||
"wine_runtime.bzl",
|
||||
])
|
||||
|
||||
rust_library(
|
||||
name = "wine_test_support",
|
||||
testonly = True,
|
||||
srcs = [
|
||||
"src/lib.rs",
|
||||
"src/lib_tests.rs",
|
||||
],
|
||||
crate_name = "wine_test_support",
|
||||
crate_root = "src/lib.rs",
|
||||
edition = "2024",
|
||||
target_compatible_with = ["@platforms//os:linux"],
|
||||
deps = [
|
||||
"//codex-rs/utils/cargo-bin",
|
||||
"//codex-rs/utils/pty",
|
||||
"@crates//:anyhow",
|
||||
"@crates//:tempfile",
|
||||
"@crates//:tokio",
|
||||
],
|
||||
)
|
||||
|
||||
rust_binary(
|
||||
name = "windows-smoke",
|
||||
testonly = True,
|
||||
srcs = ["fixtures/windows_smoke.rs"],
|
||||
crate_name = "wine_smoke",
|
||||
crate_root = "fixtures/windows_smoke.rs",
|
||||
edition = "2024",
|
||||
tags = ["manual"],
|
||||
target_compatible_with = ["@platforms//os:windows"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
wine_rust_test(
|
||||
name = "wine-test-support-unit-tests",
|
||||
timeout = "moderate",
|
||||
crate = ":wine_test_support",
|
||||
windows_binaries = {
|
||||
"wine-smoke": ":windows-smoke",
|
||||
},
|
||||
deps = [
|
||||
"@crates//:futures",
|
||||
"@crates//:pretty_assertions",
|
||||
],
|
||||
)
|
||||
15
bazel/rules/testing/wine/fixtures/windows_smoke.rs
Normal file
15
bazel/rules/testing/wine/fixtures/windows_smoke.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use std::io::Write;
|
||||
|
||||
fn main() {
|
||||
println!("WINE_TEST_READY");
|
||||
std::io::stdout().flush().expect("flush readiness marker");
|
||||
|
||||
if std::env::args().any(|arg| arg == "--fail") {
|
||||
std::process::exit(9);
|
||||
}
|
||||
if std::env::args().any(|arg| arg == "--wait") {
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
}
|
||||
402
bazel/rules/testing/wine/src/lib.rs
Normal file
402
bazel/rules/testing/wine/src/lib.rs
Normal file
@@ -0,0 +1,402 @@
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
compile_error!("wine_test_support can only run on Linux");
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::future::Future;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command as StdCommand;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use tempfile::TempDir;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
|
||||
/// Builds a command that runs a Windows executable in an isolated Wine prefix.
|
||||
pub struct WineTestCommand {
|
||||
executable: PathBuf,
|
||||
args: Vec<OsString>,
|
||||
env: Vec<(OsString, OsString)>,
|
||||
}
|
||||
|
||||
/// Owns a Wine process and its isolated wineserver.
|
||||
///
|
||||
/// Call [`Self::scope`] or [`Self::shutdown`] on every successful path. A
|
||||
/// normal unguarded drop panics, while a drop during unwinding performs
|
||||
/// blocking cleanup without introducing a second panic.
|
||||
pub struct WineTestProcess {
|
||||
processes: Option<WineProcesses>,
|
||||
}
|
||||
|
||||
struct WineProcesses {
|
||||
child: Child,
|
||||
cleanup_complete: bool,
|
||||
prefix: TempDir,
|
||||
runtime: WineRuntimePaths,
|
||||
}
|
||||
|
||||
struct WineRuntimePaths {
|
||||
dll_path: PathBuf,
|
||||
powershell_runtime: PathBuf,
|
||||
wine: PathBuf,
|
||||
wineserver: PathBuf,
|
||||
}
|
||||
|
||||
impl WineTestCommand {
|
||||
/// Creates a Wine command for `executable`.
|
||||
pub fn new(executable: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
args: Vec::new(),
|
||||
env: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an argument passed to the Windows executable.
|
||||
#[must_use]
|
||||
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
|
||||
self.args.push(arg.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds or overrides an environment variable for the Wine process.
|
||||
#[must_use]
|
||||
pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
|
||||
self.env.push((key.into(), value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Starts the Windows executable with a fresh `WINEPREFIX`.
|
||||
pub fn spawn(self) -> Result<WineTestProcess> {
|
||||
let runtime = WineRuntimePaths::from_runfiles()?;
|
||||
let prefix = TempDir::new().context("create isolated Wine prefix")?;
|
||||
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
|
||||
let mut command = StdCommand::new(&runtime.wine);
|
||||
configure_wine_environment(&mut command, &runtime, prefix.path());
|
||||
command
|
||||
.arg(self.executable)
|
||||
.args(self.args)
|
||||
.envs(self.env)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
|
||||
let mut command = TokioCommand::from(command);
|
||||
command.kill_on_drop(true);
|
||||
let child = command
|
||||
.spawn()
|
||||
.context("start Windows process under Wine")?;
|
||||
|
||||
Ok(WineTestProcess {
|
||||
processes: Some(WineProcesses {
|
||||
child,
|
||||
cleanup_complete: false,
|
||||
prefix,
|
||||
runtime,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl WineTestProcess {
|
||||
/// Returns the host path to this process's isolated Wine prefix.
|
||||
pub fn prefix_path(&self) -> &Path {
|
||||
let Some(processes) = self.processes.as_ref() else {
|
||||
panic!("Wine process guard is missing");
|
||||
};
|
||||
processes.prefix.path()
|
||||
}
|
||||
|
||||
/// Takes the piped standard output of the Wine process.
|
||||
///
|
||||
/// This may only be called once for a process created by
|
||||
/// [`WineTestCommand::spawn`].
|
||||
pub fn take_stdout(&mut self) -> ChildStdout {
|
||||
let Some(processes) = self.processes.as_mut() else {
|
||||
panic!("Wine process guard is missing");
|
||||
};
|
||||
let Some(stdout) = processes.child.stdout.take() else {
|
||||
panic!("Wine process stdout has already been taken");
|
||||
};
|
||||
stdout
|
||||
}
|
||||
|
||||
/// Runs `future`, then asynchronously tears down Wine before returning.
|
||||
///
|
||||
/// If both the scoped operation and teardown fail, the operation error is
|
||||
/// returned with the teardown error attached as context. A panic in the
|
||||
/// scoped operation triggers the blocking unwind-time fallback instead.
|
||||
pub async fn scope<T>(self, future: impl Future<Output = Result<T>>) -> Result<T> {
|
||||
let scope_result = future.await;
|
||||
let shutdown_result = self.shutdown().await;
|
||||
match (scope_result, shutdown_result) {
|
||||
(Ok(value), Ok(())) => Ok(value),
|
||||
(Err(error), Ok(())) => Err(error),
|
||||
(Ok(_), Err(error)) => Err(error),
|
||||
(Err(error), Err(shutdown_error)) => {
|
||||
Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kills the Windows process, waits for it, and stops its wineserver.
|
||||
pub async fn shutdown(mut self) -> Result<()> {
|
||||
let Some(processes) = self.processes.as_mut() else {
|
||||
anyhow::bail!("Wine process guard is missing");
|
||||
};
|
||||
let result = processes.shutdown().await;
|
||||
self.processes.take();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WineTestProcess {
|
||||
fn drop(&mut self) {
|
||||
// Panicking here starts unwinding, after which WineProcesses performs
|
||||
// the blocking fallback while its field is dropped.
|
||||
if self.processes.is_some() && !std::thread::panicking() {
|
||||
panic!("WineTestProcess dropped without async teardown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WineRuntimePaths {
|
||||
fn from_runfiles() -> Result<Self> {
|
||||
let wine = codex_utils_cargo_bin::cargo_bin("wine")?;
|
||||
let runtime_marker = codex_utils_cargo_bin::cargo_bin("wine-runtime-marker")?;
|
||||
let dll_path = runtime_marker
|
||||
.parent()
|
||||
.context("locate Wine runtime directory")?
|
||||
.to_path_buf();
|
||||
let wineserver = codex_utils_cargo_bin::cargo_bin("wineserver")?;
|
||||
let powershell_runtime = codex_utils_cargo_bin::cargo_bin("pwsh-runtime-marker")?
|
||||
.parent()
|
||||
.context("locate PowerShell runtime directory")?
|
||||
.to_path_buf();
|
||||
Ok(Self {
|
||||
dll_path,
|
||||
powershell_runtime,
|
||||
wine,
|
||||
wineserver,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl WineProcesses {
|
||||
async fn shutdown(&mut self) -> Result<()> {
|
||||
let (kill_result, check_exit_status) = match self.child.try_wait() {
|
||||
Ok(Some(_)) => (Ok(()), true),
|
||||
Ok(None) => (
|
||||
self.child
|
||||
.start_kill()
|
||||
.context("kill Windows process running under Wine"),
|
||||
false,
|
||||
),
|
||||
Err(error) => (Err(error).context("check Windows process status"), false),
|
||||
};
|
||||
let wait_result = self
|
||||
.child
|
||||
.wait()
|
||||
.await
|
||||
.context("wait for Windows process running under Wine")
|
||||
.and_then(|status| {
|
||||
anyhow::ensure!(
|
||||
!check_exit_status || status.success(),
|
||||
"Windows process exited with {status}"
|
||||
);
|
||||
Ok(())
|
||||
});
|
||||
let wineserver_result = async {
|
||||
let mut command = TokioCommand::from(self.stop_wineserver_command());
|
||||
let status = command.status().await.context("stop isolated wineserver")?;
|
||||
anyhow::ensure!(status.success(), "wineserver exited with {status}");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
|
||||
// Every cleanup action has been attempted, so an individual error
|
||||
// should not cause the blocking fallback to repeat them.
|
||||
self.cleanup_complete = true;
|
||||
kill_result?;
|
||||
wait_result?;
|
||||
wineserver_result
|
||||
}
|
||||
|
||||
fn stop_wineserver_command(&self) -> StdCommand {
|
||||
let mut command = StdCommand::new(&self.runtime.wineserver);
|
||||
configure_wine_environment(&mut command, &self.runtime, self.prefix.path());
|
||||
command
|
||||
.args(["-k", "-w"])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
command
|
||||
}
|
||||
|
||||
fn shutdown_blocking(&mut self) {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup starting for prefix {}",
|
||||
self.prefix.path().display()
|
||||
));
|
||||
if let Err(error) = self.child.start_kill() {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not kill its child: {error}"
|
||||
));
|
||||
}
|
||||
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup waiting for its child"));
|
||||
loop {
|
||||
match self.child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup child exited with {status}"
|
||||
));
|
||||
break;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
|
||||
Err(error) => {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not wait for its child: {error}"
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup stopping its wineserver"));
|
||||
match self.stop_wineserver_command().status() {
|
||||
Ok(status) => log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup wineserver exited with {status}"
|
||||
)),
|
||||
Err(error) => log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not stop its wineserver: {error}"
|
||||
)),
|
||||
}
|
||||
self.cleanup_complete = true;
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup complete"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WineProcesses {
|
||||
fn drop(&mut self) {
|
||||
// Never introduce a second panic while unwinding. Blocking here is
|
||||
// intentional because test failures must not leak Wine children.
|
||||
if !self.cleanup_complete && std::thread::panicking() {
|
||||
self.shutdown_blocking();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_panic_cleanup(args: std::fmt::Arguments<'_>) {
|
||||
let _ = writeln!(std::io::stderr().lock(), "{args}");
|
||||
}
|
||||
|
||||
fn configure_wine_environment(command: &mut StdCommand, runtime: &WineRuntimePaths, prefix: &Path) {
|
||||
command
|
||||
.env_remove("DISPLAY")
|
||||
.env("HOME", prefix)
|
||||
.env("XDG_RUNTIME_DIR", prefix)
|
||||
.env("WINEARCH", "win64")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDLLPATH", &runtime.dll_path)
|
||||
.env("WINESERVER", &runtime.wineserver)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.env("WINEDLLOVERRIDES", "mscoree,mshtml,winegstreamer=")
|
||||
.env("LANG", "C.UTF-8")
|
||||
.env("LC_ALL", "C.UTF-8")
|
||||
.env("LC_CTYPE", "C.UTF-8")
|
||||
.env("TEMP", r"C:\windows\temp")
|
||||
.env("TMP", r"C:\windows\temp");
|
||||
}
|
||||
|
||||
/// Installs the complete pinned PowerShell distribution where Windows tooling
|
||||
/// expects to discover PowerShell 7.
|
||||
///
|
||||
/// `pwsh.exe` is not a standalone executable: it loads its adjacent .NET host,
|
||||
/// managed assemblies, native libraries, modules, and configuration files at
|
||||
/// startup. The Bazel archive is exposed through runfiles rather than a normal
|
||||
/// Windows installation, while shell detection deliberately probes the
|
||||
/// conventional `C:\Program Files\PowerShell\7` fallback. We therefore have to
|
||||
/// reproduce the archive's directory tree inside each isolated Wine prefix;
|
||||
/// copying only the executable would fail before a command could run.
|
||||
fn install_powershell_runtime(prefix: &Path, runtime: &Path) -> Result<()> {
|
||||
let powershell_parent = prefix
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell");
|
||||
fs::create_dir_all(&powershell_parent).context("create PowerShell installation parent")?;
|
||||
let destination = powershell_parent.join("7");
|
||||
materialize_runtime_directory(runtime, &destination)
|
||||
}
|
||||
|
||||
/// Recursively reproduces a runfiles directory in a writable Wine prefix.
|
||||
///
|
||||
/// Bazel runfiles may be immutable, represented by a symlink forest, and may
|
||||
/// contain the PowerShell distribution on a different filesystem from the
|
||||
/// temporary prefix. Hard links avoid repeatedly copying the roughly
|
||||
/// hundred-megabyte runtime when both locations share a filesystem; the copy
|
||||
/// fallback preserves correctness for sandbox or remote-execution layouts
|
||||
/// where cross-device hard links are unavailable.
|
||||
fn materialize_runtime_directory(source: &Path, destination: &Path) -> Result<()> {
|
||||
fs::create_dir_all(destination).with_context(|| {
|
||||
format!(
|
||||
"create PowerShell runtime directory {}",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
for entry in fs::read_dir(source)
|
||||
.with_context(|| format!("read PowerShell runtime directory {}", source.display()))?
|
||||
{
|
||||
let entry = entry.context("read PowerShell runtime entry")?;
|
||||
let source_path = entry.path();
|
||||
let destination_path = destination.join(entry.file_name());
|
||||
// Local Bazel runfiles trees expose external-repository files as
|
||||
// symlinks. Resolve those trusted runfiles entries before inspecting
|
||||
// or linking them so the writable prefix contains ordinary files.
|
||||
let resolved_source_path = fs::canonicalize(&source_path).with_context(|| {
|
||||
format!("resolve PowerShell runtime entry {}", source_path.display())
|
||||
})?;
|
||||
let file_type = fs::metadata(&resolved_source_path)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"inspect PowerShell runtime entry {}",
|
||||
resolved_source_path.display()
|
||||
)
|
||||
})?
|
||||
.file_type();
|
||||
if file_type.is_dir() {
|
||||
// PowerShell resolves assemblies and modules by their relative
|
||||
// locations, so flattening the archive is not an option.
|
||||
materialize_runtime_directory(&resolved_source_path, &destination_path)?;
|
||||
} else if file_type.is_file() {
|
||||
// A hard link gives each prefix the expected installation layout
|
||||
// without duplicating the large runtime in the common local case.
|
||||
if fs::hard_link(&resolved_source_path, &destination_path).is_err() {
|
||||
// Cross-device links are common under Bazel sandboxing and
|
||||
// remote execution, where an ordinary copy is still valid.
|
||||
fs::copy(&resolved_source_path, &destination_path).with_context(|| {
|
||||
format!(
|
||||
"copy PowerShell runtime file {} to {}",
|
||||
resolved_source_path.display(),
|
||||
destination_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
} else {
|
||||
anyhow::bail!(
|
||||
"unsupported PowerShell runtime entry type at {}",
|
||||
source_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
451
bazel/rules/testing/wine/src/lib_tests.rs
Normal file
451
bazel/rules/testing/wine/src/lib_tests.rs
Normal file
@@ -0,0 +1,451 @@
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::future::Future;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_utils_pty::SpawnedProcess;
|
||||
use codex_utils_pty::TerminalSize;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::WineRuntimePaths;
|
||||
use super::WineTestCommand;
|
||||
use super::WineTestProcess;
|
||||
use super::install_powershell_runtime;
|
||||
|
||||
async fn waiting_smoke_process() -> Result<WineTestProcess> {
|
||||
let executable = codex_utils_cargo_bin::cargo_bin("wine-smoke")?;
|
||||
let mut process = WineTestCommand::new(executable).arg("--wait").spawn()?;
|
||||
let mut lines = BufReader::new(process.take_stdout()).lines();
|
||||
let ready_line = lines
|
||||
.next_line()
|
||||
.await?
|
||||
.context("Windows smoke process exited before becoming ready")?;
|
||||
assert_eq!(ready_line, "WINE_TEST_READY");
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
fn prefix_path(process: &WineTestProcess) -> PathBuf {
|
||||
process
|
||||
.processes
|
||||
.as_ref()
|
||||
.expect("Wine process guard")
|
||||
.prefix
|
||||
.path()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn assert_prefix_removed(prefix: &Path) {
|
||||
assert!(
|
||||
!prefix.exists(),
|
||||
"Wine prefix remains: {}",
|
||||
prefix.display()
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_panic_message(panic: Box<dyn Any + Send>, expected: &str) {
|
||||
assert_eq!(panic.downcast_ref::<&str>(), Some(&expected));
|
||||
}
|
||||
|
||||
async fn assert_future_panics<T>(future: impl Future<Output = T>, expected: &str) {
|
||||
let panic = match AssertUnwindSafe(future).catch_unwind().await {
|
||||
Ok(_) => panic!("future should panic"),
|
||||
Err(panic) => panic,
|
||||
};
|
||||
assert_panic_message(panic, expected);
|
||||
}
|
||||
|
||||
async fn process_with_failing_wineserver_stop() -> Result<WineTestProcess> {
|
||||
let mut process = waiting_smoke_process().await?;
|
||||
let processes = process.processes.as_mut().expect("Wine process guard");
|
||||
|
||||
let mut command = TokioCommand::from(processes.stop_wineserver_command());
|
||||
let status = command
|
||||
.status()
|
||||
.await
|
||||
.context("pre-stop isolated wineserver")?;
|
||||
assert!(status.success(), "wineserver exited with {status}");
|
||||
|
||||
processes.runtime.wineserver = processes.prefix.path().join("missing-wineserver");
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_without_teardown_panics() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async move { drop(process) },
|
||||
"WineTestProcess dropped without async teardown",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_while_panicking_does_not_panic_again() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async move {
|
||||
let _process = process;
|
||||
panic!("sentinel panic");
|
||||
},
|
||||
"sentinel panic",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_teardown_disarms_drop_bomb() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
process.shutdown().await?;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn take_stdout_panics_when_called_twice() -> Result<()> {
|
||||
let mut process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async {
|
||||
process.take_stdout();
|
||||
},
|
||||
"Wine process stdout has already been taken",
|
||||
)
|
||||
.await;
|
||||
process.shutdown().await?;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_returns_value_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
let value = process
|
||||
.scope(async { Ok::<_, anyhow::Error>("scope value") })
|
||||
.await?;
|
||||
assert_eq!(value, "scope value");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_returns_body_error_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.scope(async { Err::<(), _>(anyhow!("scope body failed")) })
|
||||
.await
|
||||
.expect_err("scope body should fail");
|
||||
|
||||
assert_eq!(error.to_string(), "scope body failed");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_panic_preserves_panic_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
assert_future_panics(
|
||||
process.scope::<()>(async { panic!("scope panic") }),
|
||||
"scope panic",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_reports_nonzero_process_exit() -> Result<()> {
|
||||
let executable = codex_utils_cargo_bin::cargo_bin("wine-smoke")?;
|
||||
let mut process = WineTestCommand::new(executable).arg("--fail").spawn()?;
|
||||
let prefix = prefix_path(&process);
|
||||
let status = process
|
||||
.processes
|
||||
.as_mut()
|
||||
.expect("Wine process guard")
|
||||
.child
|
||||
.wait()
|
||||
.await?;
|
||||
assert!(
|
||||
!status.success(),
|
||||
"Windows smoke process unexpectedly passed"
|
||||
);
|
||||
|
||||
let error = process.shutdown().await.expect_err("shutdown should fail");
|
||||
|
||||
assert!(error.to_string().starts_with("Windows process exited with"));
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_preserves_body_error_when_teardown_also_fails() -> Result<()> {
|
||||
let process = process_with_failing_wineserver_stop().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.scope(async { Err::<(), _>(anyhow!("scope body failed")) })
|
||||
.await
|
||||
.expect_err("scope body and teardown should fail");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.starts_with("Wine teardown also failed: stop isolated wineserver"),
|
||||
"unexpected error: {error:#}"
|
||||
);
|
||||
assert_eq!(
|
||||
error.chain().last().map(ToString::to_string),
|
||||
Some("scope body failed".to_string())
|
||||
);
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_returns_teardown_error() -> Result<()> {
|
||||
let process = process_with_failing_wineserver_stop().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.shutdown()
|
||||
.await
|
||||
.expect_err("shutdown should report a wineserver failure");
|
||||
|
||||
assert_eq!(error.to_string(), "stop isolated wineserver");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_runtime_is_materialized_at_the_windows_fallback_path() -> Result<()> {
|
||||
let prefix = TempDir::new()?;
|
||||
let runtime = TempDir::new()?;
|
||||
fs::create_dir(runtime.path().join("Modules"))?;
|
||||
fs::write(runtime.path().join("pwsh.exe"), b"pwsh")?;
|
||||
fs::write(runtime.path().join("Modules").join("marker.txt"), b"module")?;
|
||||
|
||||
install_powershell_runtime(prefix.path(), runtime.path())?;
|
||||
|
||||
let installed = prefix
|
||||
.path()
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell")
|
||||
.join("7");
|
||||
assert_eq!(fs::read(installed.join("pwsh.exe"))?, b"pwsh");
|
||||
assert_eq!(
|
||||
fs::read(installed.join("Modules").join("marker.txt"))?,
|
||||
b"module"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_runtime_follows_runfiles_symlinks() -> Result<()> {
|
||||
let prefix = TempDir::new()?;
|
||||
let runtime = TempDir::new()?;
|
||||
let backing = TempDir::new()?;
|
||||
let backing_file = backing.path().join("pwsh.exe");
|
||||
fs::write(&backing_file, b"pwsh")?;
|
||||
std::os::unix::fs::symlink(&backing_file, runtime.path().join("pwsh.exe"))?;
|
||||
|
||||
install_powershell_runtime(prefix.path(), runtime.path())?;
|
||||
|
||||
let installed = prefix
|
||||
.path()
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell")
|
||||
.join("7")
|
||||
.join("pwsh.exe");
|
||||
assert_eq!(fs::read(installed)?, b"pwsh");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pinned_powershell_runs_under_wine_with_a_pty() -> Result<()> {
|
||||
// Keep this integration smoke test local to the Wine support crate. The
|
||||
// production-shaped PowerShell launch path belongs to exec-server tests.
|
||||
// The marker makes the assertion resilient to Wine or PTY startup chatter.
|
||||
const POWERSHELL_SMOKE_MARKER: &str = "WINE_PWSH_SMOKE";
|
||||
// Besides proving that the pinned runtime starts, report the properties
|
||||
// that shell detection and command construction rely on: PowerShell 7 Core
|
||||
// running with Windows semantics and a backslash path separator.
|
||||
const POWERSHELL_SMOKE_SCRIPT: &str = concat!(
|
||||
"$ErrorActionPreference = 'Stop'; ",
|
||||
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ",
|
||||
"$separatorCode = [int]([System.IO.Path]::DirectorySeparatorChar); ",
|
||||
"if ($PSVersionTable.PSVersion.Major -ne 7) { throw 'expected PowerShell 7' }; ",
|
||||
"if ($PSVersionTable.PSEdition -ne 'Core') { throw 'expected PowerShell Core' }; ",
|
||||
"if (-not $IsWindows) { throw 'expected Windows semantics' }; ",
|
||||
"if ($separatorCode -ne 92) { throw 'expected backslash path separator' }; ",
|
||||
"Write-Output ('WINE_PWSH_SMOKE|' + ",
|
||||
"$PSVersionTable.PSVersion.ToString() + '|' + ",
|
||||
"$PSVersionTable.PSEdition + '|' + ",
|
||||
"$IsWindows.ToString().ToLowerInvariant() + '|' + $separatorCode)",
|
||||
);
|
||||
let runtime = WineRuntimePaths::from_runfiles()?;
|
||||
let prefix = TempDir::new()?;
|
||||
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
|
||||
let mut env = std::env::vars().collect::<HashMap<_, _>>();
|
||||
env.remove("DISPLAY");
|
||||
env.extend([
|
||||
(
|
||||
"HOME".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"XDG_RUNTIME_DIR".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
("WINEARCH".to_string(), "win64".to_string()),
|
||||
(
|
||||
"WINEPREFIX".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"WINEDLLPATH".to_string(),
|
||||
runtime.dll_path.to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"WINESERVER".to_string(),
|
||||
runtime.wineserver.to_string_lossy().into_owned(),
|
||||
),
|
||||
("WINEDEBUG".to_string(), "-all".to_string()),
|
||||
(
|
||||
"WINEDLLOVERRIDES".to_string(),
|
||||
"mscoree,mshtml,winegstreamer=".to_string(),
|
||||
),
|
||||
("LANG".to_string(), "C.UTF-8".to_string()),
|
||||
("LC_ALL".to_string(), "C.UTF-8".to_string()),
|
||||
("LC_CTYPE".to_string(), "C.UTF-8".to_string()),
|
||||
("TEMP".to_string(), r"C:\windows\temp".to_string()),
|
||||
("TMP".to_string(), r"C:\windows\temp".to_string()),
|
||||
]);
|
||||
let args = [
|
||||
r"C:\Program Files\PowerShell\7\pwsh.exe".to_string(),
|
||||
"-NoLogo".to_string(),
|
||||
"-NoProfile".to_string(),
|
||||
"-NonInteractive".to_string(),
|
||||
"-Command".to_string(),
|
||||
POWERSHELL_SMOKE_SCRIPT.to_string(),
|
||||
];
|
||||
let wine = runtime.wine.to_string_lossy().into_owned();
|
||||
let SpawnedProcess {
|
||||
session,
|
||||
mut stdout_rx,
|
||||
mut stderr_rx,
|
||||
exit_rx,
|
||||
} = codex_utils_pty::spawn_pty_process(
|
||||
&wine,
|
||||
&args,
|
||||
prefix.path(),
|
||||
&env,
|
||||
/*arg0*/ &None,
|
||||
TerminalSize::default(),
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let command_result = timeout(Duration::from_secs(90), async {
|
||||
let stdout = async {
|
||||
let mut output = Vec::new();
|
||||
while let Some(chunk) = stdout_rx.recv().await {
|
||||
output.extend(chunk);
|
||||
}
|
||||
output
|
||||
};
|
||||
let stderr = async {
|
||||
let mut output = Vec::new();
|
||||
while let Some(chunk) = stderr_rx.recv().await {
|
||||
output.extend(chunk);
|
||||
}
|
||||
output
|
||||
};
|
||||
let (stdout, stderr, exit_code) = tokio::join!(stdout, stderr, exit_rx);
|
||||
Ok::<_, anyhow::Error>((stdout, stderr, exit_code.context("wait for PowerShell")?))
|
||||
})
|
||||
.await
|
||||
.context("PowerShell smoke test timed out")
|
||||
.and_then(std::convert::identity);
|
||||
drop(session);
|
||||
let shutdown_result = timeout(Duration::from_secs(10), async {
|
||||
let mut command = TokioCommand::new(&runtime.wineserver);
|
||||
command
|
||||
.args(["-k", "-w"])
|
||||
.env("HOME", prefix.path())
|
||||
.env("WINEPREFIX", prefix.path())
|
||||
.env("XDG_RUNTIME_DIR", prefix.path())
|
||||
.kill_on_drop(true);
|
||||
let status = command.status().await.context("stop isolated wineserver")?;
|
||||
anyhow::ensure!(
|
||||
status.success() || status.code() == Some(1),
|
||||
"wineserver exited with {status}"
|
||||
);
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await
|
||||
.context("stop isolated wineserver timed out")
|
||||
.and_then(std::convert::identity);
|
||||
let (stdout, stderr, exit_code) = match (command_result, shutdown_result) {
|
||||
(Ok(output), Ok(())) => output,
|
||||
(Err(error), Ok(())) => return Err(error),
|
||||
(Ok(_), Err(error)) => return Err(error),
|
||||
(Err(error), Err(shutdown_error)) => {
|
||||
return Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")));
|
||||
}
|
||||
};
|
||||
anyhow::ensure!(
|
||||
exit_code == 0,
|
||||
"PowerShell exited with {}; stderr: {}",
|
||||
exit_code,
|
||||
String::from_utf8_lossy(&stderr),
|
||||
);
|
||||
let output = String::from_utf8(stdout)?;
|
||||
let marker_start = output
|
||||
.find(POWERSHELL_SMOKE_MARKER)
|
||||
.with_context(|| format!("PowerShell smoke marker was missing from {output:?}"))?;
|
||||
let smoke = output[marker_start..]
|
||||
.lines()
|
||||
.next()
|
||||
.context("PowerShell smoke marker line was incomplete")?
|
||||
.trim_end_matches('\r');
|
||||
let fields = smoke.split('|').collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
fields.len(),
|
||||
5,
|
||||
"unexpected PowerShell smoke output: {smoke}"
|
||||
);
|
||||
assert_eq!(fields[0], POWERSHELL_SMOKE_MARKER);
|
||||
assert_eq!(
|
||||
fields[1].split('.').next(),
|
||||
Some("7"),
|
||||
"expected PowerShell 7.x, got {}",
|
||||
fields[1],
|
||||
);
|
||||
assert_eq!(&fields[2..], &["Core", "true", "92"]);
|
||||
Ok(())
|
||||
}
|
||||
69
bazel/rules/testing/wine/wine.bzl
Normal file
69
bazel/rules/testing/wine/wine.bzl
Normal file
@@ -0,0 +1,69 @@
|
||||
"""Macros for cross-building Windows Rust binaries and testing them with Wine."""
|
||||
|
||||
load("@rules_rust//rust:defs.bzl", "rust_test")
|
||||
load("//:defs.bzl", "WINDOWS_GNULLVM_RUSTC_LINK_FLAGS")
|
||||
load("//bazel/rules/testing:foreign_platform_binary.bzl", "foreign_platform_binary")
|
||||
load(":wine_runtime.bzl", "WINE_TEST_TARGET_COMPATIBLE_WITH", "wine_test_runtime")
|
||||
|
||||
def wine_rust_test(
|
||||
name,
|
||||
windows_binaries,
|
||||
host_binaries = {},
|
||||
data = [],
|
||||
target_compatible_with = [],
|
||||
**kwargs):
|
||||
"""Defines an x86-64 Linux Rust test with a pinned Wine runtime.
|
||||
|
||||
Each `windows_binaries` executable is transitioned to GNU/LLVM Windows;
|
||||
every Rust dependency receives the repository's Windows linker flags while
|
||||
the test stays on x86-64 Linux. Its environment-variable contract is:
|
||||
|
||||
* Each `host_binaries` and `windows_binaries` entry contributes
|
||||
`CARGO_BIN_EXE_<binary_name>` for its executable.
|
||||
* `CARGO_BIN_EXE_wine` and `CARGO_BIN_EXE_wineserver` identify Wine tools.
|
||||
* `CARGO_BIN_EXE_wine-runtime-marker` identifies a file whose parent is the
|
||||
Wine DLL directory to use as `WINEDLLPATH`.
|
||||
* `CARGO_BIN_EXE_pwsh` identifies the pinned PowerShell executable and
|
||||
`CARGO_BIN_EXE_pwsh-runtime-marker` identifies a file whose parent is the
|
||||
complete PowerShell runtime.
|
||||
|
||||
These are Bazel runfile locations. Resolve binaries with
|
||||
`codex_utils_cargo_bin::cargo_bin`; `:wine_test_support` resolves the fixed
|
||||
runtime names and starts each process in an isolated prefix.
|
||||
|
||||
Args:
|
||||
name: Name of the generated Linux `rust_test`.
|
||||
windows_binaries: Map from `CARGO_BIN_EXE_*` suffixes to Windows targets.
|
||||
host_binaries: Map from `CARGO_BIN_EXE_*` suffixes to Linux host targets.
|
||||
data: Additional runtime data for the Linux test.
|
||||
target_compatible_with: Additional compatibility constraints.
|
||||
**kwargs: Remaining attributes forwarded to `rust_test`.
|
||||
"""
|
||||
binaries = dict(host_binaries)
|
||||
for index, binary_name in enumerate(sorted(windows_binaries.keys())):
|
||||
if binary_name in binaries:
|
||||
fail("Windows test binary name collides with host binary: {}".format(binary_name))
|
||||
transitioned_binary = name + "-windows-binary-" + str(index)
|
||||
foreign_platform_binary(
|
||||
name = transitioned_binary,
|
||||
binary = windows_binaries[binary_name],
|
||||
extra_rustc_flags = WINDOWS_GNULLVM_RUSTC_LINK_FLAGS,
|
||||
platform = "//:windows_x86_64_gnullvm",
|
||||
tags = ["manual"],
|
||||
target_compatible_with = [
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
],
|
||||
testonly = True,
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
binaries[binary_name] = ":" + transitioned_binary
|
||||
|
||||
runtime = wine_test_runtime(binaries)
|
||||
rust_test(
|
||||
name = name,
|
||||
data = data + runtime.data,
|
||||
env = runtime.env,
|
||||
target_compatible_with = target_compatible_with + WINE_TEST_TARGET_COMPATIBLE_WITH,
|
||||
**kwargs
|
||||
)
|
||||
40
bazel/rules/testing/wine/wine_runtime.bzl
Normal file
40
bazel/rules/testing/wine/wine_runtime.bzl
Normal file
@@ -0,0 +1,40 @@
|
||||
"""Runfiles shared by tests that execute Windows binaries through Wine."""
|
||||
|
||||
_WINE_RUNTIME_BINARIES = {
|
||||
"pwsh": "@powershell_windows_x86_64//:pwsh",
|
||||
"pwsh-runtime-marker": "@powershell_windows_x86_64//:runtime_marker",
|
||||
"wine": "@wine_linux_x86_64//:wine",
|
||||
"wine-runtime-marker": "@wine_linux_x86_64//:runtime_marker",
|
||||
"wineserver": "@wine_linux_x86_64//:wineserver",
|
||||
}
|
||||
|
||||
_WINE_RUNTIME_DATA = [
|
||||
"@powershell_windows_x86_64//:runtime",
|
||||
"@wine_linux_x86_64//:runtime",
|
||||
]
|
||||
|
||||
WINE_TEST_TARGET_COMPATIBLE_WITH = [
|
||||
"@llvm//constraints/libc:gnu.2.28",
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
]
|
||||
|
||||
def wine_test_runtime(test_binaries = {}):
|
||||
"""Returns data and environment mappings for a Wine-backed test."""
|
||||
binaries = dict(_WINE_RUNTIME_BINARIES)
|
||||
for binary_name in sorted(test_binaries.keys()):
|
||||
if binary_name in binaries:
|
||||
fail("test binary name collides with Wine runtime: {}".format(binary_name))
|
||||
binaries[binary_name] = test_binaries[binary_name]
|
||||
|
||||
return struct(
|
||||
data = _WINE_RUNTIME_DATA + [binary for binary in binaries.values()],
|
||||
env = {
|
||||
"CARGO_BIN_EXE_{}".format(binary_name): "$(rlocationpath {})".format(binary)
|
||||
for binary_name, binary in binaries.items()
|
||||
},
|
||||
runfile_env = {
|
||||
binary_label: "CARGO_BIN_EXE_" + binary_name
|
||||
for binary_name, binary_label in binaries.items()
|
||||
},
|
||||
)
|
||||
23
bazel/schema/BUILD.bazel
Normal file
23
bazel/schema/BUILD.bazel
Normal file
@@ -0,0 +1,23 @@
|
||||
load("//bazel/rules:schema_bundle.bzl", "schema_bundle")
|
||||
|
||||
schema_bundle(
|
||||
name = "public-schema-bundle",
|
||||
testonly = True,
|
||||
generator = "//codex-rs/app-server-protocol:schema-generator-on-demand",
|
||||
tags = ["manual"],
|
||||
)
|
||||
|
||||
schema_bundle(
|
||||
name = "app-server",
|
||||
generator = "//codex-rs/app-server-protocol:schema-generator-on-demand",
|
||||
tags = ["manual"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "stable",
|
||||
srcs = [":app-server"],
|
||||
output_group = "stable",
|
||||
tags = ["manual"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
16
bazel/schema/tools/BUILD.bazel
Normal file
16
bazel/schema/tools/BUILD.bazel
Normal file
@@ -0,0 +1,16 @@
|
||||
load("@rules_python//python:defs.bzl", "py_binary")
|
||||
load("@schema_python//:requirements.bzl", "requirement")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
py_binary(
|
||||
name = "python-codegen",
|
||||
srcs = ["python_codegen.py"],
|
||||
main = "python_codegen.py",
|
||||
python_version = "3.12",
|
||||
tags = ["manual"],
|
||||
deps = [
|
||||
requirement("datamodel-code-generator"),
|
||||
requirement("packaging"),
|
||||
],
|
||||
)
|
||||
51
bazel/schema/tools/python_codegen.py
Normal file
51
bazel/schema/tools/python_codegen.py
Normal file
@@ -0,0 +1,51 @@
|
||||
"""Generate SDK build outputs in scratch space without formatting."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
files = json.loads(Path(sys.argv[1]).read_text())
|
||||
schema = Path(sys.argv[2]).resolve()
|
||||
output = Path(sys.argv[3]).resolve()
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
sdk = Path(temporary) / "sdk/python"
|
||||
for source, relative in files:
|
||||
destination = sdk / relative
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, destination)
|
||||
|
||||
environment = {
|
||||
**os.environ,
|
||||
"PYTHONPATH": os.pathsep.join(sys.path),
|
||||
}
|
||||
subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(sdk / "scripts/update_sdk_artifacts.py"),
|
||||
"generate-types",
|
||||
"--no-format",
|
||||
"--schema-dir",
|
||||
str(schema),
|
||||
],
|
||||
cwd=sdk,
|
||||
env=environment,
|
||||
check=True,
|
||||
)
|
||||
for relative in (
|
||||
"src/openai_codex/api.py",
|
||||
"src/openai_codex/generated/v2_all.py",
|
||||
"src/openai_codex/generated/notification_registry.py",
|
||||
):
|
||||
destination = output / relative
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(sdk / relative, destination)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
35
bazel/toolchains/prost/BUILD.bazel
Normal file
35
bazel/toolchains/prost/BUILD.bazel
Normal file
@@ -0,0 +1,35 @@
|
||||
load("@rules_rust//extensions/prost:defs.bzl", "rust_prost_toolchain")
|
||||
load("@rules_rust//rust:defs.bzl", "rust_library_group")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
rust_library_group(
|
||||
name = "prost_runtime",
|
||||
deps = ["@crates//:prost"],
|
||||
)
|
||||
|
||||
rust_library_group(
|
||||
name = "tonic_runtime",
|
||||
deps = [
|
||||
":prost_runtime",
|
||||
"@crates//:tonic",
|
||||
"@crates//:tonic-prost",
|
||||
],
|
||||
)
|
||||
|
||||
rust_prost_toolchain(
|
||||
name = "toolchain_impl",
|
||||
compile_well_known_types = False,
|
||||
prost_plugin = "@rules_rs//rs/private/prost:protoc-gen-prost__protoc-gen-prost",
|
||||
prost_runtime = ":prost_runtime",
|
||||
prost_types = "@crates//:prost-types-0.14.3",
|
||||
tonic_plugin = "@rules_rs//rs/private/prost:protoc-gen-tonic__protoc-gen-tonic",
|
||||
tonic_plugin_flag = "--plugin=protoc-gen-tonic=%s",
|
||||
tonic_runtime = ":tonic_runtime",
|
||||
)
|
||||
|
||||
toolchain(
|
||||
name = "toolchain",
|
||||
toolchain = ":toolchain_impl",
|
||||
toolchain_type = "@rules_rust//extensions/prost:toolchain_type",
|
||||
)
|
||||
1
bazel/tools/BUILD.bazel
Normal file
1
bazel/tools/BUILD.bazel
Normal file
@@ -0,0 +1 @@
|
||||
exports_files(["dsymutil"])
|
||||
3
bazel/tools/dsymutil
Executable file
3
bazel/tools/dsymutil
Executable file
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
# rustc invokes dsymutil by name; the C toolchain supplies its hermetic path.
|
||||
exec "${LLVM_DSYMUTIL:?missing hermetic dsymutil}" "$@"
|
||||
Reference in New Issue
Block a user