We are going to build a remote cache for a monorepo that uses hermetic toolchains and sandboxing.
The goal is to cache build actions (like compilation) so that they can be reused across machines and environments, and to ensure that the builds are hermetic (i.e., the same inputs always produce the same outputs, regardless of the environment).
Steps:
We assume we have a monorepo with multiple packages, each having their own build steps.
We want to set up a remote cache (like a content-addressable storage) that stores the outputs of build actions.
We want to use hermetic toolchains (toolchains that are isolated from the host system, e.g., using a specific version of a compiler and its dependencies) and sandboxing (to isolate the build environment).
Approach:
We can model the build system after tools like Nix, Bazel, or Buck, but for simplicity, let's assume we are building a simple system that:
Computes a content hash (like SHA-256) of the build inputs (source files, toolchain, build script, etc.) and uses that as the cache key.
The build is run in a sandbox (e.g., using Docker, chroot, or other isolation mechanisms) to ensure that the build does not depend on the host system.
The toolchain is hermetic: we use a fixed set of binaries and libraries (maybe even a whole filesystem) that is the same for every build.
Implementation:
We can break it down into:
a. A cache server: a simple HTTP server that stores and retrieves build outputs by key.
b. A cache client: integrated into the build system of each package, which:
- Computes the cache key from the build inputs.
- Checks the cache server for the output.
- If cache hit, downloads the output.
- If cache miss, runs the build in a sandbox with the hermetic toolchain, then uploads the output to the cache.
However, note that the problem says "monorepo", so we might have a single build system that coordinates all packages.
Alternatively, we can design a system that works at the action level (like Bazel). Each build action (e.g., compiling a C file) is cached.
But let's assume we are caching at the package level (or even at the monorepo level) for simplicity.
Steps for the client:
Define what are the inputs for a package build:
Source files of the package (and maybe its dependencies? In a monorepo, we might have dependencies on other packages in the same repo, so we must also consider the source of those dependencies).
Build script (e.g., Makefile, build.gradle, etc.)
Hermetic toolchain: we need to specify exactly which toolchain to use. This could be a Docker image, or a tarball of the toolchain.
Compute a key that is a hash of all the inputs. We must be careful to include every bit that can affect the output.
Check the cache: if the key exists, download the output (which might be a tarball of the built artifacts) and extract it.
If not, run the build in a sandbox:
Set up the sandbox: create a clean environment (e.g., using a Docker container with a specific image that contains the hermetic toolchain and minimal system libraries).
Copy the source files and the build script into the sandbox.
Run the build command (e.g., make, gradle build, etc.) in the sandbox.
Collect the output (the built artifacts) from the sandbox.
Upload the output to the cache server with the computed key.
Then extract the output to the expected location in the workspace.
Challenges:
The build might have side effects (like generating files that are not part of the output, or accessing the network). We must ensure the build is hermetic and does not depend on the environment. This is a requirement for the cache to be correct.
The sandbox must be set up correctly. We might need to provide some system dependencies (like glibc) but in a controlled way. Alternatively, we can use a completely static build or a build that uses a very minimal libc (like musl) and then we can have a very controlled environment.
The cache key must include everything that can affect the output. This includes:
The source code (of the package and its dependencies in the monorepo).
The build script (and any scripts it calls).
The toolchain (compiler, linker, etc.) and its version.
The environment variables that the build uses (if any). We might need to capture the environment or have a fixed environment in the sandbox.
We must handle dependencies between packages. In a monorepo, we might have a package that depends on another package that is built. We must ensure that when we build a package, we use the cached version of its dependencies (or build them first).
This suggests we need a build system that understands the dependency graph and can build in the correct order.
Alternatively, we can have a two-level cache:
At the action level (like compiling a single file) but that is more complex.
At the package level, but then we must ensure that the package build is hermetic with respect to its dependencies. That is, the dependency must be built with the same toolchain and same settings, and we must include the dependency's output as an input to the dependent package.
So for a package A that depends on package B (built as a library), we must:
Build B first (or use its cached output) and then use the built B as an input to A.
Therefore, the cache key for A must include the cache key of B (or the actual output of B? but that would be too big). Instead, we can include the hash of B's output (or the hash of B's cache key) as part of A's inputs.
But note: if B's output changes, then A must be rebuilt. So we need to track the dependency on B's output.
How about:
For package A:
Inputs = source of A + build script of A + (for each dependency D: the cache key of D)
But wait: what if D's build script changed but the output didn't? Then we don't need to rebuild A. However, if we use the cache key of D, then if D's cache key changes (because of a change in D's source or build script) then A's key changes and we rebuild A. That is correct.
But note: the cache key of D is a hash of D's inputs. So if D's output changed but its inputs didn't, then D's cache key would be the same? Actually, no: if D's build is not hermetic, then the same inputs might produce different outputs. But we assume hermetic builds, so same inputs -> same output.
We need to handle the dependency graph:
We can do a topological sort of the packages and then build them in order. For each package, we compute its cache key and then check the cache.
The hermetic toolchain:
We can use Docker images that contain the exact version of the compiler and system libraries. For example, for C++ we might use an image with gcc-10.2.0 and a specific version of glibc.
We must ensure that the same Docker image is used for every build of the same package (so we include the Docker image tag in the toolchain input?).
Actually, the toolchain is part of the inputs. So we can have:
And then we include the hash of this toolchain specification (or the actual Docker image hash) in the cache key? But note: the Docker image might be large and we don't want to include the entire image in the hash. Instead, we can use the Docker image ID (which is a hash of the image layers) as the toolchain identifier.
So:
code
toolchain_input = {
"docker_image_id": "sha256:...",
... maybe other toolchain files (like a specific version of a library) ...
}
Then we compute the hash of the toolchain_input and include that in the cache key.
Alternatively, we can have a file that describes the toolchain (like a JSON file) and hash that file.
But note: the build might need more than just the source. It might need the toolchain installed in the image. And we must ensure that the build does not access the network (unless we want to allow it, but then it's not hermetic). So we might run Docker with --network none.
Also, we must set up the environment variables appropriately.
However, note that the build might generate files outside of the output directory. We must capture all the outputs. So we should have a known output directory (like /output) and the build script must be configured to put all outputs there.
Alternatively, we can run the build and then collect all files that are created (but that might be error prone). So it's better to have the build system (like Make) install to a specific directory.
Would you like me to elaborate on any specific component or show how to integrate this with a specific build system (Bazel, Buck2, Nix, etc.)?
So we can use the cache key of the dependency as a proxy for the output. However, note that the cache key of D is a hash of D's inputs, and D's output is stored under that key. So if we change D's source, then D's cache key changes, and then A's cache key changes (because A's inputs now include a different hash for D). So A will be rebuilt.
But what if we change D's build script but the output of D remains the same? Then D's cache key changes (because the build script is part of the inputs) and then A's cache key changes, so A is rebuilt even though it might not need to be. This is a false positive, but it's safe.
Alternatively, we could use the actual output hash of D as the input to A. But then we would have to build D first to get its output hash, which is a chicken-and-egg problem? Not exactly: we can build D and get its output, then compute the hash of the output (or the entire output directory) and use that as the input to A. But then we are hashing the entire output of D, which might be large. Also, what if D's output is not deterministic? Then we are in trouble.
Given that we assume hermetic builds, the output of D is determined by the inputs of D. So the hash of the inputs of D (the cache key) is the same as the hash of the output of D (if we hash the entire output). But note: the output might be large and we don't want to hash it every time. So using the cache key (which is a hash of the inputs) is more efficient and equivalent under the assumption of hermeticity.
So we can do:
cache_key(A) = hash( source_A + build_script_A + {D: cache_key(D) for each dependency D} )
But note: the dependencies might be built with different toolchains? In a monorepo, we probably use the same toolchain for all, so we don't need to include the toolchain for each dependency? Actually, we are including the toolchain for A, and we assume that the toolchain for A is the same as for D? Not necessarily: A might use a different toolchain than D? But in a monorepo, we might standardize.
However, to be safe, we should include the toolchain used to build A. And for D, we are including its cache key, which already includes the toolchain used to build D. So if D was built with a different toolchain, then D's cache key would be different, and then A's cache key would be different. That's correct because the output of D (built with a different toolchain) might be different.
So the above formula seems okay.
The cache server:
We can use a simple HTTP server that supports:
code
PUT /cache/:key (with the output tarball in the body)
GET /cache/:key (returns the tarball)
We can use something like Amazon S3, or a simple file server.
The cache client:
We can write a script that:
code
- Computes the cache key.
- Tries to download from the cache server.
- If found, extracts the tarball to the output directory.
- If not found, runs the build in the sandbox, then creates a tarball of the output and uploads it.
We must also consider:
The cache might become large, so we might want to have a cache eviction policy (but that's on the server side).
Security: we must ensure that the cache server is secure and that the hermetic builds are indeed hermetic (so that a malicious build cannot poison the cache).
Implementation:
We can write a tool in a language of our choice (let's say Python for simplicity) that:
Takes as input:
The package directory (with source and build script)
The toolchain specification (Docker image ID)
The list of dependencies (with their cache keys)
Computes the cache key by hashing:
All source files in the package directory (recursively, but maybe we can exclude some files like .git? We should only include files that are part of the build inputs. We can have a .cacheignore file? Or we can let the build system specify which files are inputs.)
The build script (and any other scripts that are part of the build, but note: if the build script calls other scripts, we must include them too. So we need to know the entire set of input files.)
How to collect the set of input files?
code
Option 1: The build system (like Make) has a way to list all the dependencies of a target. But we are not using a build system that tracks dependencies? We are just running a build script.
Option 2: We can have a configuration file that lists the input files (or patterns) for the package.
Option 3: We can use a tool that traces the build (like `strace` or `dtruss`) to see which files are read. But that is heavy and might not be 100% reliable.
Alternatively, we can design our build system to be more structured: each package has a build.py that explicitly lists the inputs and outputs. Then we can use that.
Given the complexity, let's assume we have a file inputs.txt that lists all the input files (relative to the package directory) and a file output_dir that specifies the output directory (relative to the package directory) where the build puts the artifacts.
Then:
code
Inputs = all files listed in `inputs.txt` (or all files in the package directory if we don't have `inputs.txt`? But that might include files that are not used, which would cause unnecessary cache misses.)
We can also include the toolchain specification (as a JSON file) and the build script (which is part of the inputs.txt?).
Actually, the build script is part of the inputs, so it should be listed in inputs.txt.
So:
code
cache_key = hash( concatenation of all input files (with their relative paths and contents) + toolchain_spec_json )
But note: the toolchain_spec_json might include the Docker image ID and other toolchain files (like a specific version of a library). We must include the hash of that JSON.
Alternatively, we can hash the toolchain_spec_json separately and then include that hash in the main hash? Or just include the entire JSON string.
Let's do:
code
input_string = ""
for each input file (in a deterministic order, e.g., sorted by path):
input_string += relpath + ":" + sha256(file_content) [or we can just concatenate the file contents?]
But note: if two files have the same content but different names, they are different inputs. So we must include the path.
Then we also append the toolchain_spec_json string.
Then compute the SHA256 of the entire string.
However, if the set of input files is large, we might not want to read all the files. We can compute a Merkle tree? But for simplicity, we can just read all the files.
But note: the input files might be large. We can compute the hash incrementally.
# Step 2: Check cache.
if cache_server.has(cache_key):
tarball = cache_server.get(cache_key)
extract_tarball(tarball, package_dir / "output")
return
# Step 3: Build in sandbox.
# We need to set up the sandbox with the toolchain (Docker image) and the source.
# We assume the build script (in package_dir) will write to package_dir/output.
# We run:
# docker run --rm -v {package_dir}:/work -w /work {toolchain_spec['docker_image']} /bin/bash -c "./build.sh"
# But note: the build script might be named differently. We can have a standard name, or take it as an argument.
# We also need to set environment variables? Maybe the toolchain_spec includes environment variables.
# We run the build and check the exit code.
# Step 4: After build, we assume the output is in package_dir/output.
# Step 5: Create a tarball of the output directory.
tarball = create_tarball(package_dir / "output")
# Step 6: Upload to cache.
cache_server.put(cache_key, tarball)
Dependencies:
For a package that depends on other packages, we must build the dependencies first.
So we have a monorepo with multiple packages. We can have a packages/ directory, each with its own build.
We can have a top-level script that:
code
- Reads the dependency graph (maybe from a file, or we can infer from the import statements? That's language specific).
- Does a topological sort.
- For each package in topological order:
build_package(package_dir, toolchain_spec, dependencies_cache_keys)
where dependencies_cache_keys is a dictionary of {package_name: cache_key} for the dependencies.
How do we get the cache_key of a dependency? We just built it, so we have it.
But note: what if a dependency is not in the monorepo? Then we might have an external dependency (like a system library). We must have a way to specify the version of that external dependency and include it in the cache key? Or we assume that the hermetic toolchain includes all external dependencies? That's the idea of hermetic toolchain: the toolchain includes all the system libraries it needs.
So for external dependencies, we don't need to worry because they are part of the toolchain. But if the package uses an external library that is not in the toolchain (like a system library that is not in the Docker image) then the build is not hermetic. So we must ensure that all dependencies are either in the toolchain or built from source in the monorepo.
Toolchain specification:
We can have a file toolchain.json in the monorepo root that specifies:
And then we can have different toolchains for different languages? Or one toolchain that has everything?
Alternatively, we can have a toolchain per language? But then a package that uses multiple languages would need multiple toolchains? That's complicated.
Let's assume one toolchain for the entire monorepo.
Example:
Suppose we have a monorepo with two packages: A and B, and A depends on B.
Steps:
code
- Build B:
inputs_B = all source files of B + B's build script + toolchain_spec (and no dependencies because B has no internal dependencies)
cache_key_B = hash(inputs_B)
if cache has cache_key_B, download and extract.
else, build B in sandbox and upload.
- Build A:
inputs_A = all source files of A + A's build script + toolchain_spec + { "B": cache_key_B }
cache_key_A = hash(inputs_A)
if cache has cache_key_A, download and extract.
else, build A in sandbox (using the built B from the previous step? How? We must make B available to A.
How does A use B?
code
We have two options:
Option 1: We build B and then we install B (i.e., copy the built artifacts) to a system location in the toolchain? But that would break hermeticity because the toolchain is fixed.
Option 2: We build B and then we make B's output available in the sandbox for A. How?
We can do:
When building B, we put the output in a known location (outside the sandbox) and then when building A, we mount that output in the sandbox.
But note: the toolchain for A must be able to find B. We can set environment variables (like LIBRARY_PATH) to point to B's output.
So:
When building A, we run the Docker container with:
-v {B_output_dir}:/deps/B
and set environment variable:
B_DIR=/deps/B
Then A's build script must be written to look for B in $B_DIR.
This requires that the build script of A is aware of the environment variable. We can standardize: all packages that depend on another package must use a standard way to find dependencies.
Alternatively, we can have a package manager that installs the dependencies in a standard location (like /usr/local) in the toolchain? But then we are modifying the toolchain, which is supposed to be fixed.
We can have a base toolchain and then overlay the dependencies? That's getting complex.
Another idea: we build all packages in the same sandbox? But then the sandbox would have to be built incrementally? Not really.
Alternatively, we can build each package in its own sandbox, but we mount the dependencies (which are already built) as read-only volumes.
This requires that the build script of A uses $B_DIR to find B.
How do we standardize this? We can have a convention:
code
For each dependency D, we mount D's output at /deps/D and set an environment variable D_DIR=/deps/D.
Then the build script of A must be written to use $B_DIR.
But what if A uses pkg-config? Then we can set PKG_CONFIG_PATH to include /deps/B/lib/pkgconfig.
We can have the toolchain specification include a list of dependencies and their mount points and environment variables? But that's getting too much.
Alternatively, we can have a wrapper script that sets up the environment for the build based on the dependencies.
Given the complexity, maybe we should use a build system that already handles dependencies (like Bazel). But the problem says we are building a monorepo, so we might have to design our own.
Given the time, let's simplify:
code
We assume that the monorepo uses a build system that can handle dependencies (like Make, but with a standard way to find dependencies). We will rely on the build script to be written in a way that it can find its dependencies via environment variables.
We can define:
code
For each dependency D, we set an environment variable D_ROOT to the mount point of D's output.
Then the build script of A must use $B_ROOT to find B.
How does the build script of A know about B? That's up to the package developer.
Alternatively, we can have a configuration file for each package that lists its dependencies and how to find them (like a deps.json).
But let's not overcomplicate.
Summary of the plan:
We will have:
code
- A cache server (HTTP based) that stores tarballs by key.
- A tool that builds a package (given its directory, toolchain, and dependencies' cache keys) and uses the cache.
- A top-level script that:
* Reads the monorepo structure (list of packages and their dependencies).
* Does a topological sort.
* For each package, runs the build tool.
The build tool for a package:
Step 1: Compute the cache key.
Step 2: If cache hit, extract and skip.
Step 3: Else, build in a Docker container (sandbox) with the hermetic toolchain and with the dependencies mounted.
Step 4: Upload the output to the cache.
We assume:
code
- Each package has a `build.sh` script that builds the package and puts the output in a directory called `output` (relative to the package directory).
- Each package has a file `inputs.txt` that lists all the input files (one per line, relative to the package directory). We include the `build.sh` and `inputs.txt` themselves as inputs.
- Each package has a file `deps.txt` that lists the dependencies (one per line, the package names). We use the cache keys of these dependencies.
Alternatively, we can have a single configuration file for the entire monorepo that defines the packages and their dependencies.
Let's design a simple configuration:
code
In the monorepo root, we have `packages/` directory, and each package is a subdirectory.
We can have a `packages.json`:
{
"packages": {
"A": {
"path": "packages/A",
"deps": ["B"],
"build_script": "build.sh",
"inputs_file": "inputs.txt"
},
"B": {
"path": "packages/B",
"deps": [],
"build_script": "build.sh",
"inputs_file": "inputs.txt"
}
}
}
Then the top-level script:
code
- Reads `packages.json`.
- Builds a dependency graph.
- Topologically sorts.
- For each package in order:
toolchain_spec = read_toolchain_spec() # from toolchain.json
deps_cache_keys = {}
for dep in package['deps']:
deps_cache_keys[dep] = cache_keys[dep] # from previous builds
cache_key = build_tool.compute_cache_key(package['path'], toolchain_spec, deps_cache_keys)
if cache_server.has(cache_key):
cache_server.get(cache_key, package['path'] + "/output")
else:
build_tool.build(package['path'], toolchain_spec, deps_cache_keys) # this will run in sandbox and then upload to cache with cache_key.
cache_keys[package_name] = cache_key
The build_tool (which we will write) will:
code
- compute_cache_key:
* Read the toolchain_spec and compute its hash (maybe as JSON string).
* For the package, read the inputs_file and then read each file listed, and compute a hash (like SHA256) of the file content. But note: we must include the file path. So we can compute:
hash_input = ""
for file in sorted(list_of_input_files): # sort by relative path
with open(file, 'rb') as f:
content = f.read()
hash_input += relpath + ":" + hashlib.sha256(content).hexdigest() + "\n"
hash_input += json.dumps(toolchain_spec, sort_keys=True) + "\n"
for dep_name, dep_cache_key in deps_cache_keys.items():
hash_input += dep_name + ":" + dep_cache_key + "\n"
cache_key = hashlib.sha256(hash_input.encode()).hexdigest()
- build:
* Create a temporary directory for the output? Or we assume the package has an `output` directory that we can overwrite.
* Run the build in Docker:
docker run --rm \
-v {package_path}:/work \
-v {cache_keys[dep]:?} ... we need to mount the dependencies.
How do we mount the dependencies?
For each dependency dep, we have:
dep_output_path = ... where did we put the output of dep? We have it in the cache and we extracted it to the package directory of dep? Actually, when we built dep, we extracted it to dep's output directory (which is dep_path/output). But then when building A, we need to mount B's output (which is at packages/B/output) to /deps/B.
So we can do:
mounts = []
env = {}
for dep_name, dep_cache_key in deps_cache_keys.items():
dep_package = packages[dep_name]
dep_output_path = dep_package['path'] + "/output"
mounts.append(f"-v {dep_output_path}:/deps/{dep_name}")
env[f"{dep_name}_ROOT"] = f"/deps/{dep_name}"
Then run:
docker run --rm \
{mounts} \
-e {env_vars} \
-v {package_path}:/work \
-w /work \
{toolchain_spec['docker_image']} \
/bin/bash -c "cd /work && {build_script}"
But note: the build script might be named differently. We use package['build_script'].
* After the build, we assume the output is in package_path/output.
* Then we create a tarball of the output directory and upload to cache with cache_key.
Issues:
The build script might not put the output in the expected directory. We must enforce that.
The inputs.txt must be maintained by the package developer. They must list every file that the build uses (including headers from other packages? but those are provided via the mounted dependencies). Actually, the inputs for A should not include the source of B, because B is built and then provided as a dependency. So the inputs for A are:
code
A's source files + A's build script + the cache keys of B (and other deps) + the toolchain.
But note: the build script of A might include headers from B. However, those headers are in B's output, which is mounted. So the build of A depends on B's output, not on B's source. So we don't need to include B's source in A's inputs.
However, what if A's build script uses a script from B's source? That would be a mistake because B's source is not mounted. We only mount B's output.
So we must ensure that A does not depend on B's source. Only on B's output.
What about transitive dependencies? For example, A depends on B, and B depends on C. Then:
code
We build C first, then B (using C's output), then A (using B's output).
In A's build, we mount B's output, which was built with C's output. So A does not directly depend on C, but through B.
In the cache key of A, we include the cache key of B. And B's cache key includes the cache key of C. So if C changes, then B's cache key changes, then A's cache key changes. That's correct.
What if two packages depend on the same dependency? Then we build the dependency once and use the same cache key for both.
Toolchain:
We assume the toolchain Docker image is the same for all packages. But what if a package needs a different toolchain? Then we must have a way to specify the toolchain per package.
We can extend the package configuration to include a toolchain field. Then the cache key of a package includes the toolchain specification (which includes the Docker image) and the toolchain specification of its dependencies? Actually, we are including the cache key of dependencies, which already includes their toolchain. So if B was built with a different toolchain, then B's cache key is different, and then A's cache key is different even if A uses the same toolchain? That's correct because the output of B (built with a different toolchain) might be different.
But what if A and B use different toolchains? Then we must mount B's output (which was built with a different toolchain) and then build A with its own toolchain. That might not work because the output of B might be incompatible with A's toolchain.
So we must enforce that all packages in the monorepo use the same toolchain? Or we must have a way to specify the toolchain per package and ensure compatibility.
Given the complexity, let's assume one toolchain for the entire monorepo.
Conclusion:
This is a simplified design. In practice, there are many challenges (like handling generated files, non-hermetic builds, etc.). But this is a starting point.
We will implement:
code
- cache_server.py: a simple HTTP server that stores tarballs in a directory.
- build_tool.py: the client that computes cache key, checks cache, builds, and uploads.
- top_level.py: reads packages.json, does topological sort, and calls build_tool for each package.
We assume:
code
- The monorepo has a fixed structure with packages in `packages/` and a `packages.json` at the root.
- Each package has:
build.sh
inputs.txt
(optional) deps.txt? Actually, we are using packages.json for dependencies.
- We have a toolchain.json at the root.
Steps to run:
code
python top_level.py
We must also have the Docker daemon running and the toolchain Docker image available.
We'll use the requests library for HTTP and docker library for Docker.
But note: we might not want to use the Docker Python SDK because it requires the Docker daemon to be running and accessible. We can use the docker command line.
Alternatively, we can use subprocess to run Docker.
Let's use subprocess for Docker.
Code structure:
top_level.py:
code
import json
from build_tool import BuildTool
def main():
with open('packages.json') as f:
config = json.load(f)
with open('toolchain.json') as f:
toolchain = json.load(f)
# Build dependency graph and topologically sort.
# We'll do a simple topological sort (Kahn's algorithm).
# Then for each package in order:
build_tool = BuildTool(toolchain)
cache_keys = {}
for package_name in topological_order:
package = config['packages'][package_name]
deps_cache_keys = {dep: cache_keys[dep] for dep in package['deps']}
cache_key = build_tool.compute_cache_key(package['path'], deps_cache_keys)
if not build_tool.cache_has(cache_key):
build_tool.build(package['path'], deps_cache_keys)
cache_keys[package_name] = cache_key
build_tool.py:
code
import os
import hashlib
import json
import subprocess
import tarfile
import tempfile
import requests
CACHE_SERVER_URL = "http://localhost:8000"
class BuildTool:
def __init__(self, toolchain):
self.toolchain = toolchain
def compute_cache_key(self, package_path, deps_cache_keys):
# Read inputs file
inputs_file = os.path.join(package_path, 'inputs.txt')
with open(inputs_file) as f:
input_files = [line.strip() for line in f if line.strip()]
# Compute hash
h = hashlib.sha256()
for relpath in sorted(input_files):
abspath = os.path.join(package_path, relpath)
with open(abspath, 'rb') as f:
content = f.read()
h.update(relpath.encode())
h.update(hashlib.sha256(content).digest())
# Add toolchain
toolchain_str = json.dumps(self.toolchain, sort_keys=True)
h.update(toolchain_str.encode())
# Add dependencies cache keys
for dep_name, dep_cache_key in sorted(deps_cache_keys.items()):
h.update(dep_name.encode())
h.update(dep_cache_key.encode())
return h.hexdigest()
def cache_has(self, cache_key):
response = requests.get(f"{CACHE_SERVER_URL}/cache/{cache_key}")
return response.status_code == 200
def cache_get(self, cache_key, output_dir):
response = requests.get(f"{CACHE_SERVER_URL}/cache/{cache_key}")
response.raise_for_status()
# Write to a temporary file and then extract?
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(response.content)
tmp_path = tmp.name
# Extract
with tarfile.open(tmp_path, 'r:gz') as tar:
tar.extractall(output_dir)
os.unlink(tmp_path)
def cache_put(self, cache_key, output_dir):
# Create tarball of output_dir
with tempfile.NamedTemporaryFile(delete=False, suffix='.tar.gz') as tmp:
with tarfile.open(fileobj=tmp, mode='w:gz') as tar:
tar.add(output_dir, arcname='.')
tmp_path = tmp.name
# Upload
with open(tmp_path, 'rb') as f:
response = requests.put(f"{CACHE_SERVER_URL}/cache/{cache_key}", data=f)
response.raise_for_status()
os.unlink(tmp_path)
def build(self, package_path, deps_cache_keys):
# First, check if output directory exists, if not create it? Or the build script will create it.
# We assume the build script writes to package_path/output.
# Prepare Docker command
docker_image = self.toolchain['docker_image']
build_script = os.path.join(package_path, 'build.sh') # we assume build_script is relative to package_path
# Mount the package directory and the dependencies
mounts = []
env = {}
# Mount the package directory (we will mount it as read-write? because the build will write output)
mounts.append(f"-v {package_path}:/work")
# For each dependency, mount its output and set environment variable
for dep_name, dep_cache_key in deps_cache_keys.items():
# We need to know where the dependency's output is. We assume that the dependency was built and its output is in the same relative path?
# Actually, we don't have a global location. We must have built the dependency and left its output in its package directory under 'output'.
# So we need to know the package path of the dependency. But we don't have that in the deps_cache_keys.
# We must change: the deps_cache_keys should be a mapping from dep_name to (cache_key, package_path). Or we can have a global mapping from package name to package path.
# Let's change the interface: we pass in a dict of dep_name -> (cache_key, package_path). Then we can mount the output.
pass # We'll adjust.
# We must also set the environment variables for the toolchain (if any) from self.toolchain['env'].
# Run Docker
cmd = ["docker", "run", "--rm"]
for m in mounts:
cmd.append(m)
for k, v in env.items():
cmd.append("-e")
cmd.append(f"{k}={v}")
cmd.extend(["-w", "/work", docker_image, "/bin/bash", "-c", f"cd /work && {build_script}"])
subprocess.check_call(cmd)
# After build, we assume output is in package_path/output.
output_dir = os.path.join(package_path, 'output')
if not os.path.exists(output_dir):
raise Exception(f"Build did not produce output directory: {output_dir}")
# Upload to cache
self.cache_put(cache_key, output_dir)
But note: we changed the interface of build to need the package_path of dependencies. So in top_level.py, we must pass not only the cache key but also the package path.
Alternatively, we can have a global mapping from package name to package path.
Let's adjust:
code
In top_level.py, we have:
package_name -> package_info (which includes path)
Then when building a package, we can get the package path of the dependencies from that mapping.
So:
deps_info = {}
for dep in package['deps']:
dep_package = config['packages'][dep]
deps_info[dep] = (cache_keys[dep], dep_package['path'])
Then pass deps_info to build_tool.build.
Then in build_tool.build:
code
for dep_name, (dep_cache_key, dep_package_path) in deps_info.items():
dep_output_path = os.path.join(dep_package_path, 'output')
mounts.append(f"-v {dep_output_path}:/deps/{dep_name}")
env[f"{dep_name}_ROOT"] = f"/deps/{dep_name}"
This way, we mount the output of the dependency at /deps/dep_name and set an environment variable.
The build script of the package must then use $dep_name_ROOT to find the dependency.
- A cache server (HTTP) that stores build outputs by key.
- A build tool that computes the cache key and uses the cache.
- A top-level orchestrator that builds packages in dependency order.
Assumptions:
code
- Hermetic builds: same inputs -> same outputs.
- Each package has a build script that puts output in a fixed directory (output/).
- Each package lists its input files (inputs.txt).
- Dependencies are provided by mounting their output directories and setting environment variables.
- One toolchain for the whole monorepo (Docker image).
This is a simplified version and might not cover all cases (like generated files that are not listed in inputs.txt, or non-hermetic builds).
But it's a starting point.
Next steps:
Implement the cache server.
Implement the build tool.
Implement the top-level script.
Test with a simple example.
Note: This design does not handle the case where the build produces multiple outputs (like binaries and libraries) and we want to cache them separately? We are caching the entire output directory.
Also, we are not handling the case where the build might produce different outputs on different systems (even with the same inputs) due to non-hermeticness. We assume hermeticity.
We also assume that the build does not require network access. We run Docker with --network none? We didn't include that in the Docker command. We should add --network none to the Docker run command to ensure no network access.
We also must set the user and group? We can run as root in the container? But then the output files might be owned by root. We can run with -u $(id -u):$(id -g) to match the current user.
Also, we must set the HOME directory? Some builds might write to ~. We can set -e HOME=/tmp and mount a temporary directory? Or we can set HOME to /work? But the build might not expect that.
for m in mounts:
cmd.append(m)
cmd.append(m) # wait, mounts are already in the list as strings? We did mounts as a list of strings like "-v ...". So we can just extend.
Actually, we built mounts as a list of strings. We can do:
code
cmd.extend(mounts)
Then for environment variables:
code
for k, v in env.items():
cmd.extend(["-e", f"{k}={v}"])
Then add the toolchain environment variables:
code
for k, v in self.toolchain.get('env', {}).items():
cmd.extend(["-e", f"{k}={v}"])
Then the image and command.
But note: the build script might be a relative path. We are in /work, so we can run it as ./build.sh.
We assume the build script is executable.
Alternatively, we can run with:
code
cmd = ["docker", "run", "--rm",
"-u", f"{os.getuid()}:{os.getgid()}",
"-v", f"{package_path}:/work",
"-e", "HOME=/tmp",
"--network", "none",
"-w", "/work"]
for dep_name, (dep_cache_key, dep_package_path) in deps_info.items():
dep_output_path = os.path.join(dep_package_path, 'output')
cmd.extend(["-v", f"{dep_output_path}:/deps/{dep_name}"])
env[f"{dep_name}_ROOT"] = f"/deps/{dep_name}"
for k, v in env.items():
cmd.extend(["-e", f"{k}={v}"])
for k, v in self.toolchain.get('env', {}).items():
cmd.extend(["-e", f"{k}={v}"])
cmd.extend([docker_image, "/bin/bash", "-c", f"cd /work && {build_script}"])
But note: build_script is the name of the script (from package['build_script']). We should use the absolute path? We are in /work, so we can use the relative path.
However, the build script might be in a subdirectory? We assume it's in the package_path.
We can do:
code
build_script_rel = package['build_script']
build_script_abs = os.path.join(package_path, build_script_rel)
# Then in the container, the path is /work/{build_script_rel}
This is a basic design and implementation. There are many edge cases and improvements possible.
We have not handled:
code
- Cleaning the output directory before building? The build script should handle that? Or we can remove the output directory before building.
- The cache key might be too sensitive to changes in the inputs.txt file (like adding an empty line). We are including the entire content of inputs.txt? Actually, we are reading the list of files from inputs.txt and then reading each file. So if inputs.txt changes (even a comment) then the set of input files might change.
- We are not verifying the integrity of the cache (like using signed URLs). But that's beyond the scope.
We hope this gives a good starting point.
Let's write the code accordingly.
Due to the complexity and length, I'll provide a simplified version of the code without error handling and with some assumptions.
We assume:
code
- The cache server is running.
- The toolchain Docker image is available.
- The user has permission to run Docker.
We'll write:
code
cache_server.py
build_tool.py
top_level.py
And example configuration.
Let's code accordingly.
I'll help you design and implement a monorepo remote cache system with hermetic toolchains and sandboxing. This is a complex system that combines several advanced concepts. Let me provide you with a comprehensive solution.