TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Mini Project: A Polyglot Monorepo

Mini Project: A Polyglot Monorepo

Time to put the course together. You'll build a small company monorepo with four languages in one graph, enforce its boundaries, extend Bazel with a rule, and then prove that a remote cache can rebuild the whole thing on a fresh machine without compiling anything.

Package What Language
//libs/pricing the pricing library: rounding and VAT, plus its test C++
//libs/pricing:pricing_cli a small CLI around the library C++
//tools/pricegen a tool that generates a Python module from the C++ CLI at build time (genrule), and a report that also runs the CLI from its runfiles Python
//services/catalog a catalog service with tests Go
//libs/money-java a money formatting library and a demo binary Java
//build_defs a custom release_manifest rule and a package_group for the boundaries Starlark
//release the release manifest over every shipped binary Starlark rule

The plan

  1. Write MODULE.bazel with the four rule sets and .bazelrc with ci and remote configs.
  2. Write the C++ library and CLI, with visibility restricted to a package_group of in-house tools.
  3. Write the Python tool: one generated module (C++ → Python at build time) and one subprocess call (data dependency).
  4. Write the Go service and the Java library.
  5. Write the release_manifest rule and apply it to all binaries.
  6. Build and test everything, then check a boundary violation.
  7. Start bazel-remote, build with uploads, bazel clean --expunge, rebuild: every action must be a remote cache hit.

The session

bash · try it yourself
mkdir monorepo && cd monorepo
echo "== step 1: module and rc files"
cat > MODULE.bazel <<'EOF'
module(name = "acme", version = "1.0.0")

bazel_dep(name = "rules_cc", version = "0.2.27")
bazel_dep(name = "rules_python", version = "2.4.5")
bazel_dep(name = "rules_go", version = "0.65.0")
bazel_dep(name = "rules_java", version = "9.9.0")

go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk")
go_sdk.download(version = "1.27.3")
EOF
cat > .bazelrc <<'EOF'
common --lockfile_mode=update
test --test_output=errors

build:ci --keep_going
build:remote --remote_cache=http://127.0.0.1:9090
build:remote --remote_upload_local_results=true
EOF
mkdir -p build_defs libs/pricing tools/pricegen services/catalog libs/money-java/java/com/acme/money release
cat > build_defs/BUILD.bazel <<'EOF'
package_group(
    name = "inhouse_tools",
    packages = ["//tools/...", "//release"],
)
EOF

echo "== step 2: C++ library, CLI and test"
cat > libs/pricing/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test")

cc_library(
    name = "pricing",
    srcs = ["pricing.cc"],
    hdrs = ["pricing.h"],
)

cc_binary(
    name = "pricing_cli",
    srcs = ["cli.cc"],
    deps = [":pricing"],
    visibility = ["//build_defs:inhouse_tools"],
)

cc_test(
    name = "pricing_test",
    size = "small",
    srcs = ["pricing_test.cc"],
    deps = [":pricing"],
)
EOF
cat > libs/pricing/pricing.h <<'EOF'
#pragma once
namespace pricing {
long with_vat(long net_cents, int vat_percent);   // rounds half up
}
EOF
cat > libs/pricing/pricing.cc <<'EOF'
#include "libs/pricing/pricing.h"
namespace pricing {
long with_vat(long net_cents, int vat_percent) { return (net_cents * (100 + vat_percent) + 50) / 100; }
}
EOF
cat > libs/pricing/cli.cc <<'EOF'
#include <cstdio>
#include <cstdlib>
#include "libs/pricing/pricing.h"
// pricing_cli NET VAT -> gross; pricing_cli --py-table -> a Python module
int main(int argc, char** argv) {
  if (argc == 2) {
    std::printf("# Generated by //libs/pricing:pricing_cli\nGROSS_FOR_1000 = {");
    const int vats[] = {0, 7, 19, 20};
    for (int vat : vats) std::printf("%d: %ld, ", vat, pricing::with_vat(1000, vat));
    std::printf("}\n");
    return 0;
  }
  std::printf("%ld\n", pricing::with_vat(std::atol(argv[1]), std::atoi(argv[2])));
}
EOF
cat > libs/pricing/pricing_test.cc <<'EOF'
#include "libs/pricing/pricing.h"
int main() { return pricing::with_vat(999, 19) == 1189 && pricing::with_vat(1000, 0) == 1000 ? 0 : 1; }
EOF

echo "== step 3: Python tool using the C++ code twice"
cat > tools/pricegen/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

genrule(                                   # build time: C++ tool -> Python module
    name = "gross_table",
    outs = ["gross_table.py"],
    tools = ["//libs/pricing:pricing_cli"],
    cmd = "$(execpath //libs/pricing:pricing_cli) --py-table > $@",
)

py_library(
    name = "pricegen_lib",
    srcs = ["pricegen.py", ":gross_table"],
    data = ["//libs/pricing:pricing_cli"],   # run time: subprocess
    deps = ["@rules_python//python/runfiles"],
)

py_binary(name = "report", srcs = ["report.py"], deps = [":pricegen_lib"])

py_test(name = "pricegen_test", size = "small", srcs = ["pricegen_test.py"], deps = [":pricegen_lib"])
EOF
cat > tools/pricegen/pricegen.py <<'EOF'
import subprocess
from python.runfiles import runfiles
from tools.pricegen.gross_table import GROSS_FOR_1000

_CLI = runfiles.Create().Rlocation("_main/libs/pricing/pricing_cli")

def gross(net_cents, vat):
    return int(subprocess.run([_CLI, str(net_cents), str(vat)], capture_output=True, text=True, check=True).stdout)

def table():
    return GROSS_FOR_1000
EOF
cat > tools/pricegen/report.py <<'EOF'
from tools.pricegen.pricegen import gross, table
print("generated table:", table())
for net in (999, 2500):
    print(f"net {net:>5} -> gross {gross(net, 19):>5} (19% VAT, computed by C++)")
EOF
cat > tools/pricegen/pricegen_test.py <<'EOF'
import unittest
from tools.pricegen.pricegen import gross, table

class PricegenTest(unittest.TestCase):
    def test_generated_and_runtime_agree(self):
        for vat, expected in table().items():
            self.assertEqual(gross(1000, vat), expected)

unittest.main()
EOF

echo "== step 4: Go service and Java library"
cat > services/catalog/BUILD.bazel <<'EOF'
load("@rules_go//go:def.bzl", "go_binary", "go_library", "go_test")
go_library(name = "catalog_lib", srcs = ["catalog.go"], importpath = "acme.example/catalog")
go_binary(name = "catalog", srcs = ["main.go"], deps = [":catalog_lib"], visibility = ["//release:__pkg__"])
go_test(name = "catalog_test", size = "small", srcs = ["catalog_test.go"], embed = [":catalog_lib"])
EOF
printf 'package catalog\n\nimport "sort"\n\n// SKUs returns the product codes in a stable order.\nfunc SKUs(items map[string]int) []string {\n\tout := make([]string, 0, len(items))\n\tfor k := range items {\n\t\tout = append(out, k)\n\t}\n\tsort.Strings(out)\n\treturn out\n}\n' > services/catalog/catalog.go
printf 'package catalog\n\nimport "testing"\n\nfunc TestSKUs(t *testing.T) {\n\tif got := SKUs(map[string]int{"b": 1, "a": 2}); got[0] != "a" {\n\t\tt.Fatalf("got %%v", got)\n\t}\n}\n' > services/catalog/catalog_test.go
printf 'package main\n\nimport (\n\t"fmt"\n\n\t"acme.example/catalog"\n)\n\nfunc main() { fmt.Println("catalog:", catalog.SKUs(map[string]int{"tea": 3, "coffee": 5, "cocoa": 1})) }\n' > services/catalog/main.go
cat > libs/money-java/BUILD.bazel <<'EOF'
load("@rules_java//java:defs.bzl", "java_binary", "java_library")
java_library(name = "money", srcs = ["java/com/acme/money/Money.java"])
java_binary(name = "money_demo", srcs = ["java/com/acme/money/Demo.java"], main_class = "com.acme.money.Demo",
            deps = [":money"], visibility = ["//release:__pkg__"])
EOF
printf 'package com.acme.money;\n\npublic final class Money {\n  public static String eur(long cents) { return String.format("EUR %%d.%%02d", cents / 100, cents %% 100); }\n}\n' > libs/money-java/java/com/acme/money/Money.java
printf 'package com.acme.money;\n\npublic class Demo {\n  public static void main(String[] a) { System.out.println("java: " + Money.eur(1189)); }\n}\n' > libs/money-java/java/com/acme/money/Demo.java

echo "== step 5: a custom rule for the release manifest"
touch build_defs/BUILD.bazel
cat > build_defs/manifest.bzl <<'EOF'
def _release_manifest_impl(ctx):
    out = ctx.actions.declare_file(ctx.label.name + ".txt")
    files = sorted([f for t in ctx.attr.binaries for f in t[DefaultInfo].files.to_list()], key = lambda f: f.short_path)
    args = ctx.actions.args()
    args.add(out)
    args.add(ctx.attr.version)
    args.add_all(files)
    ctx.actions.run_shell(
        inputs = files,
        outputs = [out],
        arguments = [args],
        command = 'out=$1; ver=$2; shift 2; { echo "acme $ver"; for f in "$@"; do echo "${f#bazel-out/*/bin/}"; done; } > "$out"',
        mnemonic = "ReleaseManifest",
    )
    return [DefaultInfo(files = depset([out]))]

release_manifest = rule(
    implementation = _release_manifest_impl,
    attrs = {"binaries": attr.label_list(mandatory = True), "version": attr.string(mandatory = True)},
)
EOF
cat > release/BUILD.bazel <<'EOF'
load("//build_defs:manifest.bzl", "release_manifest")
release_manifest(
    name = "manifest",
    version = "1.0.0",
    binaries = [
        "//libs/pricing:pricing_cli",
        "//services/catalog",
        "//libs/money-java:money_demo",
    ],
)
EOF

echo "== step 6: build and test everything"
bazel build //... 2>&1 | grep -E '^INFO: (Analyzed|[0-9]+ process)'
bazel test //... 2>&1 | grep -E 'PASSED|FAILED|Executed'
bazel run //tools/pricegen:report 2>/dev/null
bazel run //services/catalog 2>/dev/null
bazel run //libs/money-java:money_demo 2>/dev/null
cat bazel-bin/release/manifest.txt
echo "-- a boundary violation: the Go service may not use the pricing CLI"
cat >> services/catalog/BUILD.bazel <<'EOF'
go_binary(name = "sneaky", srcs = ["main.go"], deps = [":catalog_lib"], data = ["//libs/pricing:pricing_cli"])
EOF
bazel build //services/catalog:sneaky 2>&1 | grep -A2 'Visibility error' | sed 's#/home/learner/monorepo/##'
sed -i '/name = "sneaky"/d' services/catalog/BUILD.bazel

echo "== step 7: remote cache from a clean output base"
remote-cache start
bazel build --config=remote //... 2>&1 | grep -E '^INFO: [0-9]+ process'
bazel test --config=remote //... 2>&1 | grep -E '^INFO: [0-9]+ process'
bazel clean --expunge 2>/dev/null
bazel build --config=remote //... 2>&1 | grep -E '^INFO: [0-9]+ process'
bazel test --config=remote //... 2>&1 | grep -E '^INFO: [0-9]+ process|PASSED|FAILED'
bazel run --config=remote //tools/pricegen:report 2>/dev/null | tail -1
remote-cache stop
== step 1: module and rc files
== step 2: C++ library, CLI and test
== step 3: Python tool using the C++ code twice
== step 4: Go service and Java library
== step 5: a custom rule for the release manifest
== step 6: build and test everything
INFO: Analyzed 13 targets (138 packages loaded, 12296 targets configured).
INFO: 82 processes: 52 internal, 28 processwrapper-sandbox, 2 worker.
//libs/pricing:pricing_test                                              PASSED in 0.0s
//services/catalog:catalog_test                                          PASSED in 0.0s
//tools/pricegen:pricegen_test                                           PASSED in 0.4s
Executed 3 out of 3 tests: 3 tests pass.
generated table: {0: 1000, 7: 1070, 19: 1190, 20: 1200}
net   999 -> gross  1189 (19% VAT, computed by C++)
net  2500 -> gross  2975 (19% VAT, computed by C++)
catalog: [cocoa coffee tea]
java: EUR 11.89
acme 1.0.0
libs/money-java/money_demo
libs/money-java/money_demo.jar
libs/pricing/pricing_cli
services/catalog/catalog_/catalog
-- a boundary violation: the Go service may not use the pricing CLI
ERROR: services/catalog/BUILD.bazel:5:10: in go_binary rule //services/catalog:sneaky: Visibility error:
target '//libs/pricing:pricing_cli' is not visible from
target '//services/catalog:sneaky'
== step 7: remote cache from a clean output base
INFO: 82 processes: 52 internal, 28 processwrapper-sandbox, 2 worker.
INFO: 4 processes: 1 internal, 5 processwrapper-sandbox.
INFO: 82 processes: 30 remote cache hit, 52 internal.
INFO: 4 processes: 2 action cache hit, 5 remote cache hit, 1 internal.
//libs/pricing:pricing_test                                     (cached) PASSED in 0.0s
//services/catalog:catalog_test                                 (cached) PASSED in 0.0s
//tools/pricegen:pricegen_test                                  (cached) PASSED in 0.4s
net  2500 -> gross  2975 (19% VAT, computed by C++)

Walkthrough

  • Step 6 built 4 languages with 4 toolchains in one invocation and ran 4 test suites. The Python test checks the two cross-language links against each other: the table generated from C++ at build time and the values computed by running the C++ CLI at run time must agree.
  • The release manifest is produced by your own rule: it reads the DefaultInfo of three binaries in three languages (the Java binary contributes its launcher script and .jar), sorts them and records their paths. Change any of those binaries and the manifest is rebuilt.
  • The package_group //build_defs:inhouse_tools made the C++ CLI usable by //tools/... and //release only. The Go service's attempt to bundle it failed at analysis time.
  • Step 7: the first --config=remote build and test ran the real actions again (28 sandboxed actions plus 2 javac worker runs, then the 3 tests) and uploaded their results to bazel-remote. Then clean --expunge threw away the output base, the action cache and the server. The rebuild executed no actions (no processwrapper-sandbox or worker in its summary): all 30 of them (every compile, link, javac, Go standard-library build, the genrule and the custom rule) were remote cache hits, and the test results came back (cached). That's what a CI agent with an empty disk sees when the main branch has already been built once.

Extend it

  1. Add implementation_deps and strip_include_prefix to the C++ library and move its header to include/pricing/.
  2. Add a string_flag //build_defs:region and select() a different default VAT per region; check it with bazel cquery.
  3. Cross-compile the catalog service for linux_arm64 and add the ARM binary to a second manifest.
  4. Write a test rule (test = True) that fails if the manifest is missing a binary.
  5. Put --remote_upload_local_results=false into a dev config and prove with the remote cache's /status endpoint that a developer build no longer adds entries.

Test yourself

In the mini project, how does Python use the C++ code at build time?

  1. Through ctypes
  2. A genrule runs the C++ CLI (in tools) to generate gross_table.py
  3. By importing the .so
  4. It doesn't

Why did the Go sneaky target fail?

  1. Go can't depend on C++
  2. The C++ CLI's visibility is limited to the inhouse_tools package_group
  3. Missing load()
  4. The remote cache was off

After bazel clean --expunge, why did the rebuild run no actions?

  1. Bazel kept the outputs
  2. Every action key was found in the remote cache, so results were downloaded
  3. The build was skipped
  4. Tests were disabled