feat(build): wire --build/--no-cache flags and pass --pull during compose_build

- Extend DeployParams and UpdateParams with strict no_cache boolean implying build=True
- Wire --build and --no-cache on appctl up, deploy, and update CLI commands
- Update bash completion to suggest --build and --no-cache for up and update
- Pass --pull (and --no-cache when requested) on docker compose build in OperationalRouter
- Add comprehensive unit tests covering contract validation, CLI arguments, and router subprocess calls

Refs #11
This commit is contained in:
kiskaadee committed 2026-10-30 09:32:55 -05:00
1 parent 021c01171b
commit f631d5627c
7 files changed
+366 -11

No files matched your search

+19 -1
View File
@@ -70,7 +70,25 @@ _appctl_completions() {
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
fi
;;
up|down|restart|update|pull|logs|config)
up|deploy)
if [[ "$cur" == -* ]]; then
COMPREPLY=( $(compgen -W "--build --no-cache" -- "$cur") )
else
local services
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
fi
;;
update)
if [[ "$cur" == -* ]]; then
COMPREPLY=( $(compgen -W "--branch --build --no-cache" -- "$cur") )
else
local services
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
fi
;;
down|restart|pull|logs|config)
local services
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
+15 -1
View File
@@ -254,6 +254,7 @@ def run_cli(argv: list[str] | None = None) -> int:
up_p = subparsers.add_parser("up", aliases=["deploy"], parents=[common_parser], help="Deploy workload")
up_p.add_argument("target", help="Workload or core target")
up_p.add_argument("--build", action="store_true", help="Rebuild container images")
up_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
# down / stop
down_p = subparsers.add_parser("down", aliases=["stop"], parents=[common_parser], help="Stop workload")
@@ -267,6 +268,8 @@ def run_cli(argv: list[str] | None = None) -> int:
update_p = subparsers.add_parser("update", parents=[common_parser], help="Update workload revision")
update_p.add_argument("target", help="Workload target")
update_p.add_argument("--branch", default=None, help="Expected git branch")
update_p.add_argument("--build", action="store_true", help="Rebuild container images")
update_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
# pull
pull_p = subparsers.add_parser("pull", parents=[common_parser], help="Pull workload images")
@@ -323,10 +326,15 @@ def run_cli(argv: list[str] | None = None) -> int:
elif cmd == "health":
op_req = OperationRequest(operation=OperationType.PLATFORM_HEALTH)
elif cmd in ("up", "deploy"):
build_flag = getattr(parsed, "build", False)
no_cache_flag = getattr(parsed, "no_cache", False)
op_req = OperationRequest(
operation=OperationType.WORKLOAD_DEPLOY,
target=parsed.target,
parameters={"build": getattr(parsed, "build", False)},
parameters={
"build": build_flag or no_cache_flag,
"no_cache": no_cache_flag,
},
)
elif cmd in ("down", "stop"):
op_req = OperationRequest(
@@ -342,6 +350,12 @@ def run_cli(argv: list[str] | None = None) -> int:
params = {}
if getattr(parsed, "branch", None):
params["expected_branch"] = parsed.branch
build_flag = getattr(parsed, "build", False)
no_cache_flag = getattr(parsed, "no_cache", False)
if build_flag or no_cache_flag:
params["build"] = True
if no_cache_flag:
params["no_cache"] = True
op_req = OperationRequest(
operation=OperationType.WORKLOAD_UPDATE,
target=parsed.target,
+14
View File
@@ -161,6 +161,13 @@ class DeployParams(StrictModel):
recreate: StrictBool = True
remove_orphans: StrictBool = True
build: StrictBool = False
no_cache: StrictBool = False
@model_validator(mode="after")
def imply_build_from_no_cache(self) -> DeployParams:
if self.no_cache:
self.build = True
return self
class UpdateParams(StrictModel):
@@ -168,6 +175,13 @@ class UpdateParams(StrictModel):
expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None
build: StrictBool = False
no_cache: StrictBool = False
@model_validator(mode="after")
def imply_build_from_no_cache(self) -> UpdateParams:
if self.no_cache:
self.build = True
return self
class LogsParams(StrictModel):
+16 -4
View File
@@ -785,7 +785,9 @@ class OperationalRouter:
# Optional build
if params.build:
build_cmd = ["docker", "compose", "-f", str(compose_file), "build"]
build_cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"]
if params.no_cache:
build_cmd.append("--no-cache")
if container:
build_cmd.append(container)
code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0)
@@ -928,13 +930,23 @@ class OperationalRouter:
env = assemble_workload_env(app_dir, manifest, app.name)
output_log = [f"git: {pull_out.strip()}"]
for action in declared_actions:
actions = list(declared_actions)
if params.build and "compose_build" not in actions:
if "compose_up" in actions:
idx = actions.index("compose_up")
actions.insert(idx, "compose_build")
else:
actions.append("compose_build")
for action in actions:
if action == "git_pull":
continue # already executed in step 2
elif action == "compose_pull":
cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
elif action == "compose_build" or (params.build and action == "compose_up"):
cmd = ["docker", "compose", "-f", str(compose_file), "build"]
elif action == "compose_build":
cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"]
if params.no_cache:
cmd.append("--no-cache")
elif action == "compose_up":
cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
elif action == "compose_restart":
+77
View File
@@ -107,6 +107,81 @@ def test_cli_dispatches_mutation_command():
assert "Workload deployed" in mock_stdout.getvalue()
def test_cli_up_and_deploy_build_and_no_cache_flags():
"""Ensure appctl up/deploy with --build and --no-cache flags dispatches correct parameters."""
mock_resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_build_01",
operation=OperationType.WORKLOAD_DEPLOY,
target="jellyfin",
result={"action": "deployed", "message": "Workload deployed"},
)
# 1. up with --build
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["up", "jellyfin", "--build", "--token", "tok_secret"])
assert ret == 0
req: OperationRequest = mock_send.call_args[1]["operation_request"]
assert req.operation == OperationType.WORKLOAD_DEPLOY
assert req.parameters.get("build") is True
assert req.parameters.get("no_cache") is False
# 2. up with --no-cache implies build=True
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["up", "jellyfin", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
# 3. deploy alias with --no-cache
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["deploy", "jellyfin", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
def test_cli_update_build_and_no_cache_flags():
"""Ensure appctl update with --build and --no-cache flags dispatches correct parameters."""
mock_resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_upd_01",
operation=OperationType.WORKLOAD_UPDATE,
target="jellyfin",
result={"action": "updated", "message": "Workload updated"},
)
# 1. update with --build
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["update", "jellyfin", "--build", "--token", "tok_secret"])
assert ret == 0
req: OperationRequest = mock_send.call_args[1]["operation_request"]
assert req.operation == OperationType.WORKLOAD_UPDATE
assert req.parameters.get("build") is True
assert req.parameters.get("no_cache", False) is False
# 2. update with --no-cache implies build=True
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["update", "jellyfin", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
# 3. update with --branch and --no-cache
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["update", "jellyfin", "--branch", "main", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("expected_branch") == "main"
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
def test_cli_handles_missing_socket():
"""Ensure friendly stderr message when socket is absent."""
with patch("appctl_cli.send_daemon_request", side_effect=FileNotFoundError), patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
@@ -501,6 +576,8 @@ def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path):
)
assert res_comp.returncode == 0
assert "_appctl_completions()" in res_comp.stdout
assert "up|deploy)" in res_comp.stdout
assert "--build --no-cache" in res_comp.stdout
res_words = subprocess.run(
[bash_bin, str(appctl_script), "complete", "services"],
+34 -5
View File
@@ -210,12 +210,24 @@ def test_deploy_params_defaults_and_explicit_bounds():
assert p_default.recreate is True
assert p_default.remove_orphans is True
assert p_default.build is False
assert p_default.no_cache is False
# Explicit
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True)
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True, no_cache=False)
assert p_custom.recreate is False
assert p_custom.remove_orphans is False
assert p_custom.build is True
assert p_custom.no_cache is False
# no_cache implies build=True
p_no_cache = DeployParams(no_cache=True)
assert p_no_cache.no_cache is True
assert p_no_cache.build is True
# no_cache overrides explicit build=False
p_override = DeployParams(build=False, no_cache=True)
assert p_override.no_cache is True
assert p_override.build is True
def test_deploy_params_rejects_non_strict_types():
@@ -226,6 +238,8 @@ def test_deploy_params_rejects_non_strict_types():
DeployParams(remove_orphans=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
DeployParams(build=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
DeployParams(no_cache=bad_bool) # type: ignore[arg-type]
def test_deploy_params_rejects_extra_fields():
@@ -238,23 +252,38 @@ def test_update_params_defaults_and_explicit():
p_default = UpdateParams()
assert p_default.expected_branch is None
assert p_default.build is False
assert p_default.no_cache is False
# Explicit
p_custom = UpdateParams(expected_branch="main", build=True)
p_custom = UpdateParams(expected_branch="main", build=True, no_cache=False)
assert p_custom.expected_branch == "main"
assert p_custom.build is True
assert p_custom.no_cache is False
# no_cache implies build=True
p_no_cache = UpdateParams(no_cache=True)
assert p_no_cache.no_cache is True
assert p_no_cache.build is True
# no_cache overrides explicit build=False
p_override = UpdateParams(build=False, no_cache=True)
assert p_override.no_cache is True
assert p_override.build is True
def test_update_params_rejects_empty_branch_and_non_strict_types():
for bad_bool in ["true", "false", 1, 0, None, [True]]:
with pytest.raises(ValidationError):
UpdateParams(build=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams(no_cache=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams(expected_branch="") # min_length=1
with pytest.raises(ValidationError):
UpdateParams(expected_branch=123) # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams(build="true") # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams.model_validate({"build": False, "extra": "prohibited"})
+191
View File
@@ -411,6 +411,65 @@ def test_operational_router_dispatches_workload_deploy(
assert "up" in mock_run.call_args[0][0]
def test_operational_router_workload_deploy_build_flags(
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
):
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent,
)
mock_app = MagicMock()
mock_app.name = "snappymail"
mock_app.dir_path = str(mock_workload_dir)
# 1. Deploy with build=True passes --pull
req_build = OperationRequest.model_validate({
"operation": "workload.deploy",
"target": "snappymail",
"parameters": {"build": True},
})
executed_commands: list[list[str]] = []
def mock_subproc(cmd: list[str], **kwargs):
executed_commands.append(cmd)
return 0, "ok", ""
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"),
):
resp = router.dispatch(req_build, admin_principal)
assert resp.success is True
build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1
assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull"
]
# 2. Deploy with no_cache=True passes --pull and --no-cache
req_no_cache = OperationRequest.model_validate({
"operation": "workload.deploy",
"target": "snappymail",
"parameters": {"no_cache": True},
})
executed_commands.clear()
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"),
):
resp = router.dispatch(req_no_cache, admin_principal)
assert resp.success is True
build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1
assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache"
]
def test_operational_router_workload_update_rejects_dirty_git_tree(
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
):
@@ -527,6 +586,138 @@ def test_operational_router_workload_update_succeeds_on_clean_tree(
assert len(pull_calls) == 2 # git pull and docker compose pull
def test_operational_router_workload_update_build_and_no_cache_flags(
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
):
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent,
)
mock_app = MagicMock()
mock_app.name = "snappymail"
mock_app.dir_path = str(mock_workload_dir)
executed_commands: list[list[str]] = []
def mock_subproc(cmd: list[str], **kwargs):
executed_commands.append(cmd)
if "status" in cmd:
return 0, "", ""
if "pull" in cmd and "git" in cmd:
return 0, "Updating 1111..2222\nFast-forward", ""
if "rev-parse" in cmd:
return 0, "a1b2c3d", ""
return 0, "success", ""
# 1. Update with build=True
req_build = OperationRequest.model_validate({
"operation": "workload.update",
"target": "snappymail",
"parameters": {"build": True},
})
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"),
):
resp = router.dispatch(req_build, admin_principal)
assert resp.success is True
build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1
assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull"
]
# Also ensure compose_up was executed
up_calls = [c for c in executed_commands if "up" in c]
assert len(up_calls) == 1
# 2. Update with no_cache=True implies build=True and appends --no-cache
req_no_cache = OperationRequest.model_validate({
"operation": "workload.update",
"target": "snappymail",
"parameters": {"no_cache": True},
})
executed_commands.clear()
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"),
):
resp = router.dispatch(req_no_cache, admin_principal)
assert resp.success is True
build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1
assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache"
]
up_calls = [c for c in executed_commands if "up" in c]
assert len(up_calls) == 1
def test_operational_router_workload_update_declared_compose_build(
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
):
# Rewrite app.yaml with declared compose_build action
manifest_content = """
schema_version: "1.0"
name: "snappymail"
source:
type: "git"
url: "https://github.com/example/snappymail.git"
ref: "main"
deployment:
strategy: "compose"
actions:
- "git_pull"
- "compose_build"
- "compose_up"
"""
(mock_workload_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8")
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent,
)
mock_app = MagicMock()
mock_app.name = "snappymail"
mock_app.dir_path = str(mock_workload_dir)
executed_commands: list[list[str]] = []
def mock_subproc(cmd: list[str], **kwargs):
executed_commands.append(cmd)
if "status" in cmd:
return 0, "", ""
if "pull" in cmd and "git" in cmd:
return 0, "Updating 1111..2222\nFast-forward", ""
if "rev-parse" in cmd:
return 0, "a1b2c3d", ""
return 0, "success", ""
# Update with declared compose_build invokes build --pull
req = OperationRequest.model_validate({
"operation": "workload.update",
"target": "snappymail",
})
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"),
):
resp = router.dispatch(req, admin_principal)
assert resp.success is True
build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1
assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull"
]
# ---------------------------------------------------------------------------
# Core Platform Stack & Core Service Dispatch (Issue #2)
# ---------------------------------------------------------------------------